<commit_before>// go-rst - A reStructuredText parser for Go
// 2014 (c) The go-rst Authors
// MIT Licensed. See LICENSE for details.

// To enable debug output when testing, use "go test -debug"

package parse

import (
	"github.com/demizer/go-elog"
	"reflect"
	"strings"
	"testing"
)

type checkNode struct {
	t          *testing.T
	testName   string
	pNodeName  string
	pFieldName string
	pFieldVal  interface{}
	pFieldType reflect.Type
	eFieldName string
	eFieldVal  interface{}
	eFieldType reflect.Type
	id         int
}

func (c *checkNode) error(args ...interface{}) {
	c.t.Error(args...)
}

func (c *checkNode) errorf(format string, args ...interface{}) {
	c.t.Errorf(format, args...)
}

func (c *checkNode) dError() {
	if c.pFieldName == "Rune" {
		c.t.Errorf("Got: %s.%s = %#v (%v) (%v) (Id: %d),\n\tExpect: %s.%s = %#v (%v)\n",
			c.pNodeName, c.pFieldName, c.pFieldVal, string(c.pFieldVal.(int32)),
			c.pFieldType, c.id, "#parse-tree", c.eFieldName, c.eFieldVal, c.eFieldType)
		return
	}
	c.t.Errorf("Got: %s.%s = %#v (%v) (Id: %d),\n\tExpect: %s.%s = %#v (%v)\n",
		c.pNodeName, c.pFieldName, c.pFieldVal, c.pFieldType, c.id, "#parse-tree",
		c.eFieldName, c.eFieldVal, c.eFieldType)
}

func (c *checkNode) updateState(eKey string, eVal interface{}, pVal reflect.Value) bool {
	// Expected parser metadata
	c.eFieldName = eKey
	c.eFieldVal = eVal
	c.eFieldType = reflect.TypeOf(c.eFieldVal)
	if eKey == "id" {
		c.id = int(eVal.(float64))
	}

	// Actual parsed metadata
	c.pNodeName = pVal.Type().Name()
	c.pFieldName = strings.ToUpper(string(c.eFieldName[0])) + c.eFieldName[1:]
	c.pFieldVal = pVal.FieldByName(c.pFieldName).Interface()
	c.pFieldType = pVal.FieldByName(c.pFieldName).Type()

	// Overline adornment nodes can be null
	if c.eFieldName == "overLine" && c.eFieldVal == nil {
		return false
	} else if c.eFieldVal == nil {
		c.dError()
		return false
	}

	return true
}

func (c *checkNode) checkFields(eNodes interface{}, pNode Node) {
	for eKey, eVal := range eNodes.(map[string]interface{}) {
		pVal := reflect.Indirect(reflect.ValueOf(pNode))
		if c.updateState(eKey, eVal, pVal) == false {
			continue
		}
		switch c.eFieldName {
		case "type":
			if c.eFieldVal != c.pFieldVal.(NodeType).String() {
				c.dError()
			}
		case "id", "level", "length":
			if c.eFieldVal != float64(c.pFieldVal.(int)) {
				c.dError()
			}
		case "line":
			if c.eFieldVal != float64(c.pFieldVal.(Line)) {
				c.dError()
			}
		case "startPosition":
			if c.eFieldVal != float64(c.pFieldVal.(StartPosition)) {
				c.dError()
			}
		case "overLine", "underLine":
			c.checkFields(c.eFieldVal, c.pFieldVal.(Node))
		case "nodeList":
			for num, node := range c.eFieldVal.([]interface{}) {
				// Store and reset the parser value, otherwise a panic will occur on
				// the next iteration
				pFieldVal := c.pFieldVal
				c.checkFields(node, c.pFieldVal.(NodeList)[num])
				c.pFieldVal = pFieldVal
			}
		case "rune":
			if c.eFieldVal != string(c.pFieldVal.(rune)) {
				c.dError()
			}
		default:
			if c.eFieldVal != c.pFieldVal {
				c.dError()
			}
		}
	}

}

func checkParseNodes(t *testing.T, eTree []interface{}, pNodes []Node, testName string) {
	state := &checkNode{t: t, testName: testName}
	for eNum, eNode := range eTree {
		state.checkFields(eNode, pNodes[eNum])
	}
	return
}

func TestSectionLevelsAdd(t *testing.T) {
	var p sectionLevels
	lvl := p.Add('=', true, 5)
	if lvl != 1 {
		t.Errorf("Improper level on first add, Got level: %d, expected: %d", lvl, 1)
	}
}

func TestSectionLevelsString(t *testing.T) {
	var p sectionLevels
	p.Add('=', true, 5)
	p.Add('-', true, 8)
	p.Add('~', false, 6)
	out := p.String()
	expect := "level: 1, rune: '=', overline: true, length: 5\nlevel: 2, rune: '-', " +
		"overline: true, length: 8\nlevel: 3, rune: '~', overline: false, length: 6\n"
	if out != expect {
		t.Errorf("String output mismatch!\nExpect:\n\n\t%q,\nGot:\n\n\t%q\n", expect, out)
	}
}

func TestSectionLevelsFind(t *testing.T) {
	var p sectionLevels
	p.Add('=', true, 5)
	p.Add('-', true, 8)
	p.Add('~', false, 6)
	lvl := p.Find('-')
	if lvl == -1 {
		t.Errorf("Level not found!\nExpect:\n\n\t%d\nGot:\n\n\t%t\n", 2, lvl)
	}
	if lvl != 2 {
		t.Errorf("Level not correct!\nExpect:\n\n\t%d\nGot:\n\n\t%d\n", 2, lvl)
	}
}

func TestSectionLevelsFindNoResult(t *testing.T) {
	var p sectionLevels
	lvl := p.Find('-')
	if lvl > 0 {
		t.Errorf("Should not find any levels!\nExpect:\n\n\t%d\nGot:\n\n\t%d\n", -1, lvl)
	}
}

func TestSectionLevelsLevelEmpty(t *testing.T) {
	var p sectionLevels
	lvl := p.Level()
	expect := 0
	if lvl != expect {
		t.Errorf("Empty sectionLevels should return \"%d\"!\nExpect:\t%d\nGot:\t%d\n",
			expect, expect, lvl)
	}

}

func TestSectionLevelsLevel(t *testing.T) {
	var p sectionLevels
	p.Add('=', true, 5)
	p.Add('-', true, 8)
	p.Add('~', false, 6)
	lvl := p.Level()
	if lvl != 3 {
		t.Errorf("Level() returned incorrect level!\nExpect:\n\n\t%d\nGot:\n\n\t%d\n", 3, lvl)
	}
}

func parseTest(t *testing.T, lexTest *LexTest) (tree *Tree) {
	var errs []error
	log.Debugf("Test Name: %s\n", lexTest.name)
	log.Debugf("Description: %s\n", lexTest.description)
	log.Debugf("Test Input:\n-----------\n%s\n----------\n", lexTest.data)
	tree, errs = Parse(lexTest.name, lexTest.data)
	if errs != nil {
		for _, err := range errs {
			t.Error(err)
		}
	}
	return
}

func TestParseSectionTitleParagraph(t *testing.T) {
	testName := "SectionTitlePara"
	test := lexTests.testByName(testName)
	pTree := parseTest(t, test)
	eNodes := test.expectJson()
	checkParseNodes(t, eNodes, *pTree.Nodes, testName)
}

func TestParseSectionTitleParaNoBlankLine(t *testing.T) {
	testName := "SectionTitleParaNoBlankLine"
	test := lexTests.testByName(testName)
	pTree := parseTest(t, test)
	eNodes := test.expectJson()
	checkParseNodes(t, eNodes, *pTree.Nodes, testName)
}

func TestParseSectionParaHeadPara(t *testing.T) {
	testName := "SectionParaHeadPara"
	test := lexTests.testByName(testName)
	pTree := parseTest(t, test)
	eNodes := test.expectJson()
	checkParseNodes(t, eNodes, *pTree.Nodes, testName)
}

func TestParseSectionLevelTest1(t *testing.T) {
	testName := "SectionLevelTest1"
	test := lexTests.testByName(testName)
	pTree := parseTest(t, test)
	// spd.Dump(pTree)
	eNodes := test.expectJson()
	checkParseNodes(t, eNodes, *pTree.Nodes, testName)
}

func TestParseSectionUnexpectedTitles(t *testing.T) {
	testName := "SectionUnexpectedTitles"
	test := lexTests.testByName(testName)
	pTree := parseTest(t, test)
	eNodes := test.expectJson()
	checkParseNodes(t, eNodes, *pTree.Nodes, testName)
}
<commit_msg>parse_test.go: Fix improperly set checkNode.id<commit_after>// go-rst - A reStructuredText parser for Go
// 2014 (c) The go-rst Authors
// MIT Licensed. See LICENSE for details.

// To enable debug output when testing, use "go test -debug"

package parse

import (
	"github.com/demizer/go-elog"
	"reflect"
	"strings"
	"testing"
)

type checkNode struct {
	t          *testing.T
	testName   string
	pNodeName  string
	pFieldName string
	pFieldVal  interface{}
	pFieldType reflect.Type
	eFieldName string
	eFieldVal  interface{}
	eFieldType reflect.Type
	id         int
}

func (c *checkNode) error(args ...interface{}) {
	c.t.Error(args...)
}

func (c *checkNode) errorf(format string, args ...interface{}) {
	c.t.Errorf(format, args...)
}

func (c *checkNode) dError() {
	if c.pFieldName == "Rune" {
		c.t.Errorf("Got: %s.%s = %#v (%v) (%v) (Id: %d),\n\tExpect: %s.%s = %#v (%v)\n",
			c.pNodeName, c.pFieldName, c.pFieldVal, string(c.pFieldVal.(int32)),
			c.pFieldType, c.id, "#parse-tree", c.eFieldName, c.eFieldVal, c.eFieldType)
		return
	}
	c.t.Errorf("Got: %s.%s = %#v (%v) (Id: %d),\n\tExpect: %s.%s = %#v (%v)\n",
		c.pNodeName, c.pFieldName, c.pFieldVal, c.pFieldType, c.id, "#parse-tree",
		c.eFieldName, c.eFieldVal, c.eFieldType)
}

func (c *checkNode) updateState(eKey string, eVal interface{}, pVal reflect.Value) bool {
	// Expected parser metadata
	c.eFieldName = eKey
	c.eFieldVal = eVal
	c.eFieldType = reflect.TypeOf(c.eFieldVal)

	// Actual parsed metadata
	c.pNodeName = pVal.Type().Name()
	c.pFieldName = strings.ToUpper(string(c.eFieldName[0])) + c.eFieldName[1:]
	c.pFieldVal = pVal.FieldByName(c.pFieldName).Interface()
	c.pFieldType = pVal.FieldByName(c.pFieldName).Type()

	// Overline adornment nodes can be null
	if c.eFieldName == "overLine" && c.eFieldVal == nil {
		return false
	} else if c.eFieldVal == nil {
		c.dError()
		return false
	}

	return true
}

func (c *checkNode) checkFields(eNodes interface{}, pNode Node) {
	c.id = int(eNodes.(map[string]interface{})["id"].(float64))
	for eKey, eVal := range eNodes.(map[string]interface{}) {
		pVal := reflect.Indirect(reflect.ValueOf(pNode))
		if c.updateState(eKey, eVal, pVal) == false {
			continue
		}
		switch c.eFieldName {
		case "type":
			if c.eFieldVal != c.pFieldVal.(NodeType).String() {
				c.dError()
			}
		case "id", "level", "length":
			if c.eFieldVal != float64(c.pFieldVal.(int)) {
				c.dError()
			}
		case "line":
			if c.eFieldVal != float64(c.pFieldVal.(Line)) {
				c.dError()
			}
		case "startPosition":
			if c.eFieldVal != float64(c.pFieldVal.(StartPosition)) {
				c.dError()
			}
		case "overLine", "underLine":
			c.checkFields(c.eFieldVal, c.pFieldVal.(Node))
		case "nodeList":
			for num, node := range c.eFieldVal.([]interface{}) {
				// Store and reset the parser value, otherwise a panic will occur on
				// the next iteration
				pFieldVal := c.pFieldVal
				c.checkFields(node, c.pFieldVal.(NodeList)[num])
				c.pFieldVal = pFieldVal
			}
		case "rune":
			if c.eFieldVal != string(c.pFieldVal.(rune)) {
				c.dError()
			}
		default:
			if c.eFieldVal != c.pFieldVal {
				c.dError()
			}
		}
	}

}

func checkParseNodes(t *testing.T, eTree []interface{}, pNodes []Node, testName string) {
	state := &checkNode{t: t, testName: testName}
	for eNum, eNode := range eTree {
		state.checkFields(eNode, pNodes[eNum])
	}
	return
}

func TestSectionLevelsAdd(t *testing.T) {
	var p sectionLevels
	lvl := p.Add('=', true, 5)
	if lvl != 1 {
		t.Errorf("Improper level on first add, Got level: %d, expected: %d", lvl, 1)
	}
}

func TestSectionLevelsString(t *testing.T) {
	var p sectionLevels
	p.Add('=', true, 5)
	p.Add('-', true, 8)
	p.Add('~', false, 6)
	out := p.String()
	expect := "level: 1, rune: '=', overline: true, length: 5\nlevel: 2, rune: '-', " +
		"overline: true, length: 8\nlevel: 3, rune: '~', overline: false, length: 6\n"
	if out != expect {
		t.Errorf("String output mismatch!\nExpect:\n\n\t%q,\nGot:\n\n\t%q\n", expect, out)
	}
}

func TestSectionLevelsFind(t *testing.T) {
	var p sectionLevels
	p.Add('=', true, 5)
	p.Add('-', true, 8)
	p.Add('~', false, 6)
	lvl := p.Find('-')
	if lvl == -1 {
		t.Errorf("Level not found!\nExpect:\n\n\t%d\nGot:\n\n\t%t\n", 2, lvl)
	}
	if lvl != 2 {
		t.Errorf("Level not correct!\nExpect:\n\n\t%d\nGot:\n\n\t%d\n", 2, lvl)
	}
}

func TestSectionLevelsFindNoResult(t *testing.T) {
	var p sectionLevels
	lvl := p.Find('-')
	if lvl > 0 {
		t.Errorf("Should not find any levels!\nExpect:\n\n\t%d\nGot:\n\n\t%d\n", -1, lvl)
	}
}

func TestSectionLevelsLevelEmpty(t *testing.T) {
	var p sectionLevels
	lvl := p.Level()
	expect := 0
	if lvl != expect {
		t.Errorf("Empty sectionLevels should return \"%d\"!\nExpect:\t%d\nGot:\t%d\n",
			expect, expect, lvl)
	}

}

func TestSectionLevelsLevel(t *testing.T) {
	var p sectionLevels
	p.Add('=', true, 5)
	p.Add('-', true, 8)
	p.Add('~', false, 6)
	lvl := p.Level()
	if lvl != 3 {
		t.Errorf("Level() returned incorrect level!\nExpect:\n\n\t%d\nGot:\n\n\t%d\n", 3, lvl)
	}
}

func parseTest(t *testing.T, lexTest *LexTest) (tree *Tree) {
	var errs []error
	log.Debugf("Test Name: %s\n", lexTest.name)
	log.Debugf("Description: %s\n", lexTest.description)
	log.Debugf("Test Input:\n-----------\n%s\n----------\n", lexTest.data)
	tree, errs = Parse(lexTest.name, lexTest.data)
	if errs != nil {
		for _, err := range errs {
			t.Error(err)
		}
	}
	return
}

func TestParseSectionTitleParagraph(t *testing.T) {
	testName := "SectionTitlePara"
	test := lexTests.testByName(testName)
	pTree := parseTest(t, test)
	eNodes := test.expectJson()
	checkParseNodes(t, eNodes, *pTree.Nodes, testName)
}

func TestParseSectionTitleParaNoBlankLine(t *testing.T) {
	testName := "SectionTitleParaNoBlankLine"
	test := lexTests.testByName(testName)
	pTree := parseTest(t, test)
	eNodes := test.expectJson()
	checkParseNodes(t, eNodes, *pTree.Nodes, testName)
}

func TestParseSectionParaHeadPara(t *testing.T) {
	testName := "SectionParaHeadPara"
	test := lexTests.testByName(testName)
	pTree := parseTest(t, test)
	eNodes := test.expectJson()
	checkParseNodes(t, eNodes, *pTree.Nodes, testName)
}

func TestParseSectionLevelTest1(t *testing.T) {
	testName := "SectionLevelTest1"
	test := lexTests.testByName(testName)
	pTree := parseTest(t, test)
	eNodes := test.expectJson()
	checkParseNodes(t, eNodes, *pTree.Nodes, testName)
}

func TestParseSectionUnexpectedTitles(t *testing.T) {
	testName := "SectionUnexpectedTitles"
	test := lexTests.testByName(testName)
	pTree := parseTest(t, test)
	eNodes := test.expectJson()
	checkParseNodes(t, eNodes, *pTree.Nodes, testName)
}
<|endoftext|>


<commit_before>// go-rst - A reStructuredText parser for Go
// 2014 (c) The go-rst Authors
// MIT Licensed. See LICENSE for details.

// To enable debug output when testing, use "go test -debug"

package parse

import (
	"github.com/demizer/go-elog"
	"reflect"
	"strings"
	"testing"
)

type checkNode struct {
	t          *testing.T
	testName   string
	pNodeName  string
	pFieldName string
	pFieldVal  interface{}
	pFieldType reflect.Type
	eFieldName string
	eFieldVal  interface{}
	eFieldType reflect.Type
	id         int
}

func (c *checkNode) error(args ...interface{}) {
	c.t.Error(args...)
}

func (c *checkNode) errorf(format string, args ...interface{}) {
	c.t.Errorf(format, args...)
}

func (c *checkNode) dError() {
	if c.pFieldName == "Rune" {
		c.t.Errorf("Got: %s.%s = %#v (%v) (%v) (Id: %d),\n\tExpect: %s.%s = %#v (%v)\n",
			c.pNodeName, c.pFieldName, c.pFieldVal, string(c.pFieldVal.(int32)),
			c.pFieldType, c.id, "#parse-tree", c.eFieldName, c.eFieldVal, c.eFieldType)
		return
	}
	c.t.Errorf("Got: %s.%s = %#v (%v) (Id: %d),\n\tExpect: %s.%s = %#v (%v)\n",
		c.pNodeName, c.pFieldName, c.pFieldVal, c.pFieldType, c.id, "#parse-tree",
		c.eFieldName, c.eFieldVal, c.eFieldType)
}

func (c *checkNode) updateState(pVal reflect.Value, eVal interface{}, field int) bool {
	// Actual parsed metadata
	c.pNodeName = pVal.Type().Name()
	c.pFieldName = pVal.Type().Field(field).Name
	c.pFieldVal = pVal.Field(field).Interface()
	c.pFieldType = pVal.Type().Field(field).Type
	c.id = pVal.FieldByName("Id").Interface().(int)

	// Expected parser metadata
	c.eFieldName = strings.ToLower(string(c.pFieldName[0])) + c.pFieldName[1:]
	c.eFieldVal = eVal.(map[string]interface{})[c.eFieldName]
	c.eFieldType = reflect.TypeOf(c.eFieldVal)

	pField := pVal.Field(field)
	if pField.Kind() == reflect.Ptr && pField.IsNil() {
		// Overline adornment nodes can be null
		if c.pFieldName == "OverLine" {
			return false
		} else {
			c.dError()
			return false
		}
	} else if c.pFieldVal == nil {
		c.dError()
		return false
	}

	return true
}

func (c *checkNode) checkFields(expect interface{}, pNode Node) {
	pVal := reflect.ValueOf(pNode).Elem()
	for i := 0; i < pVal.NumField(); i++ {

		if c.updateState(pVal, expect, i) == false {
			continue
		}

		switch c.pFieldName {
		case "Type":
			if c.pFieldVal.(NodeType).String() != c.eFieldVal {
				c.dError()
			}
		case "Id", "Level", "Length":
			if float64(c.pFieldVal.(int)) != c.eFieldVal {
				c.dError()
			}
		case "Line":
			if float64(c.pFieldVal.(Line)) != c.eFieldVal {
				c.dError()
			}
		case "StartPosition":
			if float64(c.pFieldVal.(StartPosition)) != c.eFieldVal {
				c.dError()
			}
		case "OverLine", "UnderLine":
			c.checkFields(c.eFieldVal, c.pFieldVal.(Node))
		case "NodeList":
			for num, node := range c.pFieldVal.(NodeList) {
				// A little hackery to make our recursion easy
				eFieldVal := c.eFieldVal
				c.checkFields(eFieldVal.([]interface{})[num], node.(Node))
				c.eFieldVal = eFieldVal
			}
		case "Rune":
			if string(c.pFieldVal.(rune)) != c.eFieldVal {
				c.dError()
			}
		default:
			if c.pFieldVal != c.eFieldVal {
				c.dError()
			}
		}
	}

}

func checkParseNodes(t *testing.T, eTree []interface{}, pNodes []Node, testName string) {
	state := &checkNode{t: t, testName: testName}
	if len(eTree) != len(pNodes) {
		t.Fatal("len(eTree) != len(pNodes)")
	}
	for eNum, eNode := range eTree {
		state.checkFields(eNode, pNodes[eNum])
	}
	return
}

func TestSectionLevelsAdd(t *testing.T) {
	var p sectionLevels
	lvl := p.Add('=', true, 5)
	if lvl != 1 {
		t.Errorf("Improper level on first add, Got level: %d, expected: %d", lvl, 1)
	}
}

func TestSectionLevelsString(t *testing.T) {
	var p sectionLevels
	p.Add('=', true, 5)
	p.Add('-', true, 8)
	p.Add('~', false, 6)
	out := p.String()
	expect := "level: 1, rune: '=', overline: true, length: 5\nlevel: 2, rune: '-', " +
		"overline: true, length: 8\nlevel: 3, rune: '~', overline: false, length: 6\n"
	if out != expect {
		t.Errorf("String output mismatch!\nExpect:\n\n\t%q,\nGot:\n\n\t%q\n", expect, out)
	}
}

func TestSectionLevelsFind(t *testing.T) {
	var p sectionLevels
	p.Add('=', true, 5)
	p.Add('-', true, 8)
	p.Add('~', false, 6)
	lvl := p.Find('-')
	if lvl == -1 {
		t.Errorf("Level not found!\nExpect:\n\n\t%d\nGot:\n\n\t%t\n", 2, lvl)
	}
	if lvl != 2 {
		t.Errorf("Level not correct!\nExpect:\n\n\t%d\nGot:\n\n\t%d\n", 2, lvl)
	}
}

func TestSectionLevelsFindNoResult(t *testing.T) {
	var p sectionLevels
	lvl := p.Find('-')
	if lvl > 0 {
		t.Errorf("Should not find any levels!\nExpect:\n\n\t%d\nGot:\n\n\t%d\n", -1, lvl)
	}
}

func TestSectionLevelsLevelEmpty(t *testing.T) {
	var p sectionLevels
	lvl := p.Level()
	expect := 0
	if lvl != expect {
		t.Errorf("Empty sectionLevels should return \"%d\"!\nExpect:\t%d\nGot:\t%d\n",
			expect, expect, lvl)
	}

}

func TestSectionLevelsLevel(t *testing.T) {
	var p sectionLevels
	p.Add('=', true, 5)
	p.Add('-', true, 8)
	p.Add('~', false, 6)
	lvl := p.Level()
	if lvl != 3 {
		t.Errorf("Level() returned incorrect level!\nExpect:\n\n\t%d\nGot:\n\n\t%d\n", 3, lvl)
	}
}

func parseTest(t *testing.T, lexTest *LexTest) (tree *Tree) {
	var errs []error
	log.Debugf("Test Name: %s\n", lexTest.name)
	log.Debugf("Description: %s\n", lexTest.description)
	log.Debugf("Test Input:\n-----------\n%s\n----------\n", lexTest.data)
	tree, errs = Parse(lexTest.name, lexTest.data)
	if errs != nil {
		for _, err := range errs {
			t.Error(err)
		}
	}
	return
}

func TestParseSectionTitlePara(t *testing.T) {
	testName := "SectionTitlePara"
	test := lexTests.testByName(testName)
	pTree := parseTest(t, test)
	eNodes := test.expectJson()
	checkParseNodes(t, eNodes, *pTree.Nodes, testName)
}

func TestParseSectionTitleParaNoBlankLine(t *testing.T) {
	testName := "SectionTitleParaNoBlankLine"
	test := lexTests.testByName(testName)
	pTree := parseTest(t, test)
	eNodes := test.expectJson()
	checkParseNodes(t, eNodes, *pTree.Nodes, testName)
}

func TestParseSectionParaHeadPara(t *testing.T) {
	testName := "SectionParaHeadPara"
	test := lexTests.testByName(testName)
	pTree := parseTest(t, test)
	eNodes := test.expectJson()
	checkParseNodes(t, eNodes, *pTree.Nodes, testName)
}

func TestParseSectionLevelTest1(t *testing.T) {
	testName := "SectionLevelTest1"
	test := lexTests.testByName(testName)
	pTree := parseTest(t, test)
	// spd.Dump(pTree)
	eNodes := test.expectJson()
	checkParseNodes(t, eNodes, *pTree.Nodes, testName)
}

func TestParseSectionUnexpectedTitles(t *testing.T) {
	testName := "SectionUnexpectedTitles"
	test := lexTests.testByName(testName)
	pTree := parseTest(t, test)
	eNodes := test.expectJson()
	checkParseNodes(t, eNodes, *pTree.Nodes, testName)
}
<commit_msg>parse_test.go: checkFields() now checks to the test<commit_after>// go-rst - A reStructuredText parser for Go
// 2014 (c) The go-rst Authors
// MIT Licensed. See LICENSE for details.

// To enable debug output when testing, use "go test -debug"

package parse

import (
	"github.com/demizer/go-elog"
	"reflect"
	"strings"
	"testing"
	"os"
)

type checkNode struct {
	t          *testing.T
	testName   string
	pNodeName  string
	pFieldName string
	pFieldVal  interface{}
	pFieldType reflect.Type
	eFieldName string
	eFieldVal  interface{}
	eFieldType reflect.Type
	id         int
}

func (c *checkNode) error(args ...interface{}) {
	c.t.Error(args...)
}

func (c *checkNode) errorf(format string, args ...interface{}) {
	c.t.Errorf(format, args...)
}

func (c *checkNode) dError() {
	if c.pFieldName == "Rune" {
		c.t.Errorf("Got: %s.%s = %#v (%v) (%v) (Id: %d),\n\tExpect: %s.%s = %#v (%v)\n",
			c.pNodeName, c.pFieldName, c.pFieldVal, string(c.pFieldVal.(int32)),
			c.pFieldType, c.id, "#parse-tree", c.eFieldName, c.eFieldVal, c.eFieldType)
		return
	}
	c.t.Errorf("Got: %s.%s = %#v (%v) (Id: %d),\n\tExpect: %s.%s = %#v (%v)\n",
		c.pNodeName, c.pFieldName, c.pFieldVal, c.pFieldType, c.id, "#parse-tree",
		c.eFieldName, c.eFieldVal, c.eFieldType)
}

func poop() {
	os.Exit(1)
}

func (c *checkNode) updateState(eKey string, eVal interface{}, pVal reflect.Value) bool {
	// Expected parser metadata
	c.eFieldName = eKey
	c.eFieldVal = eVal
	c.eFieldType = reflect.TypeOf(c.eFieldVal)
	if eKey == "id" {
		c.id = int(eVal.(float64))
	}

	// Actual parsed metadata
	c.pNodeName = pVal.Type().Name()
	c.pFieldName = strings.ToUpper(string(c.eFieldName[0])) + c.eFieldName[1:]
	c.pFieldVal = pVal.FieldByName(c.pFieldName).Interface()
	c.pFieldType = pVal.FieldByName(c.pFieldName).Type()

	// Overline adornment nodes can be null
	if c.eFieldName == "overLine" && c.eFieldVal == nil {
		return false
	} else if c.eFieldVal == nil {
		c.dError()
		return false
	}

	return true
}

func (c *checkNode) checkFields(eNodes interface{}, pNode Node) {
	for eKey, eVal := range eNodes.(map[string]interface{}) {
		pVal := reflect.Indirect(reflect.ValueOf(pNode))
		if c.updateState(eKey, eVal, pVal) == false {
			continue
		}
		switch c.eFieldName {
		case "type":
			if c.eFieldVal != c.pFieldVal.(NodeType).String() {
				c.dError()
			}
		case "id", "level", "length":
			if c.eFieldVal != float64(c.pFieldVal.(int)) {
				c.dError()
			}
		case "line":
			if c.eFieldVal != float64(c.pFieldVal.(Line)) {
				c.dError()
			}
		case "startPosition":
			if c.eFieldVal != float64(c.pFieldVal.(StartPosition)) {
				c.dError()
			}
		case "overLine", "underLine":
			c.checkFields(c.eFieldVal, c.pFieldVal.(Node))
		case "nodeList":
			for num, node := range c.eFieldVal.([]interface{}) {
				// Store and reset the parser value, otherwise a panic will occur on
				// the next iteration
				pFieldVal := c.pFieldVal
				c.checkFields(node, c.pFieldVal.(NodeList)[num])
				c.pFieldVal = pFieldVal
			}
		case "rune":
			if c.eFieldVal != string(c.pFieldVal.(rune)) {
				c.dError()
			}
		default:
			if c.eFieldVal != c.pFieldVal {
				c.dError()
			}
		}
	}

}

func checkParseNodes(t *testing.T, eTree []interface{}, pNodes []Node, testName string) {
	state := &checkNode{t: t, testName: testName}
	for eNum, eNode := range eTree {
		state.checkFields(eNode, pNodes[eNum])
	}
	return
}

func TestSectionLevelsAdd(t *testing.T) {
	var p sectionLevels
	lvl := p.Add('=', true, 5)
	if lvl != 1 {
		t.Errorf("Improper level on first add, Got level: %d, expected: %d", lvl, 1)
	}
}

func TestSectionLevelsString(t *testing.T) {
	var p sectionLevels
	p.Add('=', true, 5)
	p.Add('-', true, 8)
	p.Add('~', false, 6)
	out := p.String()
	expect := "level: 1, rune: '=', overline: true, length: 5\nlevel: 2, rune: '-', " +
		"overline: true, length: 8\nlevel: 3, rune: '~', overline: false, length: 6\n"
	if out != expect {
		t.Errorf("String output mismatch!\nExpect:\n\n\t%q,\nGot:\n\n\t%q\n", expect, out)
	}
}

func TestSectionLevelsFind(t *testing.T) {
	var p sectionLevels
	p.Add('=', true, 5)
	p.Add('-', true, 8)
	p.Add('~', false, 6)
	lvl := p.Find('-')
	if lvl == -1 {
		t.Errorf("Level not found!\nExpect:\n\n\t%d\nGot:\n\n\t%t\n", 2, lvl)
	}
	if lvl != 2 {
		t.Errorf("Level not correct!\nExpect:\n\n\t%d\nGot:\n\n\t%d\n", 2, lvl)
	}
}

func TestSectionLevelsFindNoResult(t *testing.T) {
	var p sectionLevels
	lvl := p.Find('-')
	if lvl > 0 {
		t.Errorf("Should not find any levels!\nExpect:\n\n\t%d\nGot:\n\n\t%d\n", -1, lvl)
	}
}

func TestSectionLevelsLevelEmpty(t *testing.T) {
	var p sectionLevels
	lvl := p.Level()
	expect := 0
	if lvl != expect {
		t.Errorf("Empty sectionLevels should return \"%d\"!\nExpect:\t%d\nGot:\t%d\n",
			expect, expect, lvl)
	}

}

func TestSectionLevelsLevel(t *testing.T) {
	var p sectionLevels
	p.Add('=', true, 5)
	p.Add('-', true, 8)
	p.Add('~', false, 6)
	lvl := p.Level()
	if lvl != 3 {
		t.Errorf("Level() returned incorrect level!\nExpect:\n\n\t%d\nGot:\n\n\t%d\n", 3, lvl)
	}
}

func parseTest(t *testing.T, lexTest *LexTest) (tree *Tree) {
	var errs []error
	log.Debugf("Test Name: %s\n", lexTest.name)
	log.Debugf("Description: %s\n", lexTest.description)
	log.Debugf("Test Input:\n-----------\n%s\n----------\n", lexTest.data)
	tree, errs = Parse(lexTest.name, lexTest.data)
	if errs != nil {
		for _, err := range errs {
			t.Error(err)
		}
	}
	return
}

func TestParseSectionTitleParagraph(t *testing.T) {
	testName := "SectionTitlePara"
	test := lexTests.testByName(testName)
	pTree := parseTest(t, test)
	eNodes := test.expectJson()
	checkParseNodes(t, eNodes, *pTree.Nodes, testName)
}

func TestParseSectionTitleParaNoBlankLine(t *testing.T) {
	testName := "SectionTitleParaNoBlankLine"
	test := lexTests.testByName(testName)
	pTree := parseTest(t, test)
	eNodes := test.expectJson()
	checkParseNodes(t, eNodes, *pTree.Nodes, testName)
}

func TestParseSectionParaHeadPara(t *testing.T) {
	testName := "SectionParaHeadPara"
	test := lexTests.testByName(testName)
	pTree := parseTest(t, test)
	eNodes := test.expectJson()
	checkParseNodes(t, eNodes, *pTree.Nodes, testName)
}

func TestParseSectionLevelTest1(t *testing.T) {
	testName := "SectionLevelTest1"
	test := lexTests.testByName(testName)
	pTree := parseTest(t, test)
	// spd.Dump(pTree)
	eNodes := test.expectJson()
	checkParseNodes(t, eNodes, *pTree.Nodes, testName)
}

func TestParseSectionUnexpectedTitles(t *testing.T) {
	testName := "SectionUnexpectedTitles"
	test := lexTests.testByName(testName)
	pTree := parseTest(t, test)
	eNodes := test.expectJson()
	checkParseNodes(t, eNodes, *pTree.Nodes, testName)
}
<|endoftext|>


<commit_before>// go-rst - A reStructuredText parser for Go
// 2014 (c) The go-rst Authors
// MIT Licensed. See LICENSE for details.

// To enable debug output when testing, use "go test -debug"

package parse

import (
	"encoding/json"
	"fmt"
	"github.com/demizer/go-elog"
	"reflect"
	"strings"
	"testing"
)

var lexParseTests LexTests

func TestSectionLevelsAdd(t *testing.T) {
	var p sectionLevels
	lvl := p.Add('=', true, 5)
	if lvl != 1 {
		t.Errorf("Improper level on first add, Got level: %d, expected: %d", lvl, 1)
	}
}

func TestSectionLevelsString(t *testing.T) {
	var p sectionLevels
	p.Add('=', true, 5)
	p.Add('-', true, 8)
	p.Add('~', false, 6)
	out := p.String()
	expect := "level: 1, rune: '=', overline: true, length: 5\nlevel: 2, rune: '-', " +
		"overline: true, length: 8\nlevel: 3, rune: '~', overline: false, length: 6\n"
	if out != expect {
		t.Errorf("String output mismatch!\nExpect:\n\n\t%q,\nGot:\n\n\t%q\n", expect, out)
	}
}

func TestSectionLevelsFind(t *testing.T) {
	var p sectionLevels
	p.Add('=', true, 5)
	p.Add('-', true, 8)
	p.Add('~', false, 6)
	lvl := p.Find('-')
	if lvl == -1 {
		t.Errorf("Level not found!\nExpect:\n\n\t%d\nGot:\n\n\t%t\n", 2, lvl)
	}
	if lvl != 2 {
		t.Errorf("Level not correct!\nExpect:\n\n\t%d\nGot:\n\n\t%d\n", 2, lvl)
	}
}

func TestSectionLevelsFindNoResult(t *testing.T) {
	var p sectionLevels
	lvl := p.Find('-')
	if lvl > 0 {
		t.Errorf("Should not find any levels!\nExpect:\n\n\t%d\nGot:\n\n\t%d\n", -1, lvl)
	}
}

func TestSectionLevelsLevelEmpty(t *testing.T) {
	var p sectionLevels
	lvl := p.Level()
	expect := 0
	if lvl != expect {
		t.Errorf("Empty sectionLevels should return \"%d\"!\nExpect:\t%d\nGot:\t%d\n",
			expect, expect, lvl)
	}

}

func TestSectionLevelsLevel(t *testing.T) {
	var p sectionLevels
	p.Add('=', true, 5)
	p.Add('-', true, 8)
	p.Add('~', false, 6)
	lvl := p.Level()
	if lvl != 3 {
		t.Errorf("Level() returned incorrect level!\nExpect:\n\n\t%d\nGot:\n\n\t%d\n", 3, lvl)
	}
}

func parseTest(t *testing.T, testName string) (tree *Tree, err error) {
	if lexParseTests == nil {
		lexParseTests, err = ParseTestData("../testdata/test_lex_sections.dat")
		if err != nil {
			t.Fatal(err)
		}
	}
	test := lexParseTests.SearchByName(testName)
	if test != nil {
		log.Debugf("Test Name: \t%s\n", test.name)
		log.Debugf("Description: \t%s\n", test.description)
		log.Debugf("Test Input:\n-----------\n%s\n----------\n", test.data)
		tree, err = Parse(test.name, test.data)
		if err != nil {
			t.Fatal(err)
		}
	}
	return
}

// compareNodes is a recursive function that compares the resulting nodes (pNodes) from the parser
// with the expected output from the testdata (eNodes).
func compareNodes(pNodes *NodeList, eNodes []interface{}, testName string) (errors []error) {
	for pNum, pNode := range *pNodes {
		pVal := reflect.ValueOf(pNode).Elem()
		pType := pVal.Type()
		// Loop through the fields of the Node struct
		for i := 0; i < pVal.NumField(); i++ {
			pStructName := pType.Name()
			pFieldName := pType.Field(i).Name
			eName := strings.ToLower(string(pFieldName[0])) + pFieldName[1:]
			eVal := eNodes[pNum].(map[string]interface{})[eName]
			eType := reflect.TypeOf(eVal)

			// SectionNode.OverLine and SectionNode.UnderLine can be null
			if eVal == nil && eName != "overLine" && eName != "underLine" {
				errors = append(errors, fmt.Errorf("\"%s\" property does not exist "+
				"in %s.expectTree!\n", pFieldName, testName))
				continue
			}

			// var val interface{}
			var cErr error
			gVal := pVal.Field(i)
			match := false

			switch gVal.Kind() {
			case reflect.String:
				if gVal.String() != eVal || gVal.Kind() != reflect.String ||
					eType.Kind() != reflect.String {
					cErr = fmt.Errorf("Got Type: %s.%s = %#v (%s),\n\t"+
						"Expect Type: %s.%s = %#v (%s)\n", pStructName,
						pFieldName, gVal.String(), gVal.Type(), testName,
						eName, eVal, eType.Kind())
					break
				}
				match = true
			case reflect.Int:
				// Check for the "Type" field name, this requires a conversion from
				// string to int.
				if pFieldName == "Type" {
					gNodeType := NodeTypeFromString(eVal.(string))
					if gVal.Int() == int64(gNodeType) {
						match = true
						break
					} else {
						cErr = fmt.Errorf(
							"Got: %s.%s = %#v,\n\tExpect: %s.%s = %#v\n",
							pStructName, pFieldName, gVal.Int(),
							testName, eName, eVal)
						break
					}
				}
				// Check for matching types betwen the parsed value and expected
				// value.
				if eType.Kind() != reflect.Float64 || gVal.Kind() != reflect.Int ||
					eType.Kind() != reflect.Float64 {
					cErr = fmt.Errorf("Got Type: %s.%s = %#v (%s),\n\t"+
						"Expect Type: %s.%s = %f (%s)\n", pStructName,
						pFieldName, gVal.Int(), gVal.Type(), testName, eName,
						eVal, eType.Kind())
					break
				}
				// Finally, check the actual values
				match = gVal.Int() == int64(eVal.(float64))
			case reflect.Ptr:
				// A pointer in the struct is most likely another struct such as
				// an AdornmentNode.
				cErr = fmt.Errorf("reflect.Ptr for %s.%s not implemented yet!",
					pStructName, pFieldName)
			case reflect.Slice:
				// A silce in the struct is probably a NodeList.
				cErr = fmt.Errorf("reflect.Slice for %s.%s not implemented yet!",
					pStructName, pFieldName)
			}

			if match == false {
				errors = append(errors, cErr)
			}
		}
	}
	return
}

func TestParseSectionTitlePara(t *testing.T) {
	testName := "SectionTitlePara"
	tree, err := parseTest(t, testName)
	if err != nil {
		t.Error(err)
	}
	test := lexParseTests.SearchByName(testName)
	var nodeList []interface{}
	err = json.Unmarshal([]byte(test.expectTree), &nodeList)
	if err != nil {
		t.Error(err)
	}
	errors := compareNodes(tree.Nodes, nodeList, testName)
	if errors != nil {
		for _, err := range errors {
			t.Error(err)
		}
	}
}
<commit_msg>Rename compareNodes() to checkParseNodes()<commit_after>// go-rst - A reStructuredText parser for Go
// 2014 (c) The go-rst Authors
// MIT Licensed. See LICENSE for details.

// To enable debug output when testing, use "go test -debug"

package parse

import (
	"encoding/json"
	"fmt"
	"github.com/demizer/go-elog"
	"reflect"
	"strings"
	"testing"
)

var lexParseTests LexTests

func TestSectionLevelsAdd(t *testing.T) {
	var p sectionLevels
	lvl := p.Add('=', true, 5)
	if lvl != 1 {
		t.Errorf("Improper level on first add, Got level: %d, expected: %d", lvl, 1)
	}
}

func TestSectionLevelsString(t *testing.T) {
	var p sectionLevels
	p.Add('=', true, 5)
	p.Add('-', true, 8)
	p.Add('~', false, 6)
	out := p.String()
	expect := "level: 1, rune: '=', overline: true, length: 5\nlevel: 2, rune: '-', " +
		"overline: true, length: 8\nlevel: 3, rune: '~', overline: false, length: 6\n"
	if out != expect {
		t.Errorf("String output mismatch!\nExpect:\n\n\t%q,\nGot:\n\n\t%q\n", expect, out)
	}
}

func TestSectionLevelsFind(t *testing.T) {
	var p sectionLevels
	p.Add('=', true, 5)
	p.Add('-', true, 8)
	p.Add('~', false, 6)
	lvl := p.Find('-')
	if lvl == -1 {
		t.Errorf("Level not found!\nExpect:\n\n\t%d\nGot:\n\n\t%t\n", 2, lvl)
	}
	if lvl != 2 {
		t.Errorf("Level not correct!\nExpect:\n\n\t%d\nGot:\n\n\t%d\n", 2, lvl)
	}
}

func TestSectionLevelsFindNoResult(t *testing.T) {
	var p sectionLevels
	lvl := p.Find('-')
	if lvl > 0 {
		t.Errorf("Should not find any levels!\nExpect:\n\n\t%d\nGot:\n\n\t%d\n", -1, lvl)
	}
}

func TestSectionLevelsLevelEmpty(t *testing.T) {
	var p sectionLevels
	lvl := p.Level()
	expect := 0
	if lvl != expect {
		t.Errorf("Empty sectionLevels should return \"%d\"!\nExpect:\t%d\nGot:\t%d\n",
			expect, expect, lvl)
	}

}

func TestSectionLevelsLevel(t *testing.T) {
	var p sectionLevels
	p.Add('=', true, 5)
	p.Add('-', true, 8)
	p.Add('~', false, 6)
	lvl := p.Level()
	if lvl != 3 {
		t.Errorf("Level() returned incorrect level!\nExpect:\n\n\t%d\nGot:\n\n\t%d\n", 3, lvl)
	}
}

func parseTest(t *testing.T, testName string) (tree *Tree, err error) {
	if lexParseTests == nil {
		lexParseTests, err = ParseTestData("../testdata/test_lex_sections.dat")
		if err != nil {
			t.Fatal(err)
		}
	}
	test := lexParseTests.SearchByName(testName)
	if test != nil {
		log.Debugf("Test Name: \t%s\n", test.name)
		log.Debugf("Description: \t%s\n", test.description)
		log.Debugf("Test Input:\n-----------\n%s\n----------\n", test.data)
		tree, err = Parse(test.name, test.data)
		if err != nil {
			t.Fatal(err)
		}
	}
	return
}

// checkParseNodes is a recursive function that compares the resulting nodes (pNodes) from the
// parser with the expected output from the testdata (eNodes).
func checkParseNodes(pNodes *NodeList, eNodes []interface{}, testName string) (errors []error) {
	for pNum, pNode := range *pNodes {
		pVal := reflect.ValueOf(pNode).Elem()
		pType := pVal.Type()
		// Loop through the fields of the Node struct
		for i := 0; i < pVal.NumField(); i++ {
			pStructName := pType.Name()
			pFieldName := pType.Field(i).Name
			eName := strings.ToLower(string(pFieldName[0])) + pFieldName[1:]
			eVal := eNodes[pNum].(map[string]interface{})[eName]
			eType := reflect.TypeOf(eVal)

			// SectionNode.OverLine and SectionNode.UnderLine can be null
			if eVal == nil && eName != "overLine" && eName != "underLine" {
				errors = append(errors, fmt.Errorf("\"%s\" property does not exist "+
				"in %s.expectTree!\n", pFieldName, testName))
				continue
			}

			// var val interface{}
			var cErr error
			gVal := pVal.Field(i)
			match := false

			switch gVal.Kind() {
			case reflect.String:
				if gVal.String() != eVal || gVal.Kind() != reflect.String ||
					eType.Kind() != reflect.String {
					cErr = fmt.Errorf("Got Type: %s.%s = %#v (%s),\n\t"+
						"Expect Type: %s.%s = %#v (%s)\n", pStructName,
						pFieldName, gVal.String(), gVal.Type(), testName,
						eName, eVal, eType.Kind())
					break
				}
				match = true
			case reflect.Int:
				// Check for the "Type" field name, this requires a conversion from
				// string to int.
				if pFieldName == "Type" {
					gNodeType := NodeTypeFromString(eVal.(string))
					if gVal.Int() == int64(gNodeType) {
						match = true
						break
					} else {
						cErr = fmt.Errorf(
							"Got: %s.%s = %#v,\n\tExpect: %s.%s = %#v\n",
							pStructName, pFieldName, gVal.Int(),
							testName, eName, eVal)
						break
					}
				}
				// Check for matching types betwen the parsed value and expected
				// value.
				if eType.Kind() != reflect.Float64 || gVal.Kind() != reflect.Int ||
					eType.Kind() != reflect.Float64 {
					cErr = fmt.Errorf("Got Type: %s.%s = %#v (%s),\n\t"+
						"Expect Type: %s.%s = %f (%s)\n", pStructName,
						pFieldName, gVal.Int(), gVal.Type(), testName, eName,
						eVal, eType.Kind())
					break
				}
				// Finally, check the actual values
				match = gVal.Int() == int64(eVal.(float64))
			case reflect.Ptr:
				// A pointer in the struct is most likely another struct such as
				// an AdornmentNode.
				cErr = fmt.Errorf("reflect.Ptr for %s.%s not implemented yet!",
					pStructName, pFieldName)
			case reflect.Slice:
				// A silce in the struct is probably a NodeList.
				cErr = fmt.Errorf("reflect.Slice for %s.%s not implemented yet!",
					pStructName, pFieldName)
			}

			if match == false {
				errors = append(errors, cErr)
			}
		}
	}
	return
}

func TestParseSectionTitlePara(t *testing.T) {
	testName := "SectionTitlePara"
	tree, err := parseTest(t, testName)
	if err != nil {
		t.Error(err)
	}
	test := lexParseTests.SearchByName(testName)
	var nodeList []interface{}
	err = json.Unmarshal([]byte(test.expectTree), &nodeList)
	if err != nil {
		t.Error(err)
	}
	errors := checkParseNodes(tree.Nodes, nodeList, testName)
	if errors != nil {
		for _, err := range errors {
			t.Error(err)
		}
	}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"text/tabwriter"

	"github.com/coreos-inc/updatectl/client/update/v1"
)

var (
	adminFlags struct {
		user string
	}

	cmdAdminInit = &Command{
		Name:        "admin-init",
		Description: "Initializes the database.",
		Run:         adminInit,
	}
	cmdAdminCreateUser = &Command{
		Name:        "admin-create-user",
		Usage:       "-user USER",
		Description: "Creates an admin user.",
		Run:         adminCreateUser,
	}
	cmdAdminDeleteUser = &Command{
		Name:        "admin-delete-user",
		Usage:       "<username>",
		Description: "Deletes an admin user.",
		Run:         adminDeleteUser,
	}
	cmdAdminListUsers = &Command{
		Name:        "admin-list-users",
		Description: "Lists admin users.",
		Run:         adminListUsers,
	}
)

func init() {
	cmdAdminCreateUser.Flags.StringVar(&adminFlags.user, "user", "", "New Username")
}

func adminInit(args []string, service *update.Service, out *tabwriter.Writer) int {
	adminUrl := globalFlags.Server + "/admin/v1/init"
	client := &http.Client{}
	resp, err := client.Get(adminUrl)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(body))
	if string(body) != "ok" {
		return ERROR_API
	}
	return OK
}

func adminCreateUser(args []string, service *update.Service, out *tabwriter.Writer) int {
	req := &update.AdminUserReq{
		UserName: adminFlags.user,
	}
	call := service.Admin.CreateUser(req)
	u, err := call.Do()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(u.Token)
	return OK
}

func adminDeleteUser(args []string, service *update.Service, out *tabwriter.Writer) int {
	if len(args) != 1 {
		return ERROR_USAGE
	}
	userName := args[0]
	call := service.Admin.DeleteUser(userName)
	u, err := call.Do()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("User %s deleted\n", u.User)
	return OK
}

func adminListUsers(args []string, service *update.Service, out *tabwriter.Writer) int {
	call := service.Admin.ListUsers()
	resp, err := call.Do()
	if err != nil {
		log.Fatal(err)
	}

	for _, u := range resp.Users {
		fmt.Fprintf(out, "%s\n", u.User)
	}
	out.Flush()
	return OK
}
<commit_msg>refactor(admin): use positional argument for admin-create-user to match admin-delete-user<commit_after>package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"text/tabwriter"

	"github.com/coreos-inc/updatectl/client/update/v1"
)

var (
	cmdAdminInit = &Command{
		Name:        "admin-init",
		Description: "Initializes the database.",
		Run:         adminInit,
	}
	cmdAdminCreateUser = &Command{
		Name:        "admin-create-user",
		Usage:       "<username>",
		Description: "Creates an admin user.",
		Run:         adminCreateUser,
	}
	cmdAdminDeleteUser = &Command{
		Name:        "admin-delete-user",
		Usage:       "<username>",
		Description: "Deletes an admin user.",
		Run:         adminDeleteUser,
	}
	cmdAdminListUsers = &Command{
		Name:        "admin-list-users",
		Description: "Lists admin users.",
		Run:         adminListUsers,
	}
)

func adminInit(args []string, service *update.Service, out *tabwriter.Writer) int {
	adminUrl := globalFlags.Server + "/admin/v1/init"
	client := &http.Client{}
	resp, err := client.Get(adminUrl)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(string(body))
	if string(body) != "ok" {
		return ERROR_API
	}
	return OK
}

func adminCreateUser(args []string, service *update.Service, out *tabwriter.Writer) int {
	if len(args) != 1 {
		return ERROR_USAGE
	}

	req := &update.AdminUserReq{
		UserName: args[0],
	}
	call := service.Admin.CreateUser(req)
	u, err := call.Do()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(u.Token)
	return OK
}

func adminDeleteUser(args []string, service *update.Service, out *tabwriter.Writer) int {
	if len(args) != 1 {
		return ERROR_USAGE
	}
	userName := args[0]
	call := service.Admin.DeleteUser(userName)
	u, err := call.Do()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("User %s deleted\n", u.User)
	return OK
}

func adminListUsers(args []string, service *update.Service, out *tabwriter.Writer) int {
	call := service.Admin.ListUsers()
	resp, err := call.Do()
	if err != nil {
		log.Fatal(err)
	}

	for _, u := range resp.Users {
		fmt.Fprintf(out, "%s\n", u.User)
	}
	out.Flush()
	return OK
}
<|endoftext|>


<commit_before>package g

import (
	"time"
)

// changelog:
// 3.1.3: code refactor
// 3.1.4: bugfix ignore configuration
// 5.0.0: 支持通过配置控制是否开启/run接口；收集udp流量数据；du某个目录的大小
// 5.1.0: 同步插件的时候不再使用checksum机制
const (
	VERSION          = "5.1.2"
	COLLECT_INTERVAL = time.Second
	URL_CHECK_HEALTH = "url.check.health"
	NET_PORT_LISTEN  = "net.port.listen"
	DU_BS            = "du.bs"
	PROC_NUM         = "proc.num"
)
<commit_msg>Fix config syntax error when deploying<commit_after>package g

import (
	"time"
)

// changelog:
// 3.1.3: code refactor
// 3.1.4: bugfix ignore configuration
// 5.0.0: 支持通过配置控制是否开启/run接口；收集udp流量数据；du某个目录的大小
// 5.1.0: 同步插件的时候不再使用checksum机制
// 5.1.3: Fix config syntax error when deploying
const (
	VERSION          = "5.1.3"
	COLLECT_INTERVAL = time.Second
	URL_CHECK_HEALTH = "url.check.health"
	NET_PORT_LISTEN  = "net.port.listen"
	DU_BS            = "du.bs"
	PROC_NUM         = "proc.num"
)
<|endoftext|>


<commit_before>package gfx

import (
	"image"
	"image/color"
	"image/png"
	"os"
)

// Pic represents a complete picture converted from a PNG image
type Pic struct {
	image   *image.Paletted
	palette []color.Color
	colors  []byte
}

// Pixels return an array of pixels (color indices) from the given area in the Pic
func (pic *Pic) Pixels(x, y, w, h int) [][]byte {
	pix := make([][]byte, h)
	for yy := 0; yy < h; yy++ {
		pix[yy] = make([]byte, w)
		for xx := 0; xx < w; xx++ {
			pix[yy][xx] = pic.colors[pic.image.ColorIndexAt(x + xx, y + yy)]
		}
	}
	return pix
}

// Pixels return an array of multicolor pixels (color indices) from the given area in the Pic
func (pic *Pic) PixelsMC(x, y, w, h int) [][]byte {
	pix := make([][]byte, h)
	for yy := 0; yy < h; yy++ {
		pix[yy] = make([]byte, w)
		for xx := 0; xx < w; xx++ {
			pix[yy][xx] = pic.colors[pic.image.ColorIndexAt(2 * (x + xx), y + yy)]
		}
	}
	return pix
}

// ReadPNG reads an image from a PNG file and returns a two-dimensional
// array of bytes that are color indices in the VIC-II palette (0-15)
func ReadPNG(filename string) *Pic {
	file, err := os.Open(filename)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	decoded, err := png.Decode(file)
	if err != nil {
		panic(err)
	}

	var pic Pic
	pic.image   = decoded.(*image.Paletted)
	pic.palette = Pepto
	pic.colors  = remapIndices(pic.image.Palette, pic.palette)
	return &pic
}

func remapIndices(from color.Palette, to []color.Color) []byte {
	colors := make([]byte, 16)
	for index, color := range to {
		i := from.Index(color)
		colors[i] = byte(index)
	}
	return colors
}
<commit_msg>Started work on koala conversion.<commit_after>package gfx

import (
	"bytes"
	"image"
	"image/color"
	"image/png"
	"os"
)

// Pic represents a complete picture converted from a PNG image
type Pic struct {
	image   *image.Paletted
	palette []color.Color
	colors  []byte
	BgColor byte
}

// Pixels return an array of pixels (color indices) from the given area in the Pic
func (pic *Pic) Pixels(xoffset, yoffset, width, height int) [][]byte {
	pix := make([][]byte, height)
	for y := 0; y < height; y++ {
		pix[y] = make([]byte, width)
		for x := 0; x < width; x++ {
			pix[y][x] = pic.colors[pic.image.ColorIndexAt(xoffset + x, yoffset + y)]
		}
	}
	return pix
}

// Pixels return an array of multicolor pixels (color indices) from the given area in the Pic
func (pic *Pic) PixelsMC(xoffset, yoffset, width, height int) [][]byte {
	pix := make([][]byte, height)
	for y := 0; y < height; y++ {
		pix[y] = make([]byte, width)
		for x := 0; x < width; x++ {
			pix[y][x] = pic.colors[pic.image.ColorIndexAt((xoffset + x) * 2, yoffset + y)]
		}
	}
	return pix
}

func (pic *Pic) ToKoala(xoffset, yoffset int) *Koala {
	koala := Koala{
		Bitmap: make([]byte, 8000),
		Screen: make([]byte, 1000),
		Colmap: make([]byte, 1000),
		BgColor: pic.BgColor}
	return &koala
}

// Koala represents a full-screen image in KoalaPainter format
type Koala struct {
	Bitmap  []byte
	Screen  []byte
	Colmap  []byte
	BgColor byte
}

// Bytes returns Koala format as raw bytes without padding
func (koala *Koala) Bytes() []byte {
	return bytes.Join([][]byte{
		koala.Bitmap, koala.Screen, koala.Colmap,
		[]byte{koala.BgColor}}, []byte{})
}

// BytesAligned returns Koala format as raw bytes with padding so that
// each segment (bitmap, screen and colmap) is aligned for direct use
func (koala *Koala) BytesAligned() []byte {
	return bytes.Join([][]byte{
		koala.Bitmap, make([]byte, 192),
		koala.Screen, make([]byte, 24),
		koala.Colmap, []byte{koala.BgColor}}, []byte{})
}

// ReadPNG reads an image from a PNG file and returns a two-dimensional
// array of bytes that are color indices in the VIC-II palette (0-15)
func ReadPNG(filename string) *Pic {
	file, err := os.Open(filename)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	decoded, err := png.Decode(file)
	if err != nil {
		panic(err)
	}
	image := decoded.(*image.Paletted)

	pic := Pic{image: image, palette: Pepto, colors: remapIndices(image.Palette, Pepto)}
	return &pic
}

func remapIndices(from color.Palette, to []color.Color) []byte {
	colors := make([]byte, 16)
	for index, color := range to {
		i := from.Index(color)
		colors[i] = byte(index)
	}
	return colors
}
<|endoftext|>


<commit_before>package git

import (
	"fmt"
	"github.com/heysquirrel/tribe/apis/rally"
	tlog "github.com/heysquirrel/tribe/log"
	"github.com/heysquirrel/tribe/shell"
	"strings"
	"time"
)

type Filename string

type Repo struct {
	shell   *shell.Shell
	logger  *tlog.Log
	commits Commits
	files   map[Filename]File
	Api     *rally.Rally
}

type File struct {
	Name         string
	LastCommit   *Commit
	Contributors Contributors
	Related      []*RelatedFile
	WorkItems    []rally.Artifact
	Commits      Commits
}

func (f *File) NumberOfDefects() int {
	count := 0
	for _, work := range f.WorkItems {
		if strings.HasPrefix(work.FormattedID, "DE") {
			count += 1
		}
	}
	return count
}

func (f *File) NumberOfStories() int {
	count := 0
	for _, work := range f.WorkItems {
		if strings.HasPrefix(work.FormattedID, "S") {
			count += 1
		}
	}
	return count
}

func (repo *Repo) git(args ...string) (string, error) {
	return repo.shell.Exec("git", args...)
}

func New(dir string, logger *tlog.Log, api *rally.Rally) (*Repo, error) {
	temp := shell.New(dir, logger)
	out, err := temp.Exec("git", "rev-parse", "--show-toplevel")
	if err != nil {
		return nil, err
	}

	repo := new(Repo)
	repo.shell = shell.New(strings.TrimSpace(out), logger)
	repo.logger = logger
	repo.Api = api

	sixMonthsAgo := time.Now().AddDate(0, -6, 0)
	repo.commits, err = repo.CommitsAfter(sixMonthsAgo)
	if err != nil {
		return nil, err
	}

	logger.Add(fmt.Sprintf("Processed %d commits", len(repo.commits)))

	return repo, err
}

func (repo *Repo) Changes() []*File {
	var results = make([]*File, 0)

	cmdOut, err := repo.git("status", "--porcelain")
	if err != nil {
		repo.logger.Add(err.Error())
		return results
	}

	output := strings.Split(cmdOut, "\n")
	for _, change := range output {
		if len(change) > 0 {
			filename := change[3:len(change)]
			results = append(results, repo.GetFile(filename))
		}
	}

	return results
}

func (repo *Repo) GetFile(filename string) *File {
	commits := repo.commits.ContainsFile(filename)
	workItems, _ := repo.Api.GetByFormattedId(commits.relatedWorkItems()...)

	file := new(File)
	file.Name = filename
	file.LastCommit = commits[0]
	file.Related = commits.relatedFiles(filename)
	file.Contributors = commits.relatedContributors()
	file.WorkItems = workItems
	file.Commits = commits

	return file
}
<commit_msg>Removed unused type<commit_after>package git

import (
	"fmt"
	"github.com/heysquirrel/tribe/apis/rally"
	tlog "github.com/heysquirrel/tribe/log"
	"github.com/heysquirrel/tribe/shell"
	"strings"
	"time"
)

type Repo struct {
	shell   *shell.Shell
	logger  *tlog.Log
	commits Commits
	Api     *rally.Rally
}

type File struct {
	Name         string
	LastCommit   *Commit
	Contributors Contributors
	Related      []*RelatedFile
	WorkItems    []rally.Artifact
	Commits      Commits
}

func (f *File) NumberOfDefects() int {
	count := 0
	for _, work := range f.WorkItems {
		if strings.HasPrefix(work.FormattedID, "DE") {
			count += 1
		}
	}
	return count
}

func (f *File) NumberOfStories() int {
	count := 0
	for _, work := range f.WorkItems {
		if strings.HasPrefix(work.FormattedID, "S") {
			count += 1
		}
	}
	return count
}

func (repo *Repo) git(args ...string) (string, error) {
	return repo.shell.Exec("git", args...)
}

func New(dir string, logger *tlog.Log, api *rally.Rally) (*Repo, error) {
	temp := shell.New(dir, logger)
	out, err := temp.Exec("git", "rev-parse", "--show-toplevel")
	if err != nil {
		return nil, err
	}

	repo := new(Repo)
	repo.shell = shell.New(strings.TrimSpace(out), logger)
	repo.logger = logger
	repo.Api = api

	sixMonthsAgo := time.Now().AddDate(0, -6, 0)
	repo.commits, err = repo.CommitsAfter(sixMonthsAgo)
	if err != nil {
		return nil, err
	}

	logger.Add(fmt.Sprintf("Processed %d commits", len(repo.commits)))

	return repo, err
}

func (repo *Repo) Changes() []*File {
	var results = make([]*File, 0)

	cmdOut, err := repo.git("status", "--porcelain")
	if err != nil {
		repo.logger.Add(err.Error())
		return results
	}

	output := strings.Split(cmdOut, "\n")
	for _, change := range output {
		if len(change) > 0 {
			filename := change[3:len(change)]
			results = append(results, repo.GetFile(filename))
		}
	}

	return results
}

func (repo *Repo) GetFile(filename string) *File {
	commits := repo.commits.ContainsFile(filename)
	workItems, _ := repo.Api.GetByFormattedId(commits.relatedWorkItems()...)

	file := new(File)
	file.Name = filename
	file.LastCommit = commits[0]
	file.Related = commits.relatedFiles(filename)
	file.Contributors = commits.relatedContributors()
	file.WorkItems = workItems
	file.Commits = commits

	return file
}
<|endoftext|>


<commit_before>// Package git contains various commands that shell out to git
package git

import (
	"errors"
	"fmt"
	"io"
	"os/exec"
	"strings"

	"github.com/github/git-lfs/vendor/_nuts/github.com/rubyist/tracerx"
)

func LsRemote(remote, remoteRef string) (string, error) {
	if remote == "" {
		return "", errors.New("remote required")
	}
	if remoteRef == "" {
		return simpleExec(nil, "git", "ls-remote", remote)

	}
	return simpleExec(nil, "git", "ls-remote", remote, remoteRef)
}

func ResolveRef(ref string) (string, error) {
	return simpleExec(nil, "git", "rev-parse", ref)
}

func CurrentRef() (string, error) {
	return ResolveRef("HEAD")
}

func CurrentBranch() (string, error) {
	return simpleExec(nil, "git", "rev-parse", "--abbrev-ref", "HEAD")
}

func CurrentRemoteRef() (string, error) {
	remote, err := CurrentRemote()
	if err != nil {
		return "", err
	}

	return ResolveRef(remote)
}

func CurrentRemote() (string, error) {
	branch, err := CurrentBranch()
	if err != nil {
		return "", err
	}

	if branch == "HEAD" {
		return "", errors.New("not on a branch")
	}

	remote := Config.Find(fmt.Sprintf("branch.%s.remote", branch))
	if remote == "" {
		return "", errors.New("remote not found")
	}

	return remote + "/" + branch, nil
}

func UpdateIndex(file string) error {
	_, err := simpleExec(nil, "git", "update-index", "-q", "--refresh", file)
	return err
}

type gitConfig struct {
}

var Config = &gitConfig{}

// Find returns the git config value for the key
func (c *gitConfig) Find(val string) string {
	output, _ := simpleExec(nil, "git", "config", val)
	return output
}

// SetGlobal sets the git config value for the key in the global config
func (c *gitConfig) SetGlobal(key, val string) {
	simpleExec(nil, "git", "config", "--global", "--add", key, val)
}

// SetGlobal removes the git config value for the key from the global config
func (c *gitConfig) UnsetGlobal(key string) {
	simpleExec(nil, "git", "config", "--global", "--unset", key)
}

// List lists all of the git config values
func (c *gitConfig) List() (string, error) {
	return simpleExec(nil, "git", "config", "-l")
}

// ListFromFile lists all of the git config values in the given config file
func (c *gitConfig) ListFromFile() (string, error) {
	return simpleExec(nil, "git", "config", "-l", "-f", ".gitconfig")
}

// Version returns the git version
func (c *gitConfig) Version() (string, error) {
	return simpleExec(nil, "git", "version")
}

// simpleExec is a small wrapper around os/exec.Command. If the passed stdin
// is not nil it will be hooked up to the subprocess stdin.
func simpleExec(stdin io.Reader, name string, arg ...string) (string, error) {
	tracerx.Printf("run_command: '%s' %s", name, strings.Join(arg, " "))
	cmd := exec.Command(name, arg...)
	if stdin != nil {
		cmd.Stdin = stdin
	}

	output, err := cmd.Output()
	if _, ok := err.(*exec.ExitError); ok {
		return "", nil
	}
	if err != nil {
		return fmt.Sprintf("Error running %s %s", name, arg), err
	}

	return strings.Trim(string(output), " \n"), nil
}
<commit_msg>ララララー ラララー ララ<commit_after>// Package git contains various commands that shell out to git
package git

import (
	"errors"
	"fmt"
	"io"
	"os/exec"
	"strings"

	"github.com/github/git-lfs/vendor/_nuts/github.com/rubyist/tracerx"
)

func LsRemote(remote, remoteRef string) (string, error) {
	if remote == "" {
		return "", errors.New("remote required")
	}
	if remoteRef == "" {
		return simpleExec(nil, "git", "ls-remote", remote)

	}
	return simpleExec(nil, "git", "ls-remote", remote, remoteRef)
}

func ResolveRef(ref string) (string, error) {
	return simpleExec(nil, "git", "rev-parse", ref)
}

func CurrentRef() (string, error) {
	return ResolveRef("HEAD")
}

func CurrentBranch() (string, error) {
	return simpleExec(nil, "git", "rev-parse", "--abbrev-ref", "HEAD")
}

func CurrentRemoteRef() (string, error) {
	remote, err := CurrentRemote()
	if err != nil {
		return "", err
	}

	return ResolveRef(remote)
}

func CurrentRemote() (string, error) {
	branch, err := CurrentBranch()
	if err != nil {
		return "", err
	}

	if branch == "HEAD" {
		return "", errors.New("not on a branch")
	}

	remote := Config.Find(fmt.Sprintf("branch.%s.remote", branch))
	if remote == "" {
		return "", errors.New("remote not found")
	}

	return remote + "/" + branch, nil
}

func UpdateIndex(file string) error {
	_, err := simpleExec(nil, "git", "update-index", "-q", "--refresh", file)
	return err
}

type gitConfig struct {
}

var Config = &gitConfig{}

// Find returns the git config value for the key
func (c *gitConfig) Find(val string) string {
	output, _ := simpleExec(nil, "git", "config", val)
	return output
}

// SetGlobal sets the git config value for the key in the global config
func (c *gitConfig) SetGlobal(key, val string) {
	simpleExec(nil, "git", "config", "--global", "--add", key, val)
}

// UnsetGlobal removes the git config value for the key from the global config
func (c *gitConfig) UnsetGlobal(key string) {
	simpleExec(nil, "git", "config", "--global", "--unset", key)
}

// List lists all of the git config values
func (c *gitConfig) List() (string, error) {
	return simpleExec(nil, "git", "config", "-l")
}

// ListFromFile lists all of the git config values in the given config file
func (c *gitConfig) ListFromFile() (string, error) {
	return simpleExec(nil, "git", "config", "-l", "-f", ".gitconfig")
}

// Version returns the git version
func (c *gitConfig) Version() (string, error) {
	return simpleExec(nil, "git", "version")
}

// simpleExec is a small wrapper around os/exec.Command. If the passed stdin
// is not nil it will be hooked up to the subprocess stdin.
func simpleExec(stdin io.Reader, name string, arg ...string) (string, error) {
	tracerx.Printf("run_command: '%s' %s", name, strings.Join(arg, " "))
	cmd := exec.Command(name, arg...)
	if stdin != nil {
		cmd.Stdin = stdin
	}

	output, err := cmd.Output()
	if _, ok := err.(*exec.ExitError); ok {
		return "", nil
	}
	if err != nil {
		return fmt.Sprintf("Error running %s %s", name, arg), err
	}

	return strings.Trim(string(output), " \n"), nil
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"
	"os/exec"
	"strconv"
	"strings"

	"code.google.com/p/goplan9/plan9/acme"
)

type window struct {
	win    *acme.Win
	offset int
	name   string
}

func currentAcmeWin() (*acme.Win, error) {
	winid := os.Getenv("winid")
	if winid == "" {
		return nil, fmt.Errorf("$winid not set - not running inside acme?")
	}
	id, err := strconv.Atoi(winid)
	if err != nil {
		return nil, fmt.Errorf("invalid $winid %q", winid)
	}
	win, err := acme.Open(id, nil)
	if err != nil {
		return nil, fmt.Errorf("cannot open acme window: %v", err)
	}
	return win, nil
}

func currentWindow() (*window, error) {
	win, err := currentAcmeWin()
	if err != nil {
		return nil, err
	}
	_, _, err = win.ReadAddr()
	if err != nil {
		return nil, fmt.Errorf("cannot read address: %v", err)
	}
	err = win.Ctl("addr=dot")
	if err != nil {
		return nil, fmt.Errorf("cannot set addr=dot: %v", err)
	}
	q0, _, err := win.ReadAddr()
	if err != nil {
		return nil, fmt.Errorf("cannot read address: %v", err)
	}
	b, err := win.ReadAll("tag")
	if err != nil {
		return nil, fmt.Errorf("cannot read tag: %v", err)
	}
	tag := string(b)
	i := strings.Index(tag, " ")
	if i == -1 {
		return nil, fmt.Errorf("tag with no spaces")
	}
	return &window{win: win, name: tag[0:i], offset: q0}, nil
}

func (w *window) showAddr(addr string) {
	w.win.Fprintf("addr", addr)
	w.win.Ctl("dot=addr")
	w.win.Ctl("show")
}

func main() {
	if len(os.Args) < 2 {
		fmt.Fprintf(os.Stderr, "usage: agorn NAME\nReplaces the name under the cursor with NAME\n")
		return
	}
	to := os.Args[1]

	win, err := currentWindow()
	if err != nil {
		fmt.Fprintf(os.Stderr, err.Error())
		return
	}

	err = exec.Command("gorename", "-offset", fmt.Sprintf("%s:#%d", win.name, win.offset), "-to", to).Run()
	if err != nil {
		fmt.Fprintf(os.Stderr, err.Error())
		return
	}
	// fmt.Printf("gorename -offset %s:#%d -to %s", filename, offset, to)

	win.win.Ctl("get")
	win.showAddr(fmt.Sprintf("#%d", win.offset))
}
<commit_msg>Fixed issue #1.<commit_after>package main

import (
	"fmt"
	"io"
	"os"
	"os/exec"
	"strconv"
	"strings"

	"code.google.com/p/goplan9/plan9/acme"
)

type window struct {
	win    *acme.Win
	offset int
	name   string
}

func currentAcmeWin() (*acme.Win, error) {
	winid := os.Getenv("winid")
	if winid == "" {
		return nil, fmt.Errorf("$winid not set - not running inside acme?")
	}
	id, err := strconv.Atoi(winid)
	if err != nil {
		return nil, fmt.Errorf("invalid $winid %q", winid)
	}
	win, err := acme.Open(id, nil)
	if err != nil {
		return nil, fmt.Errorf("cannot open acme window: %v", err)
	}
	return win, nil
}

func currentWindow() (*window, error) {
	win, err := currentAcmeWin()
	if err != nil {
		return nil, err
	}
	_, _, err = win.ReadAddr()
	if err != nil {
		return nil, fmt.Errorf("cannot read address: %v", err)
	}
	err = win.Ctl("addr=dot")
	if err != nil {
		return nil, fmt.Errorf("cannot set addr=dot: %v", err)
	}
	q0, _, err := win.ReadAddr()
	if err != nil {
		return nil, fmt.Errorf("cannot read address: %v", err)
	}
	b, err := win.ReadAll("tag")
	if err != nil {
		return nil, fmt.Errorf("cannot read tag: %v", err)
	}
	tag := string(b)
	i := strings.Index(tag, " ")
	if i == -1 {
		return nil, fmt.Errorf("tag with no spaces")
	}
	body, err := readBody(win)
	if err != nil {
		return nil, fmt.Errorf("cannot read body: %v", err)
	}
	return &window{win: win, name: tag[0:i], offset: toByteOffset(body, q0)}, nil
}

// We would use win.ReadAll except for a bug in acme
// where it crashes when reading trying to read more
// than the negotiated 9P message size.
func readBody(win *acme.Win) ([]byte, error) {
	var body []byte
	buf := make([]byte, 8000)
	for {
		n, err := win.Read("body", buf)
		if err == io.EOF {
			break
		}
		if err != nil {
			return nil, err
		}
		body = append(body, buf[0:n]...)
	}
	return body, nil
}

func toByteOffset(b []byte, off int) int {
	r := 0
	for i, _ := range string(b) {
		if r == off {
			return i
		}
		r++
	}
	return len(b)
}

func (w *window) showAddr(addr string) {
	w.win.Fprintf("addr", addr)
	w.win.Ctl("dot=addr")
	w.win.Ctl("show")
}

func main() {
	if len(os.Args) < 2 {
		fmt.Fprintf(os.Stderr, "usage: agorn NAME\nReplaces the name under the cursor with NAME\n")
		return
	}
	to := os.Args[1]

	win, err := currentWindow()
	if err != nil {
		fmt.Fprintf(os.Stderr, err.Error())
		return
	}

	err = exec.Command("gorename", "-offset", fmt.Sprintf("%s:#%d", win.name, win.offset), "-to", to).Run()
	if err != nil {
		fmt.Fprintf(os.Stderr, err.Error())
		return
	}
	// fmt.Printf("gorename -offset %s:#%d -to %s", filename, offset, to)

	win.win.Ctl("get")
	win.showAddr(fmt.Sprintf("#%d", win.offset))
}
<|endoftext|>


<commit_before>package vm

import (
	"bytes"
	"math/big"
	"strconv"
	"testing"

	"github.com/ethereum/go-ethereum/ethdb"
	"github.com/ethereum/go-ethereum/ethutil"
	"github.com/ethereum/go-ethereum/logger"
	"github.com/ethereum/go-ethereum/state"
	"github.com/ethereum/go-ethereum/tests/helper"
	"github.com/ethereum/go-ethereum/vm"
)

type Account struct {
	Balance string
	Code    string
	Nonce   string
	Storage map[string]string
}

type Log struct {
	AddressF string   `json:"address"`
	DataF    string   `json:"data"`
	TopicsF  []string `json:"topics"`
	BloomF   string   `json:"bloom"`
}

func (self Log) Address() []byte      { return ethutil.Hex2Bytes(self.AddressF) }
func (self Log) Data() []byte         { return ethutil.Hex2Bytes(self.DataF) }
func (self Log) RlpData() interface{} { return nil }
func (self Log) Topics() [][]byte {
	t := make([][]byte, len(self.TopicsF))
	for i, topic := range self.TopicsF {
		t[i] = ethutil.Hex2Bytes(topic)
	}
	return t
}

func StateObjectFromAccount(db ethutil.Database, addr string, account Account) *state.StateObject {
	obj := state.NewStateObject(ethutil.Hex2Bytes(addr), db)
	obj.SetBalance(ethutil.Big(account.Balance))

	if ethutil.IsHex(account.Code) {
		account.Code = account.Code[2:]
	}
	obj.SetCode(ethutil.Hex2Bytes(account.Code))
	obj.SetNonce(ethutil.Big(account.Nonce).Uint64())

	return obj
}

type Env struct {
	CurrentCoinbase   string
	CurrentDifficulty string
	CurrentGasLimit   string
	CurrentNumber     string
	CurrentTimestamp  interface{}
	PreviousHash      string
}

type VmTest struct {
	Callcreates interface{}
	//Env         map[string]string
	Env           Env
	Exec          map[string]string
	Transaction   map[string]string
	Logs          []Log
	Gas           string
	Out           string
	Post          map[string]Account
	Pre           map[string]Account
	PostStateRoot string
}

func RunVmTest(p string, t *testing.T) {

	tests := make(map[string]VmTest)
	helper.CreateFileTests(t, p, &tests)

	for name, test := range tests {
		vm.Debug = true
		helper.Logger.SetLogLevel(4)
		if name != "signextend_Overflow_dj42" {
			continue
		}
		db, _ := ethdb.NewMemDatabase()
		statedb := state.New(nil, db)
		for addr, account := range test.Pre {
			obj := StateObjectFromAccount(db, addr, account)
			statedb.SetStateObject(obj)
			for a, v := range account.Storage {
				obj.SetState(helper.FromHex(a), ethutil.NewValue(helper.FromHex(v)))
			}
		}

		// XXX Yeah, yeah...
		env := make(map[string]string)
		env["currentCoinbase"] = test.Env.CurrentCoinbase
		env["currentDifficulty"] = test.Env.CurrentDifficulty
		env["currentGasLimit"] = test.Env.CurrentGasLimit
		env["currentNumber"] = test.Env.CurrentNumber
		env["previousHash"] = test.Env.PreviousHash
		if n, ok := test.Env.CurrentTimestamp.(float64); ok {
			env["currentTimestamp"] = strconv.Itoa(int(n))
		} else {
			env["currentTimestamp"] = test.Env.CurrentTimestamp.(string)
		}

		var (
			ret  []byte
			gas  *big.Int
			err  error
			logs state.Logs
		)

		isVmTest := len(test.Exec) > 0
		if isVmTest {
			ret, logs, gas, err = helper.RunVm(statedb, env, test.Exec)
		} else {
			ret, logs, gas, err = helper.RunState(statedb, env, test.Transaction)
		}
		statedb.Sync()

		rexp := helper.FromHex(test.Out)
		if bytes.Compare(rexp, ret) != 0 {
			t.Errorf("%s's return failed. Expected %x, got %x\n", name, rexp, ret)
		}

		if isVmTest {
			if len(test.Gas) == 0 && err == nil {
				t.Errorf("%s's gas unspecified, indicating an error. VM returned (incorrectly) successfull", name)
			} else {
				gexp := ethutil.Big(test.Gas)
				if gexp.Cmp(gas) != 0 {
					t.Errorf("%s's gas failed. Expected %v, got %v\n", name, gexp, gas)
				}
			}
		}

		for addr, account := range test.Post {
			obj := statedb.GetStateObject(helper.FromHex(addr))
			if obj == nil {
				continue
			}

			if len(test.Exec) == 0 {
				if obj.Balance().Cmp(ethutil.Big(account.Balance)) != 0 {
					t.Errorf("%s's : (%x) balance failed. Expected %v, got %v => %v\n", name, obj.Address()[:4], account.Balance, obj.Balance(), new(big.Int).Sub(ethutil.Big(account.Balance), obj.Balance()))
				}
			}

			for addr, value := range account.Storage {
				v := obj.GetState(helper.FromHex(addr)).Bytes()
				vexp := helper.FromHex(value)

				if bytes.Compare(v, vexp) != 0 {
					t.Errorf("%s's : (%x: %s) storage failed. Expected %x, got %x (%v %v)\n", name, obj.Address()[0:4], addr, vexp, v, ethutil.BigD(vexp), ethutil.BigD(v))
				}
			}
		}

		if !isVmTest {
			if !bytes.Equal(ethutil.Hex2Bytes(test.PostStateRoot), statedb.Root()) {
				t.Errorf("%s's : Post state root error. Expected %s, got %x", name, test.PostStateRoot, statedb.Root())
			}
		}

		if len(test.Logs) > 0 {
			if len(test.Logs) != len(logs) {
				t.Errorf("log length mismatch. Expected %d, got %d", len(test.Logs), len(logs))
			} else {
				/*
					fmt.Println("A", test.Logs)
					fmt.Println("B", logs)
						for i, log := range test.Logs {
							genBloom := ethutil.LeftPadBytes(types.LogsBloom(state.Logs{logs[i]}).Bytes(), 256)
							if !bytes.Equal(genBloom, ethutil.Hex2Bytes(log.BloomF)) {
								t.Errorf("bloom mismatch")
							}
						}
				*/
			}
		}
		//statedb.Trie().PrintRoot()
	}
	logger.Flush()
}

// I've created a new function for each tests so it's easier to identify where the problem lies if any of them fail.
func TestVMArithmetic(t *testing.T) {
	const fn = "../files/VMTests/vmArithmeticTest.json"
	RunVmTest(fn, t)
}

func TestBitwiseLogicOperation(t *testing.T) {
	const fn = "../files/VMTests/vmBitwiseLogicOperationTest.json"
	RunVmTest(fn, t)
}

func TestBlockInfo(t *testing.T) {
	const fn = "../files/VMTests/vmBlockInfoTest.json"
	RunVmTest(fn, t)
}

func TestEnvironmentalInfo(t *testing.T) {
	const fn = "../files/VMTests/vmEnvironmentalInfoTest.json"
	RunVmTest(fn, t)
}

func TestFlowOperation(t *testing.T) {
	const fn = "../files/VMTests/vmIOandFlowOperationsTest.json"
	RunVmTest(fn, t)
}

func TestLogTest(t *testing.T) {
	const fn = "../files/VMTests/vmLogTest.json"
	RunVmTest(fn, t)
}

func TestPerformance(t *testing.T) {
	t.Skip()
	const fn = "../files/VMTests/vmPerformance.json"
	RunVmTest(fn, t)
}

func TestPushDupSwap(t *testing.T) {
	const fn = "../files/VMTests/vmPushDupSwapTest.json"
	RunVmTest(fn, t)
}

func TestVMSha3(t *testing.T) {
	const fn = "../files/VMTests/vmSha3Test.json"
	RunVmTest(fn, t)
}

func TestVm(t *testing.T) {
	const fn = "../files/VMTests/vmtests.json"
	RunVmTest(fn, t)
}

func TestVmLog(t *testing.T) {
	const fn = "../files/VMTests/vmLogTest.json"
	RunVmTest(fn, t)
}

func TestStateExample(t *testing.T) {
	const fn = "../files/StateTests/stExample.json"
	RunVmTest(fn, t)
}

func TestStateSystemOperations(t *testing.T) {
	const fn = "../files/StateTests/stSystemOperationsTest.json"
	RunVmTest(fn, t)
}

func TestStatePreCompiledContracts(t *testing.T) {
	const fn = "../files/StateTests/stPreCompiledContracts.json"
	RunVmTest(fn, t)
}

func TestStateRecursiveCreate(t *testing.T) {
	const fn = "../files/StateTests/stRecursiveCreate.json"
	RunVmTest(fn, t)
}

func TestStateSpecial(t *testing.T) {
	const fn = "../files/StateTests/stSpecialTest.json"
	RunVmTest(fn, t)
}

func TestStateRefund(t *testing.T) {
	const fn = "../files/StateTests/stRefundTest.json"
	RunVmTest(fn, t)
}

func TestStateBlockHash(t *testing.T) {
	const fn = "../files/StateTests/stBlockHashTest.json"
	RunVmTest(fn, t)
}

func TestStateInitCode(t *testing.T) {
	const fn = "../files/StateTests/stInitCodeTest.json"
	RunVmTest(fn, t)
}

func TestStateLog(t *testing.T) {
	const fn = "../files/StateTests/stLogTests.json"
	RunVmTest(fn, t)
}

func TestStateTransaction(t *testing.T) {
	t.Skip()
	const fn = "../files/StateTests/stTransactionTest.json"
	RunVmTest(fn, t)
}
<commit_msg>run all test<commit_after>package vm

import (
	"bytes"
	"math/big"
	"strconv"
	"testing"

	"github.com/ethereum/go-ethereum/ethdb"
	"github.com/ethereum/go-ethereum/ethutil"
	"github.com/ethereum/go-ethereum/logger"
	"github.com/ethereum/go-ethereum/state"
	"github.com/ethereum/go-ethereum/tests/helper"
)

type Account struct {
	Balance string
	Code    string
	Nonce   string
	Storage map[string]string
}

type Log struct {
	AddressF string   `json:"address"`
	DataF    string   `json:"data"`
	TopicsF  []string `json:"topics"`
	BloomF   string   `json:"bloom"`
}

func (self Log) Address() []byte      { return ethutil.Hex2Bytes(self.AddressF) }
func (self Log) Data() []byte         { return ethutil.Hex2Bytes(self.DataF) }
func (self Log) RlpData() interface{} { return nil }
func (self Log) Topics() [][]byte {
	t := make([][]byte, len(self.TopicsF))
	for i, topic := range self.TopicsF {
		t[i] = ethutil.Hex2Bytes(topic)
	}
	return t
}

func StateObjectFromAccount(db ethutil.Database, addr string, account Account) *state.StateObject {
	obj := state.NewStateObject(ethutil.Hex2Bytes(addr), db)
	obj.SetBalance(ethutil.Big(account.Balance))

	if ethutil.IsHex(account.Code) {
		account.Code = account.Code[2:]
	}
	obj.SetCode(ethutil.Hex2Bytes(account.Code))
	obj.SetNonce(ethutil.Big(account.Nonce).Uint64())

	return obj
}

type Env struct {
	CurrentCoinbase   string
	CurrentDifficulty string
	CurrentGasLimit   string
	CurrentNumber     string
	CurrentTimestamp  interface{}
	PreviousHash      string
}

type VmTest struct {
	Callcreates interface{}
	//Env         map[string]string
	Env           Env
	Exec          map[string]string
	Transaction   map[string]string
	Logs          []Log
	Gas           string
	Out           string
	Post          map[string]Account
	Pre           map[string]Account
	PostStateRoot string
}

func RunVmTest(p string, t *testing.T) {

	tests := make(map[string]VmTest)
	helper.CreateFileTests(t, p, &tests)

	for name, test := range tests {
		db, _ := ethdb.NewMemDatabase()
		statedb := state.New(nil, db)
		for addr, account := range test.Pre {
			obj := StateObjectFromAccount(db, addr, account)
			statedb.SetStateObject(obj)
			for a, v := range account.Storage {
				obj.SetState(helper.FromHex(a), ethutil.NewValue(helper.FromHex(v)))
			}
		}

		// XXX Yeah, yeah...
		env := make(map[string]string)
		env["currentCoinbase"] = test.Env.CurrentCoinbase
		env["currentDifficulty"] = test.Env.CurrentDifficulty
		env["currentGasLimit"] = test.Env.CurrentGasLimit
		env["currentNumber"] = test.Env.CurrentNumber
		env["previousHash"] = test.Env.PreviousHash
		if n, ok := test.Env.CurrentTimestamp.(float64); ok {
			env["currentTimestamp"] = strconv.Itoa(int(n))
		} else {
			env["currentTimestamp"] = test.Env.CurrentTimestamp.(string)
		}

		var (
			ret  []byte
			gas  *big.Int
			err  error
			logs state.Logs
		)

		isVmTest := len(test.Exec) > 0
		if isVmTest {
			ret, logs, gas, err = helper.RunVm(statedb, env, test.Exec)
		} else {
			ret, logs, gas, err = helper.RunState(statedb, env, test.Transaction)
		}
		statedb.Sync()

		rexp := helper.FromHex(test.Out)
		if bytes.Compare(rexp, ret) != 0 {
			t.Errorf("%s's return failed. Expected %x, got %x\n", name, rexp, ret)
		}

		if isVmTest {
			if len(test.Gas) == 0 && err == nil {
				t.Errorf("%s's gas unspecified, indicating an error. VM returned (incorrectly) successfull", name)
			} else {
				gexp := ethutil.Big(test.Gas)
				if gexp.Cmp(gas) != 0 {
					t.Errorf("%s's gas failed. Expected %v, got %v\n", name, gexp, gas)
				}
			}
		}

		for addr, account := range test.Post {
			obj := statedb.GetStateObject(helper.FromHex(addr))
			if obj == nil {
				continue
			}

			if len(test.Exec) == 0 {
				if obj.Balance().Cmp(ethutil.Big(account.Balance)) != 0 {
					t.Errorf("%s's : (%x) balance failed. Expected %v, got %v => %v\n", name, obj.Address()[:4], account.Balance, obj.Balance(), new(big.Int).Sub(ethutil.Big(account.Balance), obj.Balance()))
				}
			}

			for addr, value := range account.Storage {
				v := obj.GetState(helper.FromHex(addr)).Bytes()
				vexp := helper.FromHex(value)

				if bytes.Compare(v, vexp) != 0 {
					t.Errorf("%s's : (%x: %s) storage failed. Expected %x, got %x (%v %v)\n", name, obj.Address()[0:4], addr, vexp, v, ethutil.BigD(vexp), ethutil.BigD(v))
				}
			}
		}

		if !isVmTest {
			if !bytes.Equal(ethutil.Hex2Bytes(test.PostStateRoot), statedb.Root()) {
				t.Errorf("%s's : Post state root error. Expected %s, got %x", name, test.PostStateRoot, statedb.Root())
			}
		}

		if len(test.Logs) > 0 {
			if len(test.Logs) != len(logs) {
				t.Errorf("log length mismatch. Expected %d, got %d", len(test.Logs), len(logs))
			} else {
				/*
					fmt.Println("A", test.Logs)
					fmt.Println("B", logs)
						for i, log := range test.Logs {
							genBloom := ethutil.LeftPadBytes(types.LogsBloom(state.Logs{logs[i]}).Bytes(), 256)
							if !bytes.Equal(genBloom, ethutil.Hex2Bytes(log.BloomF)) {
								t.Errorf("bloom mismatch")
							}
						}
				*/
			}
		}
		//statedb.Trie().PrintRoot()
	}
	logger.Flush()
}

// I've created a new function for each tests so it's easier to identify where the problem lies if any of them fail.
func TestVMArithmetic(t *testing.T) {
	const fn = "../files/VMTests/vmArithmeticTest.json"
	RunVmTest(fn, t)
}

func TestBitwiseLogicOperation(t *testing.T) {
	const fn = "../files/VMTests/vmBitwiseLogicOperationTest.json"
	RunVmTest(fn, t)
}

func TestBlockInfo(t *testing.T) {
	const fn = "../files/VMTests/vmBlockInfoTest.json"
	RunVmTest(fn, t)
}

func TestEnvironmentalInfo(t *testing.T) {
	const fn = "../files/VMTests/vmEnvironmentalInfoTest.json"
	RunVmTest(fn, t)
}

func TestFlowOperation(t *testing.T) {
	const fn = "../files/VMTests/vmIOandFlowOperationsTest.json"
	RunVmTest(fn, t)
}

func TestLogTest(t *testing.T) {
	const fn = "../files/VMTests/vmLogTest.json"
	RunVmTest(fn, t)
}

func TestPerformance(t *testing.T) {
	t.Skip()
	const fn = "../files/VMTests/vmPerformance.json"
	RunVmTest(fn, t)
}

func TestPushDupSwap(t *testing.T) {
	const fn = "../files/VMTests/vmPushDupSwapTest.json"
	RunVmTest(fn, t)
}

func TestVMSha3(t *testing.T) {
	const fn = "../files/VMTests/vmSha3Test.json"
	RunVmTest(fn, t)
}

func TestVm(t *testing.T) {
	const fn = "../files/VMTests/vmtests.json"
	RunVmTest(fn, t)
}

func TestVmLog(t *testing.T) {
	const fn = "../files/VMTests/vmLogTest.json"
	RunVmTest(fn, t)
}

func TestStateExample(t *testing.T) {
	const fn = "../files/StateTests/stExample.json"
	RunVmTest(fn, t)
}

func TestStateSystemOperations(t *testing.T) {
	const fn = "../files/StateTests/stSystemOperationsTest.json"
	RunVmTest(fn, t)
}

func TestStatePreCompiledContracts(t *testing.T) {
	const fn = "../files/StateTests/stPreCompiledContracts.json"
	RunVmTest(fn, t)
}

func TestStateRecursiveCreate(t *testing.T) {
	const fn = "../files/StateTests/stRecursiveCreate.json"
	RunVmTest(fn, t)
}

func TestStateSpecial(t *testing.T) {
	const fn = "../files/StateTests/stSpecialTest.json"
	RunVmTest(fn, t)
}

func TestStateRefund(t *testing.T) {
	const fn = "../files/StateTests/stRefundTest.json"
	RunVmTest(fn, t)
}

func TestStateBlockHash(t *testing.T) {
	const fn = "../files/StateTests/stBlockHashTest.json"
	RunVmTest(fn, t)
}

func TestStateInitCode(t *testing.T) {
	const fn = "../files/StateTests/stInitCodeTest.json"
	RunVmTest(fn, t)
}

func TestStateLog(t *testing.T) {
	const fn = "../files/StateTests/stLogTests.json"
	RunVmTest(fn, t)
}

func TestStateTransaction(t *testing.T) {
	t.Skip()
	const fn = "../files/StateTests/stTransactionTest.json"
	RunVmTest(fn, t)
}
<|endoftext|>


<commit_before>// Copyright 2015 Jonathan J Lawlor. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package matrixexp

import (
	"github.com/gonum/blas/blas64"
)

// General is a typical matrix literal
type General struct {
	blas64.General
}

// Dims returns the matrix dimensions.
func (g *General) Dims() (r, c int) {
	r, c = g.Rows, g.Cols
	return
}

// At returns the value at a given row, column index.
func (g *General) At(r, c int) float64 {
	return g.Data[r*g.Stride+c]
}

// Set changes the value at a given row, column index.
func (g *General) Set(r, c int, v float64) {
	g.Data[r*g.Stride+c] = v
}

// Vector returns all of the values in the matrix as a []float64, in row order.
func (g *General) Vector() []float64 {
	v := make([]float64, len(g.Data))
	copy(v, g.Data)
	return v
}
<commit_msg>Rename matrix receiver for General to m<commit_after>// Copyright 2015 Jonathan J Lawlor. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package matrixexp

import (
	"github.com/gonum/blas/blas64"
)

// General is a typical matrix literal
type General struct {
	blas64.General
}

// Dims returns the matrix dimensions.
func (m *General) Dims() (r, c int) {
	r, c = m.Rows, m.Cols
	return
}

// At returns the value at a given row, column index.
func (m *General) At(r, c int) float64 {
	return m.Data[r*m.Stride+c]
}

// Set changes the value at a given row, column index.
func (m *General) Set(r, c int, v float64) {
	m.Data[r*m.Stride+c] = v
}

// Vector returns all of the values in the matrix as a []float64, in row order.
func (m *General) Vector() []float64 {
	v := make([]float64, len(m.Data))
	copy(v, m.Data)
	return v
}
<|endoftext|>


<commit_before>package tick

import (
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
)

func TestParserLookAhead(t *testing.T) {
	assert := assert.New(t)

	tree := &tree{}
	tree.lex = lex("0 1 2 3")

	assert.Equal(token{tokenNumber, 0, "0"}, tree.next())
	assert.Equal(token{tokenNumber, 2, "1"}, tree.peek())
	assert.Equal(token{tokenNumber, 2, "1"}, tree.next())
	tree.backup()
	assert.Equal(token{tokenNumber, 2, "1"}, tree.next())
	assert.Equal(token{tokenNumber, 4, "2"}, tree.peek())
	tree.backup()
	assert.Equal(token{tokenNumber, 2, "1"}, tree.next())
	assert.Equal(token{tokenNumber, 4, "2"}, tree.next())
	assert.Equal(token{tokenNumber, 6, "3"}, tree.next())
}

func TestParseErrors(t *testing.T) {
	assert := assert.New(t)

	type testCase struct {
		Text  string
		Error string
	}

	test := func(tc testCase) {
		_, err := parse(tc.Text)
		if assert.NotNil(err) {
			assert.Equal(tc.Error, err.Error())
		}
	}

	cases := []testCase{
		testCase{
			Text:  "a\n\n\nvar b = ",
			Error: `parser: unexpected EOF line 4 char 9 in "\n\nvar b = ". expected: "identifier"`,
		},
		testCase{
			Text:  "a\n\n\nvar b = stream.window()var period",
			Error: `parser: unexpected EOF line 4 char 34 in "var period". expected: "="`,
		},
		testCase{
			Text:  "a\n\n\nvar b = stream.window(\nb.period(10s)",
			Error: `parser: unexpected EOF line 5 char 14 in "eriod(10s)". expected: ")"`,
		},
	}

	for _, tc := range cases {
		test(tc)
	}
}
func TestParseStrings(t *testing.T) {
	assert := assert.New(t)

	testCases := []struct {
		script  string
		literal string
	}{
		{
			script:  `f('a')`,
			literal: "a",
		},
		{
			script:  `f("a")`,
			literal: "a",
		},
		{
			script:  `f('''a''')`,
			literal: "a",
		},
		{
			script:  `f('a\'')`,
			literal: "a'",
		},
		{
			script:  `f("a\"")`,
			literal: "a\"",
		},
		{
			script:  `f('''\'a''')`,
			literal: `\'a`,
		},
	}

	for _, tc := range testCases {
		tree, err := parse(tc.script)
		assert.Nil(err)

		//Assert we have a list of one statement
		l, ok := tree.Root.(*listNode)
		if !assert.True(ok, "tree.Root is not a list node") {
			t.FailNow()
		}
		if !assert.Equal(1, len(l.Nodes), "Did not get exactly one node in statement list") {
			t.FailNow()
		}

		//Assert the first statement is a binary node with operator '='
		f, ok := l.Nodes[0].(*funcNode)
		if !assert.True(ok, "first statement is not a func node %q", l.Nodes[0]) {
			t.FailNow()
		}
		if !assert.Equal(1, len(f.Args), "unexpected number of args got %d exp %d", len(f.Args), 1) {
			t.FailNow()
		}
		str, ok := f.Args[0].(*stringNode)
		if !assert.True(ok, "first argument is not a string node %q", f.Args[0]) {
			t.FailNow()
		}

		assert.Equal(tc.literal, str.Literal)
	}

}

func TestParseSingleStmt(t *testing.T) {
	assert := assert.New(t)

	script := `
var x = stream
		.window()
		.period(5m)
		.every(1m)
		.map(influxql.agg.mean("value"))
`
	tree, err := parse(script)
	assert.Nil(err)

	// Expect a tree like so:
	/*
	           Root
	            |
	          (b0 =)
	           / \
	          /   \
	         /     \
	       (x)     (b1 .)
	                / \
	               /   \
	              /     \
	         (map)       (b2 .)
	          /            |   \
	         /             |    \
	        /              |     \
	    (b5 .)            (every) (b3 .)
	     /  \               |       / \
	    /    \             (1m)    /   \
	   /      \                   /     \
	 (mean)    (b6 .)         (period) (b4 .)
	    |       /  \             |       / \
	 ("value") /    \           (5m)    /   \
	          /      \                 /     \
	       (agg)  (influxql)      (window) (stream)
	*/
	//Notice the inverted nature of the tree. This structure makes evaluating the tree recursive depth first.

	//Assert we have a list of one statement
	l, ok := tree.Root.(*listNode)
	if !assert.True(ok, "tree.Root is not a list node") {
		t.FailNow()
	}
	if !assert.Equal(1, len(l.Nodes), "Did not get exactly one node in statement list") {
		t.FailNow()
	}

	//Assert the first statement is a binary node with operator '='
	b0, ok := l.Nodes[0].(*binaryNode)
	if !assert.True(ok, "first statement is not a binary node %q", l.Nodes[0]) {
		t.FailNow()
	}
	assert.Equal("=", b0.Operator.val)

	//Assert b0.left is an ident node of 'x'
	varX, ok := b0.Left.(*identNode)
	if !assert.True(ok, "b0.left is not an ident node %q", b0.Left) {
		t.FailNow()
	}
	assert.Equal("x", varX.Ident)

	//Assert b0.right is a binary node of operator '.'
	b1, ok := b0.Right.(*binaryNode)
	if !assert.True(ok, "b0.right is not a binary node %q", b0.Right) {
		t.FailNow()
	}
	assert.Equal(".", b1.Operator.val)

	//Assert b1.left is func node 'map'
	fMap, ok := b1.Left.(*funcNode)
	if !assert.True(ok, "b1.left is not func node %q", b1.Left) {
		t.FailNow()
	}
	assert.Equal("map", fMap.Func)
	if assert.Equal(1, len(fMap.Args)) {

		//Assert first arg to 'map' is binary node
		b5, ok := fMap.Args[0].(*binaryNode)
		if !assert.True(ok, "First argument to 'map' is not binary node %q", fMap.Args[0]) {
			t.FailNow()
		}

		//Assert b5.left is ident node 'mean'
		fMean, ok := b5.Left.(*funcNode)
		if assert.True(ok, "b5.left is not a func node %q", b5.Left) {
			assert.Equal("mean", fMean.Func)
		}
		// Assert mean() has single "value" argument
		if assert.Equal(1, len(fMean.Args)) {
			//Assert first arg to 'mean' is stringNode
			value, ok := fMean.Args[0].(*stringNode)
			if assert.True(ok, "first argument to 'mean' is not string node %q", fMap.Args[0]) {
				assert.Equal("value", value.Literal)
			}
		}

		//Assert b5.right is binary node of operator '.'
		b6, ok := b5.Right.(*binaryNode)
		if assert.True(ok, "b5.right is not a binary node %q", b5.Right) {
			assert.Equal(".", b6.Operator.val)
		}

		//Assert b6.left is ident node 'agg'
		agg, ok := b6.Left.(*identNode)
		if assert.True(ok, "b6.left is not a ident node %q", b6.Left) {
			assert.Equal("agg", agg.Ident)
		}

		//Assert b6.right is ident node 'influxql'
		influxql, ok := b6.Right.(*identNode)
		if assert.True(ok, "b6.right is not a ident node %q", b6.Right) {
			assert.Equal("influxql", influxql.Ident)
		}

	}

	//Assert b1.right is binary node of operator '.'
	b2, ok := b1.Right.(*binaryNode)
	if !assert.True(ok, "b1.right is not a binary node %q", b1.Right) {
		t.FailNow()
	}
	assert.Equal(".", b2.Operator.val)

	//Assert b2.left is func node 'every'
	fEvery, ok := b2.Left.(*funcNode)
	if !assert.True(ok, "b2.left is not func node %q", b2.Left) {
		t.FailNow()
	}
	assert.Equal("every", fEvery.Func)
	if assert.Equal(1, len(fEvery.Args)) {
		d, ok := fEvery.Args[0].(*durationNode)
		if assert.True(ok, "First argument to 'every' is not duration node %q", fEvery.Args[0]) {
			assert.Equal(time.Minute, d.Dur)
		}
	}

	//Assert b2.right is binary node of operator '.'
	b3, ok := b2.Right.(*binaryNode)
	if !assert.True(ok, "b2.right is not a binary node %q", b2.Right) {
		t.FailNow()
	}
	assert.Equal(".", b3.Operator.val)

	//Assert b3.left is func node 'period'
	fPeriod, ok := b3.Left.(*funcNode)
	if !assert.True(ok, "b3.left is not func node %q", b3.Left) {
		t.FailNow()
	}
	assert.Equal("period", fPeriod.Func)
	if assert.Equal(1, len(fPeriod.Args)) {
		d, ok := fPeriod.Args[0].(*durationNode)
		if assert.True(ok, "First argument to 'period' is not duration node %q", fPeriod.Args[0]) {
			assert.Equal(time.Minute*5, d.Dur)
		}
	}

	//Assert b3.right is a binary node of operator '.'
	b4, ok := b3.Right.(*binaryNode)
	if !assert.True(ok, "b3.right is not a binary node %q", b3.Right) {
		t.FailNow()
	}
	assert.Equal(".", b4.Operator.val)

	//Assert b4.left is func node 'window'
	fWindow, ok := b4.Left.(*funcNode)
	if !assert.True(ok, "b4.left is not func node %q", b4.Left) {
		t.FailNow()
	}
	assert.Equal("window", fWindow.Func)
	assert.Equal(0, len(fWindow.Args))

	//Assert b4.right is ident node 'stream'
	iStream, ok := b4.Right.(*identNode)
	if !assert.True(ok, "b4.right is not ident node %q", b4.Right) {
		t.FailNow()
	}
	assert.Equal("stream", iStream.Ident)

}
<commit_msg>update comments<commit_after>package tick

import (
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
)

func TestParserLookAhead(t *testing.T) {
	assert := assert.New(t)

	tree := &tree{}
	tree.lex = lex("0 1 2 3")

	assert.Equal(token{tokenNumber, 0, "0"}, tree.next())
	assert.Equal(token{tokenNumber, 2, "1"}, tree.peek())
	assert.Equal(token{tokenNumber, 2, "1"}, tree.next())
	tree.backup()
	assert.Equal(token{tokenNumber, 2, "1"}, tree.next())
	assert.Equal(token{tokenNumber, 4, "2"}, tree.peek())
	tree.backup()
	assert.Equal(token{tokenNumber, 2, "1"}, tree.next())
	assert.Equal(token{tokenNumber, 4, "2"}, tree.next())
	assert.Equal(token{tokenNumber, 6, "3"}, tree.next())
}

func TestParseErrors(t *testing.T) {
	assert := assert.New(t)

	type testCase struct {
		Text  string
		Error string
	}

	test := func(tc testCase) {
		_, err := parse(tc.Text)
		if assert.NotNil(err) {
			assert.Equal(tc.Error, err.Error())
		}
	}

	cases := []testCase{
		testCase{
			Text:  "a\n\n\nvar b = ",
			Error: `parser: unexpected EOF line 4 char 9 in "\n\nvar b = ". expected: "identifier"`,
		},
		testCase{
			Text:  "a\n\n\nvar b = stream.window()var period",
			Error: `parser: unexpected EOF line 4 char 34 in "var period". expected: "="`,
		},
		testCase{
			Text:  "a\n\n\nvar b = stream.window(\nb.period(10s)",
			Error: `parser: unexpected EOF line 5 char 14 in "eriod(10s)". expected: ")"`,
		},
	}

	for _, tc := range cases {
		test(tc)
	}
}
func TestParseStrings(t *testing.T) {
	assert := assert.New(t)

	testCases := []struct {
		script  string
		literal string
	}{
		{
			script:  `f('a')`,
			literal: "a",
		},
		{
			script:  `f("a")`,
			literal: "a",
		},
		{
			script:  `f('''a''')`,
			literal: "a",
		},
		{
			script:  `f('a\'')`,
			literal: "a'",
		},
		{
			script:  `f("a\"")`,
			literal: "a\"",
		},
		{
			script:  `f('''\'a''')`,
			literal: `\'a`,
		},
	}

	for _, tc := range testCases {
		tree, err := parse(tc.script)
		assert.Nil(err)

		//Assert we have a list of one statement
		l, ok := tree.Root.(*listNode)
		if !assert.True(ok, "tree.Root is not a list node") {
			t.FailNow()
		}
		if !assert.Equal(1, len(l.Nodes), "Did not get exactly one node in statement list") {
			t.FailNow()
		}

		//Assert the first statement is a function with one stringNode argument
		f, ok := l.Nodes[0].(*funcNode)
		if !assert.True(ok, "first statement is not a func node %q", l.Nodes[0]) {
			t.FailNow()
		}
		if !assert.Equal(1, len(f.Args), "unexpected number of args got %d exp %d", len(f.Args), 1) {
			t.FailNow()
		}
		str, ok := f.Args[0].(*stringNode)
		if !assert.True(ok, "first argument is not a string node %q", f.Args[0]) {
			t.FailNow()
		}

		// Assert strings literals are equal
		assert.Equal(tc.literal, str.Literal)
	}

}

func TestParseSingleStmt(t *testing.T) {
	assert := assert.New(t)

	script := `
var x = stream
		.window()
		.period(5m)
		.every(1m)
		.map(influxql.agg.mean("value"))
`
	tree, err := parse(script)
	assert.Nil(err)

	// Expect a tree like so:
	/*
	           Root
	            |
	          (b0 =)
	           / \
	          /   \
	         /     \
	       (x)     (b1 .)
	                / \
	               /   \
	              /     \
	         (map)       (b2 .)
	          /            |   \
	         /             |    \
	        /              |     \
	    (b5 .)            (every) (b3 .)
	     /  \               |       / \
	    /    \             (1m)    /   \
	   /      \                   /     \
	 (mean)    (b6 .)         (period) (b4 .)
	    |       /  \             |       / \
	 ("value") /    \           (5m)    /   \
	          /      \                 /     \
	       (agg)  (influxql)      (window) (stream)
	*/
	//Notice the inverted nature of the tree. This structure makes evaluating the tree recursive depth first.

	//Assert we have a list of one statement
	l, ok := tree.Root.(*listNode)
	if !assert.True(ok, "tree.Root is not a list node") {
		t.FailNow()
	}
	if !assert.Equal(1, len(l.Nodes), "Did not get exactly one node in statement list") {
		t.FailNow()
	}

	//Assert the first statement is a binary node with operator '='
	b0, ok := l.Nodes[0].(*binaryNode)
	if !assert.True(ok, "first statement is not a binary node %q", l.Nodes[0]) {
		t.FailNow()
	}
	assert.Equal("=", b0.Operator.val)

	//Assert b0.left is an ident node of 'x'
	varX, ok := b0.Left.(*identNode)
	if !assert.True(ok, "b0.left is not an ident node %q", b0.Left) {
		t.FailNow()
	}
	assert.Equal("x", varX.Ident)

	//Assert b0.right is a binary node of operator '.'
	b1, ok := b0.Right.(*binaryNode)
	if !assert.True(ok, "b0.right is not a binary node %q", b0.Right) {
		t.FailNow()
	}
	assert.Equal(".", b1.Operator.val)

	//Assert b1.left is func node 'map'
	fMap, ok := b1.Left.(*funcNode)
	if !assert.True(ok, "b1.left is not func node %q", b1.Left) {
		t.FailNow()
	}
	assert.Equal("map", fMap.Func)
	if assert.Equal(1, len(fMap.Args)) {

		//Assert first arg to 'map' is binary node
		b5, ok := fMap.Args[0].(*binaryNode)
		if !assert.True(ok, "First argument to 'map' is not binary node %q", fMap.Args[0]) {
			t.FailNow()
		}

		//Assert b5.left is ident node 'mean'
		fMean, ok := b5.Left.(*funcNode)
		if assert.True(ok, "b5.left is not a func node %q", b5.Left) {
			assert.Equal("mean", fMean.Func)
		}
		// Assert mean() has single "value" argument
		if assert.Equal(1, len(fMean.Args)) {
			//Assert first arg to 'mean' is stringNode
			value, ok := fMean.Args[0].(*stringNode)
			if assert.True(ok, "first argument to 'mean' is not string node %q", fMap.Args[0]) {
				assert.Equal("value", value.Literal)
			}
		}

		//Assert b5.right is binary node of operator '.'
		b6, ok := b5.Right.(*binaryNode)
		if assert.True(ok, "b5.right is not a binary node %q", b5.Right) {
			assert.Equal(".", b6.Operator.val)
		}

		//Assert b6.left is ident node 'agg'
		agg, ok := b6.Left.(*identNode)
		if assert.True(ok, "b6.left is not a ident node %q", b6.Left) {
			assert.Equal("agg", agg.Ident)
		}

		//Assert b6.right is ident node 'influxql'
		influxql, ok := b6.Right.(*identNode)
		if assert.True(ok, "b6.right is not a ident node %q", b6.Right) {
			assert.Equal("influxql", influxql.Ident)
		}

	}

	//Assert b1.right is binary node of operator '.'
	b2, ok := b1.Right.(*binaryNode)
	if !assert.True(ok, "b1.right is not a binary node %q", b1.Right) {
		t.FailNow()
	}
	assert.Equal(".", b2.Operator.val)

	//Assert b2.left is func node 'every'
	fEvery, ok := b2.Left.(*funcNode)
	if !assert.True(ok, "b2.left is not func node %q", b2.Left) {
		t.FailNow()
	}
	assert.Equal("every", fEvery.Func)
	if assert.Equal(1, len(fEvery.Args)) {
		d, ok := fEvery.Args[0].(*durationNode)
		if assert.True(ok, "First argument to 'every' is not duration node %q", fEvery.Args[0]) {
			assert.Equal(time.Minute, d.Dur)
		}
	}

	//Assert b2.right is binary node of operator '.'
	b3, ok := b2.Right.(*binaryNode)
	if !assert.True(ok, "b2.right is not a binary node %q", b2.Right) {
		t.FailNow()
	}
	assert.Equal(".", b3.Operator.val)

	//Assert b3.left is func node 'period'
	fPeriod, ok := b3.Left.(*funcNode)
	if !assert.True(ok, "b3.left is not func node %q", b3.Left) {
		t.FailNow()
	}
	assert.Equal("period", fPeriod.Func)
	if assert.Equal(1, len(fPeriod.Args)) {
		d, ok := fPeriod.Args[0].(*durationNode)
		if assert.True(ok, "First argument to 'period' is not duration node %q", fPeriod.Args[0]) {
			assert.Equal(time.Minute*5, d.Dur)
		}
	}

	//Assert b3.right is a binary node of operator '.'
	b4, ok := b3.Right.(*binaryNode)
	if !assert.True(ok, "b3.right is not a binary node %q", b3.Right) {
		t.FailNow()
	}
	assert.Equal(".", b4.Operator.val)

	//Assert b4.left is func node 'window'
	fWindow, ok := b4.Left.(*funcNode)
	if !assert.True(ok, "b4.left is not func node %q", b4.Left) {
		t.FailNow()
	}
	assert.Equal("window", fWindow.Func)
	assert.Equal(0, len(fWindow.Args))

	//Assert b4.right is ident node 'stream'
	iStream, ok := b4.Right.(*identNode)
	if !assert.True(ok, "b4.right is not ident node %q", b4.Right) {
		t.FailNow()
	}
	assert.Equal("stream", iStream.Ident)

}
<|endoftext|>


<commit_before>package genkins

import (
	"net/http"
	"net/url"
	"encoding/json"
	"bytes"
	"strings"
	"log"
)

const (
	libraryVersion = "0.1"
	userAgent      = "genkins/" + libraryVersion
)

type Client struct {
	BaseURL  *url.URL

	client *http.Client

	username string
	apiKey  string

	UserAgent string

	Jobs *JobsService
	Builds *BuildsService
}

func (c *Client) NewRequest(method string, urlString string, body interface{}) (*http.Request, error) {

	rel, err := url.Parse(urlString)

	if err != nil {
		return nil, err
	}

	u, err := url.Parse(strings.TrimRight(c.BaseURL.String(), "/") + rel.String())

	if err != nil {
		return nil, err
	}

	buf := new(bytes.Buffer)
	if body != nil {
		err := json.NewEncoder(buf).Encode(body)
		if err != nil {
			return nil, err
		}
	}
	log.Println(u.String())
	req, err := http.NewRequest(method, u.String(), buf)

	if err != nil {
		return nil, err
	}

	if c.username != "" {
		req.SetBasicAuth(c.username, c.apiKey)
	}
	req.Header.Add("User-Agent", c.UserAgent)

	return req, nil
}

func (c *Client) Do(req *http.Request, output interface {}) error {

	resp, err := c.client.Do(req)
	if err != nil {
		return err
	}

	defer resp.Body.Close()

	json.NewDecoder(resp.Body).Decode(output)

	return nil
}

func NewClient(hostname string, usernameStr string, apiKeyStr string) *Client {
	httpClient := http.DefaultClient

	baseURL, _ := url.Parse(hostname)

	c := &Client{
		client: httpClient,
		UserAgent: userAgent,
		BaseURL: baseURL,
		apiKey: apiKeyStr,
		username: usernameStr,
	}
	c.Jobs = &JobsService{client: c}
	c.Builds = &BuildsService{client: c}
	return c
}
<commit_msg>Remove log<commit_after>package genkins

import (
	"net/http"
	"net/url"
	"encoding/json"
	"bytes"
	"strings"
)

const (
	libraryVersion = "0.1"
	userAgent      = "genkins/" + libraryVersion
)

type Client struct {
	BaseURL  *url.URL

	client *http.Client

	username string
	apiKey  string

	UserAgent string

	Jobs *JobsService
	Builds *BuildsService
}

func (c *Client) NewRequest(method string, urlString string, body interface{}) (*http.Request, error) {

	rel, err := url.Parse(urlString)

	if err != nil {
		return nil, err
	}

	u, err := url.Parse(strings.TrimRight(c.BaseURL.String(), "/") + rel.String())

	if err != nil {
		return nil, err
	}

	buf := new(bytes.Buffer)
	if body != nil {
		err := json.NewEncoder(buf).Encode(body)
		if err != nil {
			return nil, err
		}
	}
	req, err := http.NewRequest(method, u.String(), buf)

	if err != nil {
		return nil, err
	}

	if c.username != "" {
		req.SetBasicAuth(c.username, c.apiKey)
	}
	req.Header.Add("User-Agent", c.UserAgent)

	return req, nil
}

func (c *Client) Do(req *http.Request, output interface {}) error {

	resp, err := c.client.Do(req)
	if err != nil {
		return err
	}

	defer resp.Body.Close()

	json.NewDecoder(resp.Body).Decode(output)

	return nil
}

func NewClient(hostname string, usernameStr string, apiKeyStr string) *Client {
	httpClient := http.DefaultClient

	baseURL, _ := url.Parse(hostname)

	c := &Client{
		client: httpClient,
		UserAgent: userAgent,
		BaseURL: baseURL,
		apiKey: apiKeyStr,
		username: usernameStr,
	}
	c.Jobs = &JobsService{client: c}
	c.Builds = &BuildsService{client: c}
	return c
}
<|endoftext|>