<commit_before>package parser

import (
	"go/ast"
	"go/token"
	"fmt"
	"log"
	"strings"

	"github.com/dglo/java2go/grammar"
)

// list of Java classes which inherit from AbstractList
var javaListType = []string { "List", "ArrayList", "LinkedList", "Stack",
	"Vector" }

type TransformFunc func(parent GoObject, prog *GoProgram, cls GoClass,
	object GoObject) (GoObject, bool)

type GoObject interface {
	RunTransform(xform TransformFunc, gp *GoProgram, cls GoClass,
		parent GoObject) (GoObject, bool)
}

type GoTypedObject interface {
	GoObject
	VarType() *TypeData
}

func convertToBlock(obj GoObject) (*GoBlock, error) {
	if blk, ok := obj.(*GoBlock); ok {
		return blk, nil
	}

	return nil, fmt.Errorf("%v<%T> is not a *GoBlock", obj, obj)
}

func convertToExpr(obj GoObject) (GoExpr, error) {
	if expr, ok := obj.(GoExpr); ok {
		return expr, nil
	}

	return nil, fmt.Errorf("%v<%T> is not a GoExpr", obj, obj)
}

func convertToMethod(obj GoObject) (GoMethod, error) {
	if mthd, ok := obj.(GoMethod); ok {
		return mthd, nil
	}

	return nil, fmt.Errorf("%v<%T> is not a GoMethod", obj, obj)
}

func convertToMethodArgs(obj GoObject) (*GoMethodArguments, error) {
	if mthd, ok := obj.(*GoMethodArguments); ok {
		return mthd, nil
	}

	return nil, fmt.Errorf("%v<%T> is not a *GoMethodArguments", obj, obj)
}

func convertToStmt(obj GoObject) (GoStatement, error) {
	if stmt, ok := obj.(GoStatement); ok {
		return stmt, nil
	}

	return nil, fmt.Errorf("%v<%T> is not a GoStatement", obj, obj)
}

func convertToVar(obj GoObject) (GoVar, error) {
	if govar, ok := obj.(GoVar); ok {
		return govar, nil
	}

	return nil, fmt.Errorf("%v<%T> is not a GoVar", obj, obj)
}

func convertToVarInit(obj GoObject) (*GoVarInit, error) {
	if vi, ok := obj.(*GoVarInit); ok {
		return vi, nil
	}

	return nil, fmt.Errorf("%v<%T> is not a *GoVarInit", obj, obj)
}

func getFmtClass(prog *GoProgram) GoClass {
	fmtcls := prog.findClass("fmt")
	if fmtcls == nil {
		fmtcls = NewGoFakeClass("fmt")
		prog.addClass(fmtcls)

		// make sure "fmt" is imported
		prog.addImport("fmt", "")
	}

	return fmtcls
}

type GoPkgName struct {
	pkg string
	name string
}

func (gpn *GoPkgName) Expr() ast.Expr {
	return &ast.SelectorExpr{X: ast.NewIdent(gpn.pkg),
		Sel: ast.NewIdent(gpn.name)}
}

func (gpn *GoPkgName) hasVariable(govar GoVar) bool {
	return false
}

func (gpn *GoPkgName) Init() ast.Stmt {
	return nil
}

func (gpn *GoPkgName) RunTransform(xform TransformFunc, prog *GoProgram,
	cls GoClass, parent GoObject) (GoObject, bool) {
	return xform(parent, prog, cls, gpn)
}

func (gpn *GoPkgName) String() string {
	return fmt.Sprintf("GoPkgName[%s|%s]", gpn.pkg, gpn.name)
}

func (gpn *GoPkgName) VarType() *TypeData {
	panic("GoPkgName.VarType() unimplemented")
}

// transform "array.length" to "len(array)"
func TransformArrayLen(parent GoObject, prog *GoProgram, cls GoClass,
	object GoObject) (GoObject, bool) {
	var ref *GoClassAttribute
	var ok bool
	if ref, ok = object.(*GoClassAttribute); !ok {
		return nil, true
	}

	if ref.Suffix() != "length" || ref.VarType().vtype != VT_ARRAY {
		return nil, true
	}

	fm := NewGoFakeMethod(nil, "len", intType)
	args := &GoMethodArguments{args: []GoExpr{ ref.govar, }}

	return &GoMethodAccess{method: fm, args: args}, false
}

// transform "System.out.print*(...)" to "fmt.Print*(...)" and
// "System.err.print*(...)" to "fmt.Fprintf(os.Stderr, ...)"
func TransformSysfile(parent GoObject, prog *GoProgram, cls GoClass,
	object GoObject) (GoObject, bool) {
	var ma *GoMethodAccess
	var ok bool
	if ma, ok = object.(*GoMethodAccess); !ok {
		return nil, true
	}

	if ma.method == nil {
		return nil, true
	}

	mcls := ma.method.Class()
	if mcls == nil || mcls.IsNil() {
		return nil, true
	}

	clsname := mcls.Name()
	name := ma.method.Name()

	if !strings.HasPrefix(clsname, "System.") ||
		!strings.HasPrefix(name, "print") {
		return nil, true
	}

	fmtcls := getFmtClass(prog)

	var fixed string
	var args *GoMethodArguments
	if strings.HasSuffix(clsname, ".out") {
		fixed = strings.ToUpper(name[:1]) + name[1:]
		args = ma.args
	} else {
		fixed = "F" + name
		arglist := make([]GoExpr, 1)
		arglist[0] = &GoPkgName{pkg: "os", name: "Stderr"}
		arglist = append(arglist, ma.args.args...)
		args = &GoMethodArguments{args: arglist}

		// make sure "os" is imported
		prog.addImport("os", "")
	}

	fm := NewGoFakeMethod(fmtcls, fixed, nil)

	return &GoMethodAccess{method: fm, args: args}, false
}

// transform "func main(String[] xxx)" to "func main()" and all "xxx" references
// to "os.Args"
func TransformMainArgs(parent GoObject, prog *GoProgram, cls GoClass,
	object GoObject) (GoObject, bool) {
	var cm *GoClassMethod
	var ok bool
	if cm, ok = object.(*GoClassMethod); !ok {
		return nil, true
	}

	if cm.method_type != mt_main {
		return nil, true
	}

	if cm.params == nil || len(cm.params) != 1 {
		return nil, true
	}

	arg := cm.params[0]

	if cm.body.hasVariable(arg) {
		arg.SetGoName("os.Args")

		// make sure "os" is imported
		prog.addImport("os", "")
	}

	cm.params = nil

	return nil, true
}

// transform "foo(this)" to "foo(rcvr)"
func TransformThisArg(parent GoObject, prog *GoProgram, cls GoClass,
	object GoObject) (GoObject, bool) {
	var mref *GoMethodReference
	var ok bool
	if mref, ok = object.(*GoMethodReference); !ok {
		return nil, true
	}

	if mref.args == nil {
		return nil, true
	}

	for i, arg := range mref.args.args {
		var kwd *GoKeyword
		if kwd, ok = arg.(*GoKeyword); ok {
			if kwd.token == grammar.THIS {
				mref.args.args[i] =
					NewFakeVar(prog.Receiver(cls.Name()), nil, 0)
			}
		}
	}

	return nil, true
}

// transform method calls for List variants to appropriate array operations
func TransformListMethods(parent GoObject, prog *GoProgram, cls GoClass,
	object GoObject) (GoObject, bool) {
	var mref *GoMethodAccessVar
	var ok bool
	if mref, ok = object.(*GoMethodAccessVar); !ok {
		return nil, true
	}

	var is_list bool
	for _, n := range javaListType {
		if mref.govar.VarType().IsClass(n) {
			is_list = true
			break
		}
	}
	if !is_list {
		return nil, true
	}

	switch mref.method.Name() {
	case "add":
		if len(mref.args.args) != 1 {
			log.Printf("//ERR// Cannot convert %v add() with %d args\n",
				mref.govar.VarType(), len(mref.args.args))
			return nil, true
		}

		apnd := NewGoFakeMethod(nil, "append", mref.govar.VarType())
		args := &GoMethodArguments{args: []GoExpr{ mref.govar,
			mref.args.args[0]}}

		rhs := []GoExpr{ &GoMethodAccess{method: apnd, args: args}, }

		return &GoAssign{govar: mref.govar, tok: token.ASSIGN, rhs: rhs}, false
	case "isEmpty":
		if len(mref.args.args) != 0 {
			log.Printf("//ERR// Cannot convert %v isEmpty() with %d args\n",
				mref.govar.VarType(), len(mref.args.args))
			return nil, true
		}

		args := &GoMethodArguments{args: []GoExpr{ mref.govar, }}
		x := &GoMethodAccess{method: NewGoFakeMethod(nil, "len", intType),
			args: args}
		return &GoBinaryExpr{x: x, op: token.EQL, y: &GoLiteral{text: "0"}},
		false
	case "get":
		if len(mref.args.args) != 1 {
			log.Printf("//ERR// Cannot convert %v get() with %d args\n",
				mref.govar.VarType(), len(mref.args.args))
			return nil, true
		}

		return &GoArrayReference{govar: mref.govar, index: mref.args.args[0]},
		false
	case "size":
		fm := NewGoFakeMethod(nil, "len", intType)
		args := &GoMethodArguments{args: []GoExpr{ mref.govar, }}

		return &GoMethodAccess{method: fm, args: args}, false
	default:
		log.Printf("//ERR// Not converting %v method %v\n",
			mref.govar.VarType(), mref.method.Name())
		break
	}

	return nil, true
}

// transform String.format method call into fmt.Sprintf
func TransformStringFormat(parent GoObject, prog *GoProgram, cls GoClass,
	object GoObject) (GoObject, bool) {

	var mref *GoMethodReference
	var ok bool
	if mref, ok = object.(*GoMethodReference); !ok {
		return nil, true
	}

	if mref.name == "format" && !mref.class.IsNil() &&
		mref.class.Name() == "String" {
		fmtcls := getFmtClass(prog)

		return NewGoMethodReference(fmtcls, "Sprintf", mref.args, false), false
	}

	return nil, true
}

// transform string addition into fmt.Sprintf
func TransformStringAddition(parent GoObject, prog *GoProgram, cls GoClass,
	object GoObject) (GoObject, bool) {

	var bex *GoBinaryExpr
	var ok bool
	if bex, ok = object.(*GoBinaryExpr); !ok {
		return nil, true
	}

	var x GoTypedObject
	if x, ok = bex.x.(GoTypedObject); !ok {
		return nil, true
	}

	if x.VarType() != stringType {
		return nil, true
	}

	return transformBinaryStringExpression(prog, bex)
}

func joinStrings(s1 string, s2 string) string {
	if s1[0] != '"' || s1[len(s1)-1] != '"' {
		panic(fmt.Sprintf("String %v is not quoted", s1))
	}
	if s2[0] != '"' || s2[len(s2)-1] != '"' {
		panic(fmt.Sprintf("String %v is not quoted", s2))
	}
	s := fmt.Sprintf("\"%s%s\"", s1[1:len(s1)-1], s2[1:len(s2)-1])
	return s
}

func transformBinaryStringExpression(prog *GoProgram, bex *GoBinaryExpr) (GoObject, bool) {
	if bex.op != token.ADD {
		return nil, true
	}

	switch x := bex.x.(type) {
	case *GoLiteral:
		if !x.isString() {
			// ignore non-string addition
			return nil, true
		}

		if y, ok := bex.y.(*GoLiteral); ok {
			if y.isString() {
				return NewGoLiteral(joinStrings(x.text, y.text)), false
			}
		}
	case *GoMethodAccess:
		if x.method.VarType() != stringType {
			return nil, true
		}

		if x.method.Name() == "Sprintf" {
			if fmtstr, ok := x.args.args[0].(*GoLiteral); !ok {
				log.Printf("//ERR// First Sprintf argument should be " +
					" *GoLiteral not %T\n", x.args.args[0])
				return nil, true
			} else {
				x.args.args[0] = NewGoLiteral(joinStrings("\"%v\"",
					fmtstr.text))
			}
			x.args.args = append(x.args.args, bex.y)
			return x, false
		}
	}

	fmtcls := getFmtClass(prog)

	fmtstr := NewGoLiteral("\"%v%v\"")
	args := &GoMethodArguments{args: []GoExpr{fmtstr, bex.x, bex.y}}

	mthd := fmtcls.FindMethod("Sprintf", args)
	if mthd == nil {
		mthd = NewGoFakeMethod(fmtcls, "Sprintf", stringType)
		fmtcls.AddMethod(mthd)
	}

	return &GoMethodAccess{method: mthd, args: args}, false
}

// list of standard transformation rules
var StandardRules = []TransformFunc {
	TransformArrayLen,
	TransformSysfile,
	TransformMainArgs,
	TransformThisArg,
	TransformListMethods,
	TransformStringAddition,
	TransformStringFormat,
}
<commit_msg>Convert Class.toString(value) to fmt.Sprintf("%v", value)<commit_after>package parser

import (
	"go/ast"
	"go/token"
	"fmt"
	"log"
	"strings"

	"github.com/dglo/java2go/grammar"
)

// list of Java classes which inherit from AbstractList
var javaListType = []string { "List", "ArrayList", "LinkedList", "Stack",
	"Vector" }

type TransformFunc func(parent GoObject, prog *GoProgram, cls GoClass,
	object GoObject) (GoObject, bool)

type GoObject interface {
	RunTransform(xform TransformFunc, gp *GoProgram, cls GoClass,
		parent GoObject) (GoObject, bool)
}

type GoTypedObject interface {
	GoObject
	VarType() *TypeData
}

func convertToBlock(obj GoObject) (*GoBlock, error) {
	if blk, ok := obj.(*GoBlock); ok {
		return blk, nil
	}

	return nil, fmt.Errorf("%v<%T> is not a *GoBlock", obj, obj)
}

func convertToExpr(obj GoObject) (GoExpr, error) {
	if expr, ok := obj.(GoExpr); ok {
		return expr, nil
	}

	return nil, fmt.Errorf("%v<%T> is not a GoExpr", obj, obj)
}

func convertToMethod(obj GoObject) (GoMethod, error) {
	if mthd, ok := obj.(GoMethod); ok {
		return mthd, nil
	}

	return nil, fmt.Errorf("%v<%T> is not a GoMethod", obj, obj)
}

func convertToMethodArgs(obj GoObject) (*GoMethodArguments, error) {
	if mthd, ok := obj.(*GoMethodArguments); ok {
		return mthd, nil
	}

	return nil, fmt.Errorf("%v<%T> is not a *GoMethodArguments", obj, obj)
}

func convertToStmt(obj GoObject) (GoStatement, error) {
	if stmt, ok := obj.(GoStatement); ok {
		return stmt, nil
	}

	return nil, fmt.Errorf("%v<%T> is not a GoStatement", obj, obj)
}

func convertToVar(obj GoObject) (GoVar, error) {
	if govar, ok := obj.(GoVar); ok {
		return govar, nil
	}

	return nil, fmt.Errorf("%v<%T> is not a GoVar", obj, obj)
}

func convertToVarInit(obj GoObject) (*GoVarInit, error) {
	if vi, ok := obj.(*GoVarInit); ok {
		return vi, nil
	}

	return nil, fmt.Errorf("%v<%T> is not a *GoVarInit", obj, obj)
}

func getFmtClass(prog *GoProgram) GoClass {
	fmtcls := prog.findClass("fmt")
	if fmtcls == nil {
		fmtcls = NewGoFakeClass("fmt")
		prog.addClass(fmtcls)

		// make sure "fmt" is imported
		prog.addImport("fmt", "")
	}

	return fmtcls
}

type GoPkgName struct {
	pkg string
	name string
}

func (gpn *GoPkgName) Expr() ast.Expr {
	return &ast.SelectorExpr{X: ast.NewIdent(gpn.pkg),
		Sel: ast.NewIdent(gpn.name)}
}

func (gpn *GoPkgName) hasVariable(govar GoVar) bool {
	return false
}

func (gpn *GoPkgName) Init() ast.Stmt {
	return nil
}

func (gpn *GoPkgName) RunTransform(xform TransformFunc, prog *GoProgram,
	cls GoClass, parent GoObject) (GoObject, bool) {
	return xform(parent, prog, cls, gpn)
}

func (gpn *GoPkgName) String() string {
	return fmt.Sprintf("GoPkgName[%s|%s]", gpn.pkg, gpn.name)
}

func (gpn *GoPkgName) VarType() *TypeData {
	panic("GoPkgName.VarType() unimplemented")
}

// transform "array.length" to "len(array)"
func TransformArrayLen(parent GoObject, prog *GoProgram, cls GoClass,
	object GoObject) (GoObject, bool) {
	var ref *GoClassAttribute
	var ok bool
	if ref, ok = object.(*GoClassAttribute); !ok {
		return nil, true
	}

	if ref.Suffix() != "length" || ref.VarType().vtype != VT_ARRAY {
		return nil, true
	}

	fm := NewGoFakeMethod(nil, "len", intType)
	args := &GoMethodArguments{args: []GoExpr{ ref.govar, }}

	return &GoMethodAccess{method: fm, args: args}, false
}

// transform "System.out.print*(...)" to "fmt.Print*(...)" and
// "System.err.print*(...)" to "fmt.Fprintf(os.Stderr, ...)"
func TransformSysfile(parent GoObject, prog *GoProgram, cls GoClass,
	object GoObject) (GoObject, bool) {
	var ma *GoMethodAccess
	var ok bool
	if ma, ok = object.(*GoMethodAccess); !ok {
		return nil, true
	}

	if ma.method == nil {
		return nil, true
	}

	mcls := ma.method.Class()
	if mcls == nil || mcls.IsNil() {
		return nil, true
	}

	clsname := mcls.Name()
	name := ma.method.Name()

	if !strings.HasPrefix(clsname, "System.") ||
		!strings.HasPrefix(name, "print") {
		return nil, true
	}

	fmtcls := getFmtClass(prog)

	var fixed string
	var args *GoMethodArguments
	if strings.HasSuffix(clsname, ".out") {
		fixed = strings.ToUpper(name[:1]) + name[1:]
		args = ma.args
	} else {
		fixed = "F" + name
		arglist := make([]GoExpr, 1)
		arglist[0] = &GoPkgName{pkg: "os", name: "Stderr"}
		arglist = append(arglist, ma.args.args...)
		args = &GoMethodArguments{args: arglist}

		// make sure "os" is imported
		prog.addImport("os", "")
	}

	fm := NewGoFakeMethod(fmtcls, fixed, nil)

	return &GoMethodAccess{method: fm, args: args}, false
}

// transform "func main(String[] xxx)" to "func main()" and all "xxx" references
// to "os.Args"
func TransformMainArgs(parent GoObject, prog *GoProgram, cls GoClass,
	object GoObject) (GoObject, bool) {
	var cm *GoClassMethod
	var ok bool
	if cm, ok = object.(*GoClassMethod); !ok {
		return nil, true
	}

	if cm.method_type != mt_main {
		return nil, true
	}

	if cm.params == nil || len(cm.params) != 1 {
		return nil, true
	}

	arg := cm.params[0]

	if cm.body.hasVariable(arg) {
		arg.SetGoName("os.Args")

		// make sure "os" is imported
		prog.addImport("os", "")
	}

	cm.params = nil

	return nil, true
}

// transform "foo(this)" to "foo(rcvr)"
func TransformThisArg(parent GoObject, prog *GoProgram, cls GoClass,
	object GoObject) (GoObject, bool) {
	var mref *GoMethodReference
	var ok bool
	if mref, ok = object.(*GoMethodReference); !ok {
		return nil, true
	}

	if mref.args == nil {
		return nil, true
	}

	for i, arg := range mref.args.args {
		var kwd *GoKeyword
		if kwd, ok = arg.(*GoKeyword); ok {
			if kwd.token == grammar.THIS {
				mref.args.args[i] =
					NewFakeVar(prog.Receiver(cls.Name()), nil, 0)
			}
		}
	}

	return nil, true
}

// transform method calls for List variants to appropriate array operations
func TransformListMethods(parent GoObject, prog *GoProgram, cls GoClass,
	object GoObject) (GoObject, bool) {
	var mref *GoMethodAccessVar
	var ok bool
	if mref, ok = object.(*GoMethodAccessVar); !ok {
		return nil, true
	}

	var is_list bool
	for _, n := range javaListType {
		if mref.govar.VarType().IsClass(n) {
			is_list = true
			break
		}
	}
	if !is_list {
		return nil, true
	}

	switch mref.method.Name() {
	case "add":
		if len(mref.args.args) != 1 {
			log.Printf("//ERR// Cannot convert %v add() with %d args\n",
				mref.govar.VarType(), len(mref.args.args))
			return nil, true
		}

		apnd := NewGoFakeMethod(nil, "append", mref.govar.VarType())
		args := &GoMethodArguments{args: []GoExpr{ mref.govar,
			mref.args.args[0]}}

		rhs := []GoExpr{ &GoMethodAccess{method: apnd, args: args}, }

		return &GoAssign{govar: mref.govar, tok: token.ASSIGN, rhs: rhs}, false
	case "isEmpty":
		if len(mref.args.args) != 0 {
			log.Printf("//ERR// Cannot convert %v isEmpty() with %d args\n",
				mref.govar.VarType(), len(mref.args.args))
			return nil, true
		}

		args := &GoMethodArguments{args: []GoExpr{ mref.govar, }}
		x := &GoMethodAccess{method: NewGoFakeMethod(nil, "len", intType),
			args: args}
		return &GoBinaryExpr{x: x, op: token.EQL, y: &GoLiteral{text: "0"}},
		false
	case "get":
		if len(mref.args.args) != 1 {
			log.Printf("//ERR// Cannot convert %v get() with %d args\n",
				mref.govar.VarType(), len(mref.args.args))
			return nil, true
		}

		return &GoArrayReference{govar: mref.govar, index: mref.args.args[0]},
		false
	case "size":
		fm := NewGoFakeMethod(nil, "len", intType)
		args := &GoMethodArguments{args: []GoExpr{ mref.govar, }}

		return &GoMethodAccess{method: fm, args: args}, false
	default:
		log.Printf("//ERR// Not converting %v method %v\n",
			mref.govar.VarType(), mref.method.Name())
		break
	}

	return nil, true
}

// transform various toString() calls into fmt.Sprintf
func TransformToString(parent GoObject, prog *GoProgram, cls GoClass,
	object GoObject) (GoObject, bool) {

	var macc *GoMethodAccess
	var ok bool
	if macc, ok = object.(*GoMethodAccess); !ok {
		return nil, true
	}

	if macc.method.Name() != "toString" {
		return nil, true
	}

	if len(macc.args.args) == 1 {
		alist := make([]GoExpr, 2)
		alist[0] = NewGoLiteral("\"%v\"")
		alist[1] = macc.args.args[0]

		args := &GoMethodArguments{args: alist}

		fmtcls := getFmtClass(prog)

		mthd := fmtcls.FindMethod("Sprintf", args)
		if mthd == nil {
			mthd = NewGoFakeMethod(fmtcls, "Sprintf", stringType)
			fmtcls.AddMethod(mthd)
		}

		return &GoMethodAccess{method: mthd, args: args}, false
	}

	log.Printf("//ERR// Cannot convert %v toString() with %d args\n",
		macc.method, len(macc.args.args))
	return nil, true
}

// transform String.format method call into fmt.Sprintf
func TransformStringFormat(parent GoObject, prog *GoProgram, cls GoClass,
	object GoObject) (GoObject, bool) {

	var mref *GoMethodReference
	var ok bool
	if mref, ok = object.(*GoMethodReference); !ok {
		return nil, true
	}

	if mref.name == "format" && !mref.class.IsNil() &&
		mref.class.Name() == "String" {
		fmtcls := getFmtClass(prog)

		return NewGoMethodReference(fmtcls, "Sprintf", mref.args, false), false
	}

	return nil, true
}

// transform string addition into fmt.Sprintf
func TransformStringAddition(parent GoObject, prog *GoProgram, cls GoClass,
	object GoObject) (GoObject, bool) {

	var bex *GoBinaryExpr
	var ok bool
	if bex, ok = object.(*GoBinaryExpr); !ok {
		return nil, true
	}

	var x GoTypedObject
	if x, ok = bex.x.(GoTypedObject); !ok {
		return nil, true
	}

	if x.VarType() != stringType {
		return nil, true
	}

	return transformBinaryStringExpression(prog, bex)
}

func joinStrings(s1 string, s2 string) string {
	if s1[0] != '"' || s1[len(s1)-1] != '"' {
		panic(fmt.Sprintf("String %v is not quoted", s1))
	}
	if s2[0] != '"' || s2[len(s2)-1] != '"' {
		panic(fmt.Sprintf("String %v is not quoted", s2))
	}
	s := fmt.Sprintf("\"%s%s\"", s1[1:len(s1)-1], s2[1:len(s2)-1])
	return s
}

func transformBinaryStringExpression(prog *GoProgram, bex *GoBinaryExpr) (GoObject, bool) {
	if bex.op != token.ADD {
		return nil, true
	}

	switch x := bex.x.(type) {
	case *GoLiteral:
		if !x.isString() {
			// ignore non-string addition
			return nil, true
		}

		if y, ok := bex.y.(*GoLiteral); ok {
			if y.isString() {
				return NewGoLiteral(joinStrings(x.text, y.text)), false
			}
		}
	case *GoMethodAccess:
		if x.method.VarType() != stringType {
			return nil, true
		}

		if x.method.Name() == "Sprintf" {
			if fmtstr, ok := x.args.args[0].(*GoLiteral); !ok {
				log.Printf("//ERR// First Sprintf argument should be " +
					" *GoLiteral not %T\n", x.args.args[0])
				return nil, true
			} else {
				x.args.args[0] = NewGoLiteral(joinStrings("\"%v\"",
					fmtstr.text))
			}
			x.args.args = append(x.args.args, bex.y)
			return x, false
		}
	}

	fmtcls := getFmtClass(prog)

	fmtstr := NewGoLiteral("\"%v%v\"")
	args := &GoMethodArguments{args: []GoExpr{fmtstr, bex.x, bex.y}}

	mthd := fmtcls.FindMethod("Sprintf", args)
	if mthd == nil {
		mthd = NewGoFakeMethod(fmtcls, "Sprintf", stringType)
		fmtcls.AddMethod(mthd)
	}

	return &GoMethodAccess{method: mthd, args: args}, false
}

// list of standard transformation rules
var StandardRules = []TransformFunc {
	TransformArrayLen,
	TransformSysfile,
	TransformMainArgs,
	TransformThisArg,
	TransformListMethods,
	TransformToString,
	TransformStringAddition,
	TransformStringFormat,
}
<|endoftext|>


<commit_before>/*
Copyright 2018 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Package podlogs enables live capturing of all events and log
// messages for some or all pods in a namespace as they get generated.
// This helps debugging both a running test (what is currently going
// on?) and the output of a CI run (events appear in chronological
// order and output that normally isn't available like the command
// stdout messages are available).
package podlogs

import (
	"bufio"
	"bytes"
	"context"
	"fmt"
	"io"
	"os"
	"path"
	"regexp"
	"strings"
	"sync"

	"github.com/pkg/errors"

	v1 "k8s.io/api/core/v1"
	meta "k8s.io/apimachinery/pkg/apis/meta/v1"
	clientset "k8s.io/client-go/kubernetes"
)

// LogOutput determines where output from CopyAllLogs goes.
type LogOutput struct {
	// If not nil, errors will be logged here.
	StatusWriter io.Writer

	// If not nil, all output goes to this writer with "<pod>/<container>:" as prefix.
	LogWriter io.Writer

	// Base directory for one log file per container.
	// The full path of each log file will be <log path prefix><pod>-<container>.log.
	LogPathPrefix string
}

// Matches harmless errors from pkg/kubelet/kubelet_pods.go.
var expectedErrors = regexp.MustCompile(`container .* in pod .* is (terminated|waiting to start|not available)|the server could not find the requested resource`)

// CopyAllLogs follows the logs of all containers in all pods,
// including those that get created in the future, and writes each log
// line as configured in the output options. It does that until the
// context is done or until an error occurs.
//
// Beware that there is currently no way to force log collection
// before removing pods, which means that there is a known race
// between "stop pod" and "collecting log entries". The alternative
// would be a blocking function with collects logs from all currently
// running pods, but that then would have the disadvantage that
// already deleted pods aren't covered.
func CopyAllLogs(ctx context.Context, cs clientset.Interface, ns string, to LogOutput) error {
	watcher, err := cs.CoreV1().Pods(ns).Watch(context.TODO(), meta.ListOptions{})
	if err != nil {
		return errors.Wrap(err, "cannot create Pod event watcher")
	}

	go func() {
		var m sync.Mutex
		logging := map[string]bool{}
		check := func() {
			m.Lock()
			defer m.Unlock()

			pods, err := cs.CoreV1().Pods(ns).List(context.TODO(), meta.ListOptions{})
			if err != nil {
				if to.StatusWriter != nil {
					fmt.Fprintf(to.StatusWriter, "ERROR: get pod list in %s: %s\n", ns, err)
				}
				return
			}

			for _, pod := range pods.Items {
				for i, c := range pod.Spec.Containers {
					name := pod.ObjectMeta.Name + "/" + c.Name
					if logging[name] ||
						// sanity check, array should have entry for each container
						len(pod.Status.ContainerStatuses) <= i ||
						// Don't attempt to get logs for a container unless it is running or has terminated.
						// Trying to get a log would just end up with an error that we would have to suppress.
						(pod.Status.ContainerStatuses[i].State.Running == nil &&
							pod.Status.ContainerStatuses[i].State.Terminated == nil) {
						continue
					}
					readCloser, err := logsForPod(ctx, cs, ns, pod.ObjectMeta.Name,
						&v1.PodLogOptions{
							Container: c.Name,
							Follow:    true,
						})
					if err != nil {
						// We do get "normal" errors here, like trying to read too early.
						// We can ignore those.
						if to.StatusWriter != nil &&
							expectedErrors.FindStringIndex(err.Error()) == nil {
							fmt.Fprintf(to.StatusWriter, "WARNING: pod log: %s: %s\n", name, err)
						}
						continue
					}

					// Determine where we write. If this fails, we intentionally return without clearing
					// the logging[name] flag, which prevents trying over and over again to
					// create the output file.
					var out io.Writer
					var closer io.Closer
					var prefix string
					if to.LogWriter != nil {
						out = to.LogWriter
						nodeName := pod.Spec.NodeName
						if len(nodeName) > 10 {
							nodeName = nodeName[0:4] + ".." + nodeName[len(nodeName)-4:]
						}
						prefix = name + "@" + nodeName + ": "
					} else {
						var err error
						filename := to.LogPathPrefix + pod.ObjectMeta.Name + "-" + c.Name + ".log"
						err = os.MkdirAll(path.Dir(filename), 0755)
						if err != nil {
							if to.StatusWriter != nil {
								fmt.Fprintf(to.StatusWriter, "ERROR: pod log: create directory for %s: %s\n", filename, err)
							}
							return
						}
						// The test suite might run the same test multiple times,
						// so we have to append here.
						file, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
						if err != nil {
							if to.StatusWriter != nil {
								fmt.Fprintf(to.StatusWriter, "ERROR: pod log: create file %s: %s\n", filename, err)
							}
							return
						}
						closer = file
						out = file
					}
					go func() {
						if closer != nil {
							defer closer.Close()
						}
						defer func() {
							m.Lock()
							logging[name] = false
							m.Unlock()
							readCloser.Close()
						}()
						scanner := bufio.NewScanner(readCloser)
						first := true
						for scanner.Scan() {
							line := scanner.Text()
							// Filter out the expected "end of stream" error message,
							// it would just confuse developers who don't know about it.
							// Same for attempts to read logs from a container that
							// isn't ready (yet?!).
							if !strings.HasPrefix(line, "rpc error: code = Unknown desc = Error: No such container:") &&
								!strings.HasPrefix(line, "Unable to retrieve container logs for ") {
								if first {
									if to.LogWriter == nil {
										// Because the same log might be written to multiple times
										// in different test instances, log an extra line to separate them.
										// Also provides some useful extra information.
										fmt.Fprintf(out, "==== start of log for container %s ====\n", name)
									}
									first = false
								}
								fmt.Fprintf(out, "%s%s\n", prefix, scanner.Text())
							}
						}
					}()
					logging[name] = true
				}
			}
		}

		// Watch events to see whether we can start logging
		// and log interesting ones.
		check()
		for {
			select {
			case <-watcher.ResultChan():
				check()
			case <-ctx.Done():
				return
			}
		}
	}()

	return nil
}

// logsForPod starts reading the logs for a certain pod. If the pod has more than one
// container, opts.Container must be set. Reading stops when the context is done.
// The stream includes formatted error messages and ends with
//    rpc error: code = Unknown desc = Error: No such container: 41a...
// when the pod gets deleted while streaming.
func logsForPod(ctx context.Context, cs clientset.Interface, ns, pod string, opts *v1.PodLogOptions) (io.ReadCloser, error) {
	return cs.CoreV1().Pods(ns).GetLogs(pod, opts).Stream(ctx)
}

// WatchPods prints pod status events for a certain namespace or all namespaces
// when namespace name is empty.
func WatchPods(ctx context.Context, cs clientset.Interface, ns string, to io.Writer) error {
	watcher, err := cs.CoreV1().Pods(ns).Watch(context.TODO(), meta.ListOptions{})
	if err != nil {
		return errors.Wrap(err, "cannot create Pod event watcher")
	}

	go func() {
		defer watcher.Stop()
		for {
			select {
			case e := <-watcher.ResultChan():
				if e.Object == nil {
					continue
				}

				pod, ok := e.Object.(*v1.Pod)
				if !ok {
					continue
				}
				buffer := new(bytes.Buffer)
				fmt.Fprintf(buffer,
					"pod event: %s: %s/%s %s: %s %s\n",
					e.Type,
					pod.Namespace,
					pod.Name,
					pod.Status.Phase,
					pod.Status.Reason,
					pod.Status.Conditions,
				)
				for _, cst := range pod.Status.ContainerStatuses {
					fmt.Fprintf(buffer, "   %s: ", cst.Name)
					if cst.State.Waiting != nil {
						fmt.Fprintf(buffer, "WAITING: %s - %s",
							cst.State.Waiting.Reason,
							cst.State.Waiting.Message,
						)
					} else if cst.State.Running != nil {
						fmt.Fprintf(buffer, "RUNNING")
					} else if cst.State.Terminated != nil {
						fmt.Fprintf(buffer, "TERMINATED: %s - %s",
							cst.State.Terminated.Reason,
							cst.State.Terminated.Message,
						)
					}
					fmt.Fprintf(buffer, "\n")
				}
				to.Write(buffer.Bytes())
			case <-ctx.Done():
				return
			}
		}
	}()

	return nil
}
<commit_msg>podlogs: adapt to modified error message<commit_after>/*
Copyright 2018 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Package podlogs enables live capturing of all events and log
// messages for some or all pods in a namespace as they get generated.
// This helps debugging both a running test (what is currently going
// on?) and the output of a CI run (events appear in chronological
// order and output that normally isn't available like the command
// stdout messages are available).
package podlogs

import (
	"bufio"
	"bytes"
	"context"
	"fmt"
	"io"
	"os"
	"path"
	"regexp"
	"strings"
	"sync"

	"github.com/pkg/errors"

	v1 "k8s.io/api/core/v1"
	meta "k8s.io/apimachinery/pkg/apis/meta/v1"
	clientset "k8s.io/client-go/kubernetes"
)

// LogOutput determines where output from CopyAllLogs goes.
type LogOutput struct {
	// If not nil, errors will be logged here.
	StatusWriter io.Writer

	// If not nil, all output goes to this writer with "<pod>/<container>:" as prefix.
	LogWriter io.Writer

	// Base directory for one log file per container.
	// The full path of each log file will be <log path prefix><pod>-<container>.log.
	LogPathPrefix string
}

// Matches harmless errors from pkg/kubelet/kubelet_pods.go.
var expectedErrors = regexp.MustCompile(`container .* in pod .* is (terminated|waiting to start|not available)|the server could not find the requested resource`)

// CopyAllLogs follows the logs of all containers in all pods,
// including those that get created in the future, and writes each log
// line as configured in the output options. It does that until the
// context is done or until an error occurs.
//
// Beware that there is currently no way to force log collection
// before removing pods, which means that there is a known race
// between "stop pod" and "collecting log entries". The alternative
// would be a blocking function with collects logs from all currently
// running pods, but that then would have the disadvantage that
// already deleted pods aren't covered.
func CopyAllLogs(ctx context.Context, cs clientset.Interface, ns string, to LogOutput) error {
	watcher, err := cs.CoreV1().Pods(ns).Watch(context.TODO(), meta.ListOptions{})
	if err != nil {
		return errors.Wrap(err, "cannot create Pod event watcher")
	}

	go func() {
		var m sync.Mutex
		logging := map[string]bool{}
		check := func() {
			m.Lock()
			defer m.Unlock()

			pods, err := cs.CoreV1().Pods(ns).List(context.TODO(), meta.ListOptions{})
			if err != nil {
				if to.StatusWriter != nil {
					fmt.Fprintf(to.StatusWriter, "ERROR: get pod list in %s: %s\n", ns, err)
				}
				return
			}

			for _, pod := range pods.Items {
				for i, c := range pod.Spec.Containers {
					name := pod.ObjectMeta.Name + "/" + c.Name
					if logging[name] ||
						// sanity check, array should have entry for each container
						len(pod.Status.ContainerStatuses) <= i ||
						// Don't attempt to get logs for a container unless it is running or has terminated.
						// Trying to get a log would just end up with an error that we would have to suppress.
						(pod.Status.ContainerStatuses[i].State.Running == nil &&
							pod.Status.ContainerStatuses[i].State.Terminated == nil) {
						continue
					}
					readCloser, err := logsForPod(ctx, cs, ns, pod.ObjectMeta.Name,
						&v1.PodLogOptions{
							Container: c.Name,
							Follow:    true,
						})
					if err != nil {
						// We do get "normal" errors here, like trying to read too early.
						// We can ignore those.
						if to.StatusWriter != nil &&
							expectedErrors.FindStringIndex(err.Error()) == nil {
							fmt.Fprintf(to.StatusWriter, "WARNING: pod log: %s: %s\n", name, err)
						}
						continue
					}

					// Determine where we write. If this fails, we intentionally return without clearing
					// the logging[name] flag, which prevents trying over and over again to
					// create the output file.
					var out io.Writer
					var closer io.Closer
					var prefix string
					if to.LogWriter != nil {
						out = to.LogWriter
						nodeName := pod.Spec.NodeName
						if len(nodeName) > 10 {
							nodeName = nodeName[0:4] + ".." + nodeName[len(nodeName)-4:]
						}
						prefix = name + "@" + nodeName + ": "
					} else {
						var err error
						filename := to.LogPathPrefix + pod.ObjectMeta.Name + "-" + c.Name + ".log"
						err = os.MkdirAll(path.Dir(filename), 0755)
						if err != nil {
							if to.StatusWriter != nil {
								fmt.Fprintf(to.StatusWriter, "ERROR: pod log: create directory for %s: %s\n", filename, err)
							}
							return
						}
						// The test suite might run the same test multiple times,
						// so we have to append here.
						file, err := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
						if err != nil {
							if to.StatusWriter != nil {
								fmt.Fprintf(to.StatusWriter, "ERROR: pod log: create file %s: %s\n", filename, err)
							}
							return
						}
						closer = file
						out = file
					}
					go func() {
						if closer != nil {
							defer closer.Close()
						}
						defer func() {
							m.Lock()
							logging[name] = false
							m.Unlock()
							readCloser.Close()
						}()
						scanner := bufio.NewScanner(readCloser)
						first := true
						for scanner.Scan() {
							line := scanner.Text()
							// Filter out the expected "end of stream" error message,
							// it would just confuse developers who don't know about it.
							// Same for attempts to read logs from a container that
							// isn't ready (yet?!).
							if !strings.HasPrefix(line, "rpc error: code = Unknown desc = Error: No such container:") &&
								!strings.HasPrefix(line, "unable to retrieve container logs for ") &&
								!strings.HasPrefix(line, "Unable to retrieve container logs for ") {
								if first {
									if to.LogWriter == nil {
										// Because the same log might be written to multiple times
										// in different test instances, log an extra line to separate them.
										// Also provides some useful extra information.
										fmt.Fprintf(out, "==== start of log for container %s ====\n", name)
									}
									first = false
								}
								fmt.Fprintf(out, "%s%s\n", prefix, scanner.Text())
							}
						}
					}()
					logging[name] = true
				}
			}
		}

		// Watch events to see whether we can start logging
		// and log interesting ones.
		check()
		for {
			select {
			case <-watcher.ResultChan():
				check()
			case <-ctx.Done():
				return
			}
		}
	}()

	return nil
}

// logsForPod starts reading the logs for a certain pod. If the pod has more than one
// container, opts.Container must be set. Reading stops when the context is done.
// The stream includes formatted error messages and ends with
//    rpc error: code = Unknown desc = Error: No such container: 41a...
// when the pod gets deleted while streaming.
func logsForPod(ctx context.Context, cs clientset.Interface, ns, pod string, opts *v1.PodLogOptions) (io.ReadCloser, error) {
	return cs.CoreV1().Pods(ns).GetLogs(pod, opts).Stream(ctx)
}

// WatchPods prints pod status events for a certain namespace or all namespaces
// when namespace name is empty.
func WatchPods(ctx context.Context, cs clientset.Interface, ns string, to io.Writer) error {
	watcher, err := cs.CoreV1().Pods(ns).Watch(context.TODO(), meta.ListOptions{})
	if err != nil {
		return errors.Wrap(err, "cannot create Pod event watcher")
	}

	go func() {
		defer watcher.Stop()
		for {
			select {
			case e := <-watcher.ResultChan():
				if e.Object == nil {
					continue
				}

				pod, ok := e.Object.(*v1.Pod)
				if !ok {
					continue
				}
				buffer := new(bytes.Buffer)
				fmt.Fprintf(buffer,
					"pod event: %s: %s/%s %s: %s %s\n",
					e.Type,
					pod.Namespace,
					pod.Name,
					pod.Status.Phase,
					pod.Status.Reason,
					pod.Status.Conditions,
				)
				for _, cst := range pod.Status.ContainerStatuses {
					fmt.Fprintf(buffer, "   %s: ", cst.Name)
					if cst.State.Waiting != nil {
						fmt.Fprintf(buffer, "WAITING: %s - %s",
							cst.State.Waiting.Reason,
							cst.State.Waiting.Message,
						)
					} else if cst.State.Running != nil {
						fmt.Fprintf(buffer, "RUNNING")
					} else if cst.State.Terminated != nil {
						fmt.Fprintf(buffer, "TERMINATED: %s - %s",
							cst.State.Terminated.Reason,
							cst.State.Terminated.Message,
						)
					}
					fmt.Fprintf(buffer, "\n")
				}
				to.Write(buffer.Bytes())
			case <-ctx.Done():
				return
			}
		}
	}()

	return nil
}
<|endoftext|>


<commit_before>// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"bytes"
	"errors"
	"fmt"
	"internal/testenv"
	"log"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
	"sync"
	"testing"
)

// TestMain executes the test binary as the vet command if
// GO_VETTEST_IS_VET is set, and runs the tests otherwise.
func TestMain(m *testing.M) {
	if os.Getenv("GO_VETTEST_IS_VET") != "" {
		main()
		os.Exit(0)
	}

	os.Setenv("GO_VETTEST_IS_VET", "1") // Set for subprocesses to inherit.
	os.Exit(m.Run())
}

// vetPath returns the path to the "vet" binary to run.
func vetPath(t testing.TB) string {
	t.Helper()
	testenv.MustHaveExec(t)

	vetPathOnce.Do(func() {
		vetExePath, vetPathErr = os.Executable()
	})
	if vetPathErr != nil {
		t.Fatal(vetPathErr)
	}
	return vetExePath
}

var (
	vetPathOnce sync.Once
	vetExePath  string
	vetPathErr  error
)

func vetCmd(t *testing.T, arg, pkg string) *exec.Cmd {
	cmd := exec.Command(testenv.GoToolPath(t), "vet", "-vettool="+vetPath(t), arg, path.Join("cmd/vet/testdata", pkg))
	cmd.Env = os.Environ()
	return cmd
}

func TestVet(t *testing.T) {
	t.Parallel()
	for _, pkg := range []string{
		"asm",
		"assign",
		"atomic",
		"bool",
		"buildtag",
		"cgo",
		"composite",
		"copylock",
		"deadcode",
		"httpresponse",
		"lostcancel",
		"method",
		"nilfunc",
		"print",
		"rangeloop",
		"shift",
		"structtag",
		"testingpkg",
		// "testtag" has its own test
		"unmarshal",
		"unsafeptr",
		"unused",
	} {
		pkg := pkg
		t.Run(pkg, func(t *testing.T) {
			t.Parallel()

			// Skip cgo test on platforms without cgo.
			if pkg == "cgo" && !cgoEnabled(t) {
				return
			}

			cmd := vetCmd(t, "-printfuncs=Warn,Warnf", pkg)

			// The asm test assumes amd64.
			if pkg == "asm" {
				cmd.Env = append(cmd.Env, "GOOS=linux", "GOARCH=amd64")
			}

			dir := filepath.Join("testdata", pkg)
			gos, err := filepath.Glob(filepath.Join(dir, "*.go"))
			if err != nil {
				t.Fatal(err)
			}
			asms, err := filepath.Glob(filepath.Join(dir, "*.s"))
			if err != nil {
				t.Fatal(err)
			}
			var files []string
			files = append(files, gos...)
			files = append(files, asms...)

			errchk(cmd, files, t)
		})
	}
}

func cgoEnabled(t *testing.T) bool {
	// Don't trust build.Default.CgoEnabled as it is false for
	// cross-builds unless CGO_ENABLED is explicitly specified.
	// That's fine for the builders, but causes commands like
	// 'GOARCH=386 go test .' to fail.
	// Instead, we ask the go command.
	cmd := exec.Command(testenv.GoToolPath(t), "list", "-f", "{{context.CgoEnabled}}")
	out, _ := cmd.CombinedOutput()
	return string(out) == "true\n"
}

func errchk(c *exec.Cmd, files []string, t *testing.T) {
	output, err := c.CombinedOutput()
	if _, ok := err.(*exec.ExitError); !ok {
		t.Logf("vet output:\n%s", output)
		t.Fatal(err)
	}
	fullshort := make([]string, 0, len(files)*2)
	for _, f := range files {
		fullshort = append(fullshort, f, filepath.Base(f))
	}
	err = errorCheck(string(output), false, fullshort...)
	if err != nil {
		t.Errorf("error check failed: %s", err)
	}
}

// TestTags verifies that the -tags argument controls which files to check.
func TestTags(t *testing.T) {
	t.Parallel()
	for tag, wantFile := range map[string]int{
		"testtag":     1, // file1
		"x testtag y": 1,
		"othertag":    2,
	} {
		tag, wantFile := tag, wantFile
		t.Run(tag, func(t *testing.T) {
			t.Parallel()
			t.Logf("-tags=%s", tag)
			cmd := vetCmd(t, "-tags="+tag, "tagtest")
			output, err := cmd.CombinedOutput()

			want := fmt.Sprintf("file%d.go", wantFile)
			dontwant := fmt.Sprintf("file%d.go", 3-wantFile)

			// file1 has testtag and file2 has !testtag.
			if !bytes.Contains(output, []byte(filepath.Join("tagtest", want))) {
				t.Errorf("%s: %s was excluded, should be included", tag, want)
			}
			if bytes.Contains(output, []byte(filepath.Join("tagtest", dontwant))) {
				t.Errorf("%s: %s was included, should be excluded", tag, dontwant)
			}
			if t.Failed() {
				t.Logf("err=%s, output=<<%s>>", err, output)
			}
		})
	}
}

// All declarations below were adapted from test/run.go.

// errorCheck matches errors in outStr against comments in source files.
// For each line of the source files which should generate an error,
// there should be a comment of the form // ERROR "regexp".
// If outStr has an error for a line which has no such comment,
// this function will report an error.
// Likewise if outStr does not have an error for a line which has a comment,
// or if the error message does not match the <regexp>.
// The <regexp> syntax is Perl but it's best to stick to egrep.
//
// Sources files are supplied as fullshort slice.
// It consists of pairs: full path to source file and its base name.
func errorCheck(outStr string, wantAuto bool, fullshort ...string) (err error) {
	var errs []error
	out := splitOutput(outStr, wantAuto)
	// Cut directory name.
	for i := range out {
		for j := 0; j < len(fullshort); j += 2 {
			full, short := fullshort[j], fullshort[j+1]
			out[i] = strings.ReplaceAll(out[i], full, short)
		}
	}

	var want []wantedError
	for j := 0; j < len(fullshort); j += 2 {
		full, short := fullshort[j], fullshort[j+1]
		want = append(want, wantedErrors(full, short)...)
	}
	for _, we := range want {
		var errmsgs []string
		if we.auto {
			errmsgs, out = partitionStrings("<autogenerated>", out)
		} else {
			errmsgs, out = partitionStrings(we.prefix, out)
		}
		if len(errmsgs) == 0 {
			errs = append(errs, fmt.Errorf("%s:%d: missing error %q", we.file, we.lineNum, we.reStr))
			continue
		}
		matched := false
		n := len(out)
		for _, errmsg := range errmsgs {
			// Assume errmsg says "file:line: foo".
			// Cut leading "file:line: " to avoid accidental matching of file name instead of message.
			text := errmsg
			if _, suffix, ok := strings.Cut(text, " "); ok {
				text = suffix
			}
			if we.re.MatchString(text) {
				matched = true
			} else {
				out = append(out, errmsg)
			}
		}
		if !matched {
			errs = append(errs, fmt.Errorf("%s:%d: no match for %#q in:\n\t%s", we.file, we.lineNum, we.reStr, strings.Join(out[n:], "\n\t")))
			continue
		}
	}

	if len(out) > 0 {
		errs = append(errs, fmt.Errorf("Unmatched Errors:"))
		for _, errLine := range out {
			errs = append(errs, fmt.Errorf("%s", errLine))
		}
	}

	if len(errs) == 0 {
		return nil
	}
	if len(errs) == 1 {
		return errs[0]
	}
	var buf strings.Builder
	fmt.Fprintf(&buf, "\n")
	for _, err := range errs {
		fmt.Fprintf(&buf, "%s\n", err.Error())
	}
	return errors.New(buf.String())
}

func splitOutput(out string, wantAuto bool) []string {
	// gc error messages continue onto additional lines with leading tabs.
	// Split the output at the beginning of each line that doesn't begin with a tab.
	// <autogenerated> lines are impossible to match so those are filtered out.
	var res []string
	for _, line := range strings.Split(out, "\n") {
		line = strings.TrimSuffix(line, "\r") // normalize Windows output
		if strings.HasPrefix(line, "\t") {
			res[len(res)-1] += "\n" + line
		} else if strings.HasPrefix(line, "go tool") || strings.HasPrefix(line, "#") || !wantAuto && strings.HasPrefix(line, "<autogenerated>") {
			continue
		} else if strings.TrimSpace(line) != "" {
			res = append(res, line)
		}
	}
	return res
}

// matchPrefix reports whether s starts with file name prefix followed by a :,
// and possibly preceded by a directory name.
func matchPrefix(s, prefix string) bool {
	i := strings.Index(s, ":")
	if i < 0 {
		return false
	}
	j := strings.LastIndex(s[:i], "/")
	s = s[j+1:]
	if len(s) <= len(prefix) || s[:len(prefix)] != prefix {
		return false
	}
	if s[len(prefix)] == ':' {
		return true
	}
	return false
}

func partitionStrings(prefix string, strs []string) (matched, unmatched []string) {
	for _, s := range strs {
		if matchPrefix(s, prefix) {
			matched = append(matched, s)
		} else {
			unmatched = append(unmatched, s)
		}
	}
	return
}

type wantedError struct {
	reStr   string
	re      *regexp.Regexp
	lineNum int
	auto    bool // match <autogenerated> line
	file    string
	prefix  string
}

var (
	errRx       = regexp.MustCompile(`// (?:GC_)?ERROR(NEXT)? (.*)`)
	errAutoRx   = regexp.MustCompile(`// (?:GC_)?ERRORAUTO(NEXT)? (.*)`)
	errQuotesRx = regexp.MustCompile(`"([^"]*)"`)
	lineRx      = regexp.MustCompile(`LINE(([+-])(\d+))?`)
)

// wantedErrors parses expected errors from comments in a file.
func wantedErrors(file, short string) (errs []wantedError) {
	cache := make(map[string]*regexp.Regexp)

	src, err := os.ReadFile(file)
	if err != nil {
		log.Fatal(err)
	}
	for i, line := range strings.Split(string(src), "\n") {
		lineNum := i + 1
		if strings.Contains(line, "////") {
			// double comment disables ERROR
			continue
		}
		var auto bool
		m := errAutoRx.FindStringSubmatch(line)
		if m != nil {
			auto = true
		} else {
			m = errRx.FindStringSubmatch(line)
		}
		if m == nil {
			continue
		}
		if m[1] == "NEXT" {
			lineNum++
		}
		all := m[2]
		mm := errQuotesRx.FindAllStringSubmatch(all, -1)
		if mm == nil {
			log.Fatalf("%s:%d: invalid errchk line: %s", file, lineNum, line)
		}
		for _, m := range mm {
			replacedOnce := false
			rx := lineRx.ReplaceAllStringFunc(m[1], func(m string) string {
				if replacedOnce {
					return m
				}
				replacedOnce = true
				n := lineNum
				if strings.HasPrefix(m, "LINE+") {
					delta, _ := strconv.Atoi(m[5:])
					n += delta
				} else if strings.HasPrefix(m, "LINE-") {
					delta, _ := strconv.Atoi(m[5:])
					n -= delta
				}
				return fmt.Sprintf("%s:%d", short, n)
			})
			re := cache[rx]
			if re == nil {
				var err error
				re, err = regexp.Compile(rx)
				if err != nil {
					log.Fatalf("%s:%d: invalid regexp \"%#q\" in ERROR line: %v", file, lineNum, rx, err)
				}
				cache[rx] = re
			}
			prefix := fmt.Sprintf("%s:%d", short, lineNum)
			errs = append(errs, wantedError{
				reStr:   rx,
				re:      re,
				prefix:  prefix,
				auto:    auto,
				lineNum: lineNum,
				file:    short,
			})
		}
	}

	return
}
<commit_msg>cmd/vet: use testenv.Command instead of exec.Command in tests<commit_after>// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"bytes"
	"errors"
	"fmt"
	"internal/testenv"
	"log"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
	"sync"
	"testing"
)

// TestMain executes the test binary as the vet command if
// GO_VETTEST_IS_VET is set, and runs the tests otherwise.
func TestMain(m *testing.M) {
	if os.Getenv("GO_VETTEST_IS_VET") != "" {
		main()
		os.Exit(0)
	}

	os.Setenv("GO_VETTEST_IS_VET", "1") // Set for subprocesses to inherit.
	os.Exit(m.Run())
}

// vetPath returns the path to the "vet" binary to run.
func vetPath(t testing.TB) string {
	t.Helper()
	testenv.MustHaveExec(t)

	vetPathOnce.Do(func() {
		vetExePath, vetPathErr = os.Executable()
	})
	if vetPathErr != nil {
		t.Fatal(vetPathErr)
	}
	return vetExePath
}

var (
	vetPathOnce sync.Once
	vetExePath  string
	vetPathErr  error
)

func vetCmd(t *testing.T, arg, pkg string) *exec.Cmd {
	cmd := testenv.Command(t, testenv.GoToolPath(t), "vet", "-vettool="+vetPath(t), arg, path.Join("cmd/vet/testdata", pkg))
	cmd.Env = os.Environ()
	return cmd
}

func TestVet(t *testing.T) {
	t.Parallel()
	for _, pkg := range []string{
		"asm",
		"assign",
		"atomic",
		"bool",
		"buildtag",
		"cgo",
		"composite",
		"copylock",
		"deadcode",
		"httpresponse",
		"lostcancel",
		"method",
		"nilfunc",
		"print",
		"rangeloop",
		"shift",
		"structtag",
		"testingpkg",
		// "testtag" has its own test
		"unmarshal",
		"unsafeptr",
		"unused",
	} {
		pkg := pkg
		t.Run(pkg, func(t *testing.T) {
			t.Parallel()

			// Skip cgo test on platforms without cgo.
			if pkg == "cgo" && !cgoEnabled(t) {
				return
			}

			cmd := vetCmd(t, "-printfuncs=Warn,Warnf", pkg)

			// The asm test assumes amd64.
			if pkg == "asm" {
				cmd.Env = append(cmd.Env, "GOOS=linux", "GOARCH=amd64")
			}

			dir := filepath.Join("testdata", pkg)
			gos, err := filepath.Glob(filepath.Join(dir, "*.go"))
			if err != nil {
				t.Fatal(err)
			}
			asms, err := filepath.Glob(filepath.Join(dir, "*.s"))
			if err != nil {
				t.Fatal(err)
			}
			var files []string
			files = append(files, gos...)
			files = append(files, asms...)

			errchk(cmd, files, t)
		})
	}
}

func cgoEnabled(t *testing.T) bool {
	// Don't trust build.Default.CgoEnabled as it is false for
	// cross-builds unless CGO_ENABLED is explicitly specified.
	// That's fine for the builders, but causes commands like
	// 'GOARCH=386 go test .' to fail.
	// Instead, we ask the go command.
	cmd := testenv.Command(t, testenv.GoToolPath(t), "list", "-f", "{{context.CgoEnabled}}")
	out, _ := cmd.CombinedOutput()
	return string(out) == "true\n"
}

func errchk(c *exec.Cmd, files []string, t *testing.T) {
	output, err := c.CombinedOutput()
	if _, ok := err.(*exec.ExitError); !ok {
		t.Logf("vet output:\n%s", output)
		t.Fatal(err)
	}
	fullshort := make([]string, 0, len(files)*2)
	for _, f := range files {
		fullshort = append(fullshort, f, filepath.Base(f))
	}
	err = errorCheck(string(output), false, fullshort...)
	if err != nil {
		t.Errorf("error check failed: %s", err)
	}
}

// TestTags verifies that the -tags argument controls which files to check.
func TestTags(t *testing.T) {
	t.Parallel()
	for tag, wantFile := range map[string]int{
		"testtag":     1, // file1
		"x testtag y": 1,
		"othertag":    2,
	} {
		tag, wantFile := tag, wantFile
		t.Run(tag, func(t *testing.T) {
			t.Parallel()
			t.Logf("-tags=%s", tag)
			cmd := vetCmd(t, "-tags="+tag, "tagtest")
			output, err := cmd.CombinedOutput()

			want := fmt.Sprintf("file%d.go", wantFile)
			dontwant := fmt.Sprintf("file%d.go", 3-wantFile)

			// file1 has testtag and file2 has !testtag.
			if !bytes.Contains(output, []byte(filepath.Join("tagtest", want))) {
				t.Errorf("%s: %s was excluded, should be included", tag, want)
			}
			if bytes.Contains(output, []byte(filepath.Join("tagtest", dontwant))) {
				t.Errorf("%s: %s was included, should be excluded", tag, dontwant)
			}
			if t.Failed() {
				t.Logf("err=%s, output=<<%s>>", err, output)
			}
		})
	}
}

// All declarations below were adapted from test/run.go.

// errorCheck matches errors in outStr against comments in source files.
// For each line of the source files which should generate an error,
// there should be a comment of the form // ERROR "regexp".
// If outStr has an error for a line which has no such comment,
// this function will report an error.
// Likewise if outStr does not have an error for a line which has a comment,
// or if the error message does not match the <regexp>.
// The <regexp> syntax is Perl but it's best to stick to egrep.
//
// Sources files are supplied as fullshort slice.
// It consists of pairs: full path to source file and its base name.
func errorCheck(outStr string, wantAuto bool, fullshort ...string) (err error) {
	var errs []error
	out := splitOutput(outStr, wantAuto)
	// Cut directory name.
	for i := range out {
		for j := 0; j < len(fullshort); j += 2 {
			full, short := fullshort[j], fullshort[j+1]
			out[i] = strings.ReplaceAll(out[i], full, short)
		}
	}

	var want []wantedError
	for j := 0; j < len(fullshort); j += 2 {
		full, short := fullshort[j], fullshort[j+1]
		want = append(want, wantedErrors(full, short)...)
	}
	for _, we := range want {
		var errmsgs []string
		if we.auto {
			errmsgs, out = partitionStrings("<autogenerated>", out)
		} else {
			errmsgs, out = partitionStrings(we.prefix, out)
		}
		if len(errmsgs) == 0 {
			errs = append(errs, fmt.Errorf("%s:%d: missing error %q", we.file, we.lineNum, we.reStr))
			continue
		}
		matched := false
		n := len(out)
		for _, errmsg := range errmsgs {
			// Assume errmsg says "file:line: foo".
			// Cut leading "file:line: " to avoid accidental matching of file name instead of message.
			text := errmsg
			if _, suffix, ok := strings.Cut(text, " "); ok {
				text = suffix
			}
			if we.re.MatchString(text) {
				matched = true
			} else {
				out = append(out, errmsg)
			}
		}
		if !matched {
			errs = append(errs, fmt.Errorf("%s:%d: no match for %#q in:\n\t%s", we.file, we.lineNum, we.reStr, strings.Join(out[n:], "\n\t")))
			continue
		}
	}

	if len(out) > 0 {
		errs = append(errs, fmt.Errorf("Unmatched Errors:"))
		for _, errLine := range out {
			errs = append(errs, fmt.Errorf("%s", errLine))
		}
	}

	if len(errs) == 0 {
		return nil
	}
	if len(errs) == 1 {
		return errs[0]
	}
	var buf strings.Builder
	fmt.Fprintf(&buf, "\n")
	for _, err := range errs {
		fmt.Fprintf(&buf, "%s\n", err.Error())
	}
	return errors.New(buf.String())
}

func splitOutput(out string, wantAuto bool) []string {
	// gc error messages continue onto additional lines with leading tabs.
	// Split the output at the beginning of each line that doesn't begin with a tab.
	// <autogenerated> lines are impossible to match so those are filtered out.
	var res []string
	for _, line := range strings.Split(out, "\n") {
		line = strings.TrimSuffix(line, "\r") // normalize Windows output
		if strings.HasPrefix(line, "\t") {
			res[len(res)-1] += "\n" + line
		} else if strings.HasPrefix(line, "go tool") || strings.HasPrefix(line, "#") || !wantAuto && strings.HasPrefix(line, "<autogenerated>") {
			continue
		} else if strings.TrimSpace(line) != "" {
			res = append(res, line)
		}
	}
	return res
}

// matchPrefix reports whether s starts with file name prefix followed by a :,
// and possibly preceded by a directory name.
func matchPrefix(s, prefix string) bool {
	i := strings.Index(s, ":")
	if i < 0 {
		return false
	}
	j := strings.LastIndex(s[:i], "/")
	s = s[j+1:]
	if len(s) <= len(prefix) || s[:len(prefix)] != prefix {
		return false
	}
	if s[len(prefix)] == ':' {
		return true
	}
	return false
}

func partitionStrings(prefix string, strs []string) (matched, unmatched []string) {
	for _, s := range strs {
		if matchPrefix(s, prefix) {
			matched = append(matched, s)
		} else {
			unmatched = append(unmatched, s)
		}
	}
	return
}

type wantedError struct {
	reStr   string
	re      *regexp.Regexp
	lineNum int
	auto    bool // match <autogenerated> line
	file    string
	prefix  string
}

var (
	errRx       = regexp.MustCompile(`// (?:GC_)?ERROR(NEXT)? (.*)`)
	errAutoRx   = regexp.MustCompile(`// (?:GC_)?ERRORAUTO(NEXT)? (.*)`)
	errQuotesRx = regexp.MustCompile(`"([^"]*)"`)
	lineRx      = regexp.MustCompile(`LINE(([+-])(\d+))?`)
)

// wantedErrors parses expected errors from comments in a file.
func wantedErrors(file, short string) (errs []wantedError) {
	cache := make(map[string]*regexp.Regexp)

	src, err := os.ReadFile(file)
	if err != nil {
		log.Fatal(err)
	}
	for i, line := range strings.Split(string(src), "\n") {
		lineNum := i + 1
		if strings.Contains(line, "////") {
			// double comment disables ERROR
			continue
		}
		var auto bool
		m := errAutoRx.FindStringSubmatch(line)
		if m != nil {
			auto = true
		} else {
			m = errRx.FindStringSubmatch(line)
		}
		if m == nil {
			continue
		}
		if m[1] == "NEXT" {
			lineNum++
		}
		all := m[2]
		mm := errQuotesRx.FindAllStringSubmatch(all, -1)
		if mm == nil {
			log.Fatalf("%s:%d: invalid errchk line: %s", file, lineNum, line)
		}
		for _, m := range mm {
			replacedOnce := false
			rx := lineRx.ReplaceAllStringFunc(m[1], func(m string) string {
				if replacedOnce {
					return m
				}
				replacedOnce = true
				n := lineNum
				if strings.HasPrefix(m, "LINE+") {
					delta, _ := strconv.Atoi(m[5:])
					n += delta
				} else if strings.HasPrefix(m, "LINE-") {
					delta, _ := strconv.Atoi(m[5:])
					n -= delta
				}
				return fmt.Sprintf("%s:%d", short, n)
			})
			re := cache[rx]
			if re == nil {
				var err error
				re, err = regexp.Compile(rx)
				if err != nil {
					log.Fatalf("%s:%d: invalid regexp \"%#q\" in ERROR line: %v", file, lineNum, rx, err)
				}
				cache[rx] = re
			}
			prefix := fmt.Sprintf("%s:%d", short, lineNum)
			errs = append(errs, wantedError{
				reStr:   rx,
				re:      re,
				prefix:  prefix,
				auto:    auto,
				lineNum: lineNum,
				file:    short,
			})
		}
	}

	return
}
<|endoftext|>


<commit_before>package raspicamera

import (
	"github.com/TIBCOSoftware/flogo-lib/core/activity"
	"github.com/TIBCOSoftware/flogo-lib/logger"
	"github.com/dhowden/raspicam"
	"time"
	"os"
	//"path"
)

// log is the default package logger
var log = logger.GetLogger("activity-raspicamera")

const (
	ivTimeout 		= "timeout" //delay before the image is taken
	ivSharpness 	= "sharpness"
	ivBrightness 	= "brightness"
	ivContrast		= "contrast"
	ivSaturation 	= "saturation"
	ivISO			= "iso"
	ivFilename		= "filename"

	ovStatus        = "status"
)

// RaspicameraActivity is a stub for your Activity implementation
type RaspicameraActivity struct {
	metadata *activity.Metadata
}

// NewActivity creates a new activity
func NewActivity(metadata *activity.Metadata) activity.Activity {
	return &RaspicameraActivity{metadata: metadata}
}

// Metadata implements activity.Activity.Metadata
func (a *RaspicameraActivity) Metadata() *activity.Metadata {
	return a.metadata
}

// Eval implements activity.Activity.Eval
func (a *RaspicameraActivity) Eval(context activity.Context) (done bool, err error) {
	timeout := context.GetInput(ivTimeout)
	sharpness := context.GetInput(ivSharpness)
	brightness := context.GetInput(ivBrightness)
	contrast := context.GetInput(ivContrast)
	saturation := context.GetInput(ivSaturation)
	iso := context.GetInput(ivISO)
	filename := context.GetInput(ivFilename)

	// Check if mandatory credentials are set in config
	if filename == nil {
		log.Error("Missing output filename")
		err := activity.NewError("Raspicam filename config not specified", "", nil)
		return false, err
	}

	// Create a client for raspicam.
	still := raspicam.NewStill()

	preview := still.Preview
	preview.Mode = raspicam.PreviewDisabled
	still.Preview = preview
	//preview := raspicam.Preview { Mode: raspicam.PreviewDisabled }

	if timeout != nil {
		still.Timeout = time.Duration(timeout.(int))
		log.Debug("Camera timeout set to %v", timeout)
	}
	if sharpness != nil {
		still.Camera.Sharpness = sharpness.(int)
		log.Debug("Camera sharpness set to %v", sharpness)
	}
	if brightness != nil {
		still.Camera.Brightness = brightness.(int)
		log.Debug("Camera brightness set to %v", brightness)
	}
	if contrast != nil {
		still.Camera.Contrast = contrast.(int)
		log.Debug("Camera contrast set to %v", contrast)
	}
	if saturation != nil {
		still.Camera.Saturation = saturation.(int)
		log.Debug("Camera saturation set to %v", saturation)
	}
	if iso != nil {
		still.Camera.ISO = iso.(int)
		log.Debug("Camera iso set to %v", iso)
	}

	/*
	imageDirectory, imageFile := path.Split(filename.(string))
	if imageFile == "" {
		context.SetOutput(ovStatus, "NO_FILENAME_ERR")
		return true, nil
	}
	if imageDirectory == "" {
		if _, err := os.Stat(imageDirectory); os.IsNotExist(err) {
			os.MkdirAll(imageDirectory, 0777)
		}
	}*/

	// create the folder for the image
	f, err := os.Create(filename.(string))
	if err != nil {
		log.Error("Raspicam error on creating the image file: %v", err)
		context.SetOutput(ovStatus, "IMAGE_CREATE__ERR")
		return true, nil
		//fmt.Fprintf(os.Stderr, "create file: %v", err)

	}
	defer f.Close()

	errCh := make(chan error)
	go func() {
		for x := range errCh {
			//fmt.Fprintf(os.Stderr, "%v\n", x)
			log.Error("%v\n", x)
		}
	}()

	//cmd := exec.Command("raspistill", "-vf", "-hf", "-a", "1024", "-a", "8", "-a", "achimera| %F %r", "-o", imageFile)
	raspicam.Capture(still, f, errCh)
	log.Info("Raspicam created image file: %v", filename)

	context.SetOutput(ovStatus, "OK")

	return true, nil
}
<commit_msg>preview<commit_after>package raspicamera

import (
	"github.com/TIBCOSoftware/flogo-lib/core/activity"
	"github.com/TIBCOSoftware/flogo-lib/logger"
	"github.com/dhowden/raspicam"
	"time"
	"os"
	//"path"
)

// log is the default package logger
var log = logger.GetLogger("activity-raspicamera")

const (
	ivTimeout 		= "timeout" //delay before the image is taken
	ivSharpness 	= "sharpness"
	ivBrightness 	= "brightness"
	ivContrast		= "contrast"
	ivSaturation 	= "saturation"
	ivISO			= "iso"
	ivFilename		= "filename"

	ovStatus        = "status"
)

// RaspicameraActivity is a stub for your Activity implementation
type RaspicameraActivity struct {
	metadata *activity.Metadata
}

// NewActivity creates a new activity
func NewActivity(metadata *activity.Metadata) activity.Activity {
	return &RaspicameraActivity{metadata: metadata}
}

// Metadata implements activity.Activity.Metadata
func (a *RaspicameraActivity) Metadata() *activity.Metadata {
	return a.metadata
}

// Eval implements activity.Activity.Eval
func (a *RaspicameraActivity) Eval(context activity.Context) (done bool, err error) {
	timeout := context.GetInput(ivTimeout)
	sharpness := context.GetInput(ivSharpness)
	brightness := context.GetInput(ivBrightness)
	contrast := context.GetInput(ivContrast)
	saturation := context.GetInput(ivSaturation)
	iso := context.GetInput(ivISO)
	filename := context.GetInput(ivFilename)

	// Check if mandatory credentials are set in config
	if filename == nil {
		log.Error("Missing output filename")
		err := activity.NewError("Raspicam filename config not specified", "", nil)
		return false, err
	}

	// Create a client for raspicam.
	still := raspicam.NewStill()
	//preview := still.Preview
	//still.Preview = preview

	myPreview := raspicam.Preview {
		Mode: raspicam.PreviewDisabled,
		Opacity: 255,
		Rect: raspicam.Rect{X: 0, Y: 0, Width: 0, Height: 0},
	}
	still.Preview = myPreview
	//preview := raspicam.Preview { Mode: raspicam.PreviewDisabled }

	if timeout != nil {
		still.Timeout = time.Duration(timeout.(int))
		log.Debug("Camera timeout set to %v", timeout)
	}
	if sharpness != nil {
		still.Camera.Sharpness = sharpness.(int)
		log.Debug("Camera sharpness set to %v", sharpness)
	}
	if brightness != nil {
		still.Camera.Brightness = brightness.(int)
		log.Debug("Camera brightness set to %v", brightness)
	}
	if contrast != nil {
		still.Camera.Contrast = contrast.(int)
		log.Debug("Camera contrast set to %v", contrast)
	}
	if saturation != nil {
		still.Camera.Saturation = saturation.(int)
		log.Debug("Camera saturation set to %v", saturation)
	}
	if iso != nil {
		still.Camera.ISO = iso.(int)
		log.Debug("Camera iso set to %v", iso)
	}

	/*
	imageDirectory, imageFile := path.Split(filename.(string))
	if imageFile == "" {
		context.SetOutput(ovStatus, "NO_FILENAME_ERR")
		return true, nil
	}
	if imageDirectory == "" {
		if _, err := os.Stat(imageDirectory); os.IsNotExist(err) {
			os.MkdirAll(imageDirectory, 0777)
		}
	}*/

	// create the folder for the image
	f, err := os.Create(filename.(string))
	if err != nil {
		log.Error("Raspicam error on creating the image file: %v", err)
		context.SetOutput(ovStatus, "IMAGE_CREATE__ERR")
		return true, nil
		//fmt.Fprintf(os.Stderr, "create file: %v", err)

	}
	defer f.Close()

	errCh := make(chan error)
	go func() {
		for x := range errCh {
			//fmt.Fprintf(os.Stderr, "%v\n", x)
			log.Error("%v\n", x)
		}
	}()

	//cmd := exec.Command("raspistill", "-vf", "-hf", "-a", "1024", "-a", "8", "-a", "achimera| %F %r", "-o", imageFile)
	raspicam.Capture(still, f, errCh)
	log.Info("Raspicam created image file: %v", filename)

	context.SetOutput(ovStatus, "OK")

	return true, nil
}
<|endoftext|>


<commit_before>package edc

// Practice - struct for practice
type Practice struct {
	ID             int64   `sql:"id" json:"id"`
	Company        Company `sql:"-"`
	CompanyID      int64   `sql:"company_id, null" json:"company_id"`
	Kind           Kind    `sql:"-"`
	KindID         int64   `sql:"kind_id, null" json:"kind_id"`
	Topic          string  `sql:"topic, null" json:"topic"`
	DateOfPractice string  `sql:"date_of_practice, null" json:"date_of_practice"`
	DateStr        string  `sql:"-" json:"date_str"`
	Note           string  `sql:"note, null" json:"note"`
	CreatedAt      string  `sql:"created_at" json:"created_at"`
	UpdatedAt      string  `sql:"updated_at" json:"updated_at"`
}

// PracticeList is struct for practice list
type PracticeList struct {
	ID             int64  `sql:"id" json:"id"`
	CompanyID      int64  `sql:"company_id, null" json:"company_id"`
	CompanyName    string `sql:"company_name, null" json:"company_name"`
	KindName       string `sql:"kind_name, null" json:"kind_name"`
	Topic          string `sql:"topic, null" json:"topic"`
	DateOfPractice string `sql:"date_of_practice, null" json:"date_of_practice"`
	DateStr        string `sql:"-" json:"date_str"`
}

// GetPractice - get one practice by id
func (e *Edb) GetPractice(id int64) (Practice, error) {
	var practice Practice
	if id == 0 {
		return practice, nil
	}
	err := e.db.Model(&practice).
		Where("id = ?", id).
		Select()
	if err != nil {
		errmsg("GetPractice select", err)
		return practice, err
	}
	return practice, err
}

// GetPracticeList - get all practices for list
func (e *Edb) GetPracticeList() ([]PracticeList, error) {
	var practices []PracticeList
	_, err := e.db.Query(&practices, `
	SELECT
		p.id,
		p.company_id,
		c.name AS company_name,
		k.name AS kind_name,
		p.topic,
		p.date_of_practice
	FROM
		practices AS p
	LEFT JOIN
		companies AS c ON c.id = p.company_id
	LEFT JOIN
		kinds AS k ON k.id = p.kind_id
	ORDER BY
		date_of_practice DESC`)
	if err != nil {
		errmsg("GetPracticeList query", err)
	}
	return practices, err
}

// GetPracticeCompany - get all practices of company
func (e *Edb) GetPracticeCompany(id int64) ([]Practice, error) {
	var practices []Practice
	if id == 0 {
		return practices, nil
	}
	_, err := e.db.Query(&practices, `SELECT
		p.id,
		k.name AS kind_name,
		p.topic,
		p.date_of_practice
	FROM
		practices AS p
	LEFT JOIN
		kinds AS k ON k.id = p.kind_id
	WHERE
	    p.company_id = ?
	ORDER BY
		date_of_practice`, id)
	if err != nil {
		errmsg("GetPracticeCompany query", err)
	}
	return practices, err
}

// GetPracticeNear - get 10 nearest practices
func (e *Edb) GetPracticeNear() ([]Practice, error) {
	var practices []Practice
	_, err := e.db.Query(&practices, `SELECT
		p.id,
		c.name AS company_name,
		k.name AS kind_name,
		p.topic,
		p.date_of_practice
	FROM
		practices AS p
	LEFT JOIN
		companies AS c ON c.id = p.company_id
	LEFT JOIN
		kinds AS k ON k.id = p.kind_id
	WHERE
		p.date_of_practice > now()
	ORDER BY
		date_of_practice
	LIMIT 10`)
	if err != nil {
		errmsg("GetPracticeNear query", err)
	}
	return practices, err
}

// CreatePractice - create new practice
func (e *Edb) CreatePractice(practice Practice) (int64, error) {
	err := e.db.Insert(&practice)
	if err != nil {
		errmsg("CreatePractice insert", err)
	}
	return practice.ID, err
}

// UpdatePractice - save practice changes
func (e *Edb) UpdatePractice(practice Practice) error {
	err := e.db.Update(&practice)
	if err != nil {
		errmsg("UpdatePractice update", err)
	}
	return err
}

// DeletePractice - delete practice by id
func (e *Edb) DeletePractice(id int64) error {
	if id == 0 {
		return nil
	}
	_, err := e.db.Model(&Practice{}).
		Where("id = ?", id).
		Delete()
	if err != nil {
		errmsg("DeletePractice delete", err)
	}
	return err
}

func (e *Edb) practiceCreateTable() error {
	str := `
		CREATE TABLE IF NOT EXISTS
			practices (
				id bigserial primary key,
				company_id bigint,
				kind_id bigint,
				topic text,
				date_of_practice date,
				note text,
				created_at TIMESTAMP without time zone,
				updated_at TIMESTAMP without time zone default now()
			)
	`
	_, err := e.db.Exec(str)
	if err != nil {
		errmsg("practiceCreateTable exec", err)
	}
	return err
}
<commit_msg>fix get company practices<commit_after>package edc

// Practice - struct for practice
type Practice struct {
	ID             int64   `sql:"id" json:"id"`
	Company        Company `sql:"-"`
	CompanyID      int64   `sql:"company_id, null" json:"company_id"`
	Kind           Kind    `sql:"-"`
	KindID         int64   `sql:"kind_id, null" json:"kind_id"`
	Topic          string  `sql:"topic, null" json:"topic"`
	DateOfPractice string  `sql:"date_of_practice, null" json:"date_of_practice"`
	DateStr        string  `sql:"-" json:"date_str"`
	Note           string  `sql:"note, null" json:"note"`
	CreatedAt      string  `sql:"created_at" json:"created_at"`
	UpdatedAt      string  `sql:"updated_at" json:"updated_at"`
}

// PracticeList is struct for practice list
type PracticeList struct {
	ID             int64  `sql:"id" json:"id"`
	CompanyID      int64  `sql:"company_id, null" json:"company_id"`
	CompanyName    string `sql:"company_name, null" json:"company_name"`
	KindName       string `sql:"kind_name, null" json:"kind_name"`
	Topic          string `sql:"topic, null" json:"topic"`
	DateOfPractice string `sql:"date_of_practice, null" json:"date_of_practice"`
	DateStr        string `sql:"-" json:"date_str"`
}

// GetPractice - get one practice by id
func (e *Edb) GetPractice(id int64) (Practice, error) {
	var practice Practice
	if id == 0 {
		return practice, nil
	}
	err := e.db.Model(&practice).
		Where("id = ?", id).
		Select()
	if err != nil {
		errmsg("GetPractice select", err)
		return practice, err
	}
	return practice, err
}

// GetPracticeList - get all practices for list
func (e *Edb) GetPracticeList() ([]PracticeList, error) {
	var practices []PracticeList
	_, err := e.db.Query(&practices, `
	SELECT
		p.id,
		p.company_id,
		c.name AS company_name,
		k.name AS kind_name,
		p.topic,
		p.date_of_practice
	FROM
		practices AS p
	LEFT JOIN
		companies AS c ON c.id = p.company_id
	LEFT JOIN
		kinds AS k ON k.id = p.kind_id
	ORDER BY
		date_of_practice DESC`)
	if err != nil {
		errmsg("GetPracticeList query", err)
	}
	return practices, err
}

// GetPracticeCompany - get all practices of company
func (e *Edb) GetPracticeCompany(id int64) ([]Practice, error) {
	var practices []Practice
	if id == 0 {
		return practices, nil
	}
	err := e.db.Model(&practices).
		Where("company_id = ?", id).
		Select()
	if err != nil {
		errmsg("GetPracticeCompany select", err)
	}
	return practices, err
}

// GetPracticeNear - get 10 nearest practices
func (e *Edb) GetPracticeNear() ([]Practice, error) {
	var practices []Practice
	_, err := e.db.Query(&practices, `SELECT
		p.id,
		c.name AS company_name,
		k.name AS kind_name,
		p.topic,
		p.date_of_practice
	FROM
		practices AS p
	LEFT JOIN
		companies AS c ON c.id = p.company_id
	LEFT JOIN
		kinds AS k ON k.id = p.kind_id
	WHERE
		p.date_of_practice > now()
	ORDER BY
		date_of_practice
	LIMIT 10`)
	if err != nil {
		errmsg("GetPracticeNear query", err)
	}
	return practices, err
}

// CreatePractice - create new practice
func (e *Edb) CreatePractice(practice Practice) (int64, error) {
	err := e.db.Insert(&practice)
	if err != nil {
		errmsg("CreatePractice insert", err)
	}
	return practice.ID, err
}

// UpdatePractice - save practice changes
func (e *Edb) UpdatePractice(practice Practice) error {
	err := e.db.Update(&practice)
	if err != nil {
		errmsg("UpdatePractice update", err)
	}
	return err
}

// DeletePractice - delete practice by id
func (e *Edb) DeletePractice(id int64) error {
	if id == 0 {
		return nil
	}
	_, err := e.db.Model(&Practice{}).
		Where("id = ?", id).
		Delete()
	if err != nil {
		errmsg("DeletePractice delete", err)
	}
	return err
}

func (e *Edb) practiceCreateTable() error {
	str := `
		CREATE TABLE IF NOT EXISTS
			practices (
				id bigserial primary key,
				company_id bigint,
				kind_id bigint,
				topic text,
				date_of_practice date,
				note text,
				created_at TIMESTAMP without time zone,
				updated_at TIMESTAMP without time zone default now()
			)
	`
	_, err := e.db.Exec(str)
	if err != nil {
		errmsg("practiceCreateTable exec", err)
	}
	return err
}
<|endoftext|>


<commit_before>// kexec command in Go.
// Wow, Linux. Just Wow. Who designs this stuff? Because, basically, it's not very good.
// I considered keeping the C declarations and such stuff here but it has not changed
// much over the years, so that seemed pointless.
// For a good design, you can always see the console device in Plan 9.
// E.g.,
// echo reboot path/to/kernel > /dev/consctl
// There, that's it, done. Is it so hard? Especially given that Linux already has an
// elf parser?
package main

// N.B. /**/ comments are verbatim from uapi/linux/kexec.h.
/* kexec system call -  It loads the new kernel to boot into.
 * kexec does not sync, or unmount filesystems so if you need
 * that to happen you need to do that yourself.
 */

import (
	"bytes"
	"debug/elf"
	"flag"
	"io"
	"io/ioutil"
	"log"
	"syscall"
	"unsafe"
)

/* kexec flags for different usage scenarios */
const (
	KEXEC_ON_CRASH         = 0x00000001
	KEXEC_PRESERVE_CONTEXT = 0x00000002
	KEXEC_ARCH_MASK        = 0xffff0000

	/* These values match the ELF architecture values.
	 * Unless there is a good reason that should continue to be the case.
	 */
	KEXEC_ARCH_DEFAULT = (0 << 16)
	KEXEC_ARCH_386     = (3 << 16)
	KEXEC_ARCH_68K     = (4 << 16)
	KEXEC_ARCH_X86_64  = (62 << 16)
	KEXEC_ARCH_PPC     = (20 << 16)
	KEXEC_ARCH_PPC64   = (21 << 16)
	KEXEC_ARCH_IA_64   = (50 << 16)
	KEXEC_ARCH_ARM     = (40 << 16)
	KEXEC_ARCH_S390    = (22 << 16)
	KEXEC_ARCH_SH      = (42 << 16)
	KEXEC_ARCH_MIPS_LE = (10 << 16)
	KEXEC_ARCH_MIPS    = (8 << 16)

	/* The artificial cap on the number of segments passed to kexec_load. */
	KEXEC_SEGMENT_MAX = 16
)

/*
 * This structure is used to hold the arguments that are used when
 * loading  kernel binaries.
 */
type kexec_segment struct {
	buf     uintptr
	bufsz   uintptr
	mem     uintptr
	memsize uintptr
}

type loader func(b[]byte) ([]kexec_segment, error)
var (
	kernel = flag.String("k", "vmlinux", "Kernel to load")
	loaders = []loader{elfexec, rawexec}
)

/* Load a new kernel image as described by the kexec_segment array
 * consisting of passed number of segments at the entry-point address.
 * The flags allow different useage types.
 */
//extern int kexec_load(void *, size_t, struct kexec_segment *,
//		unsigned long int);

// rawexec either succeeds or Fatals out. It's the last chance.
func rawexec(b []byte) ([]kexec_segment, error) {
	segs := []kexec_segment{{buf: uintptr(unsafe.Pointer(&b[0])), bufsz: uintptr(len(b)), mem: 0x1000, memsize: uintptr(len(b))}}
	return segs, nil
}

func elfexec(b []byte) ([]kexec_segment, error) {
	f, err := elf.NewFile(bytes.NewReader(b))
	if err != nil {
		return nil, err
	}
	scount := 0
	for _, v := range f.Progs {
		if v.Type.String() == "PT_LOAD" {
			scount++
		}
	}
	if scount > KEXEC_SEGMENT_MAX {
		log.Fatalf("Too many segments: got %v, max is %v", scount, KEXEC_SEGMENT_MAX)
	}
	segs := make([]kexec_segment, scount)
	for _, v := range f.Progs {
		if v.Type.String() == "PT_LOAD" {
			f := v.Open()
			b := bytes.NewBuffer([]byte{})
			io.Copy(b, f)
			segs = append(segs, kexec_segment{
				buf: uintptr(unsafe.Pointer(&b.Bytes()[0])),
				bufsz: uintptr(b.Len()),
				mem: uintptr(v.Paddr),
				memsize: uintptr(v.Memsz),
			})
		}
	}
	return segs, nil
}
func main() {
	var err error
	var segs []kexec_segment
	flag.Parse()
	b, err := ioutil.ReadFile(*kernel)
	if err != nil {
		log.Fatalf("%v", err)
	}
	log.Printf("Loading %v\n", *kernel)
	for i := range loaders {
		if segs, err = loaders[i](b); err == nil {
			break
		}
	}

	e1, e2, err := syscall.Syscall(syscall.SYS_KEXEC_LOAD, uintptr(len(segs)), uintptr(unsafe.Pointer(&segs[0])), uintptr(0))
	log.Printf("a %v b %v err %v", e1, e2, err)
}
<commit_msg>Further fixes to kexec.<commit_after>// kexec command in Go.
// Wow, Linux. Just Wow. Who designs this stuff? Because, basically, it's not very good.
// I considered keeping the C declarations and such stuff here but it has not changed
// much over the years, so that seemed pointless.
// For a good design, you can always see the console device in Plan 9.
// E.g.,
// echo reboot path/to/kernel > /dev/consctl
// There, that's it, done. Is it so hard? Especially given that Linux already has an
// elf parser?
package main

// N.B. /**/ comments are verbatim from uapi/linux/kexec.h.
/* kexec system call -  It loads the new kernel to boot into.
 * kexec does not sync, or unmount filesystems so if you need
 * that to happen you need to do that yourself.
 */

import (
	"bytes"
	"debug/elf"
	"flag"
	"io"
	"io/ioutil"
	"log"
	"syscall"
	"unsafe"
)

/* kexec flags for different usage scenarios */
const (
	KEXEC_ON_CRASH         = 0x00000001
	KEXEC_PRESERVE_CONTEXT = 0x00000002
	KEXEC_ARCH_MASK        = 0xffff0000

	/* These values match the ELF architecture values.
	 * Unless there is a good reason that should continue to be the case.
	 */
	KEXEC_ARCH_DEFAULT = (0 << 16)
	KEXEC_ARCH_386     = (3 << 16)
	KEXEC_ARCH_68K     = (4 << 16)
	KEXEC_ARCH_X86_64  = (62 << 16)
	KEXEC_ARCH_PPC     = (20 << 16)
	KEXEC_ARCH_PPC64   = (21 << 16)
	KEXEC_ARCH_IA_64   = (50 << 16)
	KEXEC_ARCH_ARM     = (40 << 16)
	KEXEC_ARCH_S390    = (22 << 16)
	KEXEC_ARCH_SH      = (42 << 16)
	KEXEC_ARCH_MIPS_LE = (10 << 16)
	KEXEC_ARCH_MIPS    = (8 << 16)

	/* The artificial cap on the number of segments passed to kexec_load. */
	KEXEC_SEGMENT_MAX = 16
)

/*
 * This structure is used to hold the arguments that are used when
 * loading  kernel binaries.
 */
type kexec_segment struct {
	buf     uintptr
	bufsz   uintptr
	mem     uintptr
	memsize uintptr
}

type loader func(b[]byte) (uintptr, []kexec_segment, error)
var (
	kernel = flag.String("k", "vmlinux", "Kernel to load")
	loaders = []loader{elfexec, rawexec}
)

/* Load a new kernel image as described by the kexec_segment array
 * consisting of passed number of segments at the entry-point address.
 * The flags allow different useage types.
 */
//extern int kexec_load(void *, size_t, struct kexec_segment *,
//		unsigned long int);

// rawexec either succeeds or Fatals out. It's the last chance.
func rawexec(b []byte) (uintptr, []kexec_segment, error) {
	var entry uintptr
	segs := []kexec_segment{{buf: uintptr(unsafe.Pointer(&b[0])), bufsz: uintptr(len(b)), mem: 0x1000, memsize: uintptr(len(b))}}
	return entry, segs, nil
}

func elfexec(b []byte) (uintptr, []kexec_segment, error) {
	f, err := elf.NewFile(bytes.NewReader(b))
	if err != nil {
		return 0, nil, err
	}
	scount := 0
	for _, v := range f.Progs {
		if v.Type.String() == "PT_LOAD" {
			scount++
		}
	}
	if scount > KEXEC_SEGMENT_MAX {
		log.Fatalf("Too many segments: got %v, max is %v", scount, KEXEC_SEGMENT_MAX)
	}
	segs := make([]kexec_segment, scount)
	for _, v := range f.Progs {
		if v.Type.String() == "PT_LOAD" {
			f := v.Open()
			b := bytes.NewBuffer([]byte{})
			io.Copy(b, f)
			segs = append(segs, kexec_segment{
				buf: uintptr(unsafe.Pointer(&b.Bytes()[0])),
				bufsz: uintptr(b.Len()),
				mem: uintptr(v.Paddr),
				memsize: uintptr(v.Memsz),
			})
		}
	}
	return uintptr(f.Entry), segs, nil
}
func main() {
	var err error
	var segs []kexec_segment
	var entry uintptr
	flag.Parse()
	b, err := ioutil.ReadFile(*kernel)
	if err != nil {
		log.Fatalf("%v", err)
	}
	log.Printf("Loading %v\n", *kernel)
	for i := range loaders {
		if entry, segs, err = loaders[i](b); err == nil {
			break
		}
	}

	log.Printf("%v %v %v %v %v", syscall.SYS_KEXEC_LOAD, entry, uintptr(len(segs)), uintptr(unsafe.Pointer(&segs[0])), uintptr(0))
	e1, e2, err := syscall.Syscall6(syscall.SYS_KEXEC_LOAD, entry, uintptr(len(segs)), uintptr(unsafe.Pointer(&segs[0])), 0, 0, 0)
	log.Printf("a %v b %v err %v", e1, e2, err)
}
<|endoftext|>