<commit_before>package sources

import (
	"net/http"
	"fmt"
	"encoding/json"
	"github.com/golang/glog"
	"bytes")

type DmrContainer struct {
	Name    string      `json:"name,omitempty"`
	Host    string      `json:"host"`
	DmrPort int         `json:"dmrPort"`
	Stats   *StatsEntry `json:"stats,omitempty"`
}

type DmrAttributeRequest struct {
	Operation 	string	`json:"operation"`
	Name      	string	`json:"name"`
	Pretty		int		`json:"json.pretty"`
}

type DmrResourceRequest struct {
	Operation 			string		`json:"operation"`
	IncludeRuntime      bool		`json:"include-runtime"`
	Address				[]string	`json:"address"`
	Pretty				int			`json:"json.pretty"`
}

type DmrResponse struct {
	Outcome 				string		`json:"outcome"`
	Result      			interface{}	`json:"result"`
	FailureDescription      string		`json:"failure-description"`
	RolledBacked      		bool		`json:"rolled-back"`
}

type WebResult struct {
	BytesReceived		StringInt			`json:"bytesReceived"`
	BytesSent			StringInt			`json:"bytesSent"`
	EnableLookups		bool				`json:"enable-lookups"`
	Enabled				bool				`json:"enabled"`
	ErrorCount			StringInt			`json:"errorCount"`
	Executor			string				`json:"executor"`
	MaxConnections		int					`json:"max-connections"`
	MaxPostSize			int64				`json:"max-post-size"`
	MaxSavePostSize		int64				`json:"max-save-post-size"`
	MaxTime				StringInt			`json:"maxTime"`
	Name				string				`json:"name"`
	ProcessingTime		StringInt			`json:"processingTime"`
	Protocol			string				`json:"protocol"`
	ProxyName			string				`json:"proxy-name"`
	ProxyPort			string				`json:"proxy-port"`
	RedirectPort		int					`json:"redirect-port"`
	RequestCount		StringInt			`json:"requestCount"`
	Scheme				string				`json:"scheme"`
	Secure				bool				`json:"secure"`
	SocketBinding		string				`json:"socket-binding"`
	SSL					string				`json:"ssl"`
	VirtualServer		string				`json:"virtual-server"`
}

func (self *DmrContainer) GetName() string {
	return self.Name
}

func (self *DmrContainer) GetStats() (*StatsEntry, error) {
	dmrRequest := DmrResourceRequest{
		Operation: "read-resource",
		IncludeRuntime: true,
		Address: []string{"subsystem", "web", "connector", "http"},
		Pretty: 1,
	}

	wr := WebResult{}
	dmrResponse := DmrResponse{
		Result: &wr,
	}

	err := self.getStats(&dmrRequest, &dmrResponse)
	if err != nil {
		return nil, err
	}

	glog.Infof("outcome: %s, result: %s, failure: %s", dmrResponse.Outcome, dmrResponse.Result, dmrResponse.FailureDescription)

	dmrStats := make(map[string]interface{})
	dmrStats["bytes_received"] = wr.BytesReceived
	dmrStats["bytes_sent"] = wr.BytesSent
	dmrStats["enable_lookups"] = wr.EnableLookups
	dmrStats["enabled"] = wr.Enabled
	dmrStats["error_count"] = wr.ErrorCount
	dmrStats["executor"] = wr.Executor
	dmrStats["max_connections"] = wr.MaxConnections
	dmrStats["max_post_size"] = wr.MaxPostSize
	dmrStats["max_save_post_size"] = wr.MaxSavePostSize
	dmrStats["max_time"] = wr.MaxTime
	dmrStats["name"] = wr.Name
	dmrStats["processing_time"] = wr.ProcessingTime
	dmrStats["protocol"] = wr.Protocol
	dmrStats["proxy_name"] = wr.ProxyName
	dmrStats["proxy_port"] = wr.ProxyPort
	dmrStats["redirect_port"] = wr.RedirectPort
	dmrStats["request_count"] = wr.RequestCount
	dmrStats["scheme"] = wr.Scheme
	dmrStats["secure"] = wr.Secure
	dmrStats["socket_binding"] = wr.SocketBinding
	dmrStats["ssl"] = wr.SSL
	dmrStats["virtual_server"] = wr.VirtualServer

	responseStats := make(map[string]StatsValue)
	responseStats["dmr"] = dmrStats

	result := &StatsEntry {
		Timestamp: time.Now().Local(),
		Stats:     responseStats,
	}

	glog.V(2).Infof("Retrieved DMR stats: %v", dmrStats)

	return result, nil
}

func (self *DmrContainer) getStats(request interface{}, result interface{}) error {
	reqBody, err := json.Marshal(request)
	if err != nil {
		return err
	}

	url := fmt.Sprintf("http://%s:%d/management", self.Host, self.DmrPort)

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(reqBody))
	if err != nil {
		return err
	}

	req.Header.Add("Content-Type", "application/json")

	err = PostRequestAndGetValue(&http.Client{}, req, result)
	if err != nil {
		return err
	}

	return nil
}
<commit_msg>Add missing import.<commit_after>package sources

import (
	"net/http"
	"fmt"
	"encoding/json"
	"github.com/golang/glog"
	"bytes"
	"time")

type DmrContainer struct {
	Name    string      `json:"name,omitempty"`
	Host    string      `json:"host"`
	DmrPort int         `json:"dmrPort"`
	Stats   *StatsEntry `json:"stats,omitempty"`
}

type DmrAttributeRequest struct {
	Operation 	string	`json:"operation"`
	Name      	string	`json:"name"`
	Pretty		int		`json:"json.pretty"`
}

type DmrResourceRequest struct {
	Operation 			string		`json:"operation"`
	IncludeRuntime      bool		`json:"include-runtime"`
	Address				[]string	`json:"address"`
	Pretty				int			`json:"json.pretty"`
}

type DmrResponse struct {
	Outcome 				string		`json:"outcome"`
	Result      			interface{}	`json:"result"`
	FailureDescription      string		`json:"failure-description"`
	RolledBacked      		bool		`json:"rolled-back"`
}

type WebResult struct {
	BytesReceived		StringInt			`json:"bytesReceived"`
	BytesSent			StringInt			`json:"bytesSent"`
	EnableLookups		bool				`json:"enable-lookups"`
	Enabled				bool				`json:"enabled"`
	ErrorCount			StringInt			`json:"errorCount"`
	Executor			string				`json:"executor"`
	MaxConnections		int					`json:"max-connections"`
	MaxPostSize			int64				`json:"max-post-size"`
	MaxSavePostSize		int64				`json:"max-save-post-size"`
	MaxTime				StringInt			`json:"maxTime"`
	Name				string				`json:"name"`
	ProcessingTime		StringInt			`json:"processingTime"`
	Protocol			string				`json:"protocol"`
	ProxyName			string				`json:"proxy-name"`
	ProxyPort			string				`json:"proxy-port"`
	RedirectPort		int					`json:"redirect-port"`
	RequestCount		StringInt			`json:"requestCount"`
	Scheme				string				`json:"scheme"`
	Secure				bool				`json:"secure"`
	SocketBinding		string				`json:"socket-binding"`
	SSL					string				`json:"ssl"`
	VirtualServer		string				`json:"virtual-server"`
}

func (self *DmrContainer) GetName() string {
	return self.Name
}

func (self *DmrContainer) GetStats() (*StatsEntry, error) {
	dmrRequest := DmrResourceRequest{
		Operation: "read-resource",
		IncludeRuntime: true,
		Address: []string{"subsystem", "web", "connector", "http"},
		Pretty: 1,
	}

	wr := WebResult{}
	dmrResponse := DmrResponse{
		Result: &wr,
	}

	err := self.getStats(&dmrRequest, &dmrResponse)
	if err != nil {
		return nil, err
	}

	glog.Infof("outcome: %s, result: %s, failure: %s", dmrResponse.Outcome, dmrResponse.Result, dmrResponse.FailureDescription)

	dmrStats := make(map[string]interface{})
	dmrStats["bytes_received"] = wr.BytesReceived
	dmrStats["bytes_sent"] = wr.BytesSent
	dmrStats["enable_lookups"] = wr.EnableLookups
	dmrStats["enabled"] = wr.Enabled
	dmrStats["error_count"] = wr.ErrorCount
	dmrStats["executor"] = wr.Executor
	dmrStats["max_connections"] = wr.MaxConnections
	dmrStats["max_post_size"] = wr.MaxPostSize
	dmrStats["max_save_post_size"] = wr.MaxSavePostSize
	dmrStats["max_time"] = wr.MaxTime
	dmrStats["name"] = wr.Name
	dmrStats["processing_time"] = wr.ProcessingTime
	dmrStats["protocol"] = wr.Protocol
	dmrStats["proxy_name"] = wr.ProxyName
	dmrStats["proxy_port"] = wr.ProxyPort
	dmrStats["redirect_port"] = wr.RedirectPort
	dmrStats["request_count"] = wr.RequestCount
	dmrStats["scheme"] = wr.Scheme
	dmrStats["secure"] = wr.Secure
	dmrStats["socket_binding"] = wr.SocketBinding
	dmrStats["ssl"] = wr.SSL
	dmrStats["virtual_server"] = wr.VirtualServer

	responseStats := make(map[string]StatsValue)
	responseStats["dmr"] = dmrStats

	result := &StatsEntry {
		Timestamp: time.Now().Local(),
		Stats:     responseStats,
	}

	glog.V(2).Infof("Retrieved DMR stats: %v", dmrStats)

	return result, nil
}

func (self *DmrContainer) getStats(request interface{}, result interface{}) error {
	reqBody, err := json.Marshal(request)
	if err != nil {
		return err
	}

	url := fmt.Sprintf("http://%s:%d/management", self.Host, self.DmrPort)

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(reqBody))
	if err != nil {
		return err
	}

	req.Header.Add("Content-Type", "application/json")

	err = PostRequestAndGetValue(&http.Client{}, req, result)
	if err != nil {
		return err
	}

	return nil
}
<|endoftext|>


<commit_before>package sched

import (
    "os"
    "net"
    "log"
    "bytes"
    "strconv"
    "encoding/json"
    "container/list"
)

func sockCheck(sockFile string) {
    _, err := os.Stat(sockFile)
    if err == nil || os.IsExist(err) {
        conn, err := net.Dial("unix", sockFile)
        if err == nil {
            conn.Close()
            log.Fatal("Huabot-sched is already started.")
        }
        os.Remove(sockFile)
    }
}

func PackJob(job Job) ([]byte, error) {
    jobStr, err := json.Marshal(job)
    if err != nil {
        return nil, err
    }
    buf := bytes.NewBuffer(jobStr)
    buf.Write(NULL_CHAR)
    buf.WriteString(strconv.FormatInt(job.Id, 10))
    return buf.Bytes(), nil
}

func removeListJob(l *list.List, jobId int64) {
    for e := l.Front(); e != nil; e = e.Next() {
        if e.Value.(Job).Id == jobId {
            l.Remove(e)
            break
        }
    }
}

func PackCmd(i int) []byte {
    buf := bytes.NewBuffer(nil)
    buf.WriteByte(byte(i))
    return buf.Bytes()
}
<commit_msg>update name<commit_after>package sched

import (
    "os"
    "net"
    "log"
    "bytes"
    "strconv"
    "encoding/json"
    "container/list"
)

func sockCheck(sockFile string) {
    _, err := os.Stat(sockFile)
    if err == nil || os.IsExist(err) {
        conn, err := net.Dial("unix", sockFile)
        if err == nil {
            conn.Close()
            log.Fatal("Periodic task system is already started.")
        }
        os.Remove(sockFile)
    }
}

func PackJob(job Job) ([]byte, error) {
    jobStr, err := json.Marshal(job)
    if err != nil {
        return nil, err
    }
    buf := bytes.NewBuffer(jobStr)
    buf.Write(NULL_CHAR)
    buf.WriteString(strconv.FormatInt(job.Id, 10))
    return buf.Bytes(), nil
}

func removeListJob(l *list.List, jobId int64) {
    for e := l.Front(); e != nil; e = e.Next() {
        if e.Value.(Job).Id == jobId {
            l.Remove(e)
            break
        }
    }
}

func PackCmd(i int) []byte {
    buf := bytes.NewBuffer(nil)
    buf.WriteByte(byte(i))
    return buf.Bytes()
}
<|endoftext|>


<commit_before>// Package tracer implements a Dapper-style tracing system. It is
// compatible with the OpenTracing specification.
//
// Sampling
//
// To keep the overhead incurred by tracing low, only a subset of
// requests should be traced. This is achieved by a sampler. Each
// tracer has a sampler that may sample requests based on chance, a
// rate, or possibly other mechanisms. The default sampler samples all
// requests, which is useful for testing, and viable for low-traffic
// systems.
//
// Only root spans make sampling decisions. Child spans will inherit
// the sampling decisions of the root spans.
//
// Errors and logging
//
// The instrumentation is defensive and will never purposefully panic.
// At the same time, most functions do not return errors, because
// they'll be called by automatic instrumentation, hidden from the
// user. Instead, errors will be logged.
package tracer

import (
	"crypto/rand"
	"encoding/binary"
	"encoding/hex"
	"log"
	"reflect"
	"sync"
	"time"

	"github.com/opentracing/opentracing-go"
	"github.com/opentracing/opentracing-go/ext"
)

// The various flags of a Span.
const (
	// The Span has been sampled.
	FlagSampled = 1 << iota
)

// A Logger logs messages.
type Logger interface {
	// Printf logs a single message, given a format and values. The
	// format is documented in the fmt package.
	Printf(format string, values ...interface{})
}

type defaultLogger struct{}

func (defaultLogger) Printf(format string, values ...interface{}) {
	log.Printf(format, values...)
}

// valueType returns the broad categorization of a value's type and
// whether it is permitted as a payload.
func valueType(v interface{}) (string, bool) {
	if v == nil {
		return "", true
	}
	rv := reflect.ValueOf(v)
	if !rv.IsValid() {
		return "", false
	}
	switch rv.Type().Kind() {
	case reflect.Bool:
		return "boolean", true
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32,
		reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16,
		reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64:
		return "number", true
	case reflect.String:
		return "string", true
	}
	return "", false
}

// A RawTrace contains all the data associated with a trace.
type RawTrace struct {
	TraceID   uint64        `json:"trace_id"`
	Spans     []RawSpan     `json:"spans"`
	Relations []RawRelation `json:"relations"`
}

// A RawRelation represents the relation between two spans.
type RawRelation struct {
	ParentID uint64 `json:"parent_id"`
	ChildID  uint64 `json:"child_id"`
	Kind     string `json:"kind"`
}

// Span is an implementation of the OpenTracing Span interface.
type Span struct {
	mu     sync.RWMutex
	tracer *Tracer
	raw    RawSpan
}

// A RawSpan contains all the data associated with a span.
type RawSpan struct {
	SpanContext
	ServiceName   string    `json:"service_name"`
	OperationName string    `json:"operation_name"`
	StartTime     time.Time `json:"start_time"`
	FinishTime    time.Time `json:"finish_time"`

	Tags map[string]interface{} `json:"tags"`
	Logs []opentracing.LogData  `json:"logs"`
}

// RawSpan returns a deep copy of the span's underlying data.
func (sp *Span) RawSpan() RawSpan {
	sp.mu.Lock()
	defer sp.mu.Unlock()
	raw := sp.raw
	tags := raw.Tags
	raw.Tags = map[string]interface{}{}
	for k, v := range tags {
		raw.Tags[k] = v
	}
	raw.Logs = append([]opentracing.LogData(nil), raw.Logs...)
	baggage := raw.Baggage
	raw.Baggage = map[string]string{}
	for k, v := range baggage {
		raw.Baggage[k] = v
	}
	return raw
}

// Sampled reports whether this span was sampled.
func (sp *Span) Sampled() bool {
	sp.mu.RLock()
	defer sp.mu.RUnlock()
	return sp.sampled()
}

func (sp *Span) sampled() bool {
	return (sp.raw.Flags & FlagSampled) > 0
}

// SetOperationName implements the opentracing.Span interface.
func (sp *Span) SetOperationName(name string) opentracing.Span {
	sp.mu.Lock()
	defer sp.mu.Unlock()
	sp.raw.OperationName = name
	return sp
}

// SetTag implements the opentracing.Span interface.
func (sp *Span) SetTag(key string, value interface{}) opentracing.Span {
	sp.mu.Lock()
	defer sp.mu.Unlock()
	if !sp.sampled() {
		return sp
	}
	if _, ok := valueType(value); !ok {
		sp.tracer.Logger.Printf("unsupported tag value type for tag %q: %T", key, value)
		return sp
	}
	if sp.raw.Tags == nil {
		sp.raw.Tags = map[string]interface{}{}
	}
	sp.raw.Tags[key] = value
	return sp
}

// Finish implements the opentracing.Span interface.
func (sp *Span) Finish() {
	if !sp.Sampled() {
		return
	}
	sp.FinishWithOptions(opentracing.FinishOptions{})
}

// FinishWithOptions implements the opentracing.Span interface.
func (sp *Span) FinishWithOptions(opts opentracing.FinishOptions) {
	sp.mu.Lock()
	defer sp.mu.Unlock()
	if !sp.sampled() {
		return
	}
	if opts.FinishTime.IsZero() {
		opts.FinishTime = time.Now()
	}
	sp.raw.FinishTime = opts.FinishTime
	for _, log := range opts.BulkLogData {
		sp.log(log)
	}
	if err := sp.tracer.storer.Store(sp.raw); err != nil {
		sp.tracer.Logger.Printf("error while storing tracing span: %s", err)
	}
}

// LogEvent implements the opentracing.Span interface.
func (sp *Span) LogEvent(event string) {
	if !sp.Sampled() {
		return
	}
	sp.Log(opentracing.LogData{
		Event: event,
	})
}

// LogEventWithPayload implements the opentracing.Span interface.
func (sp *Span) LogEventWithPayload(event string, payload interface{}) {
	if !sp.Sampled() {
		return
	}
	sp.Log(opentracing.LogData{
		Event:   event,
		Payload: payload,
	})
}

// Log implements the opentracing.Span interface.
func (sp *Span) Log(data opentracing.LogData) {
	sp.mu.Lock()
	defer sp.mu.Unlock()
	sp.log(data)
}

func (sp *Span) log(data opentracing.LogData) {
	if !sp.sampled() {
		return
	}
	if _, ok := valueType(data.Payload); !ok {
		sp.tracer.Logger.Printf("unsupported log payload type for event %q: %T", data.Event, data.Payload)
		return
	}
	if data.Timestamp.IsZero() {
		data.Timestamp = time.Now()
	}
	sp.raw.Logs = append(sp.raw.Logs, data)
}

// Context implements the opentracing.Span interface.
func (sp *Span) Context() opentracing.SpanContext {
	sp.mu.RLock()
	defer sp.mu.RUnlock()
	return sp.raw.SpanContext
}

// Tracer implements the opentracing.Span interface.
func (sp *Span) Tracer() opentracing.Tracer {
	sp.mu.RLock()
	defer sp.mu.RUnlock()
	return sp.tracer
}

// Tracer is an implementation of the OpenTracing Tracer interface.
type Tracer struct {
	ServiceName string
	Logger      Logger
	Sampler     Sampler

	storer      Storer
	idGenerator IDGenerator
}

// NewTracer returns a new tracer.
func NewTracer(serviceName string, storer Storer, idGenerator IDGenerator) *Tracer {
	return &Tracer{
		ServiceName: serviceName,
		Logger:      defaultLogger{},
		Sampler:     NewConstSampler(true),
		storer:      storer,
		idGenerator: idGenerator,
	}
}

// StartSpan implements the opentracing.Tracer interface.
func (tr *Tracer) StartSpan(operationName string, opts ...opentracing.StartSpanOption) opentracing.Span {
	var sopts opentracing.StartSpanOptions
	for _, opt := range opts {
		opt.Apply(&sopts)
	}
	if sopts.StartTime.IsZero() {
		sopts.StartTime = time.Now()
	}

	id := tr.idGenerator.GenerateID()
	sp := &Span{
		tracer: tr,
		raw: RawSpan{
			SpanContext: SpanContext{
				SpanID:  id,
				TraceID: id,
			},
			ServiceName:   tr.ServiceName,
			OperationName: operationName,
			StartTime:     sopts.StartTime,
		},
	}
	if len(sopts.References) > 0 {
		// TODO(dh): support multiple parents, support ChildOf and
		// FollowsFrom as separate kinds of relations.
		parent, ok := sopts.References[0].Referee.(SpanContext)
		if !ok {
			panic("parent span must be of type *Span")
		}
		sp.raw.ParentID = parent.SpanID
		sp.raw.TraceID = parent.TraceID
		sp.raw.Flags = parent.Flags
	} else {
		if n, _ := sopts.Tags[string(ext.SamplingPriority)].(uint16); n > 0 {
			sp.raw.Flags |= FlagSampled
		} else if tr.Sampler.Sample(id) {
			sp.raw.Flags |= FlagSampled
		}
	}
	sp.raw.Tags = sopts.Tags
	return sp
}

func idToHex(id uint64) string {
	b := make([]byte, 8)
	binary.BigEndian.PutUint64(b, id)
	return hex.EncodeToString(b)
}

func idFromHex(s string) uint64 {
	b, _ := hex.DecodeString(s)
	return binary.BigEndian.Uint64(b)
}

// Inject implements the opentracing.Tracer interface.
func (tr *Tracer) Inject(sm opentracing.SpanContext, format interface{}, carrier interface{}) error {
	context, ok := sm.(SpanContext)
	if !ok {
		return opentracing.ErrInvalidSpanContext
	}
	injecter, ok := injecters[format]
	if !ok {
		return opentracing.ErrUnsupportedFormat
	}
	return injecter(context, carrier)
}

// Extract implements the opentracing.Tracer interface.
func (tr *Tracer) Extract(format interface{}, carrier interface{}) (opentracing.SpanContext, error) {
	extracter, ok := extracters[format]
	if !ok {
		return nil, opentracing.ErrUnsupportedFormat
	}
	context, err := extracter(carrier)
	return context, err
}

// IDGenerator generates IDs for traces and spans. The ID with value 0
// is reserved to mean "no parent span" and should not be generated.
type IDGenerator interface {
	GenerateID() uint64
}

// A Storer stores a finished span. "Storing" a span may either mean
// saving it in a storage engine, or sending it to a remote
// collector.
//
// If a span with the same ID and the same trace ID already exists,
// the existing and new spans should be merged into one span.
//
// Because spans are only stored once they're done, children will be
// stored before their parents.
type Storer interface {
	Store(sp RawSpan) error
}

var _ IDGenerator = RandomID{}

// RandomID generates random IDs by using crypto/rand.
type RandomID struct{}

// GenerateID generates an ID.
func (RandomID) GenerateID() uint64 {
	b := make([]byte, 8)
	for {
		_, _ = rand.Read(b)
		x := binary.BigEndian.Uint64(b)
		if x != 0 {
			return x
		}
	}
}
<commit_msg>Don't return an extracted context if there was none<commit_after>// Package tracer implements a Dapper-style tracing system. It is
// compatible with the OpenTracing specification.
//
// Sampling
//
// To keep the overhead incurred by tracing low, only a subset of
// requests should be traced. This is achieved by a sampler. Each
// tracer has a sampler that may sample requests based on chance, a
// rate, or possibly other mechanisms. The default sampler samples all
// requests, which is useful for testing, and viable for low-traffic
// systems.
//
// Only root spans make sampling decisions. Child spans will inherit
// the sampling decisions of the root spans.
//
// Errors and logging
//
// The instrumentation is defensive and will never purposefully panic.
// At the same time, most functions do not return errors, because
// they'll be called by automatic instrumentation, hidden from the
// user. Instead, errors will be logged.
package tracer

import (
	"crypto/rand"
	"encoding/binary"
	"encoding/hex"
	"log"
	"reflect"
	"sync"
	"time"

	"github.com/opentracing/opentracing-go"
	"github.com/opentracing/opentracing-go/ext"
)

// The various flags of a Span.
const (
	// The Span has been sampled.
	FlagSampled = 1 << iota
)

// A Logger logs messages.
type Logger interface {
	// Printf logs a single message, given a format and values. The
	// format is documented in the fmt package.
	Printf(format string, values ...interface{})
}

type defaultLogger struct{}

func (defaultLogger) Printf(format string, values ...interface{}) {
	log.Printf(format, values...)
}

// valueType returns the broad categorization of a value's type and
// whether it is permitted as a payload.
func valueType(v interface{}) (string, bool) {
	if v == nil {
		return "", true
	}
	rv := reflect.ValueOf(v)
	if !rv.IsValid() {
		return "", false
	}
	switch rv.Type().Kind() {
	case reflect.Bool:
		return "boolean", true
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32,
		reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16,
		reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64:
		return "number", true
	case reflect.String:
		return "string", true
	}
	return "", false
}

// A RawTrace contains all the data associated with a trace.
type RawTrace struct {
	TraceID   uint64        `json:"trace_id"`
	Spans     []RawSpan     `json:"spans"`
	Relations []RawRelation `json:"relations"`
}

// A RawRelation represents the relation between two spans.
type RawRelation struct {
	ParentID uint64 `json:"parent_id"`
	ChildID  uint64 `json:"child_id"`
	Kind     string `json:"kind"`
}

// Span is an implementation of the OpenTracing Span interface.
type Span struct {
	mu     sync.RWMutex
	tracer *Tracer
	raw    RawSpan
}

// A RawSpan contains all the data associated with a span.
type RawSpan struct {
	SpanContext
	ServiceName   string    `json:"service_name"`
	OperationName string    `json:"operation_name"`
	StartTime     time.Time `json:"start_time"`
	FinishTime    time.Time `json:"finish_time"`

	Tags map[string]interface{} `json:"tags"`
	Logs []opentracing.LogData  `json:"logs"`
}

// RawSpan returns a deep copy of the span's underlying data.
func (sp *Span) RawSpan() RawSpan {
	sp.mu.Lock()
	defer sp.mu.Unlock()
	raw := sp.raw
	tags := raw.Tags
	raw.Tags = map[string]interface{}{}
	for k, v := range tags {
		raw.Tags[k] = v
	}
	raw.Logs = append([]opentracing.LogData(nil), raw.Logs...)
	baggage := raw.Baggage
	raw.Baggage = map[string]string{}
	for k, v := range baggage {
		raw.Baggage[k] = v
	}
	return raw
}

// Sampled reports whether this span was sampled.
func (sp *Span) Sampled() bool {
	sp.mu.RLock()
	defer sp.mu.RUnlock()
	return sp.sampled()
}

func (sp *Span) sampled() bool {
	return (sp.raw.Flags & FlagSampled) > 0
}

// SetOperationName implements the opentracing.Span interface.
func (sp *Span) SetOperationName(name string) opentracing.Span {
	sp.mu.Lock()
	defer sp.mu.Unlock()
	sp.raw.OperationName = name
	return sp
}

// SetTag implements the opentracing.Span interface.
func (sp *Span) SetTag(key string, value interface{}) opentracing.Span {
	sp.mu.Lock()
	defer sp.mu.Unlock()
	if !sp.sampled() {
		return sp
	}
	if _, ok := valueType(value); !ok {
		sp.tracer.Logger.Printf("unsupported tag value type for tag %q: %T", key, value)
		return sp
	}
	if sp.raw.Tags == nil {
		sp.raw.Tags = map[string]interface{}{}
	}
	sp.raw.Tags[key] = value
	return sp
}

// Finish implements the opentracing.Span interface.
func (sp *Span) Finish() {
	if !sp.Sampled() {
		return
	}
	sp.FinishWithOptions(opentracing.FinishOptions{})
}

// FinishWithOptions implements the opentracing.Span interface.
func (sp *Span) FinishWithOptions(opts opentracing.FinishOptions) {
	sp.mu.Lock()
	defer sp.mu.Unlock()
	if !sp.sampled() {
		return
	}
	if opts.FinishTime.IsZero() {
		opts.FinishTime = time.Now()
	}
	sp.raw.FinishTime = opts.FinishTime
	for _, log := range opts.BulkLogData {
		sp.log(log)
	}
	if err := sp.tracer.storer.Store(sp.raw); err != nil {
		sp.tracer.Logger.Printf("error while storing tracing span: %s", err)
	}
}

// LogEvent implements the opentracing.Span interface.
func (sp *Span) LogEvent(event string) {
	if !sp.Sampled() {
		return
	}
	sp.Log(opentracing.LogData{
		Event: event,
	})
}

// LogEventWithPayload implements the opentracing.Span interface.
func (sp *Span) LogEventWithPayload(event string, payload interface{}) {
	if !sp.Sampled() {
		return
	}
	sp.Log(opentracing.LogData{
		Event:   event,
		Payload: payload,
	})
}

// Log implements the opentracing.Span interface.
func (sp *Span) Log(data opentracing.LogData) {
	sp.mu.Lock()
	defer sp.mu.Unlock()
	sp.log(data)
}

func (sp *Span) log(data opentracing.LogData) {
	if !sp.sampled() {
		return
	}
	if _, ok := valueType(data.Payload); !ok {
		sp.tracer.Logger.Printf("unsupported log payload type for event %q: %T", data.Event, data.Payload)
		return
	}
	if data.Timestamp.IsZero() {
		data.Timestamp = time.Now()
	}
	sp.raw.Logs = append(sp.raw.Logs, data)
}

// Context implements the opentracing.Span interface.
func (sp *Span) Context() opentracing.SpanContext {
	sp.mu.RLock()
	defer sp.mu.RUnlock()
	return sp.raw.SpanContext
}

// Tracer implements the opentracing.Span interface.
func (sp *Span) Tracer() opentracing.Tracer {
	sp.mu.RLock()
	defer sp.mu.RUnlock()
	return sp.tracer
}

// Tracer is an implementation of the OpenTracing Tracer interface.
type Tracer struct {
	ServiceName string
	Logger      Logger
	Sampler     Sampler

	storer      Storer
	idGenerator IDGenerator
}

// NewTracer returns a new tracer.
func NewTracer(serviceName string, storer Storer, idGenerator IDGenerator) *Tracer {
	return &Tracer{
		ServiceName: serviceName,
		Logger:      defaultLogger{},
		Sampler:     NewConstSampler(true),
		storer:      storer,
		idGenerator: idGenerator,
	}
}

// StartSpan implements the opentracing.Tracer interface.
func (tr *Tracer) StartSpan(operationName string, opts ...opentracing.StartSpanOption) opentracing.Span {
	var sopts opentracing.StartSpanOptions
	for _, opt := range opts {
		opt.Apply(&sopts)
	}
	if sopts.StartTime.IsZero() {
		sopts.StartTime = time.Now()
	}

	id := tr.idGenerator.GenerateID()
	sp := &Span{
		tracer: tr,
		raw: RawSpan{
			SpanContext: SpanContext{
				SpanID:  id,
				TraceID: id,
			},
			ServiceName:   tr.ServiceName,
			OperationName: operationName,
			StartTime:     sopts.StartTime,
		},
	}
	if len(sopts.References) > 0 {
		// TODO(dh): support multiple parents, support ChildOf and
		// FollowsFrom as separate kinds of relations.
		parent, ok := sopts.References[0].Referee.(SpanContext)
		if !ok {
			panic("parent span must be of type *Span")
		}
		sp.raw.ParentID = parent.SpanID
		sp.raw.TraceID = parent.TraceID
		sp.raw.Flags = parent.Flags
	} else {
		if n, _ := sopts.Tags[string(ext.SamplingPriority)].(uint16); n > 0 {
			sp.raw.Flags |= FlagSampled
		} else if tr.Sampler.Sample(id) {
			sp.raw.Flags |= FlagSampled
		}
	}
	sp.raw.Tags = sopts.Tags
	return sp
}

func idToHex(id uint64) string {
	b := make([]byte, 8)
	binary.BigEndian.PutUint64(b, id)
	return hex.EncodeToString(b)
}

func idFromHex(s string) uint64 {
	b, _ := hex.DecodeString(s)
	return binary.BigEndian.Uint64(b)
}

// Inject implements the opentracing.Tracer interface.
func (tr *Tracer) Inject(sm opentracing.SpanContext, format interface{}, carrier interface{}) error {
	context, ok := sm.(SpanContext)
	if !ok {
		return opentracing.ErrInvalidSpanContext
	}
	injecter, ok := injecters[format]
	if !ok {
		return opentracing.ErrUnsupportedFormat
	}
	return injecter(context, carrier)
}

// Extract implements the opentracing.Tracer interface.
func (tr *Tracer) Extract(format interface{}, carrier interface{}) (opentracing.SpanContext, error) {
	extracter, ok := extracters[format]
	if !ok {
		return nil, opentracing.ErrUnsupportedFormat
	}
	context, err := extracter(carrier)
	if err != nil {
		return nil, err
	}
	return context, nil
}

// IDGenerator generates IDs for traces and spans. The ID with value 0
// is reserved to mean "no parent span" and should not be generated.
type IDGenerator interface {
	GenerateID() uint64
}

// A Storer stores a finished span. "Storing" a span may either mean
// saving it in a storage engine, or sending it to a remote
// collector.
//
// If a span with the same ID and the same trace ID already exists,
// the existing and new spans should be merged into one span.
//
// Because spans are only stored once they're done, children will be
// stored before their parents.
type Storer interface {
	Store(sp RawSpan) error
}

var _ IDGenerator = RandomID{}

// RandomID generates random IDs by using crypto/rand.
type RandomID struct{}

// GenerateID generates an ID.
func (RandomID) GenerateID() uint64 {
	b := make([]byte, 8)
	for {
		_, _ = rand.Read(b)
		x := binary.BigEndian.Uint64(b)
		if x != 0 {
			return x
		}
	}
}
<|endoftext|>


<commit_before>// Copyright 2015, Truveris Inc. All Rights Reserved.

package turret

import (
	"errors"
	"fmt"
	"time"

	"github.com/truveris/gousb/usb"
)

// Device types
const (
	DeviceTypeThunder = iota
	DeviceTypeClassic = iota
)

var (
	errNoLight = errors.New("device has no light")
)

// Turret is a wrapper around a USB Device.
type Turret struct {
	*usb.Device
	Type   int
	Closed bool
}

// NewTurret creates a Turret from a USB device.
func NewTurret(dev *usb.Device) *Turret {
	t := &Turret{
		Device: dev,
		Closed: false,
	}
	return t
}

// Command immediately passes the given command to a turret device. If you plan
// on using this function concurrently across multiple go-routines, you may
// want to use the QueueCommand and ConsumeCommands facility instead.
func (t *Turret) Command(cmdtype, cmd byte) error {
	if t.Type == DeviceTypeThunder {
		_, err := t.Device.Control(0x21, 0x09, 0, 0, []byte{cmdtype, cmd, 0, 0, 0, 0, 0, 0})
		if err != nil {
			return err
		}
	} else if t.Type == DeviceTypeClassic {
		if cmdtype != CmdTypeTurret {
			return errNoLight
		}

		_, err := t.Device.Control(0x21, 0x09, 0x0200, 0, []byte{cmd})
		if err != nil {
			return err
		}
	}

	return nil
}

// NormalizeDuration adjust the provided duration to be within reasonable limits.
// For example, most turrets take 8 seconds to do a full horizontal cycle.
// Because of that, we can safely limit the maximum horizontal movement
// duration to 8 seconds.
func (t *Turret) NormalizeDuration(cmd byte, duration time.Duration) time.Duration {
	switch cmd {
	case CmdTurretLeft, CmdTurretRight:
		if duration > 8*time.Second {
			duration = 8 * time.Second
		}
	case CmdTurretUp, CmdTurretDown:
		if duration > 2*time.Second {
			duration = 2 * time.Second
		}
	}
	return duration
}

// TimedCommand executes the given command and wait a little.
func (t *Turret) TimedCommand(cmdType, cmd byte, duration time.Duration) {
	t.Command(cmdType, cmd)
	duration = t.NormalizeDuration(cmd, duration)
	if duration > 0 {
		time.Sleep(duration)
	}
}

// Close ends the connection to the USB device, closes the Input channel. You
// should never call Close() directly if you queue commands and uses
// ConsumeCommands.  Use it if you plan on feeding the turret directly with
// commands.
func (t *Turret) Close() {
	if t.Closed {
		return
	}
	t.Device.Close()
	t.Closed = true
}

// Light is used to turn the turret light on or off.
func (t *Turret) Light(on bool) {
	var cmd byte

	if on {
		cmd = CmdLightOn
	} else {
		cmd = CmdLightOff
	}

	t.TimedCommand(CmdTypeLight, cmd, 0)
}

// BlinkOn will turn the light of the turret on and off a few times, ending
// with a lit light.
func (t *Turret) BlinkOn(times int) {
	for i := 0; i < times; i++ {
		t.TimedCommand(CmdTypeLight, CmdLightOff, 200*time.Millisecond)
		t.TimedCommand(CmdTypeLight, CmdLightOn, 200*time.Millisecond)
	}
}

// BlinkOff will turn the light of the turret on and off a few times, ending
// with a turned off light.
func (t *Turret) BlinkOff(times int) {
	for i := 0; i < times; i++ {
		t.TimedCommand(CmdTypeLight, CmdLightOn, 200*time.Millisecond)
		t.TimedCommand(CmdTypeLight, CmdLightOff, 200*time.Millisecond)
	}
}

// Left rotates the turret left for the specified duration.
func (t *Turret) Left(duration time.Duration) {
	t.TimedCommand(CmdTypeTurret, CmdTurretLeft, duration)
}

// Right rotates the turret right for the specified duration.
func (t *Turret) Right(duration time.Duration) {
	t.TimedCommand(CmdTypeTurret, CmdTurretRight, duration)
}

// Up tilts the turret up for the specified duration.
func (t *Turret) Up(duration time.Duration) {
	t.TimedCommand(CmdTypeTurret, CmdTurretUp, duration)
}

// Down tilts the turret down for the specified duration.
func (t *Turret) Down(duration time.Duration) {
	t.TimedCommand(CmdTypeTurret, CmdTurretDown, duration)
}

// Stop interrupts the turret movements.
func (t *Turret) Stop() {
	t.TimedCommand(CmdTypeTurret, CmdTurretStop, 50*time.Millisecond)
}

// Reset rotates and tilts the turret in the given direction until it gets
// parked in the leftmost and lowest position.
func (t *Turret) Reset() {
	t.Left(8 * time.Second)
	t.Down(2 * time.Second)
}

// Fire one or multiple shots.
func (t *Turret) Fire(shots int) {
	for i := 0; i < shots; i++ {
		t.TimedCommand(CmdTypeTurret, CmdTurretFire, 4500*time.Millisecond)
	}
}

// HumanReadableType returns the model of the turret in a human readable format.
func (t *Turret) HumanReadableType() string {
	switch t.Type {
	case DeviceTypeThunder:
		return "Dream Cheeky Thunder"
	case DeviceTypeClassic:
		return "Classic"
	default:
		name := fmt.Sprintf("Unknown Turret (0x%H:0x%H)", t.Device.Descriptor.Vendor, t.Device.Descriptor.Product)
		return name
	}
}
<commit_msg>Callibrate!<commit_after>// Copyright 2015, Truveris Inc. All Rights Reserved.

package turret

import (
	"errors"
	"fmt"
	"time"

	"github.com/truveris/gousb/usb"
)

// Device types
const (
	DeviceTypeThunder = iota
	DeviceTypeClassic = iota
)

var (
	errNoLight = errors.New("device has no light")
)

// Turret is a wrapper around a USB Device.
type Turret struct {
	*usb.Device
	Type   int
	Closed bool
}

// NewTurret creates a Turret from a USB device.
func NewTurret(dev *usb.Device) *Turret {
	t := &Turret{
		Device: dev,
		Closed: false,
	}
	return t
}

// Command immediately passes the given command to a turret device. If you plan
// on using this function concurrently across multiple go-routines, you may
// want to use the QueueCommand and ConsumeCommands facility instead.
func (t *Turret) Command(cmdtype, cmd byte) error {
	if t.Type == DeviceTypeThunder {
		_, err := t.Device.Control(0x21, 0x09, 0, 0, []byte{cmdtype, cmd, 0, 0, 0, 0, 0, 0})
		if err != nil {
			return err
		}
	} else if t.Type == DeviceTypeClassic {
		if cmdtype != CmdTypeTurret {
			return errNoLight
		}

		_, err := t.Device.Control(0x21, 0x09, 0x0200, 0, []byte{cmd})
		if err != nil {
			return err
		}
	}

	return nil
}

// NormalizeDuration adjust the provided duration to be within reasonable limits.
// For example, most turrets take 8 seconds to do a full horizontal cycle.
// Because of that, we can safely limit the maximum horizontal movement
// duration to 8 seconds.
func (t *Turret) NormalizeDuration(cmd byte, duration time.Duration) time.Duration {
	switch cmd {
	case CmdTurretLeft, CmdTurretRight:
		if duration > 8*time.Second {
			duration = 6800 * time.Millisecond
		}
	case CmdTurretUp, CmdTurretDown:
		if duration > 2*time.Second {
			duration = 1500 * time.Millisecond
		}
	}
	return duration
}

// TimedCommand executes the given command and wait a little.
func (t *Turret) TimedCommand(cmdType, cmd byte, duration time.Duration) {
	t.Command(cmdType, cmd)
	duration = t.NormalizeDuration(cmd, duration)
	if duration > 0 {
		time.Sleep(duration)
	}
}

// Close ends the connection to the USB device, closes the Input channel. You
// should never call Close() directly if you queue commands and uses
// ConsumeCommands.  Use it if you plan on feeding the turret directly with
// commands.
func (t *Turret) Close() {
	if t.Closed {
		return
	}
	t.Device.Close()
	t.Closed = true
}

// Light is used to turn the turret light on or off.
func (t *Turret) Light(on bool) {
	var cmd byte

	if on {
		cmd = CmdLightOn
	} else {
		cmd = CmdLightOff
	}

	t.TimedCommand(CmdTypeLight, cmd, 0)
}

// BlinkOn will turn the light of the turret on and off a few times, ending
// with a lit light.
func (t *Turret) BlinkOn(times int) {
	for i := 0; i < times; i++ {
		t.TimedCommand(CmdTypeLight, CmdLightOff, 200*time.Millisecond)
		t.TimedCommand(CmdTypeLight, CmdLightOn, 200*time.Millisecond)
	}
}

// BlinkOff will turn the light of the turret on and off a few times, ending
// with a turned off light.
func (t *Turret) BlinkOff(times int) {
	for i := 0; i < times; i++ {
		t.TimedCommand(CmdTypeLight, CmdLightOn, 200*time.Millisecond)
		t.TimedCommand(CmdTypeLight, CmdLightOff, 200*time.Millisecond)
	}
}

// Left rotates the turret left for the specified duration.
func (t *Turret) Left(duration time.Duration) {
	t.TimedCommand(CmdTypeTurret, CmdTurretLeft, duration)
}

// Right rotates the turret right for the specified duration.
func (t *Turret) Right(duration time.Duration) {
	t.TimedCommand(CmdTypeTurret, CmdTurretRight, duration)
}

// Up tilts the turret up for the specified duration.
func (t *Turret) Up(duration time.Duration) {
	t.TimedCommand(CmdTypeTurret, CmdTurretUp, duration)
}

// Down tilts the turret down for the specified duration.
func (t *Turret) Down(duration time.Duration) {
	t.TimedCommand(CmdTypeTurret, CmdTurretDown, duration)
}

// Stop interrupts the turret movements.
func (t *Turret) Stop() {
	t.TimedCommand(CmdTypeTurret, CmdTurretStop, 50*time.Millisecond)
}

// Reset rotates and tilts the turret in the given direction until it gets
// parked in the leftmost and lowest position.
func (t *Turret) Reset() {
	t.Left(8 * time.Second)
	t.Down(2 * time.Second)
}

// Fire one or multiple shots.
func (t *Turret) Fire(shots int) {
	for i := 0; i < shots; i++ {
		t.TimedCommand(CmdTypeTurret, CmdTurretFire, 4500*time.Millisecond)
	}
}

// HumanReadableType returns the model of the turret in a human readable format.
func (t *Turret) HumanReadableType() string {
	switch t.Type {
	case DeviceTypeThunder:
		return "Dream Cheeky Thunder"
	case DeviceTypeClassic:
		return "Classic"
	default:
		name := fmt.Sprintf("Unknown Turret (0x%H:0x%H)", t.Device.Descriptor.Vendor, t.Device.Descriptor.Product)
		return name
	}
}
<|endoftext|>


<commit_before>package ottojs

import (
	"github.com/loadimpact/speedboat/runner"
	"github.com/robertkrimen/otto"
	"github.com/valyala/fasthttp"
	"golang.org/x/net/context"
	"math"
	"time"
)

type Runner struct {
	Filename string
	Source   string
	Client   *fasthttp.Client
}

type VUContext struct {
	r   *Runner
	ctx context.Context
	ch  chan runner.Result
}

func New(filename, src string) *Runner {
	return &Runner{
		Filename: filename,
		Source:   src,
		Client: &fasthttp.Client{
			Dial:                fasthttp.Dial,
			MaxIdleConnDuration: time.Duration(0),
			MaxConnsPerHost:     math.MaxInt64,
		},
	}
}
func (r *Runner) Run(ctx context.Context, id int64) <-chan runner.Result {
	ch := make(chan runner.Result)

	go func() {
		defer close(ch)

		vu := VUContext{r: r, ctx: ctx, ch: ch}

		vm := otto.New()
		vm.Set("__id", id)
		vm.Set("get", vu.HTTPGet)
		vm.Set("sleep", vu.Sleep)

		script, err := vm.Compile(r.Filename, r.Source)
		if err != nil {
			ch <- runner.Result{Error: err}
			return
		}

		for {
			if _, err := vm.Run(script); err != nil {
				ch <- runner.Result{Error: err}
			}

			select {
			case <-ctx.Done():
				return
			default:
			}
		}
	}()

	return ch
}
<commit_msg>This is so farfetched<commit_after>package ottojs

import (
	"github.com/loadimpact/speedboat/runner"
	"github.com/robertkrimen/otto"
	"github.com/valyala/fasthttp"
	"golang.org/x/net/context"
	"math"
	"sync"
	"time"
)

type Runner struct {
	Filename string
	Source   string
	Client   *fasthttp.Client
	VMs      sync.Pool
}

type VUContext struct {
	r   *Runner
	ctx context.Context
	ch  chan runner.Result
}

func New(filename, src string) *Runner {
	r := &Runner{
		Filename: filename,
		Source:   src,
		Client: &fasthttp.Client{
			Dial:                fasthttp.Dial,
			MaxIdleConnDuration: time.Duration(0),
			MaxConnsPerHost:     math.MaxInt64,
		},
		VMs: sync.Pool{
			New: func() interface{} {
				return otto.New()
			},
		},
	}
	for i := 0; i < 10000; i++ {
		r.VMs.Put(r.VMs.New())
	}
	return r
}
func (r *Runner) Run(ctx context.Context, id int64) <-chan runner.Result {
	ch := make(chan runner.Result)

	go func() {
		defer close(ch)

		vu := VUContext{r: r, ctx: ctx, ch: ch}

		vm := r.VMs.Get().(*otto.Otto)
		defer r.VMs.Put(vm)

		vm.Set("__id", id)
		vm.Set("get", vu.HTTPGet)
		vm.Set("sleep", vu.Sleep)

		script, err := vm.Compile(r.Filename, r.Source)
		if err != nil {
			ch <- runner.Result{Error: err}
			return
		}

		for {
			if _, err := vm.Run(script); err != nil {
				ch <- runner.Result{Error: err}
			}

			select {
			case <-ctx.Done():
				return
			default:
			}
		}
	}()

	return ch
}
<|endoftext|>


<commit_before>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package inode

import (
	"fmt"

	"github.com/jacobsa/gcloud/syncutil"
)

type DirInode struct {
	/////////////////////////
	// Constant data
	/////////////////////////

	// The name of the GCS object backing the inode, used as a prefix when
	// listing. Special case: the empty string means this is the root inode.
	//
	// INVARIANT: name == "" || name[len(name)-1] == '/'
	name string

	/////////////////////////
	// Mutable state
	/////////////////////////

	// A mutex that must be held when calling certain methods. See documentation
	// for each method.
	Mu syncutil.InvariantMutex
}

// Create a directory inode for the directory with the given name. The name
// must end with a slash unless this is the root directory, in which case it
// must be empty.
//
// REQUIRES: name == "" || name[len(name)-1] == '/'
func NewDirInode(name string) (d *DirInode) {
	// Set up the basic struct.
	d = &DirInode{
		name: name,
	}

	// Set up invariant checking.
	d.Mu = syncutil.NewInvariantMutex(d.checkInvariants)

	return
}

func (d *DirInode) checkInvariants() {
	// Check the name.
	if !(d.name == "" || d.name[len(d.name)-1] == '/') {
		panic(fmt.Sprintf("Unexpected name: %s", d.name))
	}
}
<commit_msg>Defined a DirInode.ReadEntries interface.<commit_after>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package inode

import (
	"fmt"

	"github.com/jacobsa/fuse/fuseutil"
	"github.com/jacobsa/gcloud/syncutil"
)

type DirInode struct {
	/////////////////////////
	// Constant data
	/////////////////////////

	// The name of the GCS object backing the inode, used as a prefix when
	// listing. Special case: the empty string means this is the root inode.
	//
	// INVARIANT: name == "" || name[len(name)-1] == '/'
	name string

	/////////////////////////
	// Mutable state
	/////////////////////////

	// A mutex that must be held when calling certain methods. See documentation
	// for each method.
	Mu syncutil.InvariantMutex
}

// Create a directory inode for the directory with the given name. The name
// must end with a slash unless this is the root directory, in which case it
// must be empty.
//
// REQUIRES: name == "" || name[len(name)-1] == '/'
func NewDirInode(name string) (d *DirInode) {
	// Set up the basic struct.
	d = &DirInode{
		name: name,
	}

	// Set up invariant checking.
	d.Mu = syncutil.NewInvariantMutex(d.checkInvariants)

	return
}

////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////

func (d *DirInode) checkInvariants() {
	// Check the name.
	if !(d.name == "" || d.name[len(d.name)-1] == '/') {
		panic(fmt.Sprintf("Unexpected name: %s", d.name))
	}
}

////////////////////////////////////////////////////////////////////////
// Public interface
////////////////////////////////////////////////////////////////////////

// Read some number of entries from the directory, returning a continuation
// token that can be used to pick up the read operation where it left off.
// Supply the empty token on the first call.
//
// At the end of the directory, the returned continuation token will be empty.
// Otherwise it will be non-empty. There is no guarantee about the number of
// entries returned; it may be zero even with a non-empty continuation token.
//
// SHARED_LOCKS_REQUIRED(d.Mu)
func (d *DirInode) ReadEntries(
	tok string) (entries []fuseutil.Dirent, newTok string)
<|endoftext|>


<commit_before>// DYNAMIC UPDATES
//
// Dynamic updates reuses the DNS message format, but renames three of
// the sections. Question is Zone, Answer is Prerequisite, Authority is
// Update, only the Additional is not renamed. See RFC 2136 for the gory details.
//
// You can set a rather complex set of rules for the existence of absence of
// certain resource records or names in a zone to specify if resource records
// should be added or removed. The table from RFC 2136 supplemented with the Go
// DNS function shows which functions exist to specify the prerequisites.
//
// 3.2.4 - Table Of Metavalues Used In Prerequisite Section
//
//   CLASS    TYPE     RDATA    Meaning                    Function
//   --------------------------------------------------------------
//   ANY      ANY      empty    Name is in use             dns.NameUsed
//   ANY      rrset    empty    RRset exists (value indep) dns.RRsetUsed
//   NONE     ANY      empty    Name is not in use         dns.NameNotUsed
//   NONE     rrset    empty    RRset does not exist       dns.RRsetNotUsed
//   zone     rrset    rr       RRset exists (value dep)   dns.Used
//
// The prerequisite section can also be left empty.
// If you have decided on the prerequisites you can tell what RRs should
// be added or deleted. The next table shows the options you have and
// what functions to call.
//
// 3.4.2.6 - Table Of Metavalues Used In Update Section
//
//   CLASS    TYPE     RDATA    Meaning                     Function
//   ---------------------------------------------------------------
//   ANY      ANY      empty    Delete all RRsets from name dns.RemoveName
//   ANY      rrset    empty    Delete an RRset             dns.RemoveRRset
//   NONE     rrset    rr       Delete an RR from RRset     dns.Remove
//   zone     rrset    rr       Add to an RRset             dns.Insert
//
package dns

// NameUsed sets the RRs in the prereq section to
// "Name is in use" RRs. RFC 2136 section 2.4.4.
func (u *Msg) NameUsed(rr []RR) {
	u.Answer = make([]RR, len(rr))
	for i, r := range rr {
		u.Answer[i] = &ANY{Hdr: RR_Header{Name: r.Header().Name, Ttl: 0, Rrtype: TypeANY, Class: ClassANY}}
	}
}

// NameNotUsed sets the RRs in the prereq section to
// "Name is in not use" RRs. RFC 2136 section 2.4.5.
func (u *Msg) NameNotUsed(rr []RR) {
	u.Answer = make([]RR, len(rr))
	for i, r := range rr {
		u.Answer[i] = &ANY{Hdr: RR_Header{Name: r.Header().Name, Ttl: 0, Rrtype: TypeANY, Class: ClassNONE}}
	}
}

// Used sets the RRs in the prereq section to
// "RRset exists (value dependent -- with rdata)" RRs. RFC 2136 section 2.4.2.
func (u *Msg) Used(rr []RR) {
	if len(u.Question) == 0 {
		panic("dns: empty question section")
	}
	u.Answer = make([]RR, len(rr))
	for i, r := range rr {
		u.Answer[i] = r
		u.Answer[i].Header().Class = u.Question[0].Qclass
	}
}

// RRsetUsed sets the RRs in the prereq section to
// "RRset exists (value independent -- no rdata)" RRs. RFC 2136 section 2.4.1.
func (u *Msg) RRsetUsed(rr []RR) {
	u.Answer = make([]RR, len(rr))
	for i, r := range rr {
		u.Answer[i] = r
		u.Answer[i].Header().Class = ClassANY
		u.Answer[i].Header().Ttl = 0
		u.Answer[i].Header().Rdlength = 0
	}
}

// RRsetNotUsed sets the RRs in the prereq section to
// "RRset does not exist" RRs. RFC 2136 section 2.4.3.
func (u *Msg) RRsetNotUsed(rr []RR) {
	u.Answer = make([]RR, len(rr))
	for i, r := range rr {
		u.Answer[i] = r
		u.Answer[i].Header().Class = ClassNONE
		u.Answer[i].Header().Rdlength = 0
		u.Answer[i].Header().Ttl = 0
	}
}

// Insert creates a dynamic update packet that adds an complete RRset, see RFC 2136 section 2.5.1.
func (u *Msg) Insert(rr []RR) {
	if len(u.Question) == 0 {
		panic("dns: empty question section")
	}
	u.Ns = make([]RR, len(rr))
	for i, r := range rr {
		u.Ns[i] = r
		u.Ns[i].Header().Class = u.Question[0].Qclass
	}
}

// RemoveRRset creates a dynamic update packet that deletes an RRset, see RFC 2136 section 2.5.2.
func (u *Msg) RemoveRRset(rr []RR) {
	m := make(map[RR_Header]struct{})
	for _, r := range rr {
		h := r.Header()
		m[RR_Header{
			Name:     h.Name,
			Rrtype:   h.Rrtype,
			Class:    ClassANY,
			Ttl:      0,
			Rdlength: 0,
		}] = struct{}{}
	}
	u.Ns = make([]RR, 0, len(m))
	for t := range m {
		u.Ns = append(u.Ns, &ANY{t})
	}
}

// RemoveName creates a dynamic update packet that deletes all RRsets of a name, see RFC 2136 section 2.5.3
func (u *Msg) RemoveName(rr []RR) {
	u.Ns = make([]RR, len(rr))
	for i, r := range rr {
		u.Ns[i] = &ANY{Hdr: RR_Header{Name: r.Header().Name, Ttl: 0, Rrtype: TypeANY, Class: ClassANY}}
	}
}

// Remove creates a dynamic update packet deletes RR from the RRSset, see RFC 2136 section 2.5.4
func (u *Msg) Remove(rr []RR) {
	u.Ns = make([]RR, len(rr))
	for i, r := range rr {
		u.Ns[i] = r
		u.Ns[i].Header().Class = ClassNONE
		u.Ns[i].Header().Ttl = 0
	}
}
<commit_msg>Lose a loop in Msg.RemoveRRset() and use copyHeader()<commit_after>// DYNAMIC UPDATES
//
// Dynamic updates reuses the DNS message format, but renames three of
// the sections. Question is Zone, Answer is Prerequisite, Authority is
// Update, only the Additional is not renamed. See RFC 2136 for the gory details.
//
// You can set a rather complex set of rules for the existence of absence of
// certain resource records or names in a zone to specify if resource records
// should be added or removed. The table from RFC 2136 supplemented with the Go
// DNS function shows which functions exist to specify the prerequisites.
//
// 3.2.4 - Table Of Metavalues Used In Prerequisite Section
//
//   CLASS    TYPE     RDATA    Meaning                    Function
//   --------------------------------------------------------------
//   ANY      ANY      empty    Name is in use             dns.NameUsed
//   ANY      rrset    empty    RRset exists (value indep) dns.RRsetUsed
//   NONE     ANY      empty    Name is not in use         dns.NameNotUsed
//   NONE     rrset    empty    RRset does not exist       dns.RRsetNotUsed
//   zone     rrset    rr       RRset exists (value dep)   dns.Used
//
// The prerequisite section can also be left empty.
// If you have decided on the prerequisites you can tell what RRs should
// be added or deleted. The next table shows the options you have and
// what functions to call.
//
// 3.4.2.6 - Table Of Metavalues Used In Update Section
//
//   CLASS    TYPE     RDATA    Meaning                     Function
//   ---------------------------------------------------------------
//   ANY      ANY      empty    Delete all RRsets from name dns.RemoveName
//   ANY      rrset    empty    Delete an RRset             dns.RemoveRRset
//   NONE     rrset    rr       Delete an RR from RRset     dns.Remove
//   zone     rrset    rr       Add to an RRset             dns.Insert
//
package dns

// NameUsed sets the RRs in the prereq section to
// "Name is in use" RRs. RFC 2136 section 2.4.4.
func (u *Msg) NameUsed(rr []RR) {
	u.Answer = make([]RR, len(rr))
	for i, r := range rr {
		u.Answer[i] = &ANY{Hdr: RR_Header{Name: r.Header().Name, Ttl: 0, Rrtype: TypeANY, Class: ClassANY}}
	}
}

// NameNotUsed sets the RRs in the prereq section to
// "Name is in not use" RRs. RFC 2136 section 2.4.5.
func (u *Msg) NameNotUsed(rr []RR) {
	u.Answer = make([]RR, len(rr))
	for i, r := range rr {
		u.Answer[i] = &ANY{Hdr: RR_Header{Name: r.Header().Name, Ttl: 0, Rrtype: TypeANY, Class: ClassNONE}}
	}
}

// Used sets the RRs in the prereq section to
// "RRset exists (value dependent -- with rdata)" RRs. RFC 2136 section 2.4.2.
func (u *Msg) Used(rr []RR) {
	if len(u.Question) == 0 {
		panic("dns: empty question section")
	}
	u.Answer = make([]RR, len(rr))
	for i, r := range rr {
		u.Answer[i] = r
		u.Answer[i].Header().Class = u.Question[0].Qclass
	}
}

// RRsetUsed sets the RRs in the prereq section to
// "RRset exists (value independent -- no rdata)" RRs. RFC 2136 section 2.4.1.
func (u *Msg) RRsetUsed(rr []RR) {
	u.Answer = make([]RR, len(rr))
	for i, r := range rr {
		u.Answer[i] = r
		u.Answer[i].Header().Class = ClassANY
		u.Answer[i].Header().Ttl = 0
		u.Answer[i].Header().Rdlength = 0
	}
}

// RRsetNotUsed sets the RRs in the prereq section to
// "RRset does not exist" RRs. RFC 2136 section 2.4.3.
func (u *Msg) RRsetNotUsed(rr []RR) {
	u.Answer = make([]RR, len(rr))
	for i, r := range rr {
		u.Answer[i] = r
		u.Answer[i].Header().Class = ClassNONE
		u.Answer[i].Header().Rdlength = 0
		u.Answer[i].Header().Ttl = 0
	}
}

// Insert creates a dynamic update packet that adds an complete RRset, see RFC 2136 section 2.5.1.
func (u *Msg) Insert(rr []RR) {
	if len(u.Question) == 0 {
		panic("dns: empty question section")
	}
	u.Ns = make([]RR, len(rr))
	for i, r := range rr {
		u.Ns[i] = r
		u.Ns[i].Header().Class = u.Question[0].Qclass
	}
}

// RemoveRRset creates a dynamic update packet that deletes an RRset, see RFC 2136 section 2.5.2.
func (u *Msg) RemoveRRset(rr []RR) {
	m := make(map[RR_Header]struct{})
	u.Ns = make([]RR, 0, len(rr))
	for _, r := range rr {
		h := *r.Header().copyHeader()
		h.Class = ClassANY
		h.Ttl = 0
		h.Rdlength = 0
		if _, ok := m[h]; ok {
			continue
		}
		m[h] = struct{}{}
		u.Ns = append(u.Ns, &ANY{h})
	}
}

// RemoveName creates a dynamic update packet that deletes all RRsets of a name, see RFC 2136 section 2.5.3
func (u *Msg) RemoveName(rr []RR) {
	u.Ns = make([]RR, len(rr))
	for i, r := range rr {
		u.Ns[i] = &ANY{Hdr: RR_Header{Name: r.Header().Name, Ttl: 0, Rrtype: TypeANY, Class: ClassANY}}
	}
}

// Remove creates a dynamic update packet deletes RR from the RRSset, see RFC 2136 section 2.5.4
func (u *Msg) Remove(rr []RR) {
	u.Ns = make([]RR, len(rr))
	for i, r := range rr {
		u.Ns[i] = r
		u.Ns[i].Header().Class = ClassNONE
		u.Ns[i].Header().Ttl = 0
	}
}
<|endoftext|>


<commit_before>package util_test

import (
	"bufio"
	"bytes"
	"crypto/rand"
	"io"
	"os"
	"path/filepath"
	"testing"
	"time"

	"github.com/xxorde/pgglaskugel/util"

	"golang.org/x/crypto/openpgp/packet"
)

var (
	keyBits        int
	keyOutputDir   = "../test/tmp/"
	keyPrefix      string
	keyPrivateFile string
	keyPublicFile  string

	privKey *packet.PrivateKey
	pubKey  *packet.PublicKey

	plainFile = "../test/text/pg1661.txt"
)

func TestKeyGen(t *testing.T) {
	keyBits = 4096
	now := time.Now()
	keyPrefix = "testkey-" + now.Format("2006-01-02T15:04:05")
	keyPrivateFile = filepath.Join(keyOutputDir, keyPrefix+".privkey")
	keyPublicFile = filepath.Join(keyOutputDir, keyPrefix+".pubkey")

	key := util.GenerateKeys(keyBits, keyOutputDir, keyPrefix, keyPrivateFile, keyPublicFile, rand.Reader)
	util.WritePrivateKey(keyPrivateFile, key)
	util.WritePublicKey(keyPublicFile, key)
}

func TestKeyRead(t *testing.T) {
	privKey = util.ReadPrivateKey(keyPrivateFile)
	t.Log(privKey)
	pubKey = util.ReadPublicKey(keyPublicFile)
	t.Log(pubKey)
}

func TestCrypt(t *testing.T) {
	// Get a io.Reader for the plaintext
	plainFileReader, err := os.Open(plainFile)
	if err != nil {
		t.Fail()
	}

	// Create buffer, io.Reader, io.Writer for the plain text
	var plain bytes.Buffer
	plainWriter := bufio.NewWriter(&plain)
	plainReader := bufio.NewReader(&plain)

	// Copy contet of plain text file in buffer plain
	io.Copy(plainWriter, plainFileReader)

	// Create buffer, io.Reader, io.Writer for the cypher text
	var cypher bytes.Buffer
	cypherWriter := bufio.NewWriter(&cypher)
	cypherReader := bufio.NewReader(&cypher)

	// Encrypt the plain text
	encryptWritten := util.Encrypt(plainReader, cypherWriter, privKey, pubKey)
	t.Log("Encrypt, bytes written: ", encryptWritten)

	// Create buffer, io.Reader, io.Writer for the decrypted text
	var decrypt bytes.Buffer
	decryptWriter := bufio.NewWriter(&decrypt)
	decryptReader := bufio.NewReader(&decrypt)

	// Decrypt the cypher text
	decryptWritten := util.Decrypt(cypherReader, decryptWriter, privKey, pubKey)
	t.Log("Decrypt, bytes written: ", decryptWritten)

	bytes.Compare(plain., decrypt)

	t.Log()
}
<commit_msg>First cypher test cases done<commit_after>package util_test

import (
	"bytes"
	"crypto/rand"
	"io/ioutil"
	"path/filepath"
	"strings"
	"testing"
	"time"

	"github.com/xxorde/pgglaskugel/util"

	"golang.org/x/crypto/openpgp/packet"
)

var (
	keyBits        int
	keyOutputDir   = "../test/tmp/"
	keyPrefix      string
	keyPrivateFile string
	keyPublicFile  string

	privKey *packet.PrivateKey
	pubKey  *packet.PublicKey

	plainFile     = "../test/text/pg1661.txt"
	plainFileSize = 594933
)

func TestKeyGen(t *testing.T) {
	keyBits = 4096
	now := time.Now()
	keyPrefix = "testkey-" + now.Format("2006-01-02T15:04:05")
	keyPrivateFile = filepath.Join(keyOutputDir, keyPrefix+".privkey")
	keyPublicFile = filepath.Join(keyOutputDir, keyPrefix+".pubkey")

	key := util.GenerateKeys(keyBits, keyOutputDir, keyPrefix, keyPrivateFile, keyPublicFile, rand.Reader)
	util.WritePrivateKey(keyPrivateFile, key)
	util.WritePublicKey(keyPublicFile, key)
}

func TestKeyRead(t *testing.T) {
	privKey = util.ReadPrivateKey(keyPrivateFile)
	if privKey == nil {
		t.Fail()
	}

	pubKey = util.ReadPublicKey(keyPublicFile)
	if pubKey == nil {
		t.Fail()
	}
}

func TestCrypt(t *testing.T) {
	// Read in plain text from file
	plainText, err := ioutil.ReadFile(plainFile)
	if err != nil {
		t.Log(err)
		t.Fail()
	}

	if len(plainText) != plainFileSize {
		t.Log("Size of plaintext does not match preset plainFileSize plainText:", plainText, "plainFileSize:", plainFileSize)
		t.Fail()
	}

	// Create buffer for plain text and fill with text
	plainBuffer := bytes.NewBuffer(plainText)

	// Create buffer for cypher text
	cypherBuffer := new(bytes.Buffer)

	// Encrypt the plain text
	encryptWritten := util.Encrypt(plainBuffer, cypherBuffer, privKey, pubKey)
	t.Log("Encrypt, bytes written: ", encryptWritten)

	// Create for the decrypted text
	decryptBuffer := new(bytes.Buffer)

	// Decrypt the cypher text
	decryptWritten := util.Decrypt(cypherBuffer, decryptBuffer, privKey, pubKey)
	t.Log("Decrypt, bytes written: ", decryptWritten)

	// Convert plaintext and decrypted text to string and compare them
	delta := strings.Compare(string(plainText), decryptBuffer.String())
	t.Log("plain text size: ", len(plainText))
	t.Log("decrypted text size: ", decryptBuffer.Len())
	t.Log("The delta between plaintext and decrypted text is: ", delta)
	if delta != 0 {
		t.Log("Plaintext and decrypted text do not match")
		t.Fail()
	}
	if decryptBuffer.Len() != plainFileSize {
		t.Log("Size of decrypted text does not match preset plainFileSize, decryptBuffer.Len():", decryptBuffer.Len(), "plainFileSize:", plainFileSize)
		t.Fail()
	}
}
<|endoftext|>


<commit_before>package splice

import (
	"fmt"
	"io"
	"os"
)

func SpliceCopy(dst *os.File, src *os.File, p *Pair) (int64, error) {
	total := int64(0)

	for {
		n, err := p.LoadFrom(src.Fd(), p.size)
		if err != nil {
			return total, err
		}
		if n == 0 {
			break
		}
		m, err := p.WriteTo(dst.Fd(), n)
		total += int64(m)
		if err != nil {
			return total, err
		}
		if m < n {
			return total, err
		}
		if int(n) < p.size {
			break
		}
	}

	return total, nil
}

// Argument ordering follows io.Copy.
func CopyFile(dstName string, srcName string, mode int) error {
	src, err := os.Open(srcName)
	if err != nil {
		return err
	}
	defer src.Close()

	dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.FileMode(mode))
	if err != nil {
		return err
	}
	defer dst.Close()

	return CopyFds(dst, src)
}

func CopyFds(dst *os.File, src *os.File) (err error) {
	p, err := splicePool.get()
	if p != nil {
		p.Grow(256 * 1024)
		_, err := SpliceCopy(dst, src, p)
		splicePool.done(p)
		return err
	} else {
		_, err = io.Copy(dst, src)
	}
	if err == io.EOF {
		err = nil
	}
	return err
}
<commit_msg>Fix unnecessary import.<commit_after>package splice

import (
	"io"
	"os"
)

func SpliceCopy(dst *os.File, src *os.File, p *Pair) (int64, error) {
	total := int64(0)

	for {
		n, err := p.LoadFrom(src.Fd(), p.size)
		if err != nil {
			return total, err
		}
		if n == 0 {
			break
		}
		m, err := p.WriteTo(dst.Fd(), n)
		total += int64(m)
		if err != nil {
			return total, err
		}
		if m < n {
			return total, err
		}
		if int(n) < p.size {
			break
		}
	}

	return total, nil
}

// Argument ordering follows io.Copy.
func CopyFile(dstName string, srcName string, mode int) error {
	src, err := os.Open(srcName)
	if err != nil {
		return err
	}
	defer src.Close()

	dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.FileMode(mode))
	if err != nil {
		return err
	}
	defer dst.Close()

	return CopyFds(dst, src)
}

func CopyFds(dst *os.File, src *os.File) (err error) {
	p, err := splicePool.get()
	if p != nil {
		p.Grow(256 * 1024)
		_, err := SpliceCopy(dst, src, p)
		splicePool.done(p)
		return err
	} else {
		_, err = io.Copy(dst, src)
	}
	if err == io.EOF {
		err = nil
	}
	return err
}
<|endoftext|>


<commit_before>package main

import (
	"crypto/sha1"
	"database/sql"
	"encoding/base64"
	"encoding/json"
	"encoding/xml"
	"fmt"
	"io"
	"io/ioutil"
	"math/rand"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"time"

	"github.com/dchest/uniuri"
	_ "github.com/go-sql-driver/mysql"
)

const (
	LENGTH         = 6
	PORT           = ":8080"
	DIRECTORY      = "/tmp/"
	GRILLDIRECTORY = ""
	UPADDRESS      = "http://localhost"
	dbUSERNAME     = ""
	dbNAME         = ""
	dbPASSWORD     = ""
	DATABASE       = dbUSERNAME + ":" + dbPASSWORD + "@/" + dbNAME + "?charset=utf8"
	MAXSIZE        = 10 * 1024 * 1024
)

type Result struct {
	URL  string `json:"url"`
	Name string `json:"name"`
	Hash string `json:"hash"`
	Size int64  `json:"size"`
}

type Response struct {
	Success     bool     `json:"success"`
	ErrorCode   int      `json:"errorcode,omitempty"`
	Description string   `json:"description,omitempty"`
	Files       []Result `json:"files,omitempty"`
}

func check(err error) {
	if err != nil {
		fmt.Println(err)
		return
	}
}

func generateName() string {
	name := uniuri.NewLen(LENGTH)
	db, err := sql.Open("mysql", DATABASE)
	check(err)
	query, err := db.Query("select id from files where id=?", name)
	if err != sql.ErrNoRows {
		for query.Next() {
			generateName()
		}
	}
	db.Close()

	return name
}
func respond(w http.ResponseWriter, output string, resp Response) {
	if resp.ErrorCode != 0 {
		resp.Files = []Result{}
		resp.Success = false
	} else {
		resp.Success = true
	}

	switch output {
	case "json":

		w.Header().Set("Content-Type", "application/json")
		err := json.NewEncoder(w).Encode(resp)

		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	case "xml":
		x, err := xml.MarshalIndent(resp, "", "  ")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/xml")
		w.Write(x)

	case "html":
		w.Header().Set("Content-Type", "text/html")
		for _, file := range resp.Files {
			io.WriteString(w, ""+file.URL+"
")
		}

	case "gyazo", "text":
		w.Header().Set("Content-Type", "plain/text")
		for _, file := range resp.Files {
			io.WriteString(w, file.URL+"\n")
		}

	case "csv":
		w.Header().Set("Content-Type", "text/csv")
		io.WriteString(w, "name, url, hash, size\n")
		for _, file := range resp.Files {
			io.WriteString(w, file.Name+","+file.URL+","+file.Hash+","+strconv.FormatInt(file.Size, 10)+"\n")
		}

	default:
		w.Header().Set("Content-Type", "application/json")
		err := json.NewEncoder(w).Encode(resp)

		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

	}

}
func grillHandler(w http.ResponseWriter, r *http.Request) {
	kawaii, err := ioutil.ReadDir(GRILLDIRECTORY)
	check(err)
	http.Redirect(w, r, GRILLDIRECTORY+kawaii[rand.Intn(len(kawaii))].Name(), 301)
}
func uploadHandler(w http.ResponseWriter, r *http.Request) {
	reader, err := r.MultipartReader()
	resp := Response{Files: []Result{}}
	output := r.FormValue("output")
	if err != nil {
		resp.ErrorCode = http.StatusInternalServerError
		resp.Description = err.Error()
		respond(w, output, resp)
		return
	}

	db, err := sql.Open("mysql", DATABASE)
	check(err)

	for {
		part, err := reader.NextPart()
		if err == io.EOF {
			break
		}

		if part.FileName() == "" {
			continue
		}

		s := generateName()
		extName := filepath.Ext(part.FileName())
		filename := s + extName
		dst, err := os.Create(DIRECTORY + filename)
		defer dst.Close()

		if err != nil {
			resp.ErrorCode = http.StatusInternalServerError
			resp.Description = err.Error()
			respond(w, output, resp)
			break
		}

		h := sha1.New()
		t := io.TeeReader(part, h)
		_, err = io.Copy(dst, t)

		if err != nil {
			resp.ErrorCode = http.StatusInternalServerError
			resp.Description = err.Error()
			respond(w, output, resp)
			break
		}
		hash := h.Sum(nil)
		sha1 := base64.URLEncoding.EncodeToString(hash)
		stat, _ := dst.Stat()
		size := stat.Size()
		if size > MAXSIZE {
			resp.ErrorCode = http.StatusRequestEntityTooLarge
			resp.Description = err.Error()
			break
		}

		originalname := part.FileName()
		err = db.QueryRow("select originalname, filename, size from files where hash=?", sha1).Scan(&originalname, &filename, &size)
		res := Result{
			URL:  UPADDRESS + "/" + filename,
			Name: originalname,
			Hash: sha1,
			Size: size,
		}
		if err == sql.ErrNoRows {
			query, err := db.Prepare("INSERT into files(hash, originalname, filename, size, date) values(?, ?, ?, ?, ?)")
			check(err)
			_, err = query.Exec(res.Hash, res.Name, filename, res.Size, time.Now().Format("2016-01-02"))
			check(err)
		}
		resp.Files = append(resp.Files, res)
	}
	respond(w, output, resp)
}

func main() {
	http.HandleFunc("/upload.php", uploadHandler)
	http.HandleFunc("/grill.php", grillHandler)
	err := http.ListenAndServe(PORT, nil)
	if err != nil {
		panic(err)
	}

}
<commit_msg>Add static file handler<commit_after>package main

import (
	"crypto/sha1"
	"database/sql"
	"encoding/base64"
	"encoding/json"
	"encoding/xml"
	"fmt"
	"io"
	"io/ioutil"
	"math/rand"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"time"

	"github.com/dchest/uniuri"
	_ "github.com/go-sql-driver/mysql"
)

const (
	LENGTH         = 6
	PORT           = ":8080"
	UPDIRECTORY    = "/tmp/"
	GRILLDIRECTORY = ""
	POMFDIRECTORY  = ""
	UPADDRESS      = "http://localhost"
	dbUSERNAME     = ""
	dbNAME         = ""
	dbPASSWORD     = ""
	DATABASE       = dbUSERNAME + ":" + dbPASSWORD + "@/" + dbNAME + "?charset=utf8"
	MAXSIZE        = 10 * 1024 * 1024
)

type Result struct {
	URL  string `json:"url"`
	Name string `json:"name"`
	Hash string `json:"hash"`
	Size int64  `json:"size"`
}

type Response struct {
	Success     bool     `json:"success"`
	ErrorCode   int      `json:"errorcode,omitempty"`
	Description string   `json:"description,omitempty"`
	Files       []Result `json:"files,omitempty"`
}

func check(err error) {
	if err != nil {
		fmt.Println(err)
		return
	}
}

func generateName() string {
	name := uniuri.NewLen(LENGTH)
	db, err := sql.Open("mysql", DATABASE)
	check(err)
	query, err := db.Query("select id from files where id=?", name)
	if err != sql.ErrNoRows {
		for query.Next() {
			generateName()
		}
	}
	db.Close()

	return name
}
func respond(w http.ResponseWriter, output string, resp Response) {
	if resp.ErrorCode != 0 {
		resp.Files = []Result{}
		resp.Success = false
	} else {
		resp.Success = true
	}

	switch output {
	case "json":

		w.Header().Set("Content-Type", "application/json")
		err := json.NewEncoder(w).Encode(resp)

		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	case "xml":
		x, err := xml.MarshalIndent(resp, "", "  ")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/xml")
		w.Write(x)

	case "html":
		w.Header().Set("Content-Type", "text/html")
		for _, file := range resp.Files {
			io.WriteString(w, ""+file.URL+"
")
		}

	case "gyazo", "text":
		w.Header().Set("Content-Type", "plain/text")
		for _, file := range resp.Files {
			io.WriteString(w, file.URL+"\n")
		}

	case "csv":
		w.Header().Set("Content-Type", "text/csv")
		io.WriteString(w, "name, url, hash, size\n")
		for _, file := range resp.Files {
			io.WriteString(w, file.Name+","+file.URL+","+file.Hash+","+strconv.FormatInt(file.Size, 10)+"\n")
		}

	default:
		w.Header().Set("Content-Type", "application/json")
		err := json.NewEncoder(w).Encode(resp)

		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

	}

}
func grillHandler(w http.ResponseWriter, r *http.Request) {
	kawaii, err := ioutil.ReadDir(GRILLDIRECTORY)
	check(err)
	http.Redirect(w, r, GRILLDIRECTORY+kawaii[rand.Intn(len(kawaii))].Name(), 301)
}
func uploadHandler(w http.ResponseWriter, r *http.Request) {
	reader, err := r.MultipartReader()
	resp := Response{Files: []Result{}}
	output := r.FormValue("output")
	if err != nil {
		resp.ErrorCode = http.StatusInternalServerError
		resp.Description = err.Error()
		respond(w, output, resp)
		return
	}

	db, err := sql.Open("mysql", DATABASE)
	check(err)

	for {
		part, err := reader.NextPart()
		if err == io.EOF {
			break
		}

		if part.FileName() == "" {
			continue
		}

		s := generateName()
		extName := filepath.Ext(part.FileName())
		filename := s + extName
		dst, err := os.Create(UPDIRECTORY + filename)
		defer dst.Close()

		if err != nil {
			resp.ErrorCode = http.StatusInternalServerError
			resp.Description = err.Error()
			respond(w, output, resp)
			break
		}

		h := sha1.New()
		t := io.TeeReader(part, h)
		_, err = io.Copy(dst, t)

		if err != nil {
			resp.ErrorCode = http.StatusInternalServerError
			resp.Description = err.Error()
			respond(w, output, resp)
			break
		}
		hash := h.Sum(nil)
		sha1 := base64.URLEncoding.EncodeToString(hash)
		stat, _ := dst.Stat()
		size := stat.Size()
		if size > MAXSIZE {
			resp.ErrorCode = http.StatusRequestEntityTooLarge
			resp.Description = err.Error()
			break
		}

		originalname := part.FileName()
		err = db.QueryRow("select originalname, filename, size from files where hash=?", sha1).Scan(&originalname, &filename, &size)
		res := Result{
			URL:  UPADDRESS + "/" + filename,
			Name: originalname,
			Hash: sha1,
			Size: size,
		}
		if err == sql.ErrNoRows {
			query, err := db.Prepare("INSERT into files(hash, originalname, filename, size, date) values(?, ?, ?, ?, ?)")
			check(err)
			_, err = query.Exec(res.Hash, res.Name, filename, res.Size, time.Now().Format("2016-01-02"))
			check(err)
		}
		resp.Files = append(resp.Files, res)
	}
	respond(w, output, resp)
}

func main() {
	http.HandleFunc("/upload.php", uploadHandler)
	http.HandleFunc("/grill.php", grillHandler)
	http.Handle("/", http.FileServer(http.Dir(POMFDIRECTORY)))
	err := http.ListenAndServe(PORT, nil)
	if err != nil {
		panic(err)
	}

}
<|endoftext|>


<commit_before>package main

import (
	"crypto/sha1"
	"database/sql"
	"encoding/base64"
	"encoding/json"
	"encoding/xml"
	"fmt"
	"io"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"time"

	"github.com/dchest/uniuri"
	_ "github.com/go-sql-driver/mysql"
)

const (
	LENGTH     = 6
	PORT       = ":8080"
	DIRECTORY  = "/tmp/"
	UPADDRESS  = "http://localhost"
	dbUSERNAME = ""
	dbNAME     = ""
	dbPASSWORD = ""
	DATABASE   = dbUSERNAME + ":" + dbPASSWORD + "@/" + dbNAME + "?charset=utf8"
)

type Result struct {
	URL  string `json:"url"`
	Name string `json:"name"`
	Hash string `json:"hash"`
	Size int64  `json:"size"`
}

type Response struct {
	Success     bool     `json:"success"`
	ErrorCode   int      `json:"errorcode,omitempty"`
	Description string   `json:"description,omitempty"`
	Files       []Result `json:"files,omitempty"`
}

func check(err error) {
	if err != nil {
		fmt.Println(err)
		return
	}
}

func generateName() string {
	name := uniuri.NewLen(LENGTH)
	db, err := sql.Open("mysql", DATABASE)
	check(err)
	query, err := db.Query("select id from files where id=?", name)
	if err != sql.ErrNoRows {
		for query.Next() {
			generateName()
		}
	}
	db.Close()

	return name
}
func respond(w http.ResponseWriter, output string, resp Response) {
	if resp.ErrorCode != 0 {
		resp.Files = []Result{}
		resp.Success = false
	} else {
		resp.Success = true
	}

	switch output {
	case "json":

		w.Header().Set("Content-Type", "application/json")
		err := json.NewEncoder(w).Encode(resp)

		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	case "xml":
		x, err := xml.MarshalIndent(resp, "", "  ")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/xml")
		w.Write(x)

	case "html":
		w.Header().Set("Content-Type", "text/html")
		for _, file := range resp.Files {
			io.WriteString(w, ""+file.URL+"
")
		}

	case "gyazo", "text":
		w.Header().Set("Content-Type", "plain/text")
		for _, file := range resp.Files {
			io.WriteString(w, file.URL+"\n")
		}

	case "csv":
		w.Header().Set("Content-Type", "text/csv")
		io.WriteString(w, "name, url, hash, size\n")
		for _, file := range resp.Files {
			io.WriteString(w, file.Name+","+file.URL+","+file.Hash+","+strconv.FormatInt(file.Size, 10)+"\n")
		}

	default:
		w.Header().Set("Content-Type", "application/json")
		err := json.NewEncoder(w).Encode(resp)

		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

	}

}
func uploadHandler(w http.ResponseWriter, r *http.Request) {
	reader, err := r.MultipartReader()
	output := r.FormValue("output")

	resp := Response{Files: []Result{}}
	if err != nil {
		resp.ErrorCode = http.StatusInternalServerError
		resp.Description = err.Error()
		resp.Success = false
		return
	}

	for {
		part, err := reader.NextPart()
		if err == io.EOF {
			break
		}

		if part.FileName() == "" {
			continue
		}
		s := generateName()
		extName := filepath.Ext(part.FileName())
		filename := s + extName
		dst, err := os.Create(DIRECTORY + filename)
		defer dst.Close()

		if err != nil {
			resp.ErrorCode = http.StatusInternalServerError
			resp.Description = err.Error()
			return
		}

		h := sha1.New()
		t := io.TeeReader(part, h)
		_, err = io.Copy(dst, t)

		if err != nil {
			resp.ErrorCode = http.StatusInternalServerError
			resp.Description = err.Error()
			return
		}
		hash := h.Sum(nil)
		sha1 := base64.URLEncoding.EncodeToString(hash)
		stat, _ := dst.Stat()
		size := stat.Size()
		originalname := part.FileName()
		db, err := sql.Open("mysql", DATABASE)
		check(err)
		err = db.QueryRow("select originalname, filename, size where hash=?", sha1).Scan(&originalname, &filename, &size)
		if err != sql.ErrNoRows {
			query, err := db.Prepare("INSERT into files(hash, originalname, filename, size, date) values(?, ?, ?, ?, ?)")
			res := Result{
				URL:  UPADDRESS + "/" + s + extName,
				Name: originalname,
				Hash: sha1,
				Size: size,
			}
			_, err = query.Exec(res.Hash, res.Name, res.Hash, res.Size, time.Now().Format("2016-01-02 15:04:05"))
			check(err)
			resp.Files = append(resp.Files, res)

		}
	}
	respond(w, output, resp)
}

func main() {
	http.HandleFunc("/upload.php", uploadHandler)
	err := http.ListenAndServe(PORT, nil)
	if err != nil {
		panic(err)
	}

}
<commit_msg>Error responses<commit_after>package main

import (
	"crypto/sha1"
	"database/sql"
	"encoding/base64"
	"encoding/json"
	"encoding/xml"
	"fmt"
	"io"
	"net/http"
	"os"
	"path/filepath"
	"strconv"
	"time"

	"github.com/dchest/uniuri"
	_ "github.com/go-sql-driver/mysql"
)

const (
	LENGTH     = 6
	PORT       = ":8080"
	DIRECTORY  = "/tmp/"
	UPADDRESS  = "http://localhost"
	dbUSERNAME = ""
	dbNAME     = ""
	dbPASSWORD = ""
	DATABASE   = dbUSERNAME + ":" + dbPASSWORD + "@/" + dbNAME + "?charset=utf8"
)

type Result struct {
	URL  string `json:"url"`
	Name string `json:"name"`
	Hash string `json:"hash"`
	Size int64  `json:"size"`
}

type Response struct {
	Success     bool     `json:"success"`
	ErrorCode   int      `json:"errorcode,omitempty"`
	Description string   `json:"description,omitempty"`
	Files       []Result `json:"files,omitempty"`
}

func check(err error) {
	if err != nil {
		fmt.Println(err)
		return
	}
}

func generateName() string {
	name := uniuri.NewLen(LENGTH)
	db, err := sql.Open("mysql", DATABASE)
	check(err)
	query, err := db.Query("select id from files where id=?", name)
	if err != sql.ErrNoRows {
		for query.Next() {
			generateName()
		}
	}
	db.Close()

	return name
}
func respond(w http.ResponseWriter, output string, resp Response) {
	if resp.ErrorCode != 0 {
		resp.Files = []Result{}
		resp.Success = false
	} else {
		resp.Success = true
	}

	switch output {
	case "json":

		w.Header().Set("Content-Type", "application/json")
		err := json.NewEncoder(w).Encode(resp)

		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
	case "xml":
		x, err := xml.MarshalIndent(resp, "", "  ")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/xml")
		w.Write(x)

	case "html":
		w.Header().Set("Content-Type", "text/html")
		for _, file := range resp.Files {
			io.WriteString(w, ""+file.URL+"
")
		}

	case "gyazo", "text":
		w.Header().Set("Content-Type", "plain/text")
		for _, file := range resp.Files {
			io.WriteString(w, file.URL+"\n")
		}

	case "csv":
		w.Header().Set("Content-Type", "text/csv")
		io.WriteString(w, "name, url, hash, size\n")
		for _, file := range resp.Files {
			io.WriteString(w, file.Name+","+file.URL+","+file.Hash+","+strconv.FormatInt(file.Size, 10)+"\n")
		}

	default:
		w.Header().Set("Content-Type", "application/json")
		err := json.NewEncoder(w).Encode(resp)

		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

	}

}
func uploadHandler(w http.ResponseWriter, r *http.Request) {
	reader, err := r.MultipartReader()
	output := r.FormValue("output")

	resp := Response{Files: []Result{}}
	if err != nil {
		resp.ErrorCode = http.StatusInternalServerError
		resp.Description = err.Error()
		resp.Success = false
		respond(w, output, resp)
		return
	}

	for {
		part, err := reader.NextPart()
		if err == io.EOF {
			break
		}

		if part.FileName() == "" {
			continue
		}
		s := generateName()
		extName := filepath.Ext(part.FileName())
		filename := s + extName
		dst, err := os.Create(DIRECTORY + filename)
		defer dst.Close()

		if err != nil {
			resp.ErrorCode = http.StatusInternalServerError
			resp.Description = err.Error()
			respond(w, output, resp)
			return
		}

		h := sha1.New()
		t := io.TeeReader(part, h)
		_, err = io.Copy(dst, t)

		if err != nil {
			resp.ErrorCode = http.StatusInternalServerError
			resp.Description = err.Error()
			return
		}
		hash := h.Sum(nil)
		sha1 := base64.URLEncoding.EncodeToString(hash)
		stat, _ := dst.Stat()
		size := stat.Size()
		originalname := part.FileName()
		db, err := sql.Open("mysql", DATABASE)
		check(err)
		err = db.QueryRow("select originalname, filename, size where hash=?", sha1).Scan(&originalname, &filename, &size)
		if err != sql.ErrNoRows {
			query, err := db.Prepare("INSERT into files(hash, originalname, filename, size, date) values(?, ?, ?, ?, ?)")
			res := Result{
				URL:  UPADDRESS + "/" + s + extName,
				Name: originalname,
				Hash: sha1,
				Size: size,
			}
			_, err = query.Exec(res.Hash, res.Name, res.Hash, res.Size, time.Now().Format("2016-01-02 15:04:05"))
			check(err)
			resp.Files = append(resp.Files, res)

		}
	}
	respond(w, output, resp)
}

func main() {
	http.HandleFunc("/upload.php", uploadHandler)
	err := http.ListenAndServe(PORT, nil)
	if err != nil {
		panic(err)
	}

}
<|endoftext|>


<commit_before>package update

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"

	"github.com/nanobox-io/nanobox/util/display"
)

var Server bool

func Run(path string) error {
	if path == "" {
		fmt.Errorf("invalid path")
	}

	// create a temporary file
	tmpFileName := filepath.Join(filepath.Dir(path), TmpName)
	tmpFile, err := os.OpenFile(tmpFileName, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
	if err != nil {
		return err
	}

	// download the file and display the progress bar
	resp, err := http.Get(remotePath())
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	dp := display.DownloadPercent{Total: resp.ContentLength}
	if Server {
		// on the Server we dont really care to see this
		dp.Output = ioutil.Discard
	}
	dp.Copy(tmpFile, resp.Body)

	// close the tmp file
	tmpFile.Close()

	// replace binary
	if err := os.Rename(tmpFileName, path); err != nil {
		return err
	}

	// update the model
	update := newUpdate()

	return update.Save()
}
<commit_msg>Add version output to update<commit_after>package update

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"

	"github.com/nanobox-io/nanobox/util/display"
)

var Server bool

func Run(path string) error {
	if path == "" {
		fmt.Errorf("invalid path")
	}

	// create a temporary file
	tmpFileName := filepath.Join(filepath.Dir(path), TmpName)
	tmpFile, err := os.OpenFile(tmpFileName, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
	if err != nil {
		return err
	}

	fmt.Printf("Current version: %s", getCurrentVersion(path))
	// download the file and display the progress bar
	resp, err := http.Get(remotePath())
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	dp := display.DownloadPercent{Total: resp.ContentLength}
	if Server {
		// on the Server we dont really care to see this
		dp.Output = ioutil.Discard
	}
	dp.Copy(tmpFile, resp.Body)

	// close the tmp file
	tmpFile.Close()

	// replace binary
	if err := os.Rename(tmpFileName, path); err != nil {
		return err
	}

	// update the model
	update := newUpdate()

	fmt.Printf("Updated to version: %s", getCurrentVersion(path))

	return update.Save()
}

func getCurrentVersion(path string) string {
	if path == "" {
		fmt.Errorf("invalid path")
	}
	version, err := exec.Command(path, "version").Output()
	if err != nil {
		fmt.Errorf("Error while trying to get the nanobox version")
		return ""
	}
	return string(version)
}
<|endoftext|>


<commit_before>package sprite_sass

import (
	"bytes"
	"log"
	"os"
	"path/filepath"
	"strings"
	"testing"
)

func cleanUpSprites(sprites map[string]ImageList) {
	if sprites == nil {
		return
	}
	for _, iml := range sprites {
		err := os.Remove(filepath.Join(iml.GenImgDir, iml.OutFile))
		if err != nil {
			log.Fatal(err)
		}
	}
}

func TestSpriteLookup(t *testing.T) {

	imgs := ImageList{}
	imgs.Decode("test/139.jpg", "test/140.jpg")
	if f := imgs.Lookup("test/139.jpg"); f != 0 {
		t.Errorf("Invalid file location given found %d, expected %d", f, 0)
	}

	if f := imgs.Lookup("test/140.jpg"); f != 1 {
		t.Errorf("Invalid file location given found %d, expected %d", f, 1)
	}

	if f := imgs.Lookup("140"); f != 1 {
		t.Errorf("Invalid file location given found %d, expected %d", f, 1)
	}

	if f := imgs.Lookup("notafile.jpg"); f != -1 {
		t.Errorf("Found a file that doesn't exist was: %d, expected: %d",
			imgs.Lookup("noatfile.jpg"), -1)
	}
}

func TestSpriteCombine(t *testing.T) {
	imgs := ImageList{}
	imgs.Decode("test/139.jpg", "test/140.jpg")
	imgs.Vertical = true
	imgs.Combine()

	if imgs.Height() != 279 {
		t.Errorf("Invalid Height found %d, wanted %d", imgs.Height(), 279)
	}

	if imgs.Width() != 96 {
		t.Errorf("Invalid Width found %d, wanted %d", imgs.Width(), 192)
	}

	if x := imgs.X(1); x != 0 {
		t.Errorf("Invalid X found %d, wanted %d", x, 0)
	}

	if y := imgs.Y(1); y != 139 {
		t.Errorf("Invalid Y found %d, wanted %d", y, 139)
	}

	if e := -1; e != imgs.SImageWidth("150") {
		t.Errorf("Non-existant image width invalid"+
			"\n    was:%d\nexpected:%d",
			imgs.SImageWidth("150"), e)
	}

	if e := -1; e != imgs.SImageHeight("150") {
		t.Errorf("Non-existant image width invalid"+
			"\n    was:%d\nexpected:%d",
			imgs.SImageHeight("150"), e)
	}

	if e := ""; e != imgs.Dimensions("150") {
		t.Errorf("Non-existant image width invalid"+
			"\n    was:%s\nexpected:%s",
			imgs.Dimensions("150"), e)
	}

	//Quick cache check
	imgs.Combine()
	if imgs.Height() != 279 || imgs.Width() != 96 {
		t.Errorf("Cache invalid")
	}

	testFile, err := imgs.Export()

	defer func() {
		//Cleanup test files
		err := os.Remove(testFile)

		if err != nil {
			panic(err)
		}

	}()

	if err != nil {
		panic(err)
	}
}

// Test image dimension calls
func TestSpriteImageDimensions(t *testing.T) {
	imgs := ImageList{}
	imgs.Decode("test/*.png")

	if e := "width: 96px;\nheight: 139px"; e != imgs.Dimensions("139") {
		t.Errorf("Dimensions invalid was: %s\nexpected: %s\n",
			imgs.Dimensions("139"), e)
	}

	if e := 139; e != imgs.SImageHeight("139") {
		t.Errorf("Height invalid    was:%d\nexpected:%d",
			imgs.SImageHeight("139"), e)
	}

	if e := 96; e != imgs.SImageWidth("139") {
		t.Errorf("Height invalid was:%d\nexpected:%d",
			imgs.SImageWidth("139"), e)
	}

	if e := "-96px 0px"; imgs.Position("140") != e {
		t.Errorf("Invalid position found was: %s\nexpected:%s",
			imgs.Position("140"), e)
	}

	output := imgs.CSS("140")
	if e := `url("test-585dca.png") -96px 0px`; output != e {
		t.Errorf("Invalid CSS generated on test     was: %s\nexpected: %s",
			output, e)
	}

}

//Test file globbing
func TestSpriteGlob(t *testing.T) {
	imgs := ImageList{
		ImageDir: "test/img",
	}
	imgs.Decode("*.png")

	// Test [Un]successful lookups
	if f := imgs.Lookup("test/img/139.png"); f != 0 {
		t.Errorf("Invalid file location given found %d, expected %d", f, 0)
	}

	if f := imgs.Lookup("test/img/140.png"); f != 1 {
		t.Errorf("Invalid file location given found %d, expected %d", f, 1)
	}

	if f := imgs.Lookup("notafile.png"); f != -1 {
		t.Errorf("Found a file that doesn't exist")
	}
}

func TestSpriteExport(t *testing.T) {
	imgs := ImageList{
		ImageDir:  ".",
		GenImgDir: "build/test",
	}
	imgs.Decode("test/img/*.png")
	of := imgs.OutFile

	if e := "testimg-d65510.png"; e != of {
		t.Errorf("Outfile misnamed \n     was: %s\nexpected: %s", of, e)
	}
}

func TestSpriteDecode(t *testing.T) {
	//Should fail with unable to find file
	i := ImageList{}
	err := i.Decode("notafile")

	if e := "png: invalid format: invalid image size: 0x0"; err.Error() != e {
		t.Errorf("Unexpected error thrown was: %s expected: %s",
			e, err)
	}

	if len(i.GoImages) > 0 {
		t.Errorf("Found a non-existant file")
	}
}

func TestSpriteHorizontal(t *testing.T) {

	imgs := ImageList{}
	imgs.Decode("test/139.jpg", "test/140.jpg")
	imgs.Vertical = false
	imgs.Combine()

	if e := 140; imgs.Height() != e {
		t.Errorf("Invalid Height found %d, wanted %d", imgs.Height(), e)
	}

	if e := 192; imgs.Width() != e {
		t.Errorf("Invalid Width found %d, wanted %d", imgs.Width(), e)
	}

	if e := 96; imgs.X(1) != e {
		t.Errorf("Invalid X found %d, wanted %d", imgs.X(1), e)
	}

	if e := 0; imgs.Y(1) != e {
		t.Errorf("Invalid Y found %d, wanted %d", imgs.Y(1), e)
	}
}

func TestSpriteInline(t *testing.T) {
	imgs := ImageList{}
	imgs.Decode("test/pixel.png")
	imgs.Combine()
	bytes := imgs.inline()

	// Bytes are non-deterministic, so check length and move on
	if len(bytes) != 73 {
		t.Errorf("Pixel blog data had an invalid length"+
			"\n     was: %d\nexpected: 300-350", len(bytes))
	}

	str := imgs.Inline()
	if len(str) != 129 {
		t.Errorf("CSS length has an invalid length:%d expected: 400-500",
			len(str))
	}
}

func TestSpriteError(t *testing.T) {
	var out bytes.Buffer
	imgs := ImageList{}
	log.SetOutput(&out)
	imgs.Decode("test/bad/interlace.png")
	imgs.Combine()
	_ = imgs
	out.ReadString('\n')
	str := out.String()
	strFirst := strings.Split(str, "\n")[0]
	if e := "png: unsupported feature: compression, " +
		"filter or interlace method"; e != strFirst {
		t.Errorf("Interlaced error not received expected:\n%s was:\n%s",
			e, strFirst)
	}

	if e := -1; imgs.Y(1) != e {
		t.Errorf("Invalid position expected: %d, was: %d", e, imgs.Y(1))
	}

	if e := -1; imgs.X(1) != e {
		t.Errorf("Invalid position expected: %d, was: %d", e, imgs.X(1))
	}

	if e := -1; imgs.ImageHeight(-1) != -1 {
		t.Errorf("ImageHeight not found expected: %d, was: %d",
			e, imgs.ImageHeight(-1))
	}

	if e := -1; imgs.ImageWidth(-1) != -1 {
		t.Errorf("ImageWidth not found expected: %d, was: %d",
			e, imgs.ImageWidth(-1))
	}

	if e := ""; imgs.File("notfound") != e {
		t.Errorf("Invalid file call to File expected: %s, was %s",
			e, imgs.File("notfound"))
	}

	out.Reset()
	if e := ""; imgs.CSS("") != e {
		t.Errorf("Invalid css for non-file expected: %s, was: %s",
			e, imgs.CSS(""))
	}
	out.Reset()
	if e := ""; imgs.Position("") != e {
		t.Errorf("Invalid css for non-file expected: %s, was: %s",
			e, imgs.Position(""))
	}
	log.SetOutput(os.Stdout)
}
<commit_msg>Map test<commit_after>package sprite_sass

import (
	"bytes"
	"log"
	"os"
	"path/filepath"
	"strings"
	"testing"
)

func cleanUpSprites(sprites map[string]ImageList) {
	if sprites == nil {
		return
	}
	for _, iml := range sprites {
		err := os.Remove(filepath.Join(iml.GenImgDir, iml.OutFile))
		if err != nil {
			log.Fatal(err)
		}
	}
}

func TestSpriteLookup(t *testing.T) {

	imgs := ImageList{}
	imgs.Decode("test/139.jpg", "test/140.jpg")
	if f := imgs.Lookup("test/139.jpg"); f != 0 {
		t.Errorf("Invalid file location given found %d, expected %d", f, 0)
	}

	if f := imgs.Lookup("test/140.jpg"); f != 1 {
		t.Errorf("Invalid file location given found %d, expected %d", f, 1)
	}

	if f := imgs.Lookup("140"); f != 1 {
		t.Errorf("Invalid file location given found %d, expected %d", f, 1)
	}

	if f := imgs.Lookup("notafile.jpg"); f != -1 {
		t.Errorf("Found a file that doesn't exist was: %d, expected: %d",
			imgs.Lookup("noatfile.jpg"), -1)
	}
}

func TestSpriteCombine(t *testing.T) {
	imgs := ImageList{}
	imgs.Decode("test/139.jpg", "test/140.jpg")
	imgs.Vertical = true
	imgs.Combine()

	if imgs.Height() != 279 {
		t.Errorf("Invalid Height found %d, wanted %d", imgs.Height(), 279)
	}

	if imgs.Width() != 96 {
		t.Errorf("Invalid Width found %d, wanted %d", imgs.Width(), 192)
	}

	if x := imgs.X(1); x != 0 {
		t.Errorf("Invalid X found %d, wanted %d", x, 0)
	}

	if y := imgs.Y(1); y != 139 {
		t.Errorf("Invalid Y found %d, wanted %d", y, 139)
	}

	if e := -1; e != imgs.SImageWidth("150") {
		t.Errorf("Non-existant image width invalid"+
			"\n    was:%d\nexpected:%d",
			imgs.SImageWidth("150"), e)
	}

	if e := -1; e != imgs.SImageHeight("150") {
		t.Errorf("Non-existant image width invalid"+
			"\n    was:%d\nexpected:%d",
			imgs.SImageHeight("150"), e)
	}

	if e := ""; e != imgs.Dimensions("150") {
		t.Errorf("Non-existant image width invalid"+
			"\n    was:%s\nexpected:%s",
			imgs.Dimensions("150"), e)
	}

	//Quick cache check
	imgs.Combine()
	if imgs.Height() != 279 || imgs.Width() != 96 {
		t.Errorf("Cache invalid")
	}

	testFile, err := imgs.Export()

	defer func() {
		//Cleanup test files
		err := os.Remove(testFile)

		if err != nil {
			panic(err)
		}

	}()

	if err != nil {
		panic(err)
	}
}

// Test image dimension calls
func TestSpriteImageDimensions(t *testing.T) {
	imgs := ImageList{}
	imgs.Decode("test/*.png")

	if e := "width: 96px;\nheight: 139px"; e != imgs.Dimensions("139") {
		t.Errorf("Dimensions invalid was: %s\nexpected: %s\n",
			imgs.Dimensions("139"), e)
	}

	if e := 139; e != imgs.SImageHeight("139") {
		t.Errorf("Height invalid    was:%d\nexpected:%d",
			imgs.SImageHeight("139"), e)
	}

	if e := 96; e != imgs.SImageWidth("139") {
		t.Errorf("Height invalid was:%d\nexpected:%d",
			imgs.SImageWidth("139"), e)
	}

	if e := "-96px 0px"; imgs.Position("140") != e {
		t.Errorf("Invalid position found was: %s\nexpected:%s",
			imgs.Position("140"), e)
	}

	output := imgs.CSS("140")
	if e := `url("test-585dca.png") -96px 0px`; output != e {
		t.Errorf("Invalid CSS generated on test     was: %s\nexpected: %s",
			output, e)
	}

}

//Test file globbing
func TestSpriteGlob(t *testing.T) {
	imgs := ImageList{
		ImageDir: "test/img",
	}
	imgs.Decode("*.png")

	// Test [Un]successful lookups
	if f := imgs.Lookup("test/img/139.png"); f != 0 {
		t.Errorf("Invalid file location given found %d, expected %d", f, 0)
	}

	if f := imgs.Lookup("test/img/140.png"); f != 1 {
		t.Errorf("Invalid file location given found %d, expected %d", f, 1)
	}

	if f := imgs.Lookup("notafile.png"); f != -1 {
		t.Errorf("Found a file that doesn't exist")
	}
}

func TestSpriteExport(t *testing.T) {
	imgs := ImageList{
		ImageDir:  ".",
		GenImgDir: "build/test",
	}
	imgs.Decode("test/img/*.png")
	of := imgs.OutFile

	if e := "testimg-d65510.png"; e != of {
		t.Errorf("Outfile misnamed \n     was: %s\nexpected: %s", of, e)
	}

	if e := `(); $sprites: map_merge($sprites,(139: (width: 96, height: 139, x: 0, y: 0, url: 'build/test/testimg-d65510.png'))); $sprites: map_merge($sprites,(140: (width: 96, height: 140, x: 96, y: 0, url: 'build/test/testimg-d65510.png')));`; e != imgs.Map("$sprites") {
		t.Error("Map mismatch")
	}
}

func TestSpriteDecode(t *testing.T) {
	//Should fail with unable to find file
	i := ImageList{}
	err := i.Decode("notafile")

	if e := "png: invalid format: invalid image size: 0x0"; err.Error() != e {
		t.Errorf("Unexpected error thrown was: %s expected: %s",
			e, err)
	}

	if len(i.GoImages) > 0 {
		t.Errorf("Found a non-existant file")
	}
}

func TestSpriteHorizontal(t *testing.T) {

	imgs := ImageList{}
	imgs.Decode("test/139.jpg", "test/140.jpg")
	imgs.Vertical = false
	imgs.Combine()

	if e := 140; imgs.Height() != e {
		t.Errorf("Invalid Height found %d, wanted %d", imgs.Height(), e)
	}

	if e := 192; imgs.Width() != e {
		t.Errorf("Invalid Width found %d, wanted %d", imgs.Width(), e)
	}

	if e := 96; imgs.X(1) != e {
		t.Errorf("Invalid X found %d, wanted %d", imgs.X(1), e)
	}

	if e := 0; imgs.Y(1) != e {
		t.Errorf("Invalid Y found %d, wanted %d", imgs.Y(1), e)
	}
}

func TestSpriteInline(t *testing.T) {
	imgs := ImageList{}
	imgs.Decode("test/pixel.png")
	imgs.Combine()
	bytes := imgs.inline()

	// Bytes are non-deterministic, so check length and move on
	if len(bytes) != 73 {
		t.Errorf("Pixel blog data had an invalid length"+
			"\n     was: %d\nexpected: 300-350", len(bytes))
	}

	str := imgs.Inline()
	if len(str) != 129 {
		t.Errorf("CSS length has an invalid length:%d expected: 400-500",
			len(str))
	}
}

func TestSpriteError(t *testing.T) {
	var out bytes.Buffer
	imgs := ImageList{}
	log.SetOutput(&out)
	imgs.Decode("test/bad/interlace.png")
	imgs.Combine()
	_ = imgs
	out.ReadString('\n')
	str := out.String()
	strFirst := strings.Split(str, "\n")[0]
	if e := "png: unsupported feature: compression, " +
		"filter or interlace method"; e != strFirst {
		t.Errorf("Interlaced error not received expected:\n%s was:\n%s",
			e, strFirst)
	}

	if e := -1; imgs.Y(1) != e {
		t.Errorf("Invalid position expected: %d, was: %d", e, imgs.Y(1))
	}

	if e := -1; imgs.X(1) != e {
		t.Errorf("Invalid position expected: %d, was: %d", e, imgs.X(1))
	}

	if e := -1; imgs.ImageHeight(-1) != -1 {
		t.Errorf("ImageHeight not found expected: %d, was: %d",
			e, imgs.ImageHeight(-1))
	}

	if e := -1; imgs.ImageWidth(-1) != -1 {
		t.Errorf("ImageWidth not found expected: %d, was: %d",
			e, imgs.ImageWidth(-1))
	}

	if e := ""; imgs.File("notfound") != e {
		t.Errorf("Invalid file call to File expected: %s, was %s",
			e, imgs.File("notfound"))
	}

	out.Reset()
	if e := ""; imgs.CSS("") != e {
		t.Errorf("Invalid css for non-file expected: %s, was: %s",
			e, imgs.CSS(""))
	}
	out.Reset()
	if e := ""; imgs.Position("") != e {
		t.Errorf("Invalid css for non-file expected: %s, was: %s",
			e, imgs.Position(""))
	}
	log.SetOutput(os.Stdout)
}
<|endoftext|>


<commit_before>package trace

import (
	"io"
	"fmt"
)

//	Tracer is the interface that describes an object capable of tracing events throughout code.
//	Capital letters mean this is a publicly visible type
type Tracer interface {
	Trace(...interface{})
}

type tracer struct {
	out io.Writer
}

func (t *tracer) Trace(a...interface{}) {
	t.out.Write([]byte(fmt.Sprint(a...)))
	t.out.Write([]byte("\n"))
}

func New(w io.Writer) Tracer {
	return nil
}<commit_msg>fixed to working tracer functionality<commit_after>package trace

import (
	"io"
	"fmt"
)

//	Tracer is the interface that describes an object capable of tracing events throughout code.
//	Capital letters mean this is a publicly visible type
type Tracer interface {
	Trace(...interface{})
}

type tracer struct {
	out io.Writer
}

func (t *tracer) Trace(a...interface{}) {
	t.out.Write([]byte(fmt.Sprint(a...)))
	t.out.Write([]byte("\n"))
}

func New(w io.Writer) Tracer {
	return &tracer{out: w}
}<|endoftext|>