<commit_before>/*
MIT License

Copyright (c) 2016 Sascha Hanse
Copyright (c) 2017 Shinya Yagyu

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

package giota

import (
	"errors"
	"time"
)

//Transaction is transaction  structure for iota.
type Transaction struct {
	SignatureMessageFragment Trytes
	Address                  Address
	Value                    int64 `json:",string"`
	Tag                      Trytes
	Timestamp                time.Time `json:",string"`
	CurrentIndex             int64     `json:",string"`
	LastIndex                int64     `json:",string"`
	Bundle                   Trytes
	TrunkTransaction         Trytes
	BranchTransaction        Trytes
	Nonce                    Trytes
}

//errors for tx.
var (
	ErrInvalidTransactionType = errors.New("invalid transaction type")
	ErrInvalidTransactionHash = errors.New("invalid transaction hash")
	ErrInvalidTransaction     = errors.New("malformed transaction")
)

//sizes and offsets of tx.
const (
	signatureMessageFragmentTrinaryOffset = 0
	signatureMessageFragmentTrinarySize   = 6561
	addressTrinaryOffset                  = signatureMessageFragmentTrinaryOffset + signatureMessageFragmentTrinarySize
	addressTrinarySize                    = 243
	valueTrinaryOffset                    = addressTrinaryOffset + addressTrinarySize
	valueTrinarySize                      = 81
	tagTrinaryOffset                      = valueTrinaryOffset + valueTrinarySize
	tagTrinarySize                        = 81
	timestampTrinaryOffset                = tagTrinaryOffset + tagTrinarySize
	timestampTrinarySize                  = 27
	currentIndexTrinaryOffset             = timestampTrinaryOffset + timestampTrinarySize
	currentIndexTrinarySize               = 27
	lastIndexTrinaryOffset                = currentIndexTrinaryOffset + currentIndexTrinarySize
	lastIndexTrinarySize                  = 27
	bundleTrinaryOffset                   = lastIndexTrinaryOffset + lastIndexTrinarySize
	bundleTrinarySize                     = 243
	trunkTransactionTrinaryOffset         = bundleTrinaryOffset + bundleTrinarySize
	trunkTransactionTrinarySize           = 243
	branchTransactionTrinaryOffset        = trunkTransactionTrinaryOffset + trunkTransactionTrinarySize
	branchTransactionTrinarySize          = 243
	nonceTrinaryOffset                    = branchTransactionTrinaryOffset + branchTransactionTrinarySize
	nonceTrinarySize                      = 243

	transactionTrinarySize = signatureMessageFragmentTrinarySize + addressTrinarySize +
		valueTrinarySize + tagTrinarySize + timestampTrinarySize +
		currentIndexTrinarySize + lastIndexTrinarySize + bundleTrinarySize +
		trunkTransactionTrinarySize + branchTransactionTrinarySize +
		nonceTrinarySize
)

//NewTransaction makes tx from trits.
func NewTransaction(trits Trits) (*Transaction, error) {
	t := Transaction{}
	err := t.parser(trits)
	return &t, err
}

func (t *Transaction) parser(trits Trits) error {
	if err := trits.IsValid(); err != nil {
		return errors.New("invalid transaction " + err.Error())
	}
	if len(trits) != transactionTrinarySize {
		return errors.New("invalid trits counts in transaction")
	}

	trytes := trits.Trytes()
	if trytes[2279:2295] != "9999999999999999" {
		return errors.New("invalid value in transaction")
	}
	var err error
	t.SignatureMessageFragment = trits[signatureMessageFragmentTrinaryOffset:signatureMessageFragmentTrinarySize].Trytes()
	t.Address, err = trits[addressTrinaryOffset : addressTrinaryOffset+addressTrinarySize].Trytes().ToAddress()
	if err != nil {
		return err
	}
	t.Value = trits[valueTrinaryOffset : valueTrinaryOffset+valueTrinarySize].Int()
	t.Tag = trits[tagTrinaryOffset : tagTrinaryOffset+tagTrinarySize].Trytes()
	timestamp := trits[timestampTrinaryOffset : timestampTrinaryOffset+timestampTrinarySize].Int()
	t.Timestamp = time.Unix(timestamp, 0)
	t.CurrentIndex = trits[currentIndexTrinaryOffset : currentIndexTrinaryOffset+currentIndexTrinarySize].Int()
	t.LastIndex = trits[lastIndexTrinaryOffset : lastIndexTrinaryOffset+lastIndexTrinarySize].Int()
	t.Bundle = trits[bundleTrinaryOffset : bundleTrinaryOffset+bundleTrinarySize].Trytes()
	t.TrunkTransaction = trits[trunkTransactionTrinaryOffset : trunkTransactionTrinaryOffset+trunkTransactionTrinarySize].Trytes()
	t.BranchTransaction = trits[branchTransactionTrinaryOffset : branchTransactionTrinaryOffset+branchTransactionTrinarySize].Trytes()
	t.Nonce = trits[nonceTrinaryOffset : nonceTrinaryOffset+nonceTrinarySize].Trytes()

	return nil
}

//Trits returns trits representation of t.
func (t *Transaction) Trits() Trits {
	tr := make(Trits, transactionTrinarySize)
	copy(tr, t.SignatureMessageFragment.Trits())
	copy(tr[addressTrinaryOffset:], Trytes(t.Address).Trits())
	copy(tr[valueTrinaryOffset:], Int2Trits(t.Value, valueTrinarySize))
	copy(tr[tagTrinaryOffset:], t.Tag.Trits())
	copy(tr[timestampTrinaryOffset:], Int2Trits(t.Timestamp.Unix(), timestampTrinarySize))
	copy(tr[currentIndexTrinaryOffset:], Int2Trits(t.CurrentIndex, currentIndexTrinarySize))
	copy(tr[lastIndexTrinaryOffset:], Int2Trits(t.LastIndex, lastIndexTrinarySize))
	copy(tr[bundleTrinaryOffset:], t.Bundle.Trits())
	copy(tr[trunkTransactionTrinaryOffset:], t.TrunkTransaction.Trits())
	copy(tr[branchTransactionTrinaryOffset:], t.BranchTransaction.Trits())
	copy(tr[nonceTrinaryOffset:], t.Nonce.Trits())
	return tr
}

//HasValidNonce checks t's hash has valid mwm.
func (t *Transaction) HasValidNonce() bool {
	h := t.Trits().Hash().Trytes()
	for i := len(h) - 1; i >= len(h)-1-MinWeightMagnitude/3; i-- {
		if h[i] != '9' {
			return false
		}
	}
	return true
}
<commit_msg>readded tx unmarshal<commit_after>/*
MIT License

Copyright (c) 2016 Sascha Hanse
Copyright (c) 2017 Shinya Yagyu

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

package giota

import (
	"encoding/json"
	"errors"
	"time"
)

//Transaction is transaction  structure for iota.
type Transaction struct {
	SignatureMessageFragment Trytes
	Address                  Address
	Value                    int64 `json:",string"`
	Tag                      Trytes
	Timestamp                time.Time `json:",string"`
	CurrentIndex             int64     `json:",string"`
	LastIndex                int64     `json:",string"`
	Bundle                   Trytes
	TrunkTransaction         Trytes
	BranchTransaction        Trytes
	Nonce                    Trytes
}

//errors for tx.
var (
	ErrInvalidTransactionType = errors.New("invalid transaction type")
	ErrInvalidTransactionHash = errors.New("invalid transaction hash")
	ErrInvalidTransaction     = errors.New("malformed transaction")
)

//sizes and offsets of tx.
const (
	signatureMessageFragmentTrinaryOffset = 0
	signatureMessageFragmentTrinarySize   = 6561
	addressTrinaryOffset                  = signatureMessageFragmentTrinaryOffset + signatureMessageFragmentTrinarySize
	addressTrinarySize                    = 243
	valueTrinaryOffset                    = addressTrinaryOffset + addressTrinarySize
	valueTrinarySize                      = 81
	tagTrinaryOffset                      = valueTrinaryOffset + valueTrinarySize
	tagTrinarySize                        = 81
	timestampTrinaryOffset                = tagTrinaryOffset + tagTrinarySize
	timestampTrinarySize                  = 27
	currentIndexTrinaryOffset             = timestampTrinaryOffset + timestampTrinarySize
	currentIndexTrinarySize               = 27
	lastIndexTrinaryOffset                = currentIndexTrinaryOffset + currentIndexTrinarySize
	lastIndexTrinarySize                  = 27
	bundleTrinaryOffset                   = lastIndexTrinaryOffset + lastIndexTrinarySize
	bundleTrinarySize                     = 243
	trunkTransactionTrinaryOffset         = bundleTrinaryOffset + bundleTrinarySize
	trunkTransactionTrinarySize           = 243
	branchTransactionTrinaryOffset        = trunkTransactionTrinaryOffset + trunkTransactionTrinarySize
	branchTransactionTrinarySize          = 243
	nonceTrinaryOffset                    = branchTransactionTrinaryOffset + branchTransactionTrinarySize
	nonceTrinarySize                      = 243

	transactionTrinarySize = signatureMessageFragmentTrinarySize + addressTrinarySize +
		valueTrinarySize + tagTrinarySize + timestampTrinarySize +
		currentIndexTrinarySize + lastIndexTrinarySize + bundleTrinarySize +
		trunkTransactionTrinarySize + branchTransactionTrinarySize +
		nonceTrinarySize
)

//NewTransaction makes tx from trits.
func NewTransaction(trits Trits) (*Transaction, error) {
	t := Transaction{}
	err := t.parser(trits)
	return &t, err
}

func (t *Transaction) parser(trits Trits) error {
	if err := trits.IsValid(); err != nil {
		return errors.New("invalid transaction " + err.Error())
	}
	if len(trits) != transactionTrinarySize {
		return errors.New("invalid trits counts in transaction")
	}

	trytes := trits.Trytes()
	if trytes[2279:2295] != "9999999999999999" {
		return errors.New("invalid value in transaction")
	}
	var err error
	t.SignatureMessageFragment = trits[signatureMessageFragmentTrinaryOffset:signatureMessageFragmentTrinarySize].Trytes()
	t.Address, err = trits[addressTrinaryOffset : addressTrinaryOffset+addressTrinarySize].Trytes().ToAddress()
	if err != nil {
		return err
	}
	t.Value = trits[valueTrinaryOffset : valueTrinaryOffset+valueTrinarySize].Int()
	t.Tag = trits[tagTrinaryOffset : tagTrinaryOffset+tagTrinarySize].Trytes()
	timestamp := trits[timestampTrinaryOffset : timestampTrinaryOffset+timestampTrinarySize].Int()
	t.Timestamp = time.Unix(timestamp, 0)
	t.CurrentIndex = trits[currentIndexTrinaryOffset : currentIndexTrinaryOffset+currentIndexTrinarySize].Int()
	t.LastIndex = trits[lastIndexTrinaryOffset : lastIndexTrinaryOffset+lastIndexTrinarySize].Int()
	t.Bundle = trits[bundleTrinaryOffset : bundleTrinaryOffset+bundleTrinarySize].Trytes()
	t.TrunkTransaction = trits[trunkTransactionTrinaryOffset : trunkTransactionTrinaryOffset+trunkTransactionTrinarySize].Trytes()
	t.BranchTransaction = trits[branchTransactionTrinaryOffset : branchTransactionTrinaryOffset+branchTransactionTrinarySize].Trytes()
	t.Nonce = trits[nonceTrinaryOffset : nonceTrinaryOffset+nonceTrinarySize].Trytes()

	return nil
}

//Trits returns trits representation of t.
func (t *Transaction) Trits() Trits {
	tr := make(Trits, transactionTrinarySize)
	copy(tr, t.SignatureMessageFragment.Trits())
	copy(tr[addressTrinaryOffset:], Trytes(t.Address).Trits())
	copy(tr[valueTrinaryOffset:], Int2Trits(t.Value, valueTrinarySize))
	copy(tr[tagTrinaryOffset:], t.Tag.Trits())
	copy(tr[timestampTrinaryOffset:], Int2Trits(t.Timestamp.Unix(), timestampTrinarySize))
	copy(tr[currentIndexTrinaryOffset:], Int2Trits(t.CurrentIndex, currentIndexTrinarySize))
	copy(tr[lastIndexTrinaryOffset:], Int2Trits(t.LastIndex, lastIndexTrinarySize))
	copy(tr[bundleTrinaryOffset:], t.Bundle.Trits())
	copy(tr[trunkTransactionTrinaryOffset:], t.TrunkTransaction.Trits())
	copy(tr[branchTransactionTrinaryOffset:], t.BranchTransaction.Trits())
	copy(tr[nonceTrinaryOffset:], t.Nonce.Trits())
	return tr
}

//HasValidNonce checks t's hash has valid mwm.
func (t *Transaction) HasValidNonce() bool {
	h := t.Trits().Hash().Trytes()
	for i := len(h) - 1; i >= len(h)-1-MinWeightMagnitude/3; i-- {
		if h[i] != '9' {
			return false
		}
	}
	return true
}

//UnmarshalJSON makes transaction struct from json.
func (t *Transaction) UnmarshalJSON(b []byte) error {
	var s Trytes
	var err error
	if err = json.Unmarshal(b, &s); err != nil {
		return err
	}
	if err = t.parser(s.Trits()); err != nil {
		return err
	}
	return nil
}
<|endoftext|>


<commit_before>package types

//type Config map[string][]map[string]string
type ConfigRecord map[string]string
type Config map[string]ConfigRecord

type BaseRecord struct {
	Title string
	Link string
}

type RecordList []BaseRecord<commit_msg>Add RecordList Read, Write and documentation<commit_after>// Package types provides types for the custom JSON configuration and the
// custom JSON read, watch and book JSON file.
package types

import (
	"os"
	"fmt"
	"encoding/json"
)

// A single record of the configuration file.
type ConfigRecord map[string]string

// A whole configuration file.
type Config map[string]ConfigRecord

// A single base record of the read, watch or book JSON file.
type BaseRecord struct {
	Title string
	Link string
}

// A whole read, watch or book JSON file.
type RecordList []BaseRecord

// Read opens and read a given JSON file into the RecordList.
// It returns nil on success and the error on failure (propagates the error).
func (list *RecordList) Read(file string) error {
	// open JSON file
	readFile, err := os.Open(file)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error while opening %s\n", file)
		return err
	}

	// decode JSON file
	jsonParser := json.NewDecoder(readFile)
	if err = jsonParser.Decode(&list); err != nil {
		fmt.Fprintf(os.Stderr, "Error while parsing %s\n", file)
		readFile.Close()
		return err
	}

	readFile.Close()
	return nil
}

// Write opens and writes the RecordList to a given JSON file.
// It returns nil on success and the error on failure (propagates the error).
func (list *RecordList) Write(file string) error {
	// write back to JSON file
	readFile, err := os.Create(file)
	jsonWriter := json.NewEncoder(readFile)
	if err = jsonWriter.Encode(&list); err != nil {
		fmt.Fprintf(os.Stderr, "Error while writing back %s\n", file)
		readFile.Close()
		return err
	}

	readFile.Close()
	return nil
}<|endoftext|>


<commit_before>package iterator

import (
	"testing"

	"golang.org/x/net/context"
)

const (
	size = 10000
	eachTask = 1000
)

func doSomething(num int) int {
	for i := 0; i < eachTask; i++ {
		_ = i
	}
	return num
}

func BenchmarkCallback(b *testing.B) {
	iter := func(f func(num int)) {
		for i := 0; i < size; i++ {
			f(doSomething(i))
		}
	}

	for i := 0; i < b.N; i++ {
		iter(func(num int) {
			_ = num
		})
	}
}

func BenchmarkChannel(b *testing.B) {
	iter := func() chan int {
		out := make(chan int)
		go func() {
			defer close(out)
			for i := 0; i < size; i++ {
				out <- doSomething(i)
			}
		}()
		return out
	}

	for i := 0; i < b.N; i++ {
		for num := range iter() {
			_ = num
		}
	}
}

func BenchmarkBufferedChannel(b *testing.B) {
	iter := func() chan int {
		out := make(chan int, 10)
		go func() {
			defer close(out)
			for i := 0; i < size; i++ {
				out <- doSomething(i)
			}
		}()
		return out
	}

	for i := 0; i < b.N; i++ {
		for num := range iter() {
			_ = num
		}
	}
}
func BenchmarkChannelWithContext(b *testing.B) {
	iter := func(ctx context.Context) chan int {
		out := make(chan int)
		go func() {
			defer close(out)
			for i := 0; i < size; i++ {
				select {
				case out <- doSomething(i):
				case <-ctx.Done():
					return
				}
			}
		}()
		return out
	}

	ctx := context.Background()
	for i := 0; i < b.N; i++ {
		for num := range iter(ctx) {
			_ = num
		}
	}
}

func BenchmarkBufferedChannelWithContext(b *testing.B) {
	iter := func(ctx context.Context) chan int {
		out := make(chan int, 10)
		go func() {
			defer close(out)
			for i := 0; i < size; i++ {
				select {
				case out <- doSomething(i):
				case <-ctx.Done():
					return
				}
			}
		}()
		return out
	}

	ctx := context.Background()
	for i := 0; i < b.N; i++ {
		for num := range iter(ctx) {
			_ = num
		}
	}
}

func BenchmarkFunc(b *testing.B) {
	iter := func() func() (int, bool) {
		num, next := 0, 0
		return func() (int, bool) {
			num, next = doSomething(next), next+1
			return num, num < size
		}
	}

	for i := 0; i < b.N; i++ {
		itr := iter()
		for num, ok := itr(); ok; num, ok = itr() {
			_ = num
		}
	}
}

type iterator int
func (i *iterator) Next() int {
	out := int(*i)
	*i = iterator(doSomething(int(*i + 1)))
	return out
}

func (i iterator) Done() bool {
	return int(i) >= size
}

func BenchmarkInterface(b *testing.B) {
	for i := 0; i < b.N; i++ {
		itr := iterator(0)
		for num := itr.Next(); !itr.Done(); num = itr.Next() {
			_ = num
		}
	}
}
<commit_msg>Add options for cancel in iterator_test.<commit_after>package iterator

import (
	"testing"

	"golang.org/x/net/context"
)

const (
	size = 10000
	eachTask = 1000
)

func doSomething(num int) int {
	for i := 0; i < eachTask; i++ {
		_ = i
	}
	return num
}

func BenchmarkCallback(b *testing.B) {
	// If f returns false, stop the iteration.
	iter := func(f func(num int) bool) {
		for i := 0; i < size; i++ {
			if !f(doSomething(i)) {
				break
			}
		}
	}

	for i := 0; i < b.N; i++ {
		iter(func(num int) bool {
			_ = num
			return true
		})
	}
}

func BenchmarkChannel(b *testing.B) {
	iter := func() chan int {
		out := make(chan int)
		go func() {
			defer close(out)
			for i := 0; i < size; i++ {
				out <- doSomething(i)
			}
		}()
		return out
	}

	for i := 0; i < b.N; i++ {
		for num := range iter() {
			_ = num
		}
	}
}

func BenchmarkBufferedChannel(b *testing.B) {
	iter := func() chan int {
		out := make(chan int, 10)
		go func() {
			defer close(out)
			for i := 0; i < size; i++ {
				out <- doSomething(i)
			}
		}()
		return out
	}

	for i := 0; i < b.N; i++ {
		for num := range iter() {
			_ = num
		}
	}
}
func BenchmarkChannelWithContext(b *testing.B) {
	iter := func(ctx context.Context) chan int {
		out := make(chan int)
		go func() {
			defer close(out)
			for i := 0; i < size; i++ {
				select {
				case out <- doSomething(i):
				case <-ctx.Done():
					return
				}
			}
		}()
		return out
	}

	ctx, cancel := context.WithCancel(context.Background())
	for i := 0; i < b.N; i++ {
		for num := range iter(ctx) {
			_ = num
			// cancel()
		}
	}
	_ = cancel  // No-op
}

func BenchmarkBufferedChannelWithContext(b *testing.B) {
	iter := func(ctx context.Context) chan int {
		out := make(chan int, 10)
		go func() {
			defer close(out)
			for i := 0; i < size; i++ {
				select {
				case out <- doSomething(i):
				case <-ctx.Done():
					return
				}
			}
		}()
		return out
	}

	ctx, cancel := context.WithCancel(context.Background())
	for i := 0; i < b.N; i++ {
		for num := range iter(ctx) {
			_ = num
			// cancel()
		}
	}
	_ = cancel  // No-op
}

func BenchmarkFunc(b *testing.B) {
	iter := func() func() (int, bool) {
		num, next := 0, 0
		return func() (int, bool) {
			num, next = doSomething(next), next+1
			return num, num < size
		}
	}

	for i := 0; i < b.N; i++ {
		itr := iter()
		for num, ok := itr(); ok; num, ok = itr() {
			_ = num
		}
	}
}

type iterator int
func (i *iterator) Next() int {
	out := int(*i)
	*i = iterator(doSomething(int(*i + 1)))
	return out
}

func (i iterator) Done() bool {
	return int(i) >= size
}

func BenchmarkInterface(b *testing.B) {
	for i := 0; i < b.N; i++ {
		itr := iterator(0)
		for num := itr.Next(); !itr.Done(); num = itr.Next() {
			_ = num
		}
	}
}
<|endoftext|>


<commit_before>package main

/*

parse and generate function ti parse http.Request form

structs may be something like this

type reqProfile struct {
	ID       int64  `req:"id,nempty,nzero",json:"id"`
	Name     string `req:"name,sphinx,nempty,len>3,len<64",json:"name"`
	Language string `req:"language,nempty,len=2",json:"language"`
	Params   map[string]string `req:"prefix=param_",json:"params"`
	Groups   map[string][]string `req:"prefix=group_",json:"groups"`
	Passwd   string `req:"password,len>8",json:"-"`
}

will result in function
func reqProfileParse(request *http.Request) (reqProfile,string) {...}

*/

import (
	"fmt"
	"log"
	"os"
	"strings"

	"github.com/kanocz/goparse"
)

func main() {
	s, err := goparse.GetFileStructs(os.Args[1], "req", "req")
	if nil != err {
		fmt.Println("Error parsing file:", err)
		return
	}

	fmt.Print("package main\n\n")
	fmt.Print("import (\n\t\"net/http\"\n\t\"github.com/julienschmidt/httprouter\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n")

	for _, st := range s {
		fmt.Printf("func %sParse(request *http.Request, params httprouter.Params) (%s,string) {\n", st.Name, st.Name)
		fmt.Print("\tvar err error\n\t_ = err\n")
		fmt.Printf("\tres := %s{}\n", st.Name)
		fmt.Print("\trequest.ParseMultipartForm(0)\n\n")
		for _, f := range st.Field {

			pname := f.Name
			if nil != f.Tags && len(f.Tags) > 0 {
				pname = f.Tags[0]
			}

			checks := []string{}
			if nil != f.Tags && len(f.Tags) > 1 {
				checks = f.Tags[1:]
			}

			isParam := false
			if len(checks) > 0 && "param" == checks[0] {
				isParam = true
				checks = checks[1:]
			}

			if f.Type == "map[string][]string" {
				prefix, ok := f.TagParams["prefix"]
				if !ok {
					log.Fatalln("no prefix for map[string][]string field", f.Name, "in struct", st.Name)
				}
				prefixLen := len(prefix)
				fmt.Printf("\tres.%s = map[string][]string{}\n\n", f.Name)
				fmt.Printf("\tfor k, v := range request.Form {\n\t\tif strings.HasPrefix(k, \"%s\") {\n\t\t\tres.%s[k[%d:]] = v\n\t\t}\n\t}\n", prefix, f.Name, prefixLen)
			} else if f.Type == "map[string]string" {
				prefix, ok := f.TagParams["prefix"]
				if !ok {
					log.Fatalln("no prefix for map[string]string field", f.Name, "in struct", st.Name)
				}
				prefixLen := len(prefix)
				fmt.Printf("\tres.%s = map[string]string{}\n\n", f.Name)
				fmt.Printf("\tfor k, v := range request.Form {\n\t\tif strings.HasPrefix(k, \"%s\") {\n\t\t\tres.%s[k[%d:]] = v[0]\n\t\t}\n\t}\n", prefix, f.Name, prefixLen)

			} else if f.Type == "[]int64" {
				fmt.Printf("\tres.%s = []int64{}\n\n", f.Name)
				_, ok := f.TagParams["jarray"]
				if ok {
					if isParam {
						fmt.Printf("\tparam%s := strings.Split(params.ByName(\"%s\"), \",\")\n", f.Name, pname)
					} else {
						fmt.Printf("\tparam%s := strings.Split(request.Form.Get(\"%s\"), \",\")\n", f.Name, pname)
					}
					fmt.Printf("\tfor _, _x := range param%s {\n", f.Name)
					fmt.Print("\t\tx, err := strconv.ParseInt(_x, 10, 64)\n")
					fmt.Printf("\t\tif nil == err {\n")
					fmt.Printf("\t\t\tres.%s = append(res.%s, x)\n", f.Name, f.Name)
					fmt.Print("\t\t}\n")
					fmt.Print("\t}\n")

					// pre convert chcecks
					for _, c := range checks {
						switch c {
						case "nempty":
							fmt.Printf("\tif len(res.%s) == 0 {\n\t\treturn %s{}, \"%s_empty\"\n\t}\n", f.Name, st.Name, pname)
						}
					}

				} else {

				}

				if !ok {
					log.Fatalln("no prefix for map[string]string field", f.Name, "in struct", st.Name)
				}

			} else {

				if !strings.HasPrefix(f.Type, "[]") {
					if isParam {
						fmt.Printf("\tparam%s := params.ByName(\"%s\")\n", f.Name, pname)
					} else {
						fmt.Printf("\tparam%s := request.Form.Get(\"%s\")\n", f.Name, pname)
					}
				} else {
					// todo: other [] types
					if f.Type == "[]string" {
						fmt.Printf("\tparam%s, ok%s := request.Form.[\"%s\"]\n", f.Name, f.Name, pname)
					}
				}

				// pre convert chcecks
				for _, c := range checks {
					switch c {
					case "nempty":
						fmt.Printf("\tif \"\" == param%s {\n\t\treturn %s{}, \"%s_empty\"\n\t}\n", f.Name, st.Name, pname)
					case "sphinx":
						fmt.Printf("\tif !sphinxCheckString(param%s) {\n\t\treturn %s{}, \"%s_invalid\"\n\t}\n", f.Name, st.Name, pname)
					}
				}

				if tagLen, ok := f.TagParams["len"]; ok {
					fmt.Printf("\tif %s != len(param%s) {\n\t\treturn %s{}, \"%s_invalid\"\n\t}\n", tagLen, f.Name, st.Name, pname)
				}

				if tagLen, ok := f.TagGt["len"]; ok {
					fmt.Printf("\tif len(param%s) < %d {\n\t\treturn %s{}, \"%s_short\"\n\t}\n", f.Name, tagLen, st.Name, pname)
				}

				if tagLen, ok := f.TagLt["len"]; ok {
					fmt.Printf("\tif len(param%s) > %d {\n\t\treturn %s{}, \"%s_long\"\n\t}\n", f.Name, tagLen, st.Name, pname)
				}

				switch f.Type {
				case "string":
					fmt.Printf("\tres.%s = param%s\n\n", f.Name, f.Name)
				case "[]string":
					fmt.Printf("\tres.%s = param%s\n\n", f.Name, f.Name)
				case "int":
					fmt.Printf("\tres.%s, err = strconv.Atoi(param%s)\n\n", f.Name, f.Name)
				case "int64":
					fmt.Printf("\tres.%s, err = strconv.ParseInt(param%s, 10, 64)\n\n", f.Name, f.Name)
				case "uint64":
					fmt.Printf("\tres.%s, err = strconv.ParseUint(param%s, 10, 64)\n\n", f.Name, f.Name)
				case "float64":
					fmt.Printf("\tres.%s, err = strconv.ParseFloat(param%s, 64)\n\n", f.Name, f.Name)
				case "bool":
					fmt.Printf("\tres.%s, err = strconv.ParseBool(param%s)\n\n", f.Name, f.Name)
				case "time.Time":
					fmt.Printf("\tres.%s, err = time.Parse(time.RFC3339, param%s)\n\n", f.Name, f.Name)
				}

				// post convert chcecks
				for _, c := range checks {
					switch c {
					case "valid":
						fmt.Printf("\tif nil != err {\n\t\treturn %s{}, \"%s_invalid\"\n\t}\n", st.Name, pname)
					case "nzero":
						if f.Type == "time.Time" {
							fmt.Printf("\tif res.%s.IsZero() {\n\t\treturn %s{}, \"%s_invalid\"\n\t}\n", f.Name, st.Name, pname)
						} else {
							fmt.Printf("\tif 0 == res.%s {\n\t\treturn %s{}, \"%s_invalid\"\n\t}\n", f.Name, st.Name, pname)
						}
					}
				}

				if tagVal, ok := f.TagParams["val"]; ok {
					fmt.Printf("\tif %s != res.%s {\n\t\treturn %s{}, \"%s_invalid\"\n\t}\n", tagVal, f.Name, st.Name, pname)
				}

				if tagVal, ok := f.TagGt["val"]; ok {
					fmt.Printf("\tif %d > res.%s {\n\t\treturn %s{}, \"%s_invalid\"\n\t}\n", tagVal, f.Name, st.Name, pname)
				}

				if tagVal, ok := f.TagLt["val"]; ok {
					fmt.Printf("\tif %d < res.%s {\n\t\treturn %s{}, \"%s_invalid\"\n\t}\n", tagVal, f.Name, st.Name, pname)
				}

			}

		}
		fmt.Println("return res, \"\"")
		fmt.Println("}")
	}
}
<commit_msg>Trim spaces in request parse (example)<commit_after>package main

/*

parse and generate function ti parse http.Request form

structs may be something like this

type reqProfile struct {
	ID       int64  `req:"id,nempty,nzero",json:"id"`
	Name     string `req:"name,sphinx,nempty,len>3,len<64",json:"name"`
	Language string `req:"language,nempty,len=2",json:"language"`
	Params   map[string]string `req:"prefix=param_",json:"params"`
	Groups   map[string][]string `req:"prefix=group_",json:"groups"`
	Passwd   string `req:"password,len>8",json:"-"`
}

will result in function
func reqProfileParse(request *http.Request) (reqProfile,string) {...}

*/

import (
	"fmt"
	"log"
	"os"
	"strings"

	"github.com/kanocz/goparse"
)

func main() {
	s, err := goparse.GetFileStructs(os.Args[1], "req", "req")
	if nil != err {
		fmt.Println("Error parsing file:", err)
		return
	}

	fmt.Print("package main\n\n")
	fmt.Print("import (\n\t\"net/http\"\n\t\"github.com/julienschmidt/httprouter\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\n")

	for _, st := range s {
		fmt.Printf("func %sParse(request *http.Request, params httprouter.Params) (%s,string) {\n", st.Name, st.Name)
		fmt.Print("\tvar err error\n\t_ = err\n")
		fmt.Printf("\tres := %s{}\n", st.Name)
		fmt.Print("\trequest.ParseMultipartForm(0)\n\n")
		for _, f := range st.Field {

			pname := f.Name
			if nil != f.Tags && len(f.Tags) > 0 {
				pname = f.Tags[0]
			}

			checks := []string{}
			if nil != f.Tags && len(f.Tags) > 1 {
				checks = f.Tags[1:]
			}

			isParam := false
			if len(checks) > 0 && "param" == checks[0] {
				isParam = true
				checks = checks[1:]
			}

			if f.Type == "map[string][]string" {
				prefix, ok := f.TagParams["prefix"]
				if !ok {
					log.Fatalln("no prefix for map[string][]string field", f.Name, "in struct", st.Name)
				}
				prefixLen := len(prefix)
				fmt.Printf("\tres.%s = map[string][]string{}\n\n", f.Name)
				fmt.Printf("\tfor k, v := range request.Form {\n\t\tif strings.HasPrefix(k, \"%s\") {\n\t\t\tres.%s[k[%d:]] = v\n\t\t}\n\t}\n", prefix, f.Name, prefixLen)
			} else if f.Type == "map[string]string" {
				prefix, ok := f.TagParams["prefix"]
				if !ok {
					log.Fatalln("no prefix for map[string]string field", f.Name, "in struct", st.Name)
				}
				prefixLen := len(prefix)
				fmt.Printf("\tres.%s = map[string]string{}\n\n", f.Name)
				fmt.Printf("\tfor k, v := range request.Form {\n\t\tif strings.HasPrefix(k, \"%s\") {\n\t\t\tres.%s[k[%d:]] = v[0]\n\t\t}\n\t}\n", prefix, f.Name, prefixLen)

			} else if f.Type == "[]int64" {
				fmt.Printf("\tres.%s = []int64{}\n\n", f.Name)
				_, ok := f.TagParams["jarray"]
				if ok {
					if isParam {
						fmt.Printf("\tparam%s := strings.Split(params.ByName(\"%s\"), \",\")\n", f.Name, pname)
					} else {
						fmt.Printf("\tparam%s := strings.Split(request.Form.Get(\"%s\"), \",\")\n", f.Name, pname)
					}
					fmt.Printf("\tfor _, _x := range param%s {\n", f.Name)
					fmt.Print("\t\tx, err := strconv.ParseInt(_x, 10, 64)\n")
					fmt.Printf("\t\tif nil == err {\n")
					fmt.Printf("\t\t\tres.%s = append(res.%s, x)\n", f.Name, f.Name)
					fmt.Print("\t\t}\n")
					fmt.Print("\t}\n")

					// pre convert chcecks
					for _, c := range checks {
						switch c {
						case "nempty":
							fmt.Printf("\tif len(res.%s) == 0 {\n\t\treturn %s{}, \"%s_empty\"\n\t}\n", f.Name, st.Name, pname)
						}
					}

				} else {

				}

				if !ok {
					log.Fatalln("no prefix for map[string]string field", f.Name, "in struct", st.Name)
				}

			} else {

				if !strings.HasPrefix(f.Type, "[]") {
					if isParam {
						fmt.Printf("\tparam%s := strings.TrimSpace(params.ByName(\"%s\"))\n", f.Name, pname)
					} else {
						fmt.Printf("\tparam%s := strings.TrimSpace(request.Form.Get(\"%s\"))\n", f.Name, pname)
					}
				} else {
					// todo: other [] types
					if f.Type == "[]string" {
						fmt.Printf("\tparam%s, ok%s := request.Form.[\"%s\"]\n", f.Name, f.Name, pname)
					}
				}

				// pre convert chcecks
				for _, c := range checks {
					switch c {
					case "nempty":
						fmt.Printf("\tif \"\" == param%s {\n\t\treturn %s{}, \"%s_empty\"\n\t}\n", f.Name, st.Name, pname)
					case "sphinx":
						fmt.Printf("\tif !sphinxCheckString(param%s) {\n\t\treturn %s{}, \"%s_invalid\"\n\t}\n", f.Name, st.Name, pname)
					}
				}

				if tagLen, ok := f.TagParams["len"]; ok {
					fmt.Printf("\tif %s != len(param%s) {\n\t\treturn %s{}, \"%s_invalid\"\n\t}\n", tagLen, f.Name, st.Name, pname)
				}

				if tagLen, ok := f.TagGt["len"]; ok {
					fmt.Printf("\tif len(param%s) < %d {\n\t\treturn %s{}, \"%s_short\"\n\t}\n", f.Name, tagLen, st.Name, pname)
				}

				if tagLen, ok := f.TagLt["len"]; ok {
					fmt.Printf("\tif len(param%s) > %d {\n\t\treturn %s{}, \"%s_long\"\n\t}\n", f.Name, tagLen, st.Name, pname)
				}

				switch f.Type {
				case "string":
					fmt.Printf("\tres.%s = param%s\n\n", f.Name, f.Name)
				case "[]string":
					fmt.Printf("\tres.%s = param%s\n\n", f.Name, f.Name)
				case "int":
					fmt.Printf("\tres.%s, err = strconv.Atoi(param%s)\n\n", f.Name, f.Name)
				case "int64":
					fmt.Printf("\tres.%s, err = strconv.ParseInt(param%s, 10, 64)\n\n", f.Name, f.Name)
				case "uint64":
					fmt.Printf("\tres.%s, err = strconv.ParseUint(param%s, 10, 64)\n\n", f.Name, f.Name)
				case "float64":
					fmt.Printf("\tres.%s, err = strconv.ParseFloat(param%s, 64)\n\n", f.Name, f.Name)
				case "bool":
					fmt.Printf("\tres.%s, err = strconv.ParseBool(param%s)\n\n", f.Name, f.Name)
				case "time.Time":
					fmt.Printf("\tres.%s, err = time.Parse(time.RFC3339, param%s)\n\n", f.Name, f.Name)
				}

				// post convert chcecks
				for _, c := range checks {
					switch c {
					case "valid":
						fmt.Printf("\tif nil != err {\n\t\treturn %s{}, \"%s_invalid\"\n\t}\n", st.Name, pname)
					case "nzero":
						if f.Type == "time.Time" {
							fmt.Printf("\tif res.%s.IsZero() {\n\t\treturn %s{}, \"%s_invalid\"\n\t}\n", f.Name, st.Name, pname)
						} else {
							fmt.Printf("\tif 0 == res.%s {\n\t\treturn %s{}, \"%s_invalid\"\n\t}\n", f.Name, st.Name, pname)
						}
					}
				}

				if tagVal, ok := f.TagParams["val"]; ok {
					fmt.Printf("\tif %s != res.%s {\n\t\treturn %s{}, \"%s_invalid\"\n\t}\n", tagVal, f.Name, st.Name, pname)
				}

				if tagVal, ok := f.TagGt["val"]; ok {
					fmt.Printf("\tif %d > res.%s {\n\t\treturn %s{}, \"%s_invalid\"\n\t}\n", tagVal, f.Name, st.Name, pname)
				}

				if tagVal, ok := f.TagLt["val"]; ok {
					fmt.Printf("\tif %d < res.%s {\n\t\treturn %s{}, \"%s_invalid\"\n\t}\n", tagVal, f.Name, st.Name, pname)
				}

			}

		}
		fmt.Println("return res, \"\"")
		fmt.Println("}")
	}
}
<|endoftext|>


<commit_before>package main

/*

parse and generate function ti parse http.Request form

structs may be something like this

type reqProfile struct {
	ID       int64  `req:"id,nempty,nzero",json:"id"`
	Name     string `req:"name,sphinx,nempty,len>3,len<64",json:"name"`
	Language string `req:"language,nempty,len=2",json:"language"`
	Groups   map[string][]string `req:"prefix=group_",json:"groups"`
	Passwd   string `req:"password,len>8",json:"-"`
}

will result in function
func reqProfileParse(request *http.Request) (reqProfile,string) {...}

*/

import (
	"fmt"
	"log"
	"os"
	"strings"

	"github.com/kanocz/goparse"
)

func main() {
	s, err := goparse.GetFileStructs(os.Args[1], "req", "req")
	if nil != err {
		fmt.Println("Error parsing file:", err)
		return
	}

	fmt.Print("package main\n\n")
	fmt.Print("import (\n\t\"net/http\"\n\t\"strconv\"\nt\"strings\"\n)\n\n")

	for _, st := range s {
		errDefined := false
		fmt.Printf("func %sParse(request *http.Request) (%s,string) {\n", st.Name, st.Name)
		fmt.Printf("\tres := %s{}\n", st.Name)
		fmt.Print("\trequest.ParseMultipartForm(0)\n\n")
		for _, f := range st.Field {

			pname := f.Name
			if nil != f.Tags && len(f.Tags) > 0 {
				pname = f.Tags[0]
			}

			checks := []string{}
			if nil != f.Tags && len(f.Tags) > 1 {
				checks = f.Tags[1:]
			}

			if f.Type != "map[string][]string" {

				if !strings.HasPrefix(f.Type, "[]") {
					fmt.Printf("\tparam%s := request.Form.Get(\"%s\")\n", f.Name, pname)
				} else {
					// todo: other [] types
					if f.Type == "[]string" {
						fmt.Printf("\tparam%s, ok%s := request.Form.[\"%s\"]\n", f.Name, f.Name, pname)
					}
				}

				// pre convert chcecks
				for _, c := range checks {
					switch c {
					case "nempty":
						fmt.Printf("\tif \"\" == param%s {\n\t\treturn %s{}, \"%s_empty\"\n\t}\n", f.Name, st.Name, pname)
					case "sphinx":
						fmt.Printf("\tif !sphinxCheckString(param%s) {\n\t\treturn %s{}, \"%s_invalid\"\n\t}\n", f.Name, st.Name, pname)
					}
				}

				if tagLen, ok := f.TagParams["len"]; ok {
					fmt.Printf("\tif %s != len(param%s) {\n\t\treturn %s{}, \"%s_invalid\"\n\t}\n", tagLen, f.Name, st.Name, pname)
				}

				if tagLen, ok := f.TagGt["len"]; ok {
					fmt.Printf("\tif len(param%s) < %d {\n\t\treturn %s{}, \"%s_short\"\n\t}\n", f.Name, tagLen, st.Name, pname)
				}

				if tagLen, ok := f.TagLt["len"]; ok {
					fmt.Printf("\tif len(param%s) > %d {\n\t\treturn %s{}, \"%s_long\"\n\t}\n", f.Name, tagLen, st.Name, pname)
				}

				switch f.Type {
				case "string":
					fmt.Printf("\tres.%s = param%s\n\n", f.Name, f.Name)
				case "[]string":
					fmt.Printf("\tres.%s = param%s\n\n", f.Name, f.Name)
				case "int":
					fmt.Printf("\tres.%s = strconv.Atoi(param%s)\n\n", f.Name, f.Name)
				case "int64":
					if !errDefined {
						fmt.Println("\tvar err error\n")
						errDefined = true
					}
					fmt.Printf("\tres.%s, err = strconv.ParseInt(param%s, 10, 64)\n\n", f.Name, f.Name)
				case "uint64":
					if !errDefined {
						fmt.Println("\tvar err error\n")
						errDefined = true
					}
					fmt.Printf("\tres.%s, err = strconv.ParseUint(param%s, 10, 64)\n\n", f.Name, f.Name)
				case "float64":
					if !errDefined {
						fmt.Println("\tvar err error\n")
						errDefined = true
					}
					fmt.Printf("\tres.%s, err = strconv.ParseFloat(param%s, 64)\n\n", f.Name, f.Name)
				case "bool":
					if !errDefined {
						fmt.Println("\tvar err error\n")
						errDefined = true
					}
					fmt.Printf("\tres.%s, err = strconv.ParseBool(param%s)\n\n", f.Name, f.Name)
				}

				// post convert chcecks
				for _, c := range checks {
					switch c {
					case "valid":
						fmt.Printf("\tif nil != err {\n\t\treturn %s{}, \"%s_invalid\"\n\t}\n", st.Name, pname)
					case "nzero":
						fmt.Printf("\tif 0 == res.%s {\n\t\treturn %s{}, \"%s_invalid\"\n\t}\n", f.Name, st.Name, pname)
					}
				}
			} else {
				prefix, ok := f.TagParams["prefix"]
				if !ok {
					log.Fatalln("no prefix for map[string][]string field", f.Name, "in struct", st.Name)
				}
				prefixLen := len(prefix)
				fmt.Printf("\tres.%s = map[string][]string{}\n\n", f.Name)
				fmt.Printf("\tfor k, v := range request.Form {\n\t\tif strings.HasPrefix(k, \"%s\") {\n\t\t\tres.%s[k[%d:]] = v\n\t\t}\n\t}\n", prefix, f.Name, prefixLen)
			}

		}
		if errDefined {
			fmt.Println("\t_ = err")
		}
		fmt.Println("return res, \"\"")
		fmt.Println("}")
	}
}
<commit_msg>Example update<commit_after>package main

/*

parse and generate function ti parse http.Request form

structs may be something like this

type reqProfile struct {
	ID       int64  `req:"id,nempty,nzero",json:"id"`
	Name     string `req:"name,sphinx,nempty,len>3,len<64",json:"name"`
	Language string `req:"language,nempty,len=2",json:"language"`
	Params   map[string]string `req:"prefix=param_",json:"params"`
	Groups   map[string][]string `req:"prefix=group_",json:"groups"`
	Passwd   string `req:"password,len>8",json:"-"`
}

will result in function
func reqProfileParse(request *http.Request) (reqProfile,string) {...}

*/

import (
	"fmt"
	"log"
	"os"
	"strings"

	"github.com/kanocz/goparse"
)

func main() {
	s, err := goparse.GetFileStructs(os.Args[1], "req", "req")
	if nil != err {
		fmt.Println("Error parsing file:", err)
		return
	}

	fmt.Print("package main\n\n")
	fmt.Print("import (\n\t\"net/http\"\n\t\"strconv\"\nt\"strings\"\n)\n\n")

	for _, st := range s {
		errDefined := false
		fmt.Printf("func %sParse(request *http.Request) (%s,string) {\n", st.Name, st.Name)
		fmt.Printf("\tres := %s{}\n", st.Name)
		fmt.Print("\trequest.ParseMultipartForm(0)\n\n")
		for _, f := range st.Field {

			pname := f.Name
			if nil != f.Tags && len(f.Tags) > 0 {
				pname = f.Tags[0]
			}

			checks := []string{}
			if nil != f.Tags && len(f.Tags) > 1 {
				checks = f.Tags[1:]
			}

			if f.Type == "map[string][]string" {
				prefix, ok := f.TagParams["prefix"]
				if !ok {
					log.Fatalln("no prefix for map[string][]string field", f.Name, "in struct", st.Name)
				}
				prefixLen := len(prefix)
				fmt.Printf("\tres.%s = map[string][]string{}\n\n", f.Name)
				fmt.Printf("\tfor k, v := range request.Form {\n\t\tif strings.HasPrefix(k, \"%s\") {\n\t\t\tres.%s[k[%d:]] = v\n\t\t}\n\t}\n", prefix, f.Name, prefixLen)
			} else if f.Type == "map[string]string" {
				prefix, ok := f.TagParams["prefix"]
				if !ok {
					log.Fatalln("no prefix for map[string]string field", f.Name, "in struct", st.Name)
				}
				prefixLen := len(prefix)
				fmt.Printf("\tres.%s = map[string]string{}\n\n", f.Name)
				fmt.Printf("\tfor k, v := range request.Form {\n\t\tif strings.HasPrefix(k, \"%s\") {\n\t\t\tres.%s[k[%d:]] = v[0]\n\t\t}\n\t}\n", prefix, f.Name, prefixLen)

			} else if f.Type == "[]int64" {
				fmt.Printf("\tres.%s = []int64{}\n\n", f.Name)
				_, ok := f.TagParams["jarray"]
				if ok {
					fmt.Printf("\tparam%s := strings.Split(request.Form.Get(\"%s\"), \",\")\n", f.Name, pname)
					fmt.Printf("\tfor _, _x := range param%s {\n", f.Name)
					fmt.Print("\t\tx, err := strconv.ParseInt(_x, 10, 64)\n")
					fmt.Printf("\t\tif nil == err {\n")
					fmt.Printf("\t\t\tres.%s = append(res.%s, x)\n", f.Name, f.Name)
					fmt.Print("\t\t}\n")
					fmt.Print("\t}\n")

					// pre convert chcecks
					for _, c := range checks {
						switch c {
						case "nempty":
							fmt.Printf("\tif len(res.%s) == 0 {\n\t\treturn %s{}, \"%s_empty\"\n\t}\n", f.Name, st.Name, pname)
						}
					}

				} else {

				}

				if !ok {
					log.Fatalln("no prefix for map[string]string field", f.Name, "in struct", st.Name)
				}

			} else {

				if !strings.HasPrefix(f.Type, "[]") {
					fmt.Printf("\tparam%s := request.Form.Get(\"%s\")\n", f.Name, pname)
				} else {
					// todo: other [] types
					if f.Type == "[]string" {
						fmt.Printf("\tparam%s, ok%s := request.Form.[\"%s\"]\n", f.Name, f.Name, pname)
					}
				}

				// pre convert chcecks
				for _, c := range checks {
					switch c {
					case "nempty":
						fmt.Printf("\tif \"\" == param%s {\n\t\treturn %s{}, \"%s_empty\"\n\t}\n", f.Name, st.Name, pname)
					case "sphinx":
						fmt.Printf("\tif !sphinxCheckString(param%s) {\n\t\treturn %s{}, \"%s_invalid\"\n\t}\n", f.Name, st.Name, pname)
					}
				}

				if tagLen, ok := f.TagParams["len"]; ok {
					fmt.Printf("\tif %s != len(param%s) {\n\t\treturn %s{}, \"%s_invalid\"\n\t}\n", tagLen, f.Name, st.Name, pname)
				}

				if tagLen, ok := f.TagGt["len"]; ok {
					fmt.Printf("\tif len(param%s) < %d {\n\t\treturn %s{}, \"%s_short\"\n\t}\n", f.Name, tagLen, st.Name, pname)
				}

				if tagLen, ok := f.TagLt["len"]; ok {
					fmt.Printf("\tif len(param%s) > %d {\n\t\treturn %s{}, \"%s_long\"\n\t}\n", f.Name, tagLen, st.Name, pname)
				}

				switch f.Type {
				case "string":
					fmt.Printf("\tres.%s = param%s\n\n", f.Name, f.Name)
				case "[]string":
					fmt.Printf("\tres.%s = param%s\n\n", f.Name, f.Name)
				case "int":
					fmt.Printf("\tres.%s, err = strconv.Atoi(param%s)\n\n", f.Name, f.Name)
				case "int64":
					if !errDefined {
						fmt.Print("\tvar err error\n\n")
						errDefined = true
					}
					fmt.Printf("\tres.%s, err = strconv.ParseInt(param%s, 10, 64)\n\n", f.Name, f.Name)
				case "uint64":
					if !errDefined {
						fmt.Print("\tvar err error\n\n")
						errDefined = true
					}
					fmt.Printf("\tres.%s, err = strconv.ParseUint(param%s, 10, 64)\n\n", f.Name, f.Name)
				case "float64":
					if !errDefined {
						fmt.Print("\tvar err error\n\n")
						errDefined = true
					}
					fmt.Printf("\tres.%s, err = strconv.ParseFloat(param%s, 64)\n\n", f.Name, f.Name)
				case "bool":
					if !errDefined {
						fmt.Print("\tvar err error\n\n")
						errDefined = true
					}
					fmt.Printf("\tres.%s, err = strconv.ParseBool(param%s)\n\n", f.Name, f.Name)
				}

				// post convert chcecks
				for _, c := range checks {
					switch c {
					case "valid":
						fmt.Printf("\tif nil != err {\n\t\treturn %s{}, \"%s_invalid\"\n\t}\n", st.Name, pname)
					case "nzero":
						fmt.Printf("\tif 0 == res.%s {\n\t\treturn %s{}, \"%s_invalid\"\n\t}\n", f.Name, st.Name, pname)
					}
				}

				if tagVal, ok := f.TagParams["val"]; ok {
					fmt.Printf("\tif %s != res.%s {\n\t\treturn %s{}, \"%s_invalid\"\n\t}\n", tagVal, f.Name, st.Name, pname)
				}

				if tagVal, ok := f.TagGt["val"]; ok {
					fmt.Printf("\tif %d > res.%s {\n\t\treturn %s{}, \"%s_invalid\"\n\t}\n", tagVal, f.Name, st.Name, pname)
				}

				if tagVal, ok := f.TagLt["val"]; ok {
					fmt.Printf("\tif %d < res.%s {\n\t\treturn %s{}, \"%s_invalid\"\n\t}\n", tagVal, f.Name, st.Name, pname)
				}

			}

		}
		if errDefined {
			fmt.Println("\t_ = err")
		}
		fmt.Println("return res, \"\"")
		fmt.Println("}")
	}
}
<|endoftext|>


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

package testonly

import (
	"context"
	"errors"
	"testing"
	"time"

	"github.com/google/trillian/util/clock"
	"github.com/google/trillian/util/election2"
)

// Tests is the full list of available Election tests.
// TODO(pavelkalinnikov): Add tests for unexpected mastership loss.
var Tests = []NamedTest{
	{Name: "RunElectionAwait", Run: runElectionAwait},
	{Name: "RunElectionWithMastership", Run: runElectionWithMastership},
	{Name: "RunElectionResign", Run: runElectionResign},
	{Name: "RunElectionClose", Run: runElectionClose},
	{Name: "RunElectionLoop", Run: runElectionLoop},
}

// NamedTest is a test function paired with its string name.
type NamedTest struct {
	Name string
	Run  func(t *testing.T, f election2.Factory)
}

// checkNotDone ensures that the context is not done for some time.
func checkNotDone(ctx context.Context, t *testing.T) {
	t.Helper()
	if err := clock.SleepContext(ctx, 10*time.Millisecond); err != nil {
		t.Error("unexpected context cancelation")
	}
}

// checkDone ensures that the context is done within the specified duration.
func checkDone(ctx context.Context, t *testing.T, wait time.Duration) {
	t.Helper()
	if wait == 0 {
		select {
		case <-ctx.Done(): // Ok.
		default:
			t.Error("expected context done")
		}
	} else if err := clock.SleepContext(ctx, wait); err == nil {
		t.Errorf("expected context done within %v", wait)
	}
}

// runElectionAwait tests the Await call with different pre-conditions.
func runElectionAwait(t *testing.T, f election2.Factory) {
	awaitErr := errors.New("Await error")
	for _, tc := range []struct {
		desc    string
		block   bool
		cancel  bool
		err     error
		wantErr error
	}{
		{desc: "ok", wantErr: nil},
		{desc: "cancel", block: true, cancel: true, wantErr: context.Canceled},
		{desc: "deadline", block: true, cancel: false, wantErr: context.DeadlineExceeded},
		{desc: "error", err: awaitErr, wantErr: awaitErr},
	} {
		t.Run(tc.desc, func(t *testing.T) {
			ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
			defer cancel()
			e, err := f.NewElection(ctx, tc.desc)
			if err != nil {
				t.Fatalf("NewElection(): %v", err)
			}
			d := NewDecorator(e)
			d.Update(Errs{Await: tc.err})
			d.BlockAwait(tc.block)

			if tc.cancel {
				cancel()
			}
			if got, want := d.Await(ctx), tc.wantErr; got != want {
				t.Errorf("Await(): %v, want %v", got, want)
			}
		})
	}
}

// runElectionWithMastership tests the WithMastership call.
func runElectionWithMastership(t *testing.T, f election2.Factory) {
	ctxErr := errors.New("WithMastership error")
	for _, tc := range []struct {
		desc     string
		beMaster bool
		cancel   bool
		err      error
		wantErr  error
	}{
		{desc: "master", beMaster: true},
		{desc: "master-cancel", beMaster: true, cancel: true},
		{desc: "not-master", beMaster: false},
		{desc: "not-master-cancel", cancel: true},
		{desc: "error", err: ctxErr, wantErr: ctxErr},
	} {
		t.Run(tc.desc, func(t *testing.T) {
			ctx, cancel := context.WithCancel(context.Background())
			defer cancel()
			e, err := f.NewElection(ctx, tc.desc)
			if err != nil {
				t.Fatalf("NewElection(): %v", err)
			}
			d := NewDecorator(e)
			d.Update(Errs{WithMastership: tc.err})
			if tc.beMaster {
				if err := d.Await(ctx); err != nil {
					t.Fatalf("Await(): %v", err)
				}
			}
			mctx, err := d.WithMastership(ctx)
			if want := tc.wantErr; err != want {
				t.Fatalf("WithMastership(): %v, want %v", err, want)
			}
			if err != nil {
				return
			}
			if tc.cancel {
				cancel()
			}
			if tc.beMaster && !tc.cancel {
				checkNotDone(mctx, t)
			} else {
				checkDone(mctx, t, 0)
			}
		})
	}
}

// runElectionResign tests the Resign call.
func runElectionResign(t *testing.T, f election2.Factory) {
	resignErr := errors.New("Resign error")
	for _, tc := range []struct {
		desc     string
		beMaster bool
		err      error
		wantErr  error
	}{
		{desc: "master", beMaster: true, wantErr: nil},
		{desc: "master-error", beMaster: true, err: resignErr, wantErr: resignErr},
		{desc: "not-master", beMaster: false, wantErr: nil},
		{desc: "not-master-error", err: resignErr, wantErr: resignErr},
	} {
		t.Run(tc.desc, func(t *testing.T) {
			ctx := context.Background()
			e, err := f.NewElection(ctx, tc.desc)
			if err != nil {
				t.Fatalf("NewElection(): %v", err)
			}
			d := NewDecorator(e)
			d.Update(Errs{Resign: tc.err})

			if tc.beMaster {
				if err := d.Await(ctx); err != nil {
					t.Fatalf("Await(): %v", err)
				}
			}
			mctx, err := d.WithMastership(ctx)
			if err != nil {
				t.Fatalf("WithMastership(): %v", err)
			}
			if got, want := d.Resign(ctx), tc.wantErr; got != want {
				t.Errorf("Resign(): %v, want %v", got, want)
			}
			if tc.beMaster && tc.wantErr == nil {
				checkDone(mctx, t, 200*time.Millisecond)
			} else if tc.beMaster {
				checkNotDone(mctx, t)
			} else {
				checkDone(mctx, t, 0)
			}
		})
	}
}

// runElectionClose tests the Close call.
func runElectionClose(t *testing.T, f election2.Factory) {
	closeErr := errors.New("Close error")
	for _, tc := range []struct {
		desc     string
		beMaster bool
		cancel   bool
		err      error
		wantErr  error
	}{
		{desc: "master", beMaster: true, wantErr: nil},
		{desc: "master-error", beMaster: true, err: closeErr, wantErr: closeErr},
		{desc: "not-master", beMaster: false, wantErr: nil},
		{desc: "not-master-error", err: closeErr, wantErr: closeErr},
		{desc: "cancel", cancel: true, wantErr: nil},
	} {
		t.Run(tc.desc, func(t *testing.T) {
			ctx := context.Background()
			e, err := f.NewElection(ctx, tc.desc)
			if err != nil {
				t.Fatalf("NewElection(): %v", err)
			}
			d := NewDecorator(e)
			d.Update(Errs{Close: tc.err})

			if tc.beMaster {
				if err := d.Await(ctx); err != nil {
					t.Fatalf("Await(): %v", err)
				}
			}
			mctx, err := d.WithMastership(ctx)
			if err != nil {
				t.Fatalf("WithMastership(): %v", err)
			}

			cctx, cancel := context.WithCancel(ctx)
			defer cancel()
			if tc.cancel {
				cancel()
			}
			if got, want := d.Close(cctx), tc.wantErr; got != want {
				t.Errorf("Close(): %v, want %v", got, want)
			}
			if tc.beMaster && tc.wantErr == nil {
				checkDone(mctx, t, 200*time.Millisecond)
			} else if tc.beMaster {
				checkNotDone(mctx, t)
			} else {
				checkDone(mctx, t, 0)
			}
		})
	}
}

// runElectionLoop runs a typical mastership loop.
func runElectionLoop(t *testing.T, f election2.Factory) {
	ctx := context.Background()
	e, err := f.NewElection(ctx, "testID")
	if err != nil {
		t.Fatalf("NewElection(): %v", err)
	}
	d := NewDecorator(e)

	defer func() {
		if err := d.Close(ctx); err != nil {
			t.Errorf("Close(): %v", err)
		}
	}()

	for i := 0; i < 10; i++ {
		t.Logf("Mastership iteration: %d", i)
		if err := d.Await(ctx); err != nil {
			t.Fatalf("Await(): %v", err)
		}
		mctx, err := d.WithMastership(ctx)
		if err != nil {
			t.Fatalf("WithMastership(): %v", err)
		}
		checkNotDone(mctx, t) // Do some work as master.
		if err := d.Resign(ctx); err != nil {
			t.Errorf("Resign(): %v", err)
		}
		checkDone(mctx, t, 200*time.Millisecond) // The mastership context should close.
	}
}
<commit_msg>election2: Increase timeouts in tests (#1390)<commit_after>// Copyright 2018 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package testonly

import (
	"context"
	"errors"
	"testing"
	"time"

	"github.com/google/trillian/util/clock"
	"github.com/google/trillian/util/election2"
)

// Tests is the full list of available Election tests.
// TODO(pavelkalinnikov): Add tests for unexpected mastership loss.
var Tests = []NamedTest{
	{Name: "RunElectionAwait", Run: runElectionAwait},
	{Name: "RunElectionWithMastership", Run: runElectionWithMastership},
	{Name: "RunElectionResign", Run: runElectionResign},
	{Name: "RunElectionClose", Run: runElectionClose},
	{Name: "RunElectionLoop", Run: runElectionLoop},
}

// NamedTest is a test function paired with its string name.
type NamedTest struct {
	Name string
	Run  func(t *testing.T, f election2.Factory)
}

// checkNotDone ensures that the context is not done for some time.
func checkNotDone(ctx context.Context, t *testing.T) {
	t.Helper()
	if err := clock.SleepContext(ctx, 100*time.Millisecond); err != nil {
		t.Error("unexpected context cancelation")
	}
}

// checkDone ensures that the context is done within the specified duration.
func checkDone(ctx context.Context, t *testing.T, wait time.Duration) {
	t.Helper()
	if wait == 0 {
		select {
		case <-ctx.Done(): // Ok.
		default:
			t.Error("expected context done")
		}
	} else if err := clock.SleepContext(ctx, wait); err == nil {
		t.Errorf("expected context done within %v", wait)
	}
}

// runElectionAwait tests the Await call with different pre-conditions.
func runElectionAwait(t *testing.T, f election2.Factory) {
	awaitErr := errors.New("Await error")
	for _, tc := range []struct {
		desc    string
		block   bool
		cancel  bool
		err     error
		wantErr error
	}{
		{desc: "ok", wantErr: nil},
		{desc: "cancel", block: true, cancel: true, wantErr: context.Canceled},
		{desc: "deadline", block: true, cancel: false, wantErr: context.DeadlineExceeded},
		{desc: "error", err: awaitErr, wantErr: awaitErr},
	} {
		t.Run(tc.desc, func(t *testing.T) {
			ctx, cancel := context.WithCancel(context.Background())
			defer cancel()
			e, err := f.NewElection(ctx, tc.desc)
			if err != nil {
				t.Fatalf("NewElection(): %v", err)
			}
			d := NewDecorator(e)
			d.Update(Errs{Await: tc.err})
			d.BlockAwait(tc.block)

			if tc.cancel {
				cancel()
			} else if tc.block {
				ctx, cancel = context.WithTimeout(ctx, 100*time.Millisecond)
				defer cancel()
			}
			if got, want := d.Await(ctx), tc.wantErr; got != want {
				t.Errorf("Await(): %v, want %v", got, want)
			}
		})
	}
}

// runElectionWithMastership tests the WithMastership call.
func runElectionWithMastership(t *testing.T, f election2.Factory) {
	ctxErr := errors.New("WithMastership error")
	for _, tc := range []struct {
		desc     string
		beMaster bool
		cancel   bool
		err      error
		wantErr  error
	}{
		{desc: "master", beMaster: true},
		{desc: "master-cancel", beMaster: true, cancel: true},
		{desc: "not-master", beMaster: false},
		{desc: "not-master-cancel", cancel: true},
		{desc: "error", err: ctxErr, wantErr: ctxErr},
	} {
		t.Run(tc.desc, func(t *testing.T) {
			ctx, cancel := context.WithCancel(context.Background())
			defer cancel()
			e, err := f.NewElection(ctx, tc.desc)
			if err != nil {
				t.Fatalf("NewElection(): %v", err)
			}
			d := NewDecorator(e)
			d.Update(Errs{WithMastership: tc.err})
			if tc.beMaster {
				if err := d.Await(ctx); err != nil {
					t.Fatalf("Await(): %v", err)
				}
			}
			mctx, err := d.WithMastership(ctx)
			if want := tc.wantErr; err != want {
				t.Fatalf("WithMastership(): %v, want %v", err, want)
			}
			if err != nil {
				return
			}
			if tc.cancel {
				cancel()
			}
			if tc.beMaster && !tc.cancel {
				checkNotDone(mctx, t)
			} else {
				checkDone(mctx, t, 0)
			}
		})
	}
}

// runElectionResign tests the Resign call.
func runElectionResign(t *testing.T, f election2.Factory) {
	resignErr := errors.New("Resign error")
	for _, tc := range []struct {
		desc     string
		beMaster bool
		err      error
		wantErr  error
	}{
		{desc: "master", beMaster: true, wantErr: nil},
		{desc: "master-error", beMaster: true, err: resignErr, wantErr: resignErr},
		{desc: "not-master", beMaster: false, wantErr: nil},
		{desc: "not-master-error", err: resignErr, wantErr: resignErr},
	} {
		t.Run(tc.desc, func(t *testing.T) {
			ctx := context.Background()
			e, err := f.NewElection(ctx, tc.desc)
			if err != nil {
				t.Fatalf("NewElection(): %v", err)
			}
			d := NewDecorator(e)
			d.Update(Errs{Resign: tc.err})

			if tc.beMaster {
				if err := d.Await(ctx); err != nil {
					t.Fatalf("Await(): %v", err)
				}
			}
			mctx, err := d.WithMastership(ctx)
			if err != nil {
				t.Fatalf("WithMastership(): %v", err)
			}
			if got, want := d.Resign(ctx), tc.wantErr; got != want {
				t.Errorf("Resign(): %v, want %v", got, want)
			}
			if tc.beMaster && tc.wantErr == nil {
				checkDone(mctx, t, 1*time.Second)
			} else if tc.beMaster {
				checkNotDone(mctx, t)
			} else {
				checkDone(mctx, t, 0)
			}
		})
	}
}

// runElectionClose tests the Close call.
func runElectionClose(t *testing.T, f election2.Factory) {
	closeErr := errors.New("Close error")
	for _, tc := range []struct {
		desc     string
		beMaster bool
		cancel   bool
		err      error
		wantErr  error
	}{
		{desc: "master", beMaster: true, wantErr: nil},
		{desc: "master-error", beMaster: true, err: closeErr, wantErr: closeErr},
		{desc: "not-master", beMaster: false, wantErr: nil},
		{desc: "not-master-error", err: closeErr, wantErr: closeErr},
		{desc: "cancel", cancel: true, wantErr: nil},
	} {
		t.Run(tc.desc, func(t *testing.T) {
			ctx := context.Background()
			e, err := f.NewElection(ctx, tc.desc)
			if err != nil {
				t.Fatalf("NewElection(): %v", err)
			}
			d := NewDecorator(e)
			d.Update(Errs{Close: tc.err})

			if tc.beMaster {
				if err := d.Await(ctx); err != nil {
					t.Fatalf("Await(): %v", err)
				}
			}
			mctx, err := d.WithMastership(ctx)
			if err != nil {
				t.Fatalf("WithMastership(): %v", err)
			}

			cctx, cancel := context.WithCancel(ctx)
			defer cancel()
			if tc.cancel {
				cancel()
			}
			if got, want := d.Close(cctx), tc.wantErr; got != want {
				t.Errorf("Close(): %v, want %v", got, want)
			}
			if tc.beMaster && tc.wantErr == nil {
				checkDone(mctx, t, 1*time.Second)
			} else if tc.beMaster {
				checkNotDone(mctx, t)
			} else {
				checkDone(mctx, t, 0)
			}
		})
	}
}

// runElectionLoop runs a typical mastership loop.
func runElectionLoop(t *testing.T, f election2.Factory) {
	ctx := context.Background()
	e, err := f.NewElection(ctx, "testID")
	if err != nil {
		t.Fatalf("NewElection(): %v", err)
	}
	d := NewDecorator(e)

	defer func() {
		if err := d.Close(ctx); err != nil {
			t.Errorf("Close(): %v", err)
		}
	}()

	for i := 0; i < 10; i++ {
		t.Logf("Mastership iteration: %d", i)
		if err := d.Await(ctx); err != nil {
			t.Fatalf("Await(): %v", err)
		}
		mctx, err := d.WithMastership(ctx)
		if err != nil {
			t.Fatalf("WithMastership(): %v", err)
		}
		checkNotDone(mctx, t) // Do some work as master.
		if err := d.Resign(ctx); err != nil {
			t.Errorf("Resign(): %v", err)
		}
		checkDone(mctx, t, 1*time.Second) // The mastership context should close.
	}
}
<|endoftext|>


<commit_before>// Copyright 2012 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.

// +build !windows

package cgotest

/*
#include <dlfcn.h>
#cgo linux LDFLAGS: -ldl
*/
import "C"

import (
	"fmt"
	"testing"
)

//export IMPIsOpaque
func IMPIsOpaque() {
	fmt.Println("isOpaque")
}

//export IMPInitWithFrame
func IMPInitWithFrame() {
	fmt.Println("IInitWithFrame")
}

//export IMPDrawRect
func IMPDrawRect() {
	fmt.Println("drawRect:")
}

//export IMPWindowResize
func IMPWindowResize() {
	fmt.Println("windowDidResize:")
}

func test4029(t *testing.T) {
	loadThySelf(t, "IMPWindowResize")
	loadThySelf(t, "IMPDrawRect")
	loadThySelf(t, "IMPInitWithFrame")
	loadThySelf(t, "IMPIsOpaque")
}

func loadThySelf(t *testing.T, symbol string) {
	this_process := C.dlopen(nil, C.RTLD_NOW)
	if this_process == nil {
		t.Fatal("dlopen:", C.GoString(C.dlerror()))
	}
	defer C.dlclose(this_process)

	symbol_address := C.dlsym(this_process, C.CString(symbol))
	if symbol_address == nil {
		t.Fatal("dlsym:", C.GoString(C.dlerror()))
	} else {
		t.Log(symbol, symbol_address)
	}
}
<commit_msg>misc/cgo/test: do not stop on first error<commit_after>// Copyright 2012 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.

// +build !windows

package cgotest

/*
#include <dlfcn.h>
#cgo linux LDFLAGS: -ldl
*/
import "C"

import (
	"fmt"
	"testing"
)

//export IMPIsOpaque
func IMPIsOpaque() {
	fmt.Println("isOpaque")
}

//export IMPInitWithFrame
func IMPInitWithFrame() {
	fmt.Println("IInitWithFrame")
}

//export IMPDrawRect
func IMPDrawRect() {
	fmt.Println("drawRect:")
}

//export IMPWindowResize
func IMPWindowResize() {
	fmt.Println("windowDidResize:")
}

func test4029(t *testing.T) {
	loadThySelf(t, "IMPWindowResize")
	loadThySelf(t, "IMPDrawRect")
	loadThySelf(t, "IMPInitWithFrame")
	loadThySelf(t, "IMPIsOpaque")
}

func loadThySelf(t *testing.T, symbol string) {
	this_process := C.dlopen(nil, C.RTLD_NOW)
	if this_process == nil {
		t.Error("dlopen:", C.GoString(C.dlerror()))
		return
	}
	defer C.dlclose(this_process)

	symbol_address := C.dlsym(this_process, C.CString(symbol))
	if symbol_address == nil {
		t.Error("dlsym:", C.GoString(C.dlerror()))
		return
	}
	t.Log(symbol, symbol_address)
}
<|endoftext|>


<commit_before>package testdata

func    fmt     () {
	// test
	// test line
	// test line
	// test line
	// test line
	// test line
	// test line
	// test line

println(
		"hello, gofmt test"    )
//comment
}

type s struct{ A int }

func (s s) String() { return "s" }
<commit_msg>Revert "Apply suggestions from code review
"<commit_after>package testdata

func    fmt     () {
	// test
	// test line
	// test line
	// test line
	// test line
	// test line
	// test line
	// test line

println(
		"hello, gofmt test"    )
//comment
}

type s struct { A int }
func (s s) String() { return "s" }
<|endoftext|>


<commit_before>// Copyright 2017 Google Inc.
//
// 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 battery provides a battery status i3bar module.
package battery

import (
	"bufio"
	"fmt"
	"math"
	"strconv"
	"strings"
	"time"

	"github.com/spf13/afero"

	"github.com/soumya92/barista/bar"
	"github.com/soumya92/barista/base"
	"github.com/soumya92/barista/outputs"
)

// Info represents the current battery information.
type Info struct {
	// Capacity in *percents*, from 0 to 100.
	Capacity int
	// Energy when the battery is full, in Wh.
	EnergyFull float64
	// Max Energy the battery can store, in Wh.
	EnergyMax float64
	// Energy currently stored in the battery, in Wh.
	EnergyNow float64
	// Power currently being drawn from the battery, in W.
	Power float64
	// Current voltage of the batter, in V.
	Voltage float64
	// Status of the battery, e.g. "Charging", "Full", "Disconnected".
	Status string
	// Technology of the battery, e.g. "Li-Ion", "Li-Poly", "Ni-MH".
	Technology string
}

// Remaining returns the fraction of battery capacity remaining.
func (i Info) Remaining() float64 {
	if math.Nextafter(i.EnergyFull, 0) == 0 {
		return 0
	}
	return float64(i.EnergyNow) / float64(i.EnergyFull)
}

// RemainingPct returns the percentage of battery capacity remaining.
func (i Info) RemainingPct() int {
	return int(i.Remaining() * 100)
}

// RemainingTime returns the best guess for remaining time.
// This is based on the current power draw and remaining capacity.
// TODO: Moving average?
func (i Info) RemainingTime() time.Duration {
	// Battery does not report current draw,
	// cannot estimate remaining time.
	if math.Nextafter(i.Power, 0) == 0 {
		return time.Duration(0)
	}
	// ACPI spec says this must be in hours.
	hours := float64(i.EnergyNow) / float64(i.Power)
	return time.Duration(int(hours*3600)) * time.Second
}

// PluggedIn returns true if the laptop is plugged in.
func (i Info) PluggedIn() bool {
	return i.Status == "Charging" || i.Status == "Full"
}

// Module represents a battery bar module. It supports setting the output
// format, click handler, update frequency, and urgency/colour functions.
type Module interface {
	base.WithClickHandler

	// RefreshInterval configures the polling frequency for battery info.
	RefreshInterval(time.Duration) Module

	// OutputFunc configures a module to display the output of a user-defined function.
	OutputFunc(func(Info) bar.Output) Module

	// OutputTemplate configures a module to display the output of a template.
	OutputTemplate(func(interface{}) bar.Output) Module

	// OutputColor configures a module to change the colour of its output based on a
	// user-defined function. This allows you to set up color thresholds, or even
	// blend between two colours based on the current battery state.
	OutputColor(func(Info) bar.Color) Module

	// UrgentWhen configures a module to mark its output as urgent based on a
	// user-defined function.
	UrgentWhen(func(Info) bool) Module
}

type module struct {
	*base.Base
	batteryName string
	outputFunc  func(Info) bar.Output
	colorFunc   func(Info) bar.Color
	urgentFunc  func(Info) bool
}

// New constructs an instance of the battery module for the given battery name.
func New(name string) Module {
	m := &module{
		Base:        base.New(),
		batteryName: name,
	}
	// Default is to refresh every 3s, matching the behaviour of top.
	m.RefreshInterval(3 * time.Second)
	// Construct a simple template that's just the available battery percent.
	m.OutputTemplate(outputs.TextTemplate(`BATT {{.RemainingPct}}%`))
	// Update battery stats whenever an update is requested.
	m.OnUpdate(m.update)
	return m
}

// Default constructs an instance of the battery module with BAT0.
func Default() Module {
	return New("BAT0")
}

func (m *module) OutputFunc(outputFunc func(Info) bar.Output) Module {
	m.Lock()
	m.outputFunc = outputFunc
	m.Unlock()
	m.Update()
	return m
}

func (m *module) OutputTemplate(template func(interface{}) bar.Output) Module {
	return m.OutputFunc(func(i Info) bar.Output {
		return template(i)
	})
}

func (m *module) RefreshInterval(interval time.Duration) Module {
	m.Schedule().Every(interval)
	return m
}

func (m *module) OutputColor(colorFunc func(Info) bar.Color) Module {
	m.Lock()
	m.colorFunc = colorFunc
	m.Unlock()
	m.Update()
	return m
}

func (m *module) UrgentWhen(urgentFunc func(Info) bool) Module {
	m.Lock()
	m.urgentFunc = urgentFunc
	m.Unlock()
	m.Update()
	return m
}

func (m *module) update() {
	info := batteryInfo(m.batteryName)
	m.Lock()
	out := m.outputFunc(info)
	if m.urgentFunc != nil {
		out.Urgent(m.urgentFunc(info))
	}
	if m.colorFunc != nil {
		out.Color(m.colorFunc(info))
	}
	m.Unlock()
	m.Output(out)
}

// electricValue represents a value that is either watts or amperes.
// ACPI permits several of the properties to be in either unit, so to
// simplify reading such values, this type can represent either unit
// and convert as needed.
type electricValue struct {
	value   float64
	isWatts bool
}

func (e electricValue) toWatts(voltage float64) float64 {
	if e.isWatts {
		return e.value
	}
	return e.value * voltage
}

// uwatts constructs an electricValue from a string in micro-watts.
func uwatts(value string) electricValue {
	return electricValue{fromMicroStr(value), true}
}

// uamps constructs an electricValue from a string in micro-amps.
func uamps(value string) electricValue {
	return electricValue{fromMicroStr(value), false}
}

func fromMicroStr(str string) float64 {
	uValue, _ := strconv.Atoi(str)
	return float64(uValue) / math.Pow(10, 6 /* micros */)
}

var fs = afero.NewOsFs()

func batteryPath(name string) string {
	return fmt.Sprintf("/sys/class/power_supply/%s/uevent", name)
}

func batteryInfo(name string) Info {
	f, err := fs.Open(batteryPath(name))
	if err != nil {
		return Info{Status: "Disconnected"}
	}
	defer f.Close()
	s := bufio.NewScanner(f)
	s.Split(bufio.ScanLines)

	info := Info{Status: "Unknown"}
	var energyNow, powerNow, energyFull, energyMax electricValue
	for s.Scan() {
		line := strings.TrimSpace(s.Text())
		if !strings.Contains(line, "=") {
			continue
		}
		split := strings.Split(line, "=")
		if len(split) != 2 {
			continue
		}
		key := strings.TrimPrefix(split[0], "POWER_SUPPLY_")
		value := split[1]
		switch key {
		case "CHARGE_NOW":
			energyNow = uamps(value)
		case "ENERGY_NOW":
			energyNow = uwatts(value)
		case "CHARGE_FULL":
			energyFull = uamps(value)
		case "ENERGY_FULL":
			energyFull = uwatts(value)
		case "CHARGE_FULL_DESIGN":
			energyMax = uamps(value)
		case "ENERGY_FULL_DESIGN":
			energyMax = uwatts(value)
		case "CURRENT_NOW":
			powerNow = uamps(value)
		case "POWER_NOW":
			powerNow = uwatts(value)
		case "VOLTAGE_NOW":
			info.Voltage = fromMicroStr(value)
		case "STATUS":
			info.Status = value
		case "TECHNOLOGY":
			info.Technology = value
		case "CAPACITY":
			info.Capacity, _ = strconv.Atoi(value)
		}
	}
	info.EnergyNow = energyNow.toWatts(info.Voltage)
	info.EnergyMax = energyMax.toWatts(info.Voltage)
	info.EnergyFull = energyFull.toWatts(info.Voltage)
	info.Power = powerNow.toWatts(info.Voltage)
	return info
}
<commit_msg>Remove redundant float conversions in battery<commit_after>// Copyright 2017 Google Inc.
//
// 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 battery provides a battery status i3bar module.
package battery

import (
	"bufio"
	"fmt"
	"math"
	"strconv"
	"strings"
	"time"

	"github.com/spf13/afero"

	"github.com/soumya92/barista/bar"
	"github.com/soumya92/barista/base"
	"github.com/soumya92/barista/outputs"
)

// Info represents the current battery information.
type Info struct {
	// Capacity in *percents*, from 0 to 100.
	Capacity int
	// Energy when the battery is full, in Wh.
	EnergyFull float64
	// Max Energy the battery can store, in Wh.
	EnergyMax float64
	// Energy currently stored in the battery, in Wh.
	EnergyNow float64
	// Power currently being drawn from the battery, in W.
	Power float64
	// Current voltage of the batter, in V.
	Voltage float64
	// Status of the battery, e.g. "Charging", "Full", "Disconnected".
	Status string
	// Technology of the battery, e.g. "Li-Ion", "Li-Poly", "Ni-MH".
	Technology string
}

// Remaining returns the fraction of battery capacity remaining.
func (i Info) Remaining() float64 {
	if math.Nextafter(i.EnergyFull, 0) == 0 {
		return 0
	}
	return i.EnergyNow / i.EnergyFull
}

// RemainingPct returns the percentage of battery capacity remaining.
func (i Info) RemainingPct() int {
	return int(i.Remaining() * 100)
}

// RemainingTime returns the best guess for remaining time.
// This is based on the current power draw and remaining capacity.
// TODO: Moving average?
func (i Info) RemainingTime() time.Duration {
	// Battery does not report current draw,
	// cannot estimate remaining time.
	if math.Nextafter(i.Power, 0) == 0 {
		return time.Duration(0)
	}
	// ACPI spec says this must be in hours.
	hours := i.EnergyNow / i.Power
	return time.Duration(int(hours*3600)) * time.Second
}

// PluggedIn returns true if the laptop is plugged in.
func (i Info) PluggedIn() bool {
	return i.Status == "Charging" || i.Status == "Full"
}

// Module represents a battery bar module. It supports setting the output
// format, click handler, update frequency, and urgency/colour functions.
type Module interface {
	base.WithClickHandler

	// RefreshInterval configures the polling frequency for battery info.
	RefreshInterval(time.Duration) Module

	// OutputFunc configures a module to display the output of a user-defined function.
	OutputFunc(func(Info) bar.Output) Module

	// OutputTemplate configures a module to display the output of a template.
	OutputTemplate(func(interface{}) bar.Output) Module

	// OutputColor configures a module to change the colour of its output based on a
	// user-defined function. This allows you to set up color thresholds, or even
	// blend between two colours based on the current battery state.
	OutputColor(func(Info) bar.Color) Module

	// UrgentWhen configures a module to mark its output as urgent based on a
	// user-defined function.
	UrgentWhen(func(Info) bool) Module
}

type module struct {
	*base.Base
	batteryName string
	outputFunc  func(Info) bar.Output
	colorFunc   func(Info) bar.Color
	urgentFunc  func(Info) bool
}

// New constructs an instance of the battery module for the given battery name.
func New(name string) Module {
	m := &module{
		Base:        base.New(),
		batteryName: name,
	}
	// Default is to refresh every 3s, matching the behaviour of top.
	m.RefreshInterval(3 * time.Second)
	// Construct a simple template that's just the available battery percent.
	m.OutputTemplate(outputs.TextTemplate(`BATT {{.RemainingPct}}%`))
	// Update battery stats whenever an update is requested.
	m.OnUpdate(m.update)
	return m
}

// Default constructs an instance of the battery module with BAT0.
func Default() Module {
	return New("BAT0")
}

func (m *module) OutputFunc(outputFunc func(Info) bar.Output) Module {
	m.Lock()
	m.outputFunc = outputFunc
	m.Unlock()
	m.Update()
	return m
}

func (m *module) OutputTemplate(template func(interface{}) bar.Output) Module {
	return m.OutputFunc(func(i Info) bar.Output {
		return template(i)
	})
}

func (m *module) RefreshInterval(interval time.Duration) Module {
	m.Schedule().Every(interval)
	return m
}

func (m *module) OutputColor(colorFunc func(Info) bar.Color) Module {
	m.Lock()
	m.colorFunc = colorFunc
	m.Unlock()
	m.Update()
	return m
}

func (m *module) UrgentWhen(urgentFunc func(Info) bool) Module {
	m.Lock()
	m.urgentFunc = urgentFunc
	m.Unlock()
	m.Update()
	return m
}

func (m *module) update() {
	info := batteryInfo(m.batteryName)
	m.Lock()
	out := m.outputFunc(info)
	if m.urgentFunc != nil {
		out.Urgent(m.urgentFunc(info))
	}
	if m.colorFunc != nil {
		out.Color(m.colorFunc(info))
	}
	m.Unlock()
	m.Output(out)
}

// electricValue represents a value that is either watts or amperes.
// ACPI permits several of the properties to be in either unit, so to
// simplify reading such values, this type can represent either unit
// and convert as needed.
type electricValue struct {
	value   float64
	isWatts bool
}

func (e electricValue) toWatts(voltage float64) float64 {
	if e.isWatts {
		return e.value
	}
	return e.value * voltage
}

// uwatts constructs an electricValue from a string in micro-watts.
func uwatts(value string) electricValue {
	return electricValue{fromMicroStr(value), true}
}

// uamps constructs an electricValue from a string in micro-amps.
func uamps(value string) electricValue {
	return electricValue{fromMicroStr(value), false}
}

func fromMicroStr(str string) float64 {
	uValue, _ := strconv.Atoi(str)
	return float64(uValue) / math.Pow(10, 6 /* micros */)
}

var fs = afero.NewOsFs()

func batteryPath(name string) string {
	return fmt.Sprintf("/sys/class/power_supply/%s/uevent", name)
}

func batteryInfo(name string) Info {
	f, err := fs.Open(batteryPath(name))
	if err != nil {
		return Info{Status: "Disconnected"}
	}
	defer f.Close()
	s := bufio.NewScanner(f)
	s.Split(bufio.ScanLines)

	info := Info{Status: "Unknown"}
	var energyNow, powerNow, energyFull, energyMax electricValue
	for s.Scan() {
		line := strings.TrimSpace(s.Text())
		if !strings.Contains(line, "=") {
			continue
		}
		split := strings.Split(line, "=")
		if len(split) != 2 {
			continue
		}
		key := strings.TrimPrefix(split[0], "POWER_SUPPLY_")
		value := split[1]
		switch key {
		case "CHARGE_NOW":
			energyNow = uamps(value)
		case "ENERGY_NOW":
			energyNow = uwatts(value)
		case "CHARGE_FULL":
			energyFull = uamps(value)
		case "ENERGY_FULL":
			energyFull = uwatts(value)
		case "CHARGE_FULL_DESIGN":
			energyMax = uamps(value)
		case "ENERGY_FULL_DESIGN":
			energyMax = uwatts(value)
		case "CURRENT_NOW":
			powerNow = uamps(value)
		case "POWER_NOW":
			powerNow = uwatts(value)
		case "VOLTAGE_NOW":
			info.Voltage = fromMicroStr(value)
		case "STATUS":
			info.Status = value
		case "TECHNOLOGY":
			info.Technology = value
		case "CAPACITY":
			info.Capacity, _ = strconv.Atoi(value)
		}
	}
	info.EnergyNow = energyNow.toWatts(info.Voltage)
	info.EnergyMax = energyMax.toWatts(info.Voltage)
	info.EnergyFull = energyFull.toWatts(info.Voltage)
	info.Power = powerNow.toWatts(info.Voltage)
	return info
}
<|endoftext|>


<commit_before>package Serial_Srv

import (
	"RMS_Node/util"
	"fmt"
	"github.com/juju/errors"
	log "github.com/sirupsen/logrus"
	"go.bug.st/serial.v1"
)

var port serial.Port
var ComPortDown_ch chan int
var ctr uint

// Open the first serial port detected at 9600bps N81
var mode = &serial.Mode{
	BaudRate: 115200,
	Parity:   serial.NoParity,
	DataBits: 8,
	StopBits: serial.OneStopBit,
}

func SerialPortDaemon() {
	for port == nil {
		//enum ports
		ports, err := serial.GetPortsList()
		if err != nil {
			log.Fatal(err)
		}
		if len(ports) == 0 {
			log.Fatal("No serial ports found!")
		}
		// Print the list of detected ports
		for _, port := range ports {
			fmt.Printf("Found port: %v\n", port)
		}

		for _, portx := range ports {

			port, err = serial.Open(portx, mode)
			if err != nil {
				log.Fatal(err)
			}
			for {
				echo(port)
				EchoWaiter(port)
			}
		}

		fmt.Println("\nserv end ")
		<-ComPortDown_ch
	}

}

func echo(port serial.Port) {

	send := make([]byte, 32)
	send[0] = 0xaa
	send[1] = 0x55
	send[2] = 0x01
	send[3] = 0x00
	send[4] = 0x00
	send[5] = 0xF0
	send[6] = 0x80
	ret := util.CRC16(send, 7)
	send[7] = byte((ret >> 8) & 0xff)
	send[8] = byte(ret & 0xff)

	n, err := port.Write(send[:9])
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Handshake echo, %d bytes:%x \n", n, send[:9])

}

func EchoWaiter(port serial.Port) { // Read and print the response

	buff := make([]byte, 4096)
	var res []byte
	var cnt int = 0

Out:
	for true {
		for {
			// Reads up to 100 bytes
			n, err := port.Read(buff)

			if err != nil {
				log.Fatal(err)
				break
			}
			if n == 0 {

				log.Println("\nEOF")
				break
			}

			cnt++
			//for _, as := range buff[:n] {
			//	fmt.Printf("%02X ", as)
			//}
			res = append(res, buff[:n]...)
			//fmt.Printf("\r\nrec %d     \r\n", cnt, res)
			if len(res) > 7 {
				err := DeFrame(res)
				if err == nil {
					break Out
				} else if err.Error() =="1" {

				}else {
					fmt.Println(err)
					panic(err)
				}

			}

		}

	}
}

func DeFrame(res []byte) error {
	if res[0] == 0xAA && res[1] == 0x55 && len(res) == int(9+res[4]) {
		ctr++
		fmt.Println("\ngot pack",ctr, res)
		return nil
	}else if res[0] == 0xAA && res[1] == 0x55 && len(res) < int(9+res[4]){
		fmt.Println("\nshort pack",ctr, res)
		return errors.New("1")
	}
	fmt.Println("\nwrong pack", res)
	return errors.New("wrong Frame~!")
}
<commit_msg>daily up<commit_after>package Serial_Srv

import (
	"RMS_Node/util"
	"fmt"
	"github.com/juju/errors"
	log "github.com/sirupsen/logrus"
	"go.bug.st/serial.v1"
)

var port serial.Port
var ComPortDown_ch chan int
var ctr uint

// Open the first serial port detected at 9600bps N81
var mode = &serial.Mode{
	BaudRate: 115200,
	Parity:   serial.NoParity,
	DataBits: 8,
	StopBits: serial.OneStopBit,
}

func SerialPortDaemon() {
	for port == nil {
		//enum ports
		ports, err := serial.GetPortsList()
		if err != nil {
			log.Fatal(err)
		}
		if len(ports) == 0 {
			log.Fatal("No serial ports found!")
		}
		// Print the list of detected ports
		for _, port := range ports {
			fmt.Printf("Found port: %v\n", port)
		}

		for _, portx := range ports {

			port, err = serial.Open(portx, mode)
			if err != nil {
				log.Fatal(err)
			}
			//for {
			go EchoWaiter(port)
				echo(port)
			//}
			SendCMD(port ,[]byte{0xa1,02},[]byte{00,01})
			//EchoWaiter(port)
		}

		fmt.Println("\nserv end ")
		<-ComPortDown_ch
	}

}

func echo(port serial.Port) {

	send := make([]byte, 32)
	send[0] = 0xaa
	send[1] = 0x55
	send[2] = 0x01
	send[3] = 0x00
	send[4] = 0x00
	send[5] = 0xF0
	send[6] = 0x80
	ret := util.CRC16(send, 7)
	send[7] = byte((ret >> 8) & 0xff)
	send[8] = byte(ret & 0xff)

	n, err := port.Write(send[:9])
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Handshake echo, %d bytes:%x \n", n, send[:9])

}

func EchoWaiter(port serial.Port) { // Read and print the response

	buff := make([]byte, 4096)
	var res []byte
	var cnt int = 0

//Out:
	for true {
		for {
			// Reads up to 100 bytes
			n, err := port.Read(buff)

			if err != nil {
				log.Fatal(err)
				break
			}
			if n == 0 {

				log.Println("\nEOF")
				break
			}

			cnt++
			//for _, as := range buff[:n] {
			//	fmt.Printf("%02X ", as)
			//}
			res = append(res, buff[:n]...)
			//fmt.Printf("\r\nrec %d     \r\n", cnt, res)
			if len(res) > 7 {
				err := DeFrame(res)
				if err == nil {
					//break Out
				} else if err.Error() =="1" {

				}else if err.Error() =="2" {
					res=res[int(9+res[4]):]
				}else {
					fmt.Println(err)
					panic(err)
				}

			}

		}

	}
}

func DeFrame(res []byte) error {
	if res[0] == 0xAA && res[1] == 0x55 && len(res) == int(9+res[4]) {
		ctr++
		fmt.Println("\ngot pack",ctr, res)
		return nil
	}else if res[0] == 0xAA && res[1] == 0x55 && len(res) < int(9+res[4]){
		fmt.Println("\nshort pack",ctr, res)
		return errors.New("1")
	}else if  res[0] == 0xAA && res[1] == 0x55 && len(res) > int(9+res[4]) {
		fmt.Println("\nshort pack", ctr, res[:int(9+res[4])])
		return errors.New("2")
	}
	fmt.Println("\nwrong pack", res)
	return errors.New("wrong Frame~!")
}

func SendCMD(port serial.Port,cmd []byte,dat []byte) {

	send := make([]byte, 32)
	send[0] = 0xaa
	send[1] = 0x55
	send[2] = 0x01
	//len 3h 4l
	send[3] = 0x00
	send[4] = byte(len(dat))
	//cmd
	send[5] = cmd[0]
	send[6] = cmd[1]
	var i int=0
	var k byte
	for i,k =range dat {
		send[7+i] = k
	}
	ret := util.CRC16(send, 7+i)
	send[i+8] = byte((ret >> 8) & 0xff)
	send[i+9] = byte(ret & 0xff)

	n, err := port.Write(send[:9+i])
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Handshake echo, %d bytes:%x \n", n, send[:9+i])

}

<|endoftext|>