<commit_before>package class

import (
	"encoding/binary"
	"io"
)

var byteOrder = binary.BigEndian

var initFuncs = []func(*ClassFile, io.Reader) error{
	(*ClassFile).readMagic,
	(*ClassFile).readVersion,
	(*ClassFile).readConstPool,
	(*ClassFile).readAccessFlags,
	(*ClassFile).readThisClass,
	(*ClassFile).readSuperClass,
	(*ClassFile).readInterfaces,
	(*ClassFile).readFields,
	(*ClassFile).readMethods,
	(*ClassFile).readAttributes,
}

const (
	ConstUTF8               ConstInfoTag = 1
	ConstInteger                         = 3
	ConstFloat                           = 4
	ConstLong                            = 5
	ConstDouble                          = 6
	ConstClass                           = 7
	ConstString                          = 8
	ConstFieldRef                        = 9
	ConstMethodRef                       = 10
	ConstInterfaceMehtodRef              = 11
	ConstNameAndType                     = 12
	ConstMethodHandle                    = 15
	ConstMethodType                      = 16
	ConstInvokeDynamic                   = 18
)

const (
	AccPublic     AccessFlag = 0x0001
	AccFinal                 = 0x0010
	AccSuper                 = 0x0020
	AccInterface             = 0x0200
	AccAbstract              = 0x0400
	AccSynthetic             = 0x1000
	AccAnnotation            = 0x2000
	AccEnum                  = 0x4000
)

func Parse(r io.Reader) (*ClassFile, error) {
	c := &ClassFile{}

	var err error

	for _, f := range initFuncs {
		err = f(c, r)
		if err != nil {
			return nil, err
		}
	}

	return c, nil
}

func (c *ClassFile) readMagic(r io.Reader) error {
	return binary.Read(r, byteOrder, &c.Magic)
}

func (c *ClassFile) readVersion(r io.Reader) error {
	err := binary.Read(r, byteOrder, &c.MinorVersion)
	if err != nil {
		return err
	}

	return binary.Read(r, byteOrder, &c.MajorVersion)
}

func (c *ClassFile) readConstPool(r io.Reader) error {
	err := binary.Read(r, byteOrder, &c.ConstPoolSize)
	if err != nil {
		return err
	}

	c.ConstPool = make([]*ConstInfo, 0, c.ConstPoolSize)

	for i := uint16(1); i < c.ConstPoolSize; i++ {
		info, err := c.readConstInfo(r)
		if err != nil {
			return err
		}

		c.ConstPool = append(c.ConstPool, info)
	}

	return nil
}

func (c *ClassFile) readConstInfo(r io.Reader) (*ConstInfo, error) {
	info := &ConstInfo{}

	err := binary.Read(r, byteOrder, &info.Tag)
	if err != nil {
		return nil, err
	}

	bytesToRead := uint16(0)
	switch info.Tag {
	case ConstClass, ConstString, ConstMethodType:
		bytesToRead = 2

	case ConstMethodHandle:
		bytesToRead = 3

	case ConstFieldRef, ConstMethodRef,
		ConstInterfaceMehtodRef, ConstInteger,
		ConstFloat, ConstNameAndType, ConstInvokeDynamic:
		bytesToRead = 4

	case ConstLong, ConstDouble:
		bytesToRead = 8

	case ConstUTF8:
		err = binary.Read(r, byteOrder, &bytesToRead)
		if err != nil {
			return nil, err
		}

	default:
		panic("unknown tag in class file!")
	}

	info.Info = make([]uint8, bytesToRead)

	err = binary.Read(r, byteOrder, &info.Info)
	if err != nil {
		return nil, err
	}

	return info, nil
}

func (c *ClassFile) readAccessFlags(r io.Reader) error {
	return binary.Read(r, byteOrder, &c.AccessFlags)
}

func (c *ClassFile) readThisClass(r io.Reader) error {
	return binary.Read(r, byteOrder, &c.ThisClass)
}

func (c *ClassFile) readSuperClass(r io.Reader) error {
	return binary.Read(r, byteOrder, &c.SuperClass)
}

func (c *ClassFile) readInterfaces(r io.Reader) error {
	err := binary.Read(r, byteOrder, &c.InterfacesCount)
	if err != nil {
		return err
	}

	c.Interfaces = make([]ConstPoolIndex, 0, c.InterfacesCount)

	var idx ConstPoolIndex
	for i := uint16(0); i < c.InterfacesCount; i++ {
		err = binary.Read(r, byteOrder, &idx)
		if err != nil {
			return err
		}

		c.Interfaces = append(c.Interfaces, idx)
	}

	return nil
}

func (c *ClassFile) readFields(r io.Reader) error {
	err := binary.Read(r, byteOrder, &c.FieldsCount)
	if err != nil {
		return err
	}

	c.Fields = make([]*FieldInfo, 0, c.FieldsCount)

	var field FieldInfo
	var fieldOrMethod *fieldOrMethodInfo
	for i := uint16(0); i < c.FieldsCount; i++ {
		fieldOrMethod, err = c.readFieldOrMethod(r)
		if err != nil {
			return err
		}

		field = FieldInfo(*fieldOrMethod)
		c.Fields = append(c.Fields, &field)
	}

	return nil
}

func (c *ClassFile) readMethods(r io.Reader) error {
	err := binary.Read(r, byteOrder, &c.MethodsCount)
	if err != nil {
		return err
	}

	c.Methods = make([]*MethodInfo, 0, c.MethodsCount)

	var method MethodInfo
	var fieldOrMethod *fieldOrMethodInfo
	for i := uint16(0); i < c.MethodsCount; i++ {
		fieldOrMethod, err = c.readFieldOrMethod(r)
		if err != nil {
			return err
		}

		method = MethodInfo(*fieldOrMethod)
		c.Methods = append(c.Methods, &method)
	}

	return nil
}

func (c *ClassFile) readFieldOrMethod(r io.Reader) (*fieldOrMethodInfo, error) {
	fom := &fieldOrMethodInfo{}

	errs := []error{
		binary.Read(r, byteOrder, &fom.AccessFlags),
		binary.Read(r, byteOrder, &fom.NameIndex),
		binary.Read(r, byteOrder, &fom.DescriptorIndex),
		binary.Read(r, byteOrder, &fom.AttributesCount),
	}

	for _, err := range errs {
		if err != nil {
			return nil, err
		}
	}

	fom.Attributes = make([]*AttributeInfo, 0, fom.AttributesCount)

	for i := uint16(0); i < fom.AttributesCount; i++ {
		attr, err := c.readAttribute(r)
		if err != nil {
			return nil, err
		}

		fom.Attributes = append(fom.Attributes, attr)
	}

	return fom, nil
}

func (c *ClassFile) readAttributes(r io.Reader) error {
	err := binary.Read(r, byteOrder, &c.AttributesCount)
	if err != nil {
		return err
	}

	c.Attributes = make([]*AttributeInfo, 0, c.AttributesCount)

	var attr *AttributeInfo
	for i := uint16(0); i < c.AttributesCount; i++ {
		attr, err = c.readAttribute(r)
		if err != nil {
			return err
		}

		c.Attributes = append(c.Attributes, attr)
	}

	return nil
}

func (c *ClassFile) readAttribute(r io.Reader) (*AttributeInfo, error) {
	return nil, nil
}
<commit_msg>Added attribute reader.<commit_after>package class

import (
	"encoding/binary"
	"io"
)

var byteOrder = binary.BigEndian

var initFuncs = []func(*ClassFile, io.Reader) error{
	(*ClassFile).readMagic,
	(*ClassFile).readVersion,
	(*ClassFile).readConstPool,
	(*ClassFile).readAccessFlags,
	(*ClassFile).readThisClass,
	(*ClassFile).readSuperClass,
	(*ClassFile).readInterfaces,
	(*ClassFile).readFields,
	(*ClassFile).readMethods,
	(*ClassFile).readAttributes,
}

const (
	ConstUTF8               ConstInfoTag = 1
	ConstInteger                         = 3
	ConstFloat                           = 4
	ConstLong                            = 5
	ConstDouble                          = 6
	ConstClass                           = 7
	ConstString                          = 8
	ConstFieldRef                        = 9
	ConstMethodRef                       = 10
	ConstInterfaceMehtodRef              = 11
	ConstNameAndType                     = 12
	ConstMethodHandle                    = 15
	ConstMethodType                      = 16
	ConstInvokeDynamic                   = 18
)

const (
	AccPublic     AccessFlag = 0x0001
	AccFinal                 = 0x0010
	AccSuper                 = 0x0020
	AccInterface             = 0x0200
	AccAbstract              = 0x0400
	AccSynthetic             = 0x1000
	AccAnnotation            = 0x2000
	AccEnum                  = 0x4000
)

func Parse(r io.Reader) (*ClassFile, error) {
	c := &ClassFile{}

	var err error

	for _, f := range initFuncs {
		err = f(c, r)
		if err != nil {
			return nil, err
		}
	}

	return c, nil
}

func (c *ClassFile) readMagic(r io.Reader) error {
	return binary.Read(r, byteOrder, &c.Magic)
}

func (c *ClassFile) readVersion(r io.Reader) error {
	err := binary.Read(r, byteOrder, &c.MinorVersion)
	if err != nil {
		return err
	}

	return binary.Read(r, byteOrder, &c.MajorVersion)
}

func (c *ClassFile) readConstPool(r io.Reader) error {
	err := binary.Read(r, byteOrder, &c.ConstPoolSize)
	if err != nil {
		return err
	}

	c.ConstPool = make([]*ConstInfo, 0, c.ConstPoolSize)

	for i := uint16(1); i < c.ConstPoolSize; i++ {
		info, err := c.readConstInfo(r)
		if err != nil {
			return err
		}

		c.ConstPool = append(c.ConstPool, info)
	}

	return nil
}

func (c *ClassFile) readConstInfo(r io.Reader) (*ConstInfo, error) {
	info := &ConstInfo{}

	err := binary.Read(r, byteOrder, &info.Tag)
	if err != nil {
		return nil, err
	}

	bytesToRead := uint16(0)
	switch info.Tag {
	case ConstClass, ConstString, ConstMethodType:
		bytesToRead = 2

	case ConstMethodHandle:
		bytesToRead = 3

	case ConstFieldRef, ConstMethodRef,
		ConstInterfaceMehtodRef, ConstInteger,
		ConstFloat, ConstNameAndType, ConstInvokeDynamic:
		bytesToRead = 4

	case ConstLong, ConstDouble:
		bytesToRead = 8

	case ConstUTF8:
		err = binary.Read(r, byteOrder, &bytesToRead)
		if err != nil {
			return nil, err
		}

	default:
		panic("unknown tag in class file!")
	}

	info.Info = make([]uint8, bytesToRead)

	err = binary.Read(r, byteOrder, &info.Info)
	if err != nil {
		return nil, err
	}

	return info, nil
}

func (c *ClassFile) readAccessFlags(r io.Reader) error {
	return binary.Read(r, byteOrder, &c.AccessFlags)
}

func (c *ClassFile) readThisClass(r io.Reader) error {
	return binary.Read(r, byteOrder, &c.ThisClass)
}

func (c *ClassFile) readSuperClass(r io.Reader) error {
	return binary.Read(r, byteOrder, &c.SuperClass)
}

func (c *ClassFile) readInterfaces(r io.Reader) error {
	err := binary.Read(r, byteOrder, &c.InterfacesCount)
	if err != nil {
		return err
	}

	c.Interfaces = make([]ConstPoolIndex, 0, c.InterfacesCount)

	var idx ConstPoolIndex
	for i := uint16(0); i < c.InterfacesCount; i++ {
		err = binary.Read(r, byteOrder, &idx)
		if err != nil {
			return err
		}

		c.Interfaces = append(c.Interfaces, idx)
	}

	return nil
}

func (c *ClassFile) readFields(r io.Reader) error {
	err := binary.Read(r, byteOrder, &c.FieldsCount)
	if err != nil {
		return err
	}

	c.Fields = make([]*FieldInfo, 0, c.FieldsCount)

	var field FieldInfo
	var fieldOrMethod *fieldOrMethodInfo
	for i := uint16(0); i < c.FieldsCount; i++ {
		fieldOrMethod, err = c.readFieldOrMethod(r)
		if err != nil {
			return err
		}

		field = FieldInfo(*fieldOrMethod)
		c.Fields = append(c.Fields, &field)
	}

	return nil
}

func (c *ClassFile) readMethods(r io.Reader) error {
	err := binary.Read(r, byteOrder, &c.MethodsCount)
	if err != nil {
		return err
	}

	c.Methods = make([]*MethodInfo, 0, c.MethodsCount)

	var method MethodInfo
	var fieldOrMethod *fieldOrMethodInfo
	for i := uint16(0); i < c.MethodsCount; i++ {
		fieldOrMethod, err = c.readFieldOrMethod(r)
		if err != nil {
			return err
		}

		method = MethodInfo(*fieldOrMethod)
		c.Methods = append(c.Methods, &method)
	}

	return nil
}

func (c *ClassFile) readFieldOrMethod(r io.Reader) (*fieldOrMethodInfo, error) {
	fom := &fieldOrMethodInfo{}

	errs := []error{
		binary.Read(r, byteOrder, &fom.AccessFlags),
		binary.Read(r, byteOrder, &fom.NameIndex),
		binary.Read(r, byteOrder, &fom.DescriptorIndex),
		binary.Read(r, byteOrder, &fom.AttributesCount),
	}

	for _, err := range errs {
		if err != nil {
			return nil, err
		}
	}

	fom.Attributes = make([]*AttributeInfo, 0, fom.AttributesCount)

	for i := uint16(0); i < fom.AttributesCount; i++ {
		attr, err := c.readAttribute(r)
		if err != nil {
			return nil, err
		}

		fom.Attributes = append(fom.Attributes, attr)
	}

	return fom, nil
}

func (c *ClassFile) readAttributes(r io.Reader) error {
	err := binary.Read(r, byteOrder, &c.AttributesCount)
	if err != nil {
		return err
	}

	c.Attributes = make([]*AttributeInfo, 0, c.AttributesCount)

	var attr *AttributeInfo
	for i := uint16(0); i < c.AttributesCount; i++ {
		attr, err = c.readAttribute(r)
		if err != nil {
			return err
		}

		c.Attributes = append(c.Attributes, attr)
	}

	return nil
}

func (c *ClassFile) readAttribute(r io.Reader) (*AttributeInfo, error) {
	attr := &AttributeInfo{}

	errs := []error{
		binary.Read(r, byteOrder, &attr.NameIndex),
		binary.Read(r, byteOrder, &attr.Length),
	}

	for _, err := range errs {
		if err != nil {
			return nil, err
		}
	}

	attr.Info = make([]uint8, attr.Length)

	err := binary.Read(r, byteOrder, &attr.Info)
	if err != nil {
		return nil, err
	}

	return attr, nil
}
<|endoftext|>


<commit_before>package js

import (
	log "github.com/Sirupsen/logrus"
	"gopkg.in/olebedev/go-duktape.v2"
)

type apiFunc func(r *Runner, c *duktape.Context) int

func apiHTTPDo(r *Runner, c *duktape.Context) int {
	method := argString(c, 0)
	if method == "" {
		log.Error("Missing method in http call")
		return 0
	}

	url := argString(c, 1)
	if url == "" {
		log.Error("Missing URL in http call")
		return 0
	}

	body := ""
	switch c.GetType(2) {
	case duktape.TypeNone, duktape.TypeNull, duktape.TypeUndefined:
	case duktape.TypeString, duktape.TypeNumber, duktape.TypeBoolean:
		body = c.ToString(2)
	case duktape.TypeObject:
		body = c.JsonEncode(2)
	default:
		log.Error("Unknown type for request body")
		return 0
	}

	args := httpArgs{}
	if err := argJSON(c, 3, &args); err != nil {
		log.Error("Invalid arguments to http call")
		return 0
	}

	res, duration, err := httpDo(r.Client, method, url, body, args)
	if err != nil {
		log.WithError(err).Error("Request error")
	}
	if !args.Quiet {
		r.mDuration.Duration(duration)
	}

	pushInstance(c, res, "HTTPResponse")

	return 1
}

func apiHTTPSetMaxConnectionsPerHost(r *Runner, c *duktape.Context) int {
	num := int(argNumber(c, 0))
	if num < 1 {
		log.Error("Max connections per host must be at least 1")
		return 0
	}
	r.Client.MaxConnsPerHost = num
	return 0
}

func apiLogType(r *Runner, c *duktape.Context) int {
	kind := argString(c, 0)
	text := argString(c, 1)
	extra := map[string]interface{}{}
	if err := argJSON(c, 2, &extra); err != nil {
		log.Error("Log context is not an object")
		return 0
	}

	l := log.WithFields(log.Fields(extra))
	switch kind {
	case "debug":
		l.Debug(text)
	case "info":
		l.Info(text)
	case "warn":
		l.Warn(text)
	case "error":
		l.Error(text)
	}

	return 0
}

func apiTestAbort(r *Runner, c *duktape.Context) int {
	// TODO: Do this some better way.
	log.Fatal("Test aborted")
	return 0
}
<commit_msg>[fix] Log URLs with JS-based metrics<commit_after>package js

import (
	log "github.com/Sirupsen/logrus"
	"gopkg.in/olebedev/go-duktape.v2"
)

type apiFunc func(r *Runner, c *duktape.Context) int

func apiHTTPDo(r *Runner, c *duktape.Context) int {
	method := argString(c, 0)
	if method == "" {
		log.Error("Missing method in http call")
		return 0
	}

	url := argString(c, 1)
	if url == "" {
		log.Error("Missing URL in http call")
		return 0
	}

	body := ""
	switch c.GetType(2) {
	case duktape.TypeNone, duktape.TypeNull, duktape.TypeUndefined:
	case duktape.TypeString, duktape.TypeNumber, duktape.TypeBoolean:
		body = c.ToString(2)
	case duktape.TypeObject:
		body = c.JsonEncode(2)
	default:
		log.Error("Unknown type for request body")
		return 0
	}

	args := httpArgs{}
	if err := argJSON(c, 3, &args); err != nil {
		log.Error("Invalid arguments to http call")
		return 0
	}

	res, duration, err := httpDo(r.Client, method, url, body, args)
	if err != nil {
		log.WithError(err).Error("Request error")
	}
	if !args.Quiet {
		r.mDuration.WithField("url", url).Duration(duration)
	}

	pushInstance(c, res, "HTTPResponse")

	return 1
}

func apiHTTPSetMaxConnectionsPerHost(r *Runner, c *duktape.Context) int {
	num := int(argNumber(c, 0))
	if num < 1 {
		log.Error("Max connections per host must be at least 1")
		return 0
	}
	r.Client.MaxConnsPerHost = num
	return 0
}

func apiLogType(r *Runner, c *duktape.Context) int {
	kind := argString(c, 0)
	text := argString(c, 1)
	extra := map[string]interface{}{}
	if err := argJSON(c, 2, &extra); err != nil {
		log.Error("Log context is not an object")
		return 0
	}

	l := log.WithFields(log.Fields(extra))
	switch kind {
	case "debug":
		l.Debug(text)
	case "info":
		l.Info(text)
	case "warn":
		l.Warn(text)
	case "error":
		l.Error(text)
	}

	return 0
}

func apiTestAbort(r *Runner, c *duktape.Context) int {
	// TODO: Do this some better way.
	log.Fatal("Test aborted")
	return 0
}
<|endoftext|>


<commit_before>package piet

import (
  "bufio"
  "fmt"
  "os"
  "strconv"
)

func (p *Piet) None() { return }

func (p *Piet) Pop() { p.PopStack() }

func (p *Piet) Push() { p.PushStack(p.area) }

func (p *Piet) Add() {
  if len(p.stack) < 2 { return }
  a, ok1 := p.PopStack()
  b, ok2 := p.PopStack()
  if ok1 && ok2 { p.PushStack(b + a) }
}

func (p *Piet) Subtract() {
  if len(p.stack) < 2 { return }
  a, ok1 := p.PopStack()
  b, ok2 := p.PopStack()
  if ok1 && ok2 { p.PushStack(b - a) }
}

func (p *Piet) Multiply() {
  if len(p.stack) < 2 {
    return
  }
  a, ok1 := p.PopStack()
  b, ok2 := p.PopStack()
  if ok1 && ok2 {
    p.PushStack(b * a)
  }
}

func (p *Piet) Divide() {
  if len(p.stack) < 2 { return }
  a, ok1 := p.PopStack()
  b, ok2 := p.PopStack()
  if ok1 && ok2 {
    if a == 0 {
      return
    } else {
      p.PushStack(b / a)
    }
  }
}

func (p *Piet) Mod() {
  if len(p.stack) < 2 { return }
  a, ok1 := p.PopStack()
  b, ok2 := p.PopStack()
  if ok1 && ok2 {
    if a == 0 {
      return
    } else {
      p.PushStack(b % a)
    }
  }
}

func (p *Piet) Not() {
  a, ok1 := p.PopStack()
  if ok1 { p.PushStack(BoolToInt64(a == 0)) }
}

func (p *Piet) Greater() {
  if len(p.stack) < 2 { return }
  a, ok1 := p.PopStack()
  b, ok2 := p.PopStack()
  if ok1 && ok2 { p.PushStack(BoolToInt64(a < b)) }
}

func (p *Piet) Pointer() {
  a, ok1 := p.PopStack()
  if ok1 {
    p.DP += int(a)
    p.DP %= 4
  }
}

func (p *Piet) Switch() {
  a, ok1 := p.PopStack()
  if ok1 {
    if a < 0 {
      a *= -1
      p.CC = true
    }
    for i := 0; i < int(a); i++ { p.CC = !p.CC }
  }
}

func (p *Piet) Duplicate() {
  a, ok1 := p.PopStack()
  if ok1 {
    p.PushStack(a)
    p.PushStack(a)
  }
}

func (p *Piet) Roll() {
  if len(p.stack) < 2 { return }
  a, ok1 := p.PopStack()
  b, ok2 := p.PopStack()
  if ok1 && ok2 {
    if b <= 0 {
      p.PushStack(b)
      p.PushStack(a)
      return
    }
    var reverse bool = false
    if a < 0 {
      a *= -1
      reverse = true
    }
    if int(b) > len(p.stack) {
      p.PushStack(b)
      p.PushStack(a)
      return
    }
    var x, xs []int64
    if int(b) == len(p.stack){
      x = []int64{}
      xs = []int64{}
    } else {
      x = []int64{p.stack[b]}
      xs = p.stack[b+1:]
    }
    for i := 0; i < int(a); i++ { p.stack = append(roll(p.stack[:b], reverse), append(x, xs...)...) }
  }
}

func (p *Piet) InNumber() {
  scanner := bufio.NewScanner(os.Stdin)
  scanner.Scan()
  a, err := strconv.Atoi(scanner.Text())
  if err != nil { return }
  p.PushStack(int64(a))
}

func (p *Piet) InChar() {
  var b []byte = make([]byte, 1)
  os.Stdin.Read(b)
  p.PushStack(int64(b[0]))
}

func (p *Piet) OutNumber() {
  a, ok1 := p.PopStack()
  if ok1 {
    fmt.Print(a)
    p.output += fmt.Sprintf("%d",a)
  }
}

func (p *Piet) OutChar() {
  a, ok1 := p.PopStack()
  if ok1 {
    fmt.Print(string(a))
    p.output += string(a)
  }
}<commit_msg>follow the rule of mod: The result has the same sign as the divisor (the top value).<commit_after>package piet

import (
  "bufio"
  "fmt"
  "math"
  "os"
  "strconv"
)

func (p *Piet) None() { return }

func (p *Piet) Pop() { p.PopStack() }

func (p *Piet) Push() { p.PushStack(p.area) }

func (p *Piet) Add() {
  if len(p.stack) < 2 { return }
  a, ok1 := p.PopStack()
  b, ok2 := p.PopStack()
  if ok1 && ok2 { p.PushStack(b + a) }
}

func (p *Piet) Subtract() {
  if len(p.stack) < 2 { return }
  a, ok1 := p.PopStack()
  b, ok2 := p.PopStack()
  if ok1 && ok2 { p.PushStack(b - a) }
}

func (p *Piet) Multiply() {
  if len(p.stack) < 2 {
    return
  }
  a, ok1 := p.PopStack()
  b, ok2 := p.PopStack()
  if ok1 && ok2 {
    p.PushStack(b * a)
  }
}

func (p *Piet) Divide() {
  if len(p.stack) < 2 { return }
  a, ok1 := p.PopStack()
  b, ok2 := p.PopStack()
  if ok1 && ok2 {
    if a == 0 {
      return
    } else {
      p.PushStack(b / a)
    }
  }
}

func (p *Piet) Mod() {
  if len(p.stack) < 2 { return }
  a, ok1 := p.PopStack()
  b, ok2 := p.PopStack()
  if ok1 && ok2 {
    sgn := a < 0
    if a == 0 {
      p.PushStack(b)
      p.PushStack(a)
      return
    } else {
      v := int64(math.Abs(float64(b%a)))
      if sgn {
        p.PushStack(v * (-1))
      } else {
        p.PushStack(v)
      }
    }
  }
}

func (p *Piet) Not() {
  a, ok1 := p.PopStack()
  if ok1 { p.PushStack(BoolToInt64(a == 0)) }
}

func (p *Piet) Greater() {
  if len(p.stack) < 2 { return }
  a, ok1 := p.PopStack()
  b, ok2 := p.PopStack()
  if ok1 && ok2 { p.PushStack(BoolToInt64(a < b)) }
}

func (p *Piet) Pointer() {
  a, ok1 := p.PopStack()
  if ok1 {
    p.DP += int(a)
    p.DP %= 4
  }
}

func (p *Piet) Switch() {
  a, ok1 := p.PopStack()
  if ok1 {
    if a < 0 {
      a *= -1
      p.CC = true
    }
    for i := 0; i < int(a); i++ { p.CC = !p.CC }
  }
}

func (p *Piet) Duplicate() {
  a, ok1 := p.PopStack()
  if ok1 {
    p.PushStack(a)
    p.PushStack(a)
  }
}

func (p *Piet) Roll() {
  if len(p.stack) < 2 { return }
  a, ok1 := p.PopStack()
  b, ok2 := p.PopStack()
  if ok1 && ok2 {
    if b <= 0 {
      p.PushStack(b)
      p.PushStack(a)
      return
    }
    var reverse bool = false
    if a < 0 {
      a *= -1
      reverse = true
    }
    if int(b) > len(p.stack) {
      p.PushStack(b)
      p.PushStack(a)
      return
    }
    var x, xs []int64
    if int(b) == len(p.stack){
      x = []int64{}
      xs = []int64{}
    } else {
      x = []int64{p.stack[b]}
      xs = p.stack[b+1:]
    }
    for i := 0; i < int(a); i++ { p.stack = append(roll(p.stack[:b], reverse), append(x, xs...)...) }
  }
}

func (p *Piet) InNumber() {
  scanner := bufio.NewScanner(os.Stdin)
  scanner.Scan()
  a, err := strconv.Atoi(scanner.Text())
  if err != nil { return }
  p.PushStack(int64(a))
}

func (p *Piet) InChar() {
  var b []byte = make([]byte, 1)
  os.Stdin.Read(b)
  p.PushStack(int64(b[0]))
}

func (p *Piet) OutNumber() {
  a, ok1 := p.PopStack()
  if ok1 {
    fmt.Print(a)
    p.output += fmt.Sprintf("%d",a)
  }
}

func (p *Piet) OutChar() {
  a, ok1 := p.PopStack()
  if ok1 {
    fmt.Print(string(a))
    p.output += string(a)
  }
}<|endoftext|>


<commit_before>// Code generated by protoc-gen-go.
// source: game.proto
// DO NOT EDIT!

/*
Package proto is a generated protocol buffer package.

It is generated from these files:
	game.proto

It has these top-level messages:
	Game
*/
package proto

import proto1 "github.com/golang/protobuf/proto"

import (
	context "golang.org/x/net/context"
	grpc "google.golang.org/grpc"
)

// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto1.Marshal

type Game_FrameType int32

const (
	Game_Message    Game_FrameType = 0
	Game_Register   Game_FrameType = 1
	Game_Unregister Game_FrameType = 2
	Game_Kick       Game_FrameType = 3
	Game_Ping       Game_FrameType = 4
)

var Game_FrameType_name = map[int32]string{
	0: "Message",
	1: "Register",
	2: "Unregister",
	3: "Kick",
	4: "Ping",
}
var Game_FrameType_value = map[string]int32{
	"Message":    0,
	"Register":   1,
	"Unregister": 2,
	"Kick":       3,
	"Ping":       4,
}

func (x Game_FrameType) String() string {
	return proto1.EnumName(Game_FrameType_name, int32(x))
}

type Game struct {
}

func (m *Game) Reset()         { *m = Game{} }
func (m *Game) String() string { return proto1.CompactTextString(m) }
func (*Game) ProtoMessage()    {}

type Game_Frame struct {
	Type    Game_FrameType `protobuf:"varint,1,opt,enum=proto.Game_FrameType" json:"Type,omitempty"`
	Message []byte         `protobuf:"bytes,2,opt,proto3" json:"Message,omitempty"`
	UserId  int32          `protobuf:"varint,3,opt" json:"UserId,omitempty"`
}

func (m *Game_Frame) Reset()         { *m = Game_Frame{} }
func (m *Game_Frame) String() string { return proto1.CompactTextString(m) }
func (*Game_Frame) ProtoMessage()    {}

func init() {
	proto1.RegisterEnum("proto.Game_FrameType", Game_FrameType_name, Game_FrameType_value)
}

// Client API for GameService service

type GameServiceClient interface {
	Stream(ctx context.Context, opts ...grpc.CallOption) (GameService_StreamClient, error)
}

type gameServiceClient struct {
	cc *grpc.ClientConn
}

func NewGameServiceClient(cc *grpc.ClientConn) GameServiceClient {
	return &gameServiceClient{cc}
}

func (c *gameServiceClient) Stream(ctx context.Context, opts ...grpc.CallOption) (GameService_StreamClient, error) {
	stream, err := grpc.NewClientStream(ctx, &_GameService_serviceDesc.Streams[0], c.cc, "/proto.GameService/Stream", opts...)
	if err != nil {
		return nil, err
	}
	x := &gameServiceStreamClient{stream}
	return x, nil
}

type GameService_StreamClient interface {
	Send(*Game_Frame) error
	Recv() (*Game_Frame, error)
	grpc.ClientStream
}

type gameServiceStreamClient struct {
	grpc.ClientStream
}

func (x *gameServiceStreamClient) Send(m *Game_Frame) error {
	return x.ClientStream.SendMsg(m)
}

func (x *gameServiceStreamClient) Recv() (*Game_Frame, error) {
	m := new(Game_Frame)
	if err := x.ClientStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

// Server API for GameService service

type GameServiceServer interface {
	Stream(GameService_StreamServer) error
}

func RegisterGameServiceServer(s *grpc.Server, srv GameServiceServer) {
	s.RegisterService(&_GameService_serviceDesc, srv)
}

func _GameService_Stream_Handler(srv interface{}, stream grpc.ServerStream) error {
	return srv.(GameServiceServer).Stream(&gameServiceStreamServer{stream})
}

type GameService_StreamServer interface {
	Send(*Game_Frame) error
	Recv() (*Game_Frame, error)
	grpc.ServerStream
}

type gameServiceStreamServer struct {
	grpc.ServerStream
}

func (x *gameServiceStreamServer) Send(m *Game_Frame) error {
	return x.ServerStream.SendMsg(m)
}

func (x *gameServiceStreamServer) Recv() (*Game_Frame, error) {
	m := new(Game_Frame)
	if err := x.ServerStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

var _GameService_serviceDesc = grpc.ServiceDesc{
	ServiceName: "proto.GameService",
	HandlerType: (*GameServiceServer)(nil),
	Methods:     []grpc.MethodDesc{},
	Streams: []grpc.StreamDesc{
		{
			StreamName:    "Stream",
			Handler:       _GameService_Stream_Handler,
			ServerStreams: true,
			ClientStreams: true,
		},
	},
}
<commit_msg>update<commit_after>// Code generated by protoc-gen-go.
// source: game.proto
// DO NOT EDIT!

/*
Package proto is a generated protocol buffer package.

It is generated from these files:
	game.proto

It has these top-level messages:
	Game
*/
package proto

import proto1 "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"

import (
	context "golang.org/x/net/context"
	grpc "google.golang.org/grpc"
)

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto1.Marshal
var _ = fmt.Errorf
var _ = math.Inf

type Game_FrameType int32

const (
	Game_Message    Game_FrameType = 0
	Game_Register   Game_FrameType = 1
	Game_Unregister Game_FrameType = 2
	Game_Kick       Game_FrameType = 3
	Game_Ping       Game_FrameType = 4
)

var Game_FrameType_name = map[int32]string{
	0: "Message",
	1: "Register",
	2: "Unregister",
	3: "Kick",
	4: "Ping",
}
var Game_FrameType_value = map[string]int32{
	"Message":    0,
	"Register":   1,
	"Unregister": 2,
	"Kick":       3,
	"Ping":       4,
}

func (x Game_FrameType) String() string {
	return proto1.EnumName(Game_FrameType_name, int32(x))
}

type Game struct {
}

func (m *Game) Reset()         { *m = Game{} }
func (m *Game) String() string { return proto1.CompactTextString(m) }
func (*Game) ProtoMessage()    {}

type Game_Frame struct {
	Type    Game_FrameType `protobuf:"varint,1,opt,name=Type,enum=proto.Game_FrameType" json:"Type,omitempty"`
	Message []byte         `protobuf:"bytes,2,opt,name=Message,proto3" json:"Message,omitempty"`
	UserId  int32          `protobuf:"varint,3,opt,name=UserId" json:"UserId,omitempty"`
}

func (m *Game_Frame) Reset()         { *m = Game_Frame{} }
func (m *Game_Frame) String() string { return proto1.CompactTextString(m) }
func (*Game_Frame) ProtoMessage()    {}

func init() {
	proto1.RegisterEnum("proto.Game_FrameType", Game_FrameType_name, Game_FrameType_value)
}

// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn

// Client API for GameService service

type GameServiceClient interface {
	Stream(ctx context.Context, opts ...grpc.CallOption) (GameService_StreamClient, error)
}

type gameServiceClient struct {
	cc *grpc.ClientConn
}

func NewGameServiceClient(cc *grpc.ClientConn) GameServiceClient {
	return &gameServiceClient{cc}
}

func (c *gameServiceClient) Stream(ctx context.Context, opts ...grpc.CallOption) (GameService_StreamClient, error) {
	stream, err := grpc.NewClientStream(ctx, &_GameService_serviceDesc.Streams[0], c.cc, "/proto.GameService/Stream", opts...)
	if err != nil {
		return nil, err
	}
	x := &gameServiceStreamClient{stream}
	return x, nil
}

type GameService_StreamClient interface {
	Send(*Game_Frame) error
	Recv() (*Game_Frame, error)
	grpc.ClientStream
}

type gameServiceStreamClient struct {
	grpc.ClientStream
}

func (x *gameServiceStreamClient) Send(m *Game_Frame) error {
	return x.ClientStream.SendMsg(m)
}

func (x *gameServiceStreamClient) Recv() (*Game_Frame, error) {
	m := new(Game_Frame)
	if err := x.ClientStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

// Server API for GameService service

type GameServiceServer interface {
	Stream(GameService_StreamServer) error
}

func RegisterGameServiceServer(s *grpc.Server, srv GameServiceServer) {
	s.RegisterService(&_GameService_serviceDesc, srv)
}

func _GameService_Stream_Handler(srv interface{}, stream grpc.ServerStream) error {
	return srv.(GameServiceServer).Stream(&gameServiceStreamServer{stream})
}

type GameService_StreamServer interface {
	Send(*Game_Frame) error
	Recv() (*Game_Frame, error)
	grpc.ServerStream
}

type gameServiceStreamServer struct {
	grpc.ServerStream
}

func (x *gameServiceStreamServer) Send(m *Game_Frame) error {
	return x.ServerStream.SendMsg(m)
}

func (x *gameServiceStreamServer) Recv() (*Game_Frame, error) {
	m := new(Game_Frame)
	if err := x.ServerStream.RecvMsg(m); err != nil {
		return nil, err
	}
	return m, nil
}

var _GameService_serviceDesc = grpc.ServiceDesc{
	ServiceName: "proto.GameService",
	HandlerType: (*GameServiceServer)(nil),
	Methods:     []grpc.MethodDesc{},
	Streams: []grpc.StreamDesc{
		{
			StreamName:    "Stream",
			Handler:       _GameService_Stream_Handler,
			ServerStreams: true,
			ClientStreams: true,
		},
	},
}
<|endoftext|>


<commit_before>package util

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"os/exec"
	"strings"

	"github.com/fatih/color"
)

// DoesCommandOuputContain runs the given command
// and returns whether its output contains the given string.
func DoesCommandOuputContain(cmd []string, value string) bool {
	return strings.Contains(GetCommandOutput(cmd...), value)
}

// DoesCommandOuputContainLine runs the given command
// and returns whether its output contains teh given string as an entire line.
func DoesCommandOuputContainLine(cmd []string, value string) bool {
	list := strings.Split(GetCommandOutput(cmd...), "\n")
	return DoesStringArrayContain(list, value)
}

// DoesStringArrayContain returns whether the given string slice
// contains the given string.
func DoesStringArrayContain(list []string, value string) bool {
	for _, element := range list {
		if element == value {
			return true
		}
	}
	return false
}

// ExitWithErrorMessage prints the given error message and terminates the application.
func ExitWithErrorMessage(messages ...string) {
	PrintError(messages...)
	os.Exit(1)
}

// GetCommandOutput runs the given command and returns its output.
func GetCommandOutput(cmd ...string) string {
	subProcess := exec.Command(cmd[0], cmd[1:]...)
	output, err := subProcess.CombinedOutput()
	if err != nil {
		log.Fatal("Command: ", strings.Join(cmd, " "), "\nOutput: "+string(output), "\nError: ", err)
	}
	return strings.TrimSpace(string(output))
}

// GetFullCommandOutput runs the given command and returns its output and error
func GetFullCommandOutput(cmd ...string) (string, error) {
	subProcess := exec.Command(cmd[0], cmd[1:]...)
	output, err := subProcess.CombinedOutput()
	return strings.TrimSpace(string(output)), err
}

var openBrowserCommands = []string{"xdg-open", "open"}
var missingOpenBrowserCommandMessages = []string{
	"Opening a browser requires 'open' on Mac or 'xdg-open' on Linux.",
	"If you would like another command to be supported,",
	"please open an issue at https://github.com/Originate/git-town/issues",
}

// GetOpenBrowserCommand returns the command to run on the console
// to open the default browser.
func GetOpenBrowserCommand() string {
	for _, command := range openBrowserCommands {
		output, err := GetFullCommandOutput("which", command)
		if err == nil && output != "" {
			return command
		}
	}
	ExitWithErrorMessage(missingOpenBrowserCommandMessages...)
	return ""
}

var inputReader = bufio.NewReader(os.Stdin)

// GetUserInput reads input from the user and returns it.
func GetUserInput() string {
	text, err := inputReader.ReadString('\n')
	if err != nil {
		log.Fatal("Error getting user input:", err)
	}
	return strings.TrimSpace(text)
}

// Indent outputs the given string with the given level of indentation
// on each line. Each level of indentation is two spaces.
func Indent(message string, level int) string {
	prefix := strings.Repeat("  ", level)
	return prefix + strings.Replace(message, "\n", "\n"+prefix, -1)
}

// Pluralize outputs the count and the word. The word is made plural
// if the count isn't one
func Pluralize(count, word string) string {
	result := count + " " + word
	if count != "1" {
		result = result + "s"
	}
	return result
}

// PrintError prints the given error message to the console.
func PrintError(messages ...string) {
	errHeaderFmt := color.New(color.Bold).Add(color.FgRed)
	errMessageFmt := color.New(color.FgRed)
	fmt.Println()
	errHeaderFmt.Println("  Error")
	for _, message := range messages {
		errMessageFmt.Println("  " + message)
	}
	fmt.Println()
}

// PrintLabelAndValue prints the label bolded and underlined
// the value indented on the next line
// followed by an empty line
func PrintLabelAndValue(label, value string) {
	labelFmt := color.New(color.Bold).Add(color.Underline)
	labelFmt.Println(label + ":")
	fmt.Println(Indent(value, 1))
	fmt.Println()
}

// RemoveStringFromSlice returns a new string slice which is the given string slice
// with the given string removed
func RemoveStringFromSlice(list []string, value string) (result []string) {
	for _, element := range list {
		if element != value {
			result = append(result, element)
		}
	}
	return
}
<commit_msg>cleanup: fix mispelling<commit_after>package util

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"os/exec"
	"strings"

	"github.com/fatih/color"
)

// DoesCommandOuputContain runs the given command
// and returns whether its output contains the given string.
func DoesCommandOuputContain(cmd []string, value string) bool {
	return strings.Contains(GetCommandOutput(cmd...), value)
}

// DoesCommandOuputContainLine runs the given command
// and returns whether its output contains the given string as an entire line.
func DoesCommandOuputContainLine(cmd []string, value string) bool {
	list := strings.Split(GetCommandOutput(cmd...), "\n")
	return DoesStringArrayContain(list, value)
}

// DoesStringArrayContain returns whether the given string slice
// contains the given string.
func DoesStringArrayContain(list []string, value string) bool {
	for _, element := range list {
		if element == value {
			return true
		}
	}
	return false
}

// ExitWithErrorMessage prints the given error message and terminates the application.
func ExitWithErrorMessage(messages ...string) {
	PrintError(messages...)
	os.Exit(1)
}

// GetCommandOutput runs the given command and returns its output.
func GetCommandOutput(cmd ...string) string {
	subProcess := exec.Command(cmd[0], cmd[1:]...)
	output, err := subProcess.CombinedOutput()
	if err != nil {
		log.Fatal("Command: ", strings.Join(cmd, " "), "\nOutput: "+string(output), "\nError: ", err)
	}
	return strings.TrimSpace(string(output))
}

// GetFullCommandOutput runs the given command and returns its output and error
func GetFullCommandOutput(cmd ...string) (string, error) {
	subProcess := exec.Command(cmd[0], cmd[1:]...)
	output, err := subProcess.CombinedOutput()
	return strings.TrimSpace(string(output)), err
}

var openBrowserCommands = []string{"xdg-open", "open"}
var missingOpenBrowserCommandMessages = []string{
	"Opening a browser requires 'open' on Mac or 'xdg-open' on Linux.",
	"If you would like another command to be supported,",
	"please open an issue at https://github.com/Originate/git-town/issues",
}

// GetOpenBrowserCommand returns the command to run on the console
// to open the default browser.
func GetOpenBrowserCommand() string {
	for _, command := range openBrowserCommands {
		output, err := GetFullCommandOutput("which", command)
		if err == nil && output != "" {
			return command
		}
	}
	ExitWithErrorMessage(missingOpenBrowserCommandMessages...)
	return ""
}

var inputReader = bufio.NewReader(os.Stdin)

// GetUserInput reads input from the user and returns it.
func GetUserInput() string {
	text, err := inputReader.ReadString('\n')
	if err != nil {
		log.Fatal("Error getting user input:", err)
	}
	return strings.TrimSpace(text)
}

// Indent outputs the given string with the given level of indentation
// on each line. Each level of indentation is two spaces.
func Indent(message string, level int) string {
	prefix := strings.Repeat("  ", level)
	return prefix + strings.Replace(message, "\n", "\n"+prefix, -1)
}

// Pluralize outputs the count and the word. The word is made plural
// if the count isn't one
func Pluralize(count, word string) string {
	result := count + " " + word
	if count != "1" {
		result = result + "s"
	}
	return result
}

// PrintError prints the given error message to the console.
func PrintError(messages ...string) {
	errHeaderFmt := color.New(color.Bold).Add(color.FgRed)
	errMessageFmt := color.New(color.FgRed)
	fmt.Println()
	errHeaderFmt.Println("  Error")
	for _, message := range messages {
		errMessageFmt.Println("  " + message)
	}
	fmt.Println()
}

// PrintLabelAndValue prints the label bolded and underlined
// the value indented on the next line
// followed by an empty line
func PrintLabelAndValue(label, value string) {
	labelFmt := color.New(color.Bold).Add(color.Underline)
	labelFmt.Println(label + ":")
	fmt.Println(Indent(value, 1))
	fmt.Println()
}

// RemoveStringFromSlice returns a new string slice which is the given string slice
// with the given string removed
func RemoveStringFromSlice(list []string, value string) (result []string) {
	for _, element := range list {
		if element != value {
			result = append(result, element)
		}
	}
	return
}
<|endoftext|>


<commit_before>package state

import (
	"labix.org/v2/mgo"
	"labix.org/v2/mgo/txn"
)

// environGlobalKey is the key for the environment, its
// settings and constraints.
const environGlobalKey = "e"

// Environment represents the state of an environment.
type Environment struct {
	st  *State
	doc environmentDoc
	annotator
}

// environmentDoc represents the internal state of the environment in MongoDB.
type environmentDoc struct {
	UUID string `bson:"_id"`
	Name string
}

// Environment returns the environment entity.
func (st *State) Environment() (*Environment, error) {
	doc := environmentDoc{}
	err := st.environments.Find(D{{"uuid", D{{"$ne", ""}}}}).One(&doc)
	if err == mgo.ErrNotFound {
		return nil, NotFoundf("environment")
	} else if err != nil {
		return nil, err
	}
	env := &Environment{
		st:  st,
		doc: doc,
	}
	env.annotator = annotator{
		globalKey: env.globalKey(),
		tag:       env.Tag(),
		st:        st,
	}
	return env, nil
}

// Tag returns a name identifying the environment.
// The returned name will be different from other Tag values returned
// by any other entities from the same state.
func (e Environment) Tag() string {
	return "environment-" + e.doc.Name
}

// UUID returns the universally unique identifier of the environment.
func (e Environment) UUID() string {
	return e.doc.UUID
}

// globalKey returns the global database key for the environment.
func (e *Environment) globalKey() string {
	return environGlobalKey
}

// createEnvironmentOp returns the operation needed to create
// an environment document with the given name and UUID.
func createEnvironmentOp(st *State, name, uuid string) txn.Op {
	doc := &environmentDoc{
		UUID: uuid,
		Name: name,
	}
	return txn.Op{
		C:      st.environments.Name,
		Id:     uuid,
		Assert: txn.DocMissing,
		Insert: doc,
	}
}
<commit_msg>environment: another review change<commit_after>package state

import (
	"labix.org/v2/mgo"
	"labix.org/v2/mgo/txn"
)

// environGlobalKey is the key for the environment, its
// settings and constraints.
const environGlobalKey = "e"

// Environment represents the state of an environment.
type Environment struct {
	st  *State
	doc environmentDoc
	annotator
}

// environmentDoc represents the internal state of the environment in MongoDB.
type environmentDoc struct {
	UUID string `bson:"_id"`
	Name string
}

// Environment returns the environment entity.
func (st *State) Environment() (*Environment, error) {
	doc := environmentDoc{}
	err := st.environments.Find(D{{"uuid", D{{"$ne", ""}}}}).One(&doc)
	if err == mgo.ErrNotFound {
		return nil, NotFoundf("environment")
	} else if err != nil {
		return nil, err
	}
	env := &Environment{
		st:  st,
		doc: doc,
	}
	env.annotator = annotator{
		globalKey: env.globalKey(),
		tag:       env.Tag(),
		st:        st,
	}
	return env, nil
}

// Tag returns a name identifying the environment.
// The returned name will be different from other Tag values returned
// by any other entities from the same state.
func (e Environment) Tag() string {
	return "environment-" + e.doc.Name
}

// UUID returns the universally unique identifier of the environment.
func (e Environment) UUID() string {
	return e.doc.UUID
}

// globalKey returns the global database key for the environment.
func (e *Environment) globalKey() string {
	return environGlobalKey
}

// createEnvironmentOp returns the operation needed to create
// an environment document with the given name and UUID.
func createEnvironmentOp(st *State, name, uuid string) txn.Op {
	doc := &environmentDoc{uuid, name}
	return txn.Op{
		C:      st.environments.Name,
		Id:     uuid,
		Assert: txn.DocMissing,
		Insert: doc,
	}
}
<|endoftext|>


<commit_before>package state

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"strings"
	"sync"
	"time"

	"github.com/byuoitav/authmiddleware/bearertoken"
	"github.com/byuoitav/av-api/base"
	se "github.com/byuoitav/av-api/statusevaluators"
	"github.com/byuoitav/common/log"
	"github.com/byuoitav/common/v2/events"
	"github.com/fatih/color"
)

//TIMEOUT is the duration constant to wait before timing out.
const TIMEOUT = 5

// const LOCAL_CHECK_INDEX = 21
// const GATEWAY_CHECK_INDEX = 5

//builds a Status object corresponding to a device and writes it to the channel
func issueCommands(commands []se.StatusCommand, channel chan []se.StatusResponse, control *sync.WaitGroup) {
	//final output
	outputs := []se.StatusResponse{}

	//iterate over list of StatusCommands
	//TODO:make sure devices can handle rapid-fire API requests
	for _, command := range commands {

		log.L.Infof("[state] issuing command: %s against device %s, destination device: %s, parameters: %v", command.Action.ID, command.Device.ID, command.DestinationDevice.Device.ID, command.Parameters)

		output := se.StatusResponse{
			Callback:          command.Callback,
			Generator:         command.Generator,
			SourceDevice:      command.Device,
			DestinationDevice: command.DestinationDevice,
		}
		statusResponseMap := make(map[string]interface{})

		// build url
		url, lerr := command.Device.BuildCommandURL(command.Action.ID)
		if lerr != nil {
			msg := fmt.Sprintf("unable to build command '%s' for %s: %s", command.Action.ID, command.Device.ID, lerr.Error())
			log.L.Errorf("%s", color.HiRedString("[error] %s", msg))
			base.PublishError(msg, events.Error, command.Device.ID)
			continue
		}

		// replace params
		var gerr error
		url, gerr = ReplaceParameters(url, command.Parameters)
		if gerr != nil {
			msg := fmt.Sprintf("unable to replace parameters for command '%s' on %s: %s", command.Action.ID, command.Device.ID, gerr)
			log.L.Errorf("%s", color.HiRedString("[error] %s", msg))
			base.PublishError(msg, events.Error, command.Device.ID)
			continue
		}

		log.L.Infof("%s", color.HiBlueString("[state] sending request to %s", url))
		timeout := time.Duration(TIMEOUT * time.Second)
		client := http.Client{Timeout: timeout}
		response, gerr := client.Get(url)
		if gerr != nil {
			msg := fmt.Sprintf("unable to complete request to %s for device %s: %s", url, command.Device.Name, gerr.Error())
			log.L.Errorf("%s", color.HiRedString("[error] %s", msg))
			output.ErrorMessage = &msg //do we want to do this? why not just publish the error here?
			outputs = append(outputs, output)
			continue
		}

		defer response.Body.Close()

		body, gerr := ioutil.ReadAll(response.Body)
		if gerr != nil {
			msg := fmt.Sprintf("unable to read response from %s for device %s: %s", url, command.Device.Name, gerr.Error())
			log.L.Errorf("%s", color.HiRedString("[error] %s", msg))
			output.ErrorMessage = &msg
			outputs = append(outputs, output)
			continue
		}

		//check to see if it returned a non 200 response, if so, we need to build the error.
		if response.StatusCode != 200 {
			msg := fmt.Sprintf("non-200 response code: %d, message: %s", response.StatusCode, string(body))
			log.L.Errorf("%s", color.HiRedString("[error] %s", msg))
			base.PublishError(msg, events.Error, command.Device.ID)
			continue
		}

		log.L.Infof("[state] microservice returned: %s for action %s against device %s", string(body), command.Action.ID, command.Device.ID, string(body))

		var status map[string]interface{}
		gerr = json.Unmarshal(body, &status)
		if gerr != nil {
			msg := fmt.Sprintf("failed to unmarshal response: %s, microservice returned: %s", command.Device.Name, string(body))
			output.ErrorMessage = &msg
			outputs = append(outputs, output)
			log.L.Errorf("%s", color.HiRedString("[error] %s", msg))
			base.PublishError(msg, events.Error, command.Device.ID)
			continue
		}

		log.L.Info("[state] copying data into output")
		for device, object := range status {
			statusResponseMap[device] = object
			//		base.Log("%s maps to %v", device, object) TODO make this visible with debugging mode
		}

		output.Status = statusResponseMap
		outputs = append(outputs, output) //add the full status response
	}

	//write output to channel
	log.L.Info("[state] writing output to channel...")
	for _, output := range outputs {
		log.L.Infof("outputs from device %v", output.SourceDevice.ID)
		for key, value := range output.Status {
			log.L.Infof("%s maps to %v", key, value)
		}
	}

	channel <- outputs
	log.L.Infof("%s", color.HiBlueString("[state] done acquiring statuses from  %s", commands[0].Device.ID))
	control.Done()
}

func processAudioDevice(device se.Status) (base.AudioDevice, error) {
	log.L.Infof("Adding audio device: %s", device.DestinationDevice.Name)
	log.L.Infof("Status map: %v", device.Status)

	var audioDevice base.AudioDevice

	muted, ok := device.Status["muted"]
	mutedBool, ok := muted.(bool)
	if ok {
		audioDevice.Muted = &mutedBool
	}

	volume, ok := device.Status["volume"]
	if ok {
		//Default unmarshals to a float 64 - so we have to coerce it to an int
		var volumeInt int
		if volFloat, ok := volume.(float64); ok {
			volumeInt = int(volFloat)
		} else {
			volumeInt, ok = volume.(int)
		}

		//volumeint should be set now
		if ok {
			audioDevice.Volume = &volumeInt
		} else {
			log.L.Errorf("%s", color.HiRedString("[error] volume type assertion failed for %v", volume))
		}
	}

	power, ok := device.Status["power"]
	powerString, ok := power.(string)
	if ok {
		audioDevice.Power = powerString
	}

	input, ok := device.Status["input"]
	inputString, ok := input.(string)
	if ok {
		audioDevice.Input = inputString
	}

	audioDevice.Name = device.DestinationDevice.Name
	return audioDevice, nil
}

func processDisplay(device se.Status) (base.Display, error) {

	log.L.Infof("Adding display: %s", device.DestinationDevice.Name)

	var display base.Display

	blanked, ok := device.Status["blanked"]
	blankedBool, ok := blanked.(bool)
	if ok {
		display.Blanked = &blankedBool
	}

	power, ok := device.Status["power"]
	powerString, ok := power.(string)
	if ok {
		display.Power = powerString
	}

	input, ok := device.Status["input"]
	inputString, ok := input.(string)
	if ok {
		display.Input = inputString
	}

	display.Name = device.DestinationDevice.Name

	return display, nil
}

//ExecuteCommand makes a GET request given a microservice and endpoint and publishes the results
//returns the state the microservice reports or nothing if the microservice doesn't respond
//publishes a state event or an error
//@pre the parameters have been filled, e.g. the endpoint does not contain ":"
func ExecuteCommand(action base.ActionStructure, url, requestor string) se.StatusResponse {
	client := &http.Client{
		Timeout: TIMEOUT * time.Second,
	}

	log.L.Infof("%s", color.HiBlueString("[state] sending request to %s...", url))

	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		msg := err.Error()
		return se.StatusResponse{ErrorMessage: &msg}
	}

	if len(os.Getenv("ROOM_SYSTEM")) == 0 {
		//TODO: do new auth stuff .
		token, err := bearertoken.GetToken()
		if err != nil {
			return se.StatusResponse{}
		}
		req.Header.Set("Authorization", "Bearer "+token.Token)
	}

	resp, err := client.Do(req)
	if err != nil { //record any errors
		msg := fmt.Sprintf("error sending request: %s", err.Error())
		log.L.Errorf("%s", color.HiRedString("[error] %s", msg))
		PublishError(msg, action, requestor)
		return se.StatusResponse{ErrorMessage: &msg}
	}

	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK { //check the response code, if non-200, we need to record and report

		log.L.Errorf("%s", color.HiRedString("[error] non-200 response code: %v", resp.StatusCode))

		b, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			log.L.Errorf("%s", color.HiRedString("[error] problem reading the response: %s", err.Error()))
		}

		log.L.Errorf("%s", color.HiRedString("[error] microservice returned: %s for action %s against device %s.", b, action.Action, action.Device.Name))
		PublishError(fmt.Sprintf("%s", b), action, requestor)

		return se.StatusResponse{}

	}

	//TODO: we need to find some way to check against the correct response value, just as a further validation
	for _, event := range action.EventLog {
		base.SendEvent(event)
	}

	log.L.Infof("%s", color.HiGreenString("[state] sent command %s to device %s.", action.Action, action.Device.Name))
	status := make(map[string]interface{})
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		errorString := fmt.Sprintf("could not read response body: %s", err.Error())
		PublishError(errorString, action, requestor)
	}

	err = json.Unmarshal(body, &status)
	if err != nil {
		message := fmt.Sprintf("could not unmarshal response struct: %s", err.Error())
		PublishError(message, action, requestor)
	}
	response := se.StatusResponse{
		SourceDevice:      action.Device,
		DestinationDevice: action.DestinationDevice,
		Generator:         SET_STATE_STATUS_EVALUATORS[action.GeneratingEvaluator],
		Status:            status,
		Callback:          action.Callback,
	}

	return response

}

/*
ReplaceIPAddressEndpoint is a simple helper
*/
func ReplaceIPAddressEndpoint(path string, address string) string {
	//magic strings
	toReplace := ":address"

	return strings.Replace(path, toReplace, address, -1)

}

//ReplaceParameters replaces parameters in the command endpoint
//@pre the endpoint's IP parameter has already been replaced
//@post the endpoint does not contain ':'
func ReplaceParameters(addr string, parameters map[string]string) (string, error) {
	if parameters == nil { //should I keep this check?
		return addr, nil
	}

	u, err := url.Parse(addr)
	if err != nil {
		return addr, err
	}

	endpoint := u.Path

	for k, v := range parameters {
		toReplace := ":" + k
		if !strings.Contains(endpoint, toReplace) {
			msg := fmt.Sprintf("%s not found", toReplace)
			log.L.Errorf("%s", color.HiRedString("[error] %s", msg))
			return "", errors.New(msg)
		}

		endpoint = strings.Replace(endpoint, toReplace, v, -1)
	}

	index := strings.IndexRune(endpoint, ':')

	if index >= 0 {
		if strings.Contains(endpoint[index+1:], ":") {
			errorString := fmt.Sprintf("not enough parameters provided for command: %s", endpoint) //TODO change this setup?
			return "", errors.New(errorString)
		}
	}

	u.Path = endpoint
	return u.String(), nil
}

//PublishError creates an Event based on the error message and ActionStructure information, and then sends it to the event messaging system.
func PublishError(message string, action base.ActionStructure, requestor string) {
	log.L.Errorf("[error] publishing error: %s...", message)

	e := events.Event{
		TargetDevice: events.GenerateBasicDeviceInfo(action.Device.ID),
		AffectedRoom: events.GenerateBasicRoomInfo(action.Device.GetDeviceRoomID()),
		Key:          action.Action,
		Value:        message,
		User:         requestor,
	}

	e.AddToTags(events.Error)

	base.SendEvent(e)
}
<commit_msg>show the error<commit_after>package state

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"strings"
	"sync"
	"time"

	"github.com/byuoitav/authmiddleware/bearertoken"
	"github.com/byuoitav/av-api/base"
	se "github.com/byuoitav/av-api/statusevaluators"
	"github.com/byuoitav/common/log"
	"github.com/byuoitav/common/v2/events"
	"github.com/fatih/color"
)

//TIMEOUT is the duration constant to wait before timing out.
const TIMEOUT = 5

// const LOCAL_CHECK_INDEX = 21
// const GATEWAY_CHECK_INDEX = 5

//builds a Status object corresponding to a device and writes it to the channel
func issueCommands(commands []se.StatusCommand, channel chan []se.StatusResponse, control *sync.WaitGroup) {
	//final output
	outputs := []se.StatusResponse{}

	//iterate over list of StatusCommands
	//TODO:make sure devices can handle rapid-fire API requests
	for _, command := range commands {

		log.L.Infof("[state] issuing command: %s against device %s, destination device: %s, parameters: %v", command.Action.ID, command.Device.ID, command.DestinationDevice.Device.ID, command.Parameters)

		output := se.StatusResponse{
			Callback:          command.Callback,
			Generator:         command.Generator,
			SourceDevice:      command.Device,
			DestinationDevice: command.DestinationDevice,
		}
		statusResponseMap := make(map[string]interface{})

		// build url
		url, lerr := command.Device.BuildCommandURL(command.Action.ID)
		if lerr != nil {
			msg := fmt.Sprintf("unable to build command '%s' for %s: %s", command.Action.ID, command.Device.ID, lerr.Error())
			log.L.Errorf("%s", color.HiRedString("[error] %s", msg))
			base.PublishError(msg, events.Error, command.Device.ID)
			continue
		}

		// replace params
		var gerr error
		url, gerr = ReplaceParameters(url, command.Parameters)
		if gerr != nil {
			msg := fmt.Sprintf("unable to replace parameters for command '%s' on %s: %s", command.Action.ID, command.Device.ID, gerr)
			log.L.Errorf("%s", color.HiRedString("[error] %s", msg))
			base.PublishError(msg, events.Error, command.Device.ID)
			continue
		}

		log.L.Infof("%s", color.HiBlueString("[state] sending request to %s", url))
		timeout := time.Duration(TIMEOUT * time.Second)
		client := http.Client{Timeout: timeout}
		response, gerr := client.Get(url)
		if gerr != nil {
			msg := fmt.Sprintf("unable to complete request to %s for device %s: %s", url, command.Device.Name, gerr.Error())
			log.L.Errorf("%s", color.HiRedString("[error] %s", msg))
			output.ErrorMessage = &msg //do we want to do this? why not just publish the error here?
			outputs = append(outputs, output)
			continue
		}

		defer response.Body.Close()

		body, gerr := ioutil.ReadAll(response.Body)
		if gerr != nil {
			msg := fmt.Sprintf("unable to read response from %s for device %s: %s", url, command.Device.Name, gerr.Error())
			log.L.Errorf("%s", color.HiRedString("[error] %s", msg))
			output.ErrorMessage = &msg
			outputs = append(outputs, output)
			continue
		}

		//check to see if it returned a non 200 response, if so, we need to build the error.
		if response.StatusCode != 200 {
			msg := fmt.Sprintf("non-200 response code: %d, message: %s", response.StatusCode, string(body))
			log.L.Errorf("%s", color.HiRedString("[error] %s", msg))
			base.PublishError(msg, events.Error, command.Device.ID)
			continue
		}

		log.L.Infof("[state] microservice returned: %s for action %s against device %s", string(body), command.Action.ID, command.Device.ID, string(body))

		var status map[string]interface{}
		gerr = json.Unmarshal(body, &status)
		if gerr != nil {
			msg := fmt.Sprintf("failed to unmarshal response: %s, microservice returned: %s", command.Device.Name, string(body))
			output.ErrorMessage = &msg
			outputs = append(outputs, output)
			log.L.Errorf("%s", color.HiRedString("[error] %s", msg))
			base.PublishError(msg, events.Error, command.Device.ID)
			continue
		}

		log.L.Info("[state] copying data into output")
		for device, object := range status {
			statusResponseMap[device] = object
			//		base.Log("%s maps to %v", device, object) TODO make this visible with debugging mode
		}

		output.Status = statusResponseMap
		outputs = append(outputs, output) //add the full status response
	}

	//write output to channel
	log.L.Info("[state] writing output to channel...")
	for _, output := range outputs {
		log.L.Infof("outputs from device %v", output.SourceDevice.ID)
		for key, value := range output.Status {
			log.L.Infof("%s maps to %v", key, value)
		}
	}

	channel <- outputs
	log.L.Infof("%s", color.HiBlueString("[state] done acquiring statuses from  %s", commands[0].Device.ID))
	control.Done()
}

func processAudioDevice(device se.Status) (base.AudioDevice, error) {
	log.L.Infof("Adding audio device: %s", device.DestinationDevice.Name)
	log.L.Infof("Status map: %v", device.Status)

	var audioDevice base.AudioDevice

	muted, ok := device.Status["muted"]
	mutedBool, ok := muted.(bool)
	if ok {
		audioDevice.Muted = &mutedBool
	}

	volume, ok := device.Status["volume"]
	if ok {
		//Default unmarshals to a float 64 - so we have to coerce it to an int
		var volumeInt int
		if volFloat, ok := volume.(float64); ok {
			volumeInt = int(volFloat)
		} else {
			volumeInt, ok = volume.(int)
		}

		//volumeint should be set now
		if ok {
			audioDevice.Volume = &volumeInt
		} else {
			log.L.Errorf("%s", color.HiRedString("[error] volume type assertion failed for %v", volume))
		}
	}

	power, ok := device.Status["power"]
	powerString, ok := power.(string)
	if ok {
		audioDevice.Power = powerString
	}

	input, ok := device.Status["input"]
	inputString, ok := input.(string)
	if ok {
		audioDevice.Input = inputString
	}

	audioDevice.Name = device.DestinationDevice.Name
	return audioDevice, nil
}

func processDisplay(device se.Status) (base.Display, error) {

	log.L.Infof("Adding display: %s", device.DestinationDevice.Name)

	var display base.Display

	blanked, ok := device.Status["blanked"]
	blankedBool, ok := blanked.(bool)
	if ok {
		display.Blanked = &blankedBool
	}

	power, ok := device.Status["power"]
	powerString, ok := power.(string)
	if ok {
		display.Power = powerString
	}

	input, ok := device.Status["input"]
	inputString, ok := input.(string)
	if ok {
		display.Input = inputString
	}

	display.Name = device.DestinationDevice.Name

	return display, nil
}

//ExecuteCommand makes a GET request given a microservice and endpoint and publishes the results
//returns the state the microservice reports or nothing if the microservice doesn't respond
//publishes a state event or an error
//@pre the parameters have been filled, e.g. the endpoint does not contain ":"
func ExecuteCommand(action base.ActionStructure, url, requestor string) se.StatusResponse {
	client := &http.Client{
		Timeout: TIMEOUT * time.Second,
	}

	log.L.Infof("%s", color.HiBlueString("[state] sending request to %s...", url))

	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		msg := err.Error()
		return se.StatusResponse{ErrorMessage: &msg}
	}

	if len(os.Getenv("ROOM_SYSTEM")) == 0 {
		//TODO: do new auth stuff .
		token, err := bearertoken.GetToken()
		if err != nil {
			return se.StatusResponse{}
		}
		req.Header.Set("Authorization", "Bearer "+token.Token)
	}

	resp, err := client.Do(req)
	if err != nil { //record any errors
		msg := fmt.Sprintf("error sending request: %s", err.Error())
		log.L.Errorf("%s", color.HiRedString("[error] %s", msg))
		PublishError(msg, action, requestor)
		return se.StatusResponse{ErrorMessage: &msg}
	}

	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK { //check the response code, if non-200, we need to record and report

		log.L.Errorf("%s", color.HiRedString("[error] non-200 response code: %v", resp.StatusCode))

		b, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			log.L.Errorf("%s", color.HiRedString("[error] problem reading the response: %s", err.Error()))
		}

		log.L.Errorf("%s", color.HiRedString("[error] microservice returned: %s for action %s against device %s.", b, action.Action, action.Device.Name))
		PublishError(fmt.Sprintf("%s", b), action, requestor)

		return se.StatusResponse{}

	}

	//TODO: we need to find some way to check against the correct response value, just as a further validation
	for _, event := range action.EventLog {
		base.SendEvent(event)
	}

	log.L.Infof("%s", color.HiGreenString("[state] sent command %s to device %s.", action.Action, action.Device.Name))
	status := make(map[string]interface{})
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		errorString := fmt.Sprintf("could not read response body: %s", err.Error())
		PublishError(errorString, action, requestor)
	}

	err = json.Unmarshal(body, &status)
	if err != nil {
		message := fmt.Sprintf("could not unmarshal response struct: %s\n\nbody: %s\n", err.Error(), body)
		PublishError(message, action, requestor)
	}
	response := se.StatusResponse{
		SourceDevice:      action.Device,
		DestinationDevice: action.DestinationDevice,
		Generator:         SET_STATE_STATUS_EVALUATORS[action.GeneratingEvaluator],
		Status:            status,
		Callback:          action.Callback,
	}

	return response

}

/*
ReplaceIPAddressEndpoint is a simple helper
*/
func ReplaceIPAddressEndpoint(path string, address string) string {
	//magic strings
	toReplace := ":address"

	return strings.Replace(path, toReplace, address, -1)

}

//ReplaceParameters replaces parameters in the command endpoint
//@pre the endpoint's IP parameter has already been replaced
//@post the endpoint does not contain ':'
func ReplaceParameters(addr string, parameters map[string]string) (string, error) {
	if parameters == nil { //should I keep this check?
		return addr, nil
	}

	u, err := url.Parse(addr)
	if err != nil {
		return addr, err
	}

	endpoint := u.Path

	for k, v := range parameters {
		toReplace := ":" + k
		if !strings.Contains(endpoint, toReplace) {
			msg := fmt.Sprintf("%s not found", toReplace)
			log.L.Errorf("%s", color.HiRedString("[error] %s", msg))
			return "", errors.New(msg)
		}

		endpoint = strings.Replace(endpoint, toReplace, v, -1)
	}

	index := strings.IndexRune(endpoint, ':')

	if index >= 0 {
		if strings.Contains(endpoint[index+1:], ":") {
			errorString := fmt.Sprintf("not enough parameters provided for command: %s", endpoint) //TODO change this setup?
			return "", errors.New(errorString)
		}
	}

	u.Path = endpoint
	return u.String(), nil
}

//PublishError creates an Event based on the error message and ActionStructure information, and then sends it to the event messaging system.
func PublishError(message string, action base.ActionStructure, requestor string) {
	log.L.Errorf("[error] publishing error: %s...", message)

	e := events.Event{
		TargetDevice: events.GenerateBasicDeviceInfo(action.Device.ID),
		AffectedRoom: events.GenerateBasicRoomInfo(action.Device.GetDeviceRoomID()),
		Key:          action.Action,
		Value:        message,
		User:         requestor,
	}

	e.AddToTags(events.Error)

	base.SendEvent(e)
}
<|endoftext|>


<commit_before>// +build windows

package clt

import (
	"bytes"
	"fmt"
)

// Color represents a ANSI-coded color style for text
type Color struct {
	before int
	after  int
}

// Codes returns ANSI styling values for a color
func (c Color) Codes() (int, int) { return c.before, c.after }

// Textstyle represents a ANSI-coded text style
type Textstyle struct {
	before int
	after  int
}

// Codes returns ANSI styling values for a textstyle
func (t Textstyle) Codes() (int, int) { return t.before, t.after }

// Styler is an interface that is fulfilled by either a Color
// or Textstyle to be applied to a string
type Styler interface {
	Codes() (int, int)
}

// Style represents a computed style from one or more colors or textstyles
// as the ANSI code suitable for terminal output
type Style struct {
	before string
	after  string
}

// ApplyTo applies styles created using the Styled command to a string
// to generate an styled output using ANSI terminal codes
func (s *Style) ApplyTo(content string) string {
	var out bytes.Buffer
	out.WriteString(s.before)
	out.WriteString(content)
	out.WriteString(s.after)
	return out.String()
}

var (
	// Colors
	Black   = Color{30, 39}
	Red     = Color{31, 39}
	Green   = Color{32, 39}
	Yellow  = Color{33, 39}
	Blue    = Color{34, 39}
	Magenta = Color{35, 39}
	Cyan    = Color{36, 39}
	White   = Color{37, 39}
	Default = Color{39, 39}

	// Shortcut Colors
	K   = Color{30, 39}
	R   = Color{31, 39}
	G   = Color{32, 39}
	Y   = Color{33, 39}
	B   = Color{34, 39}
	M   = Color{35, 39}
	C   = Color{36, 39}
	W   = Color{37, 39}
	Def = Color{39, 39}

	// Textstyles
	Bold      = Textstyle{1, 22}
	Italic    = Textstyle{3, 23}
	Underline = Textstyle{4, 24}
)

// Background returns a style that sets the background to the appropriate color
func Background(c Color) Color {
	c.before += 10
	c.after += 10
	return c
}

// Styled contructs a composite style from one of more color or textstyle values.  Styles
// can be applied to a string via ApplyTo or as a shortcut use SStyled which returns a string directly
// Example:  Styled(White, Underline)
func Styled(s ...Styler) *Style {
	switch {
	case len(s) == 1:
		bef, aft := s[0].Codes()
		var computedStyle Style
		computedStyle.before = fmt.Sprintf("", bef)
		computedStyle.after = fmt.Sprintf("", aft)
		return &computedStyle
	case len(s) > 1:
		var computedStyle Style
		var beforeConcat, afterConcat bytes.Buffer

		beforeConcat.WriteString("")
		afterConcat.WriteString("")

		var bef, aft int
		for idx, sty := range s {
			bef, aft = sty.Codes()
			if idx < len(s)-1 {
				beforeConcat.WriteString(fmt.Sprintf("", bef))
				afterConcat.WriteString(fmt.Sprintf("", aft))
			} else {
				beforeConcat.WriteString(fmt.Sprintf("", bef))
				afterConcat.WriteString(fmt.Sprintf("", aft))
			}
		}
		computedStyle.before = beforeConcat.String()
		computedStyle.after = afterConcat.String()
		return &computedStyle
	}
	return &Style{}
}

// SStyled is a shorter version of Styled(s...).ApplyTo(content)
func SStyled(content string, s ...Styler) string {
	return Styled(s...).ApplyTo(content)
}
<commit_msg>remove all formatting codes for windows<commit_after>// +build windows

package clt

import (
	"bytes"
)

// Color represents a ANSI-coded color style for text
type Color struct {
	before int
	after  int
}

// Codes returns ANSI styling values for a color
func (c Color) Codes() (int, int) { return c.before, c.after }

// Textstyle represents a ANSI-coded text style
type Textstyle struct {
	before int
	after  int
}

// Codes returns ANSI styling values for a textstyle
func (t Textstyle) Codes() (int, int) { return t.before, t.after }

// Styler is an interface that is fulfilled by either a Color
// or Textstyle to be applied to a string
type Styler interface {
	Codes() (int, int)
}

// Style represents a computed style from one or more colors or textstyles
// as the ANSI code suitable for terminal output
type Style struct {
	before string
	after  string
}

// ApplyTo applies styles created using the Styled command to a string
// to generate an styled output using ANSI terminal codes
func (s *Style) ApplyTo(content string) string {
	var out bytes.Buffer
	out.WriteString(s.before)
	out.WriteString(content)
	out.WriteString(s.after)
	return out.String()
}

var (
	// Colors
	Black   = Color{30, 39}
	Red     = Color{31, 39}
	Green   = Color{32, 39}
	Yellow  = Color{33, 39}
	Blue    = Color{34, 39}
	Magenta = Color{35, 39}
	Cyan    = Color{36, 39}
	White   = Color{37, 39}
	Default = Color{39, 39}

	// Shortcut Colors
	K   = Color{30, 39}
	R   = Color{31, 39}
	G   = Color{32, 39}
	Y   = Color{33, 39}
	B   = Color{34, 39}
	M   = Color{35, 39}
	C   = Color{36, 39}
	W   = Color{37, 39}
	Def = Color{39, 39}

	// Textstyles
	Bold      = Textstyle{1, 22}
	Italic    = Textstyle{3, 23}
	Underline = Textstyle{4, 24}
)

// Background returns a style that sets the background to the appropriate color
func Background(c Color) Color {
	c.before += 10
	c.after += 10
	return c
}

// Styled contructs a composite style from one of more color or textstyle values.  Styles
// can be applied to a string via ApplyTo or as a shortcut use SStyled which returns a string directly
// Example:  Styled(White, Underline)
func Styled(s ...Styler) *Style {
	switch {
	case len(s) == 1:
		bef, aft := s[0].Codes()
		var computedStyle Style
		computedStyle.before = ""
		computedStyle.after = ""
		return &computedStyle
	case len(s) > 1:
		var computedStyle Style
		var beforeConcat, afterConcat bytes.Buffer

		beforeConcat.WriteString("")
		afterConcat.WriteString("")

		var bef, aft int
		for idx, sty := range s {
			bef, aft = sty.Codes()
			if idx < len(s)-1 {
				beforeConcat.WriteString("")
				afterConcat.WriteString("")
			} else {
				beforeConcat.WriteString("")
				afterConcat.WriteString("")
			}
		}
		computedStyle.before = beforeConcat.String()
		computedStyle.after = afterConcat.String()
		return &computedStyle
	}
	return &Style{}
}

// SStyled is a shorter version of Styled(s...).ApplyTo(content)
func SStyled(content string, s ...Styler) string {
	return Styled(s...).ApplyTo(content)
}
<|endoftext|>


<commit_before>package syntax

import (
	"regexp"
	"unicode/utf8"

	"github.com/kybin/tor/cell"
	term "github.com/nsf/termbox-go"
)

var Languages = make(map[string]*Language)

func init() {
	def := NewLanguage()
	def.AddSyntax(Syntax{"trailing spaces", regexp.MustCompile(`^(?m)[ \t]+$`), Color{term.ColorBlack, term.ColorYellow}})
	Languages[""] = def

	golang := NewLanguage()
	golang.AddSyntax(Syntax{"string", regexp.MustCompile(`^(?m)".*?(?:[^\\]?"|$)`), Color{term.ColorRed, term.ColorBlack}})
	golang.AddSyntax(Syntax{"raw string", regexp.MustCompile(`^(?s)` + "`" + `.*?` + "(?:`|$)"), Color{term.ColorRed, term.ColorBlack}})
	golang.AddSyntax(Syntax{"rune", regexp.MustCompile(`^(?m)'.*?(?:[^\\]?'|$)`), Color{term.ColorYellow, term.ColorBlack}})
	golang.AddSyntax(Syntax{"comment", regexp.MustCompile(`^(?m)//.*`), Color{term.ColorMagenta, term.ColorBlack}})
	golang.AddSyntax(Syntax{"multi line comment", regexp.MustCompile(`^(?s)/[*].*?(?:[*]/|$)`), Color{term.ColorMagenta, term.ColorBlack}})
	golang.AddSyntax(Syntax{"trailing spaces", regexp.MustCompile(`^(?m)[ \t]+$`), Color{term.ColorBlack, term.ColorYellow}})
	golang.AddSyntax(Syntax{"package", regexp.MustCompile(`^package\s`), Color{term.ColorYellow, term.ColorBlack}})
	Languages["go"] = golang

	py := NewLanguage()
	py.AddSyntax(Syntax{"multi line string1", regexp.MustCompile(`^(?s)""".*?(?:"""|$)`), Color{term.ColorRed, term.ColorBlack}})
	py.AddSyntax(Syntax{"multi line string2", regexp.MustCompile(`^(?s)'''.*?(?:'''|$)`), Color{term.ColorYellow, term.ColorBlack}})
	py.AddSyntax(Syntax{"string1", regexp.MustCompile(`^(?m)".*?(?:[^\\]?"|$)`), Color{term.ColorRed, term.ColorBlack}})
	py.AddSyntax(Syntax{"string2", regexp.MustCompile(`^(?m)'.*?(?:[^\\]?'|$)`), Color{term.ColorYellow, term.ColorBlack}})
	py.AddSyntax(Syntax{"comment", regexp.MustCompile(`^(?m)#.*`), Color{term.ColorMagenta, term.ColorBlack}})
	py.AddSyntax(Syntax{"trailing spaces", regexp.MustCompile(`^(?m)[ \t]+$`), Color{term.ColorBlack, term.ColorYellow}})
	Languages["py"] = py

	ts := NewLanguage()
	ts.AddSyntax(Syntax{"raw string", regexp.MustCompile(`^(?s)` + "`" + `.*?` + "(?:`|$)"), Color{term.ColorRed, term.ColorBlack}})
	ts.AddSyntax(Syntax{"string1", regexp.MustCompile(`^(?m)".*?(?:[^\\]?"|$)`), Color{term.ColorRed, term.ColorBlack}})
	ts.AddSyntax(Syntax{"string2", regexp.MustCompile(`^(?m)'.*?(?:[^\\]?'|$)`), Color{term.ColorYellow, term.ColorBlack}})
	ts.AddSyntax(Syntax{"comment", regexp.MustCompile(`^(?m)//.*`), Color{term.ColorMagenta, term.ColorBlack}})
	ts.AddSyntax(Syntax{"trailing spaces", regexp.MustCompile(`^(?m)[ \t]+$`), Color{term.ColorBlack, term.ColorYellow}})
	ts.AddSyntax(Syntax{"import", regexp.MustCompile(`^import\s`), Color{term.ColorYellow, term.ColorBlack}})
	ts.AddSyntax(Syntax{"function", regexp.MustCompile(`^function\s`), Color{term.ColorYellow, term.ColorBlack}})
	ts.AddSyntax(Syntax{"let", regexp.MustCompile(`^let\s`), Color{term.ColorYellow, term.ColorBlack}})
	Languages["ts"] = ts
}

// Byter could converted to []bytes.
type Byter interface {
	Bytes() []byte
}

// Parser is syntax parser.
type Parser struct {
	text        Byter
	textChanged bool
	lang        *Language
	Matches     []Match

	nextStart cell.Pt // next parse starting point, exclusive.
}

// NewParser creates a new Parser.
func NewParser(text Byter, langName string) *Parser {
	p := &Parser{}
	lang, ok := Languages[langName]
	if ok {
		p.lang = lang
	} else {
		p.lang = Languages[""]
	}
	p.SetText(text)
	return p
}

// SetText set it's text.
// After done this, first ParseTo will clear current matches
// and calculate matches from start.
func (p *Parser) SetText(text Byter) {
	p.text = text
	p.textChanged = true
}

// ParseTo calculates it's matches to pt.
// If a match started but not ended when reached to pt,
// it will continue parsing to the match's end.
func (p *Parser) ParseTo(pt cell.Pt) {
	if p.textChanged {
		p.nextStart = cell.Pt{0, 0}
		p.Matches = []Match{}
		p.textChanged = false
	}

	// move cursor to start position.
	c := NewCursor(p.text.Bytes())
	for c.Pos().Compare(p.nextStart) < 0 {
		ok := c.Advance()
		if !ok {
			// already end of text. nothing to do.
			return
		}
	}

	matches := []Match{}
Loop:
	for {
		if c.Pos().Compare(pt) >= 0 {
			break
		}
		for _, syn := range p.lang.syntaxes {
			ms := syn.Re.FindSubmatch(c.Remain())
			if ms == nil {
				continue
			}
			m := ms[0]
			if len(ms) == 2 {
				// if the match has subgroup, use a first one.
				m = ms[1]
			}
			if string(m) == "" {
				continue
			}
			start := c.Pos()
			c.Skip(len(m))
			end := c.Pos()
			matches = append(matches, syn.NewMatch(start, end))
			continue Loop
		}
		if !c.Advance() {
			break
		}
	}
	p.Matches = append(p.Matches, matches...)
	p.nextStart = cell.Pt{0, 0}
	if len(p.Matches) != 0 {
		p.nextStart = p.Matches[len(p.Matches)-1].Range.Max()
	}
}

// ClearFrom clears it's match from pt.
// If there is an overwrap with a match,
// it will clear that match too.
func (p *Parser) ClearFrom(pt cell.Pt) {
	clip := 0
	for i, m := range p.Matches {
		if m.Range.Max().Compare(pt) < 0 {
			continue
		}
		clip = i
		break
	}
	if clip == 0 {
		p.nextStart = cell.Pt{0, 0}
		p.Matches = []Match{}
		return
	}
	p.nextStart = p.Matches[clip-1].Range.Max()
	p.Matches = p.Matches[:clip]
}

type Syntax struct {
	Name  string
	Re    *regexp.Regexp
	Color Color
}

func (s Syntax) NewMatch(start, end cell.Pt) Match {
	return Match{Name: s.Name, Range: cell.Range{start, end}, Color: s.Color}
}

type Color struct {
	Fg term.Attribute
	Bg term.Attribute
}

type Language struct {
	syntaxes []Syntax // should be ordered
}

func NewLanguage() *Language {
	return &Language{
		syntaxes: []Syntax{},
	}
}

func (l *Language) AddSyntax(s Syntax) {
	l.syntaxes = append(l.syntaxes, s)
}

type Cursor struct {
	text []byte
	b    int // byte offset
	l    int // line offset
	o    int // byte in line offset
}

func NewCursor(text []byte) *Cursor {
	return &Cursor{text: text}
}

func (c *Cursor) Pos() cell.Pt {
	return cell.Pt{c.l, c.o}
}

func (c *Cursor) Remain() []byte {
	if c.l == len(c.text) {
		return []byte("")
	}
	return c.text[c.b:]
}

func (c *Cursor) Advance() bool {
	if c.b == len(c.text) {
		return false
	}
	c.next()
	return true
}

func (c *Cursor) Skip(b int) {
	i := 0
	for i < b {
		_, size := c.next()
		i += size
	}
}

func (c *Cursor) next() (r rune, size int) {
	r, size = utf8.DecodeRune(c.Remain())
	c.b += size
	c.o += size
	if r == '\n' {
		c.l += 1
		c.o = 0
	}
	return r, size
}

type Match struct {
	Name  string
	Range cell.Range
	Color Color
}
<commit_msg>change typescript syntax a little bit<commit_after>package syntax

import (
	"regexp"
	"unicode/utf8"

	"github.com/kybin/tor/cell"
	term "github.com/nsf/termbox-go"
)

var Languages = make(map[string]*Language)

func init() {
	def := NewLanguage()
	def.AddSyntax(Syntax{"trailing spaces", regexp.MustCompile(`^(?m)[ \t]+$`), Color{term.ColorBlack, term.ColorYellow}})
	Languages[""] = def

	golang := NewLanguage()
	golang.AddSyntax(Syntax{"string", regexp.MustCompile(`^(?m)".*?(?:[^\\]?"|$)`), Color{term.ColorRed, term.ColorBlack}})
	golang.AddSyntax(Syntax{"raw string", regexp.MustCompile(`^(?s)` + "`" + `.*?` + "(?:`|$)"), Color{term.ColorRed, term.ColorBlack}})
	golang.AddSyntax(Syntax{"rune", regexp.MustCompile(`^(?m)'.*?(?:[^\\]?'|$)`), Color{term.ColorYellow, term.ColorBlack}})
	golang.AddSyntax(Syntax{"comment", regexp.MustCompile(`^(?m)//.*`), Color{term.ColorMagenta, term.ColorBlack}})
	golang.AddSyntax(Syntax{"multi line comment", regexp.MustCompile(`^(?s)/[*].*?(?:[*]/|$)`), Color{term.ColorMagenta, term.ColorBlack}})
	golang.AddSyntax(Syntax{"trailing spaces", regexp.MustCompile(`^(?m)[ \t]+$`), Color{term.ColorBlack, term.ColorYellow}})
	golang.AddSyntax(Syntax{"package", regexp.MustCompile(`^package\s`), Color{term.ColorYellow, term.ColorBlack}})
	Languages["go"] = golang

	py := NewLanguage()
	py.AddSyntax(Syntax{"multi line string1", regexp.MustCompile(`^(?s)""".*?(?:"""|$)`), Color{term.ColorRed, term.ColorBlack}})
	py.AddSyntax(Syntax{"multi line string2", regexp.MustCompile(`^(?s)'''.*?(?:'''|$)`), Color{term.ColorYellow, term.ColorBlack}})
	py.AddSyntax(Syntax{"string1", regexp.MustCompile(`^(?m)".*?(?:[^\\]?"|$)`), Color{term.ColorRed, term.ColorBlack}})
	py.AddSyntax(Syntax{"string2", regexp.MustCompile(`^(?m)'.*?(?:[^\\]?'|$)`), Color{term.ColorYellow, term.ColorBlack}})
	py.AddSyntax(Syntax{"comment", regexp.MustCompile(`^(?m)#.*`), Color{term.ColorMagenta, term.ColorBlack}})
	py.AddSyntax(Syntax{"trailing spaces", regexp.MustCompile(`^(?m)[ \t]+$`), Color{term.ColorBlack, term.ColorYellow}})
	Languages["py"] = py

	ts := NewLanguage()
	ts.AddSyntax(Syntax{"raw string", regexp.MustCompile(`^(?s)` + "`" + `.*?` + "(?:`|$)"), Color{term.ColorRed, term.ColorBlack}})
	ts.AddSyntax(Syntax{"string1", regexp.MustCompile(`^(?m)".*?(?:[^\\]?"|$)`), Color{term.ColorRed, term.ColorBlack}})
	ts.AddSyntax(Syntax{"string2", regexp.MustCompile(`^(?m)'.*?(?:[^\\]?'|$)`), Color{term.ColorYellow, term.ColorBlack}})
	ts.AddSyntax(Syntax{"comment", regexp.MustCompile(`^(?m)//.*`), Color{term.ColorMagenta, term.ColorBlack}})
	ts.AddSyntax(Syntax{"trailing spaces", regexp.MustCompile(`^(?m)[ \t]+$`), Color{term.ColorBlack, term.ColorYellow}})
	ts.AddSyntax(Syntax{"keywords", regexp.MustCompile(`^(import|export|function)\s`), Color{term.ColorYellow, term.ColorBlack}})
	Languages["ts"] = ts
}

// Byter could converted to []bytes.
type Byter interface {
	Bytes() []byte
}

// Parser is syntax parser.
type Parser struct {
	text        Byter
	textChanged bool
	lang        *Language
	Matches     []Match

	nextStart cell.Pt // next parse starting point, exclusive.
}

// NewParser creates a new Parser.
func NewParser(text Byter, langName string) *Parser {
	p := &Parser{}
	lang, ok := Languages[langName]
	if ok {
		p.lang = lang
	} else {
		p.lang = Languages[""]
	}
	p.SetText(text)
	return p
}

// SetText set it's text.
// After done this, first ParseTo will clear current matches
// and calculate matches from start.
func (p *Parser) SetText(text Byter) {
	p.text = text
	p.textChanged = true
}

// ParseTo calculates it's matches to pt.
// If a match started but not ended when reached to pt,
// it will continue parsing to the match's end.
func (p *Parser) ParseTo(pt cell.Pt) {
	if p.textChanged {
		p.nextStart = cell.Pt{0, 0}
		p.Matches = []Match{}
		p.textChanged = false
	}

	// move cursor to start position.
	c := NewCursor(p.text.Bytes())
	for c.Pos().Compare(p.nextStart) < 0 {
		ok := c.Advance()
		if !ok {
			// already end of text. nothing to do.
			return
		}
	}

	matches := []Match{}
Loop:
	for {
		if c.Pos().Compare(pt) >= 0 {
			break
		}
		for _, syn := range p.lang.syntaxes {
			ms := syn.Re.FindSubmatch(c.Remain())
			if ms == nil {
				continue
			}
			m := ms[0]
			if len(ms) == 2 {
				// if the match has subgroup, use a first one.
				m = ms[1]
			}
			if string(m) == "" {
				continue
			}
			start := c.Pos()
			c.Skip(len(m))
			end := c.Pos()
			matches = append(matches, syn.NewMatch(start, end))
			continue Loop
		}
		if !c.Advance() {
			break
		}
	}
	p.Matches = append(p.Matches, matches...)
	p.nextStart = cell.Pt{0, 0}
	if len(p.Matches) != 0 {
		p.nextStart = p.Matches[len(p.Matches)-1].Range.Max()
	}
}

// ClearFrom clears it's match from pt.
// If there is an overwrap with a match,
// it will clear that match too.
func (p *Parser) ClearFrom(pt cell.Pt) {
	clip := 0
	for i, m := range p.Matches {
		if m.Range.Max().Compare(pt) < 0 {
			continue
		}
		clip = i
		break
	}
	if clip == 0 {
		p.nextStart = cell.Pt{0, 0}
		p.Matches = []Match{}
		return
	}
	p.nextStart = p.Matches[clip-1].Range.Max()
	p.Matches = p.Matches[:clip]
}

type Syntax struct {
	Name  string
	Re    *regexp.Regexp
	Color Color
}

func (s Syntax) NewMatch(start, end cell.Pt) Match {
	return Match{Name: s.Name, Range: cell.Range{start, end}, Color: s.Color}
}

type Color struct {
	Fg term.Attribute
	Bg term.Attribute
}

type Language struct {
	syntaxes []Syntax // should be ordered
}

func NewLanguage() *Language {
	return &Language{
		syntaxes: []Syntax{},
	}
}

func (l *Language) AddSyntax(s Syntax) {
	l.syntaxes = append(l.syntaxes, s)
}

type Cursor struct {
	text []byte
	b    int // byte offset
	l    int // line offset
	o    int // byte in line offset
}

func NewCursor(text []byte) *Cursor {
	return &Cursor{text: text}
}

func (c *Cursor) Pos() cell.Pt {
	return cell.Pt{c.l, c.o}
}

func (c *Cursor) Remain() []byte {
	if c.l == len(c.text) {
		return []byte("")
	}
	return c.text[c.b:]
}

func (c *Cursor) Advance() bool {
	if c.b == len(c.text) {
		return false
	}
	c.next()
	return true
}

func (c *Cursor) Skip(b int) {
	i := 0
	for i < b {
		_, size := c.next()
		i += size
	}
}

func (c *Cursor) next() (r rune, size int) {
	r, size = utf8.DecodeRune(c.Remain())
	c.b += size
	c.o += size
	if r == '\n' {
		c.l += 1
		c.o = 0
	}
	return r, size
}

type Match struct {
	Name  string
	Range cell.Range
	Color Color
}
<|endoftext|>


<commit_before>package syntax

import "github.com/gcapizzi/moka"

type Target struct {
	double moka.Double
}

func AllowDouble(double moka.Double) AllowanceTarget {
	return Target{double: double}
}

func (t Target) To(invocation Interaction) {
	invocation.Apply(t.double)
}
<commit_msg>Target -> AllowanceTarget<commit_after>package syntax

import "github.com/gcapizzi/moka"

type AllowanceTarget struct {
	double moka.Double
}

func AllowDouble(double moka.Double) AllowanceTarget {
	return AllowanceTarget{double: double}
}

func (t AllowanceTarget) To(invocation Interaction) {
	invocation.Apply(t.double)
}
<|endoftext|>


<commit_before>package main

import (
"io/ioutil"
"fmt"
)

func ExampleRenderTemplate() {
	members := []Member{
		{
			Name: "web-1",
			Addr: "172.16.0.21",
			Port: 7946,
			Status: "alive",
			Tags: map[string]string{
				"app": "nginx",
				"webport": "8080",
			},
		},
		{
			Name: "web-2",
			Addr: "172.16.0.22",
			Port: 7946,
			Status: "alive",
			Tags: map[string]string{
				"app": "nginx",
				"webport": "8080",
			},
		},
		{
			Name: "web-3",
			Addr: "172.16.0.23",
			Port: 7946,
			Status: "alive",
			Tags: map[string]string{
				"app": "httpd",
				"webport": "80",
			},
		},

	}
	RenderTemplate("test/template_1.tpl", "test/result_1.txt", members)
	out, err := ioutil.ReadFile("test/result_1.txt")
	if err != nil {
		panic(err)
	}
	fmt.Println(string(out))
/* Output:
BEGIN
server web-1 at 172.16.0.21 with serf at 7946 and nginx at 8080
server web-2 at 172.16.0.22 with serf at 7946 and nginx at 8080
server web-3 at 172.16.0.23 with serf at 7946 and httpd at 80

END
*/
}
<commit_msg>reformat<commit_after>package main

import (
	"fmt"
	"io/ioutil"
)

func ExampleRenderTemplate() {
	members := []Member{
		{
			Name:   "web-1",
			Addr:   "172.16.0.21",
			Port:   7946,
			Status: "alive",
			Tags: map[string]string{
				"app":     "nginx",
				"webport": "8080",
			},
		},
		{
			Name:   "web-2",
			Addr:   "172.16.0.22",
			Port:   7946,
			Status: "alive",
			Tags: map[string]string{
				"app":     "nginx",
				"webport": "8080",
			},
		},
		{
			Name:   "web-3",
			Addr:   "172.16.0.23",
			Port:   7946,
			Status: "alive",
			Tags: map[string]string{
				"app":     "httpd",
				"webport": "80",
			},
		},
	}
	RenderTemplate("test/template_1.tpl", "test/result_1.txt", members)
	out, err := ioutil.ReadFile("test/result_1.txt")
	if err != nil {
		panic(err)
	}
	fmt.Println(string(out))
/*
Output:
BEGIN
server web-1 at 172.16.0.21 with serf at 7946 and nginx at 8080
server web-2 at 172.16.0.22 with serf at 7946 and nginx at 8080
server web-3 at 172.16.0.23 with serf at 7946 and httpd at 80

END
*/
}
<|endoftext|>


<commit_before>package route

import (
	"fmt"
  "net/http"
	"net/http/httptest"
  "testing"
)

var endpoints = []string{"/test/handler/1", "/test/handler/2"}

func TestRouter(t *testing.T) {
  r := new(Router)
	r.HandleFunc(endpoints[0], testHandler1)
  r.HandleFunc(endpoints[1], testHandler2)

  server := httptest.NewServer(r)
  defer server.Close()

  for _, endpoint := range endpoints {
    res, err := http.Get(server.URL+endpoint)
    if err != nil {
      t.Fatal(err)
    }

  	if res.StatusCode != http.StatusOK {
  		t.Fatal(err)
  	}
  }
}

func TestNotFoundRoute(t *testing.T) {
  r := new(Router)
  r.HandleFunc(endpoints[0], testHandler1)
  r.HandleFunc(endpoints[1], testHandler2)

  server := httptest.NewServer(r)
  defer server.Close()

  res, err := http.Get(server.URL+"/test/handler/3")
    if err != nil {
      t.Fatal(err)
    }

  	if res.StatusCode != http.StatusNotFound {
  		t.Fatal(err)
  	}
}

func testHandler1(w http.ResponseWriter, r *http.Request){
  fmt.Fprintf(w, "testHandler1 has been reached!")
}

func testHandler2(w http.ResponseWriter, r *http.Request){
  fmt.Fprintf(w, "testHandler2 has been reached!")
}
<commit_msg>add formating to router test :)<commit_after>package route

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"
)

var endpoints = []string{"/test/handler/1", "/test/handler/2"}

func TestRouter(t *testing.T) {
	r := new(Router)
	r.HandleFunc(endpoints[0], testHandler1)
	r.HandleFunc(endpoints[1], testHandler2)

	server := httptest.NewServer(r)
	defer server.Close()

	for _, endpoint := range endpoints {
		res, err := http.Get(server.URL + endpoint)
		if err != nil {
			t.Fatal(err)
		}

		if res.StatusCode != http.StatusOK {
			t.Fatal(err)
		}
	}
}

func TestNotFoundRoute(t *testing.T) {
	r := new(Router)
	r.HandleFunc(endpoints[0], testHandler1)
	r.HandleFunc(endpoints[1], testHandler2)

	server := httptest.NewServer(r)
	defer server.Close()

	res, err := http.Get(server.URL + "/test/handler/3")
	if err != nil {
		t.Fatal(err)
	}

	if res.StatusCode != http.StatusNotFound {
		t.Fatal(err)
	}
}

func testHandler1(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "testHandler1 has been reached!")
}

func testHandler2(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "testHandler2 has been reached!")
}
<|endoftext|>


<commit_before>package brctl

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"os/exec"
	"regexp"
	"strings"
)

type Bridge struct {
	Name       string
	ID         string
	STP        bool
	Interfaces []string
}

func Show() ([]Bridge, error) {
	out, err := exec.Command("brctl", "show").Output()
	if err != nil {
		return nil, err
	}

	return parseBrctlShow(bytes.NewBuffer(out))
}

func parseBrctlShowDeclLine(line string) (*Bridge, error) {
	line = strings.TrimSpace(line)
	parts := regexp.MustCompile("\\s+").Split(line, -1)
	if len(parts) != 4 && len(parts) != 3 {
		return nil, fmt.Errorf("not a valid brctl bridge declaration: '%s'", line)
	}

	b := Bridge{
		Name: parts[0],
		ID:   parts[1],
		STP:  false,
	}
	if parts[2] == "yes" {
		b.STP = true
	}
	if len(parts) == 4 {
		b.Interfaces = []string{parts[3]}
	}
	return &b, nil
}

func parseBrctlShowIntefaceLine(line string) string {
	return strings.TrimSpace(line)
}

func parseBrctlShow(reader io.Reader) ([]Bridge, error) {
	whitespace := regexp.MustCompile("^\\s+.*$")
	s := bufio.NewScanner(reader)

	// Discard header
	if !s.Scan() {
		return nil, s.Err()
	}

	// Parse bridges
	var current *Bridge
	bridges := make([]Bridge, 0)
	for i := 2; s.Scan(); i++ {
		line := s.Text()
		if len(line) == 0 {
			return nil, fmt.Errorf("line %d: unexpected empty line", i)
		}

		if whitespace.MatchString(line) {
			if current == nil {
				return nil, fmt.Errorf("line %d: no bridge declaration before interface spec", i)
			}
			current.Interfaces = append(current.Interfaces, parseBrctlShowIntefaceLine(line))
		} else {
			if current != nil {
				bridges = append(bridges, *current)
			}
			b, err := parseBrctlShowDeclLine(line)
			if err != nil {
				return nil, fmt.Errorf("line %d: %v", i, err)
			}
			current = b
		}
	}

	if current != nil {
		bridges = append(bridges, *current)
	}

	return bridges, s.Err()
}
<commit_msg>Add utility function to create bridges<commit_after>package brctl

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"os/exec"
	"regexp"
	"strings"
)

type Bridge struct {
	Name       string
	ID         string
	STP        bool
	Interfaces []string
}

func Show() ([]Bridge, error) {
	out, err := exec.Command("brctl", "show").Output()
	if err != nil {
		return nil, err
	}

	return parseBrctlShow(bytes.NewBuffer(out))
}

func Create(name string) error {
	out, err := exec.Command("brctl", "addbr", name).CombinedOutput()
	if err != nil {
		return fmt.Errorf("error: brctl addbr: %v", out)
	}
	return nil
}

func CreateNumbered(prefix string) error {
	var err error

	for i := 0; i < 5; i++ {
		bridges, err := Show()
		if err != nil {
			return err
		}

		next := 0
		for {
			name := fmt.Sprintf("%s%d", prefix, next)

			found := false
			for _, b := range bridges {
				if b.Name == name {
					found = true
					break
				}
			}

			if !found {
				break
			}

			next++
		}

		name := fmt.Sprintf("%s%d", prefix, next)
		err = Create(name)
		if err == nil {
			break
		}
	}

	return err
}

func parseBrctlShowDeclLine(line string) (*Bridge, error) {
	line = strings.TrimSpace(line)
	parts := regexp.MustCompile("\\s+").Split(line, -1)
	if len(parts) != 4 && len(parts) != 3 {
		return nil, fmt.Errorf("not a valid brctl bridge declaration: '%s'", line)
	}

	b := Bridge{
		Name: parts[0],
		ID:   parts[1],
		STP:  false,
	}
	if parts[2] == "yes" {
		b.STP = true
	}
	if len(parts) == 4 {
		b.Interfaces = []string{parts[3]}
	}
	return &b, nil
}

func parseBrctlShowIntefaceLine(line string) string {
	return strings.TrimSpace(line)
}

func parseBrctlShow(reader io.Reader) ([]Bridge, error) {
	whitespace := regexp.MustCompile("^\\s+.*$")
	s := bufio.NewScanner(reader)

	// Discard header
	if !s.Scan() {
		return nil, s.Err()
	}

	// Parse bridges
	var current *Bridge
	bridges := make([]Bridge, 0)
	for i := 2; s.Scan(); i++ {
		line := s.Text()
		if len(line) == 0 {
			return nil, fmt.Errorf("line %d: unexpected empty line", i)
		}

		if whitespace.MatchString(line) {
			if current == nil {
				return nil, fmt.Errorf("line %d: no bridge declaration before interface spec", i)
			}
			current.Interfaces = append(current.Interfaces, parseBrctlShowIntefaceLine(line))
		} else {
			if current != nil {
				bridges = append(bridges, *current)
			}
			b, err := parseBrctlShowDeclLine(line)
			if err != nil {
				return nil, fmt.Errorf("line %d: %v", i, err)
			}
			current = b
		}
	}

	if current != nil {
		bridges = append(bridges, *current)
	}

	return bridges, s.Err()
}
<|endoftext|>