<commit_before>// Copyright © 2016, The T Authors.

package editor

import (
	"bytes"
	"encoding/json"
	"errors"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"time"

	"github.com/eaburns/T/edit"
	"github.com/gorilla/websocket"
)

var (
	// ErrNotFound indicates that a resource is not found.
	ErrNotFound = errors.New("not found")

	// ErrRange indicates an out-of-range Address.
	ErrRange = errors.New("bad range")
)

func request(url *url.URL, method string, body io.Reader, resp interface{}) error {
	httpReq, err := http.NewRequest(method, url.String(), body)
	if err != nil {
		return err
	}
	httpResp, err := http.DefaultClient.Do(httpReq)
	if err != nil {
		return err
	}
	defer httpResp.Body.Close()
	if httpResp.StatusCode != http.StatusOK {
		return responseError(httpResp)
	}
	if resp == nil {
		return nil
	}
	return json.NewDecoder(httpResp.Body).Decode(resp)
}

// Close does a DELETE.
// The URL is expected to point at either a buffer path or an editor path.
func Close(URL *url.URL) error { return request(URL, http.MethodDelete, nil, nil) }

// BufferList does a GET and returns a list of Buffers from the response body.
// The URL is expected to point at an editor server's buffers list.
func BufferList(URL *url.URL) ([]Buffer, error) {
	var list []Buffer
	if err := request(URL, http.MethodGet, nil, &list); err != nil {
		return nil, err
	}
	return list, nil
}

// NewBuffer does a PUT and returns a Buffer from the response body.
// The URL is expected to point at an editor server's buffers list.
func NewBuffer(URL *url.URL) (Buffer, error) {
	var buf Buffer
	if err := request(URL, http.MethodPut, nil, &buf); err != nil {
		return Buffer{}, err
	}
	return buf, nil
}

// BufferInfo does a GET and returns a Buffer from the response body.
// The URL is expected to point at a buffer path.
func BufferInfo(URL *url.URL) (Buffer, error) {
	var buf Buffer
	if err := request(URL, http.MethodGet, nil, &buf); err != nil {
		return Buffer{}, err
	}
	return buf, nil
}

// A ChangeStream reads changes made to a buffer.
type ChangeStream struct {
	conn *websocket.Conn
}

// Close closes the stream.
// The ChangeStream should not be used after being closed.
func (s *ChangeStream) Close() error {
	dl := time.Now().Add(wsTimeout)
	if err := s.conn.WriteControl(websocket.CloseMessage, nil, dl); err == nil {
		// Make a best-effort attempt to wait for the close response.
		for {
			code, _, err := s.conn.ReadMessage()
			if err != nil || code == websocket.CloseMessage {
				break
			}
		}
	}
	return s.conn.Close()
}

// Next returns the next ChangeList from the stream.
func (s *ChangeStream) Next() (ChangeList, error) {
	var cl ChangeList
	return cl, s.conn.ReadJSON(&cl)
}

// Changes returns a ChangeStream that reads changes made to a buffer.
// The URL is expected to point at the changes file of a buffer.
// Note that the changes file is a websocket, and must use a ws scheme:
// 	ws://host:port/buffer/<ID>/changes
func Changes(URL *url.URL) (*ChangeStream, error) {
	conn, resp, err := websocket.DefaultDialer.Dial(URL.String(), make(http.Header))
	switch {
	case err == websocket.ErrBadHandshake:
		if resp.StatusCode != http.StatusOK {
			return nil, responseError(resp)
		}
		fallthrough
	case err != nil:
		return nil, err
	}
	return &ChangeStream{conn: conn}, nil
}

// NewEditor does a PUT and returns an Editor from the response body.
// The URL is expected to point at a buffer path.
func NewEditor(URL *url.URL) (Editor, error) {
	var ed Editor
	if err := request(URL, http.MethodPut, nil, &ed); err != nil {
		return Editor{}, err
	}
	return ed, nil
}

// EditorInfo does a GET and returns an Editor from the response body.
// The URL is expected to point at an editor path.
func EditorInfo(URL *url.URL) (Editor, error) {
	var ed Editor
	if err := request(URL, http.MethodGet, nil, &ed); err != nil {
		return Editor{}, err
	}
	return ed, nil
}

// Reader returns an io.ReadCloser that reads the text from a given Address.
// If non-nil, the returned io.ReadCloser must be closed by the caller.
// If the Address is non-nil, it is set as the value of the addr URL parameter.
// The URL is expected to point at an editor's text path.
func Reader(URL *url.URL, addr edit.Address) (io.ReadCloser, error) {
	urlCopy := *URL
	if addr != nil {
		vals := make(url.Values)
		vals["addr"] = []string{addr.String()}
		urlCopy.RawQuery += "&" + vals.Encode()
	}

	httpResp, err := http.Get(urlCopy.String())
	if err != nil {
		return nil, err
	}
	if httpResp.StatusCode != http.StatusOK {
		defer httpResp.Body.Close()
		return nil, responseError(httpResp)
	}
	return httpResp.Body, nil
}

// Do POSTs a sequence of edits and returns a list of the EditResults
// from the response body.
// The URL is expected to point at an editor path.
func Do(URL *url.URL, edits ...edit.Edit) ([]EditResult, error) {
	var eds []editRequest
	for _, ed := range edits {
		eds = append(eds, editRequest{ed})
	}
	body := bytes.NewBuffer(nil)
	if err := json.NewEncoder(body).Encode(eds); err != nil {
		return nil, err
	}
	var results []EditResult
	if err := request(URL, http.MethodPost, body, &results); err != nil {
		return nil, err
	}
	return results, nil
}

func responseError(resp *http.Response) error {
	switch resp.StatusCode {
	case http.StatusNotFound:
		return ErrNotFound
	case http.StatusRequestedRangeNotSatisfiable:
		return ErrRange
	default:
		data, _ := ioutil.ReadAll(resp.Body)
		return errors.New(resp.Status + ": " + string(data))
	}
}
<commit_msg>editor: fix data race in ChangeStream close.<commit_after>// Copyright © 2016, The T Authors.

package editor

import (
	"bytes"
	"encoding/json"
	"errors"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"time"

	"github.com/eaburns/T/edit"
	"github.com/gorilla/websocket"
)

var (
	// ErrNotFound indicates that a resource is not found.
	ErrNotFound = errors.New("not found")

	// ErrRange indicates an out-of-range Address.
	ErrRange = errors.New("bad range")
)

func request(url *url.URL, method string, body io.Reader, resp interface{}) error {
	httpReq, err := http.NewRequest(method, url.String(), body)
	if err != nil {
		return err
	}
	httpResp, err := http.DefaultClient.Do(httpReq)
	if err != nil {
		return err
	}
	defer httpResp.Body.Close()
	if httpResp.StatusCode != http.StatusOK {
		return responseError(httpResp)
	}
	if resp == nil {
		return nil
	}
	return json.NewDecoder(httpResp.Body).Decode(resp)
}

// Close does a DELETE.
// The URL is expected to point at either a buffer path or an editor path.
func Close(URL *url.URL) error { return request(URL, http.MethodDelete, nil, nil) }

// BufferList does a GET and returns a list of Buffers from the response body.
// The URL is expected to point at an editor server's buffers list.
func BufferList(URL *url.URL) ([]Buffer, error) {
	var list []Buffer
	if err := request(URL, http.MethodGet, nil, &list); err != nil {
		return nil, err
	}
	return list, nil
}

// NewBuffer does a PUT and returns a Buffer from the response body.
// The URL is expected to point at an editor server's buffers list.
func NewBuffer(URL *url.URL) (Buffer, error) {
	var buf Buffer
	if err := request(URL, http.MethodPut, nil, &buf); err != nil {
		return Buffer{}, err
	}
	return buf, nil
}

// BufferInfo does a GET and returns a Buffer from the response body.
// The URL is expected to point at a buffer path.
func BufferInfo(URL *url.URL) (Buffer, error) {
	var buf Buffer
	if err := request(URL, http.MethodGet, nil, &buf); err != nil {
		return Buffer{}, err
	}
	return buf, nil
}

// A ChangeStream reads changes made to a buffer.
type ChangeStream struct {
	conn *websocket.Conn
}

// Close closes the stream.
// The ChangeStream should not be used after being closed.
func (s *ChangeStream) Close() error {
	dl := time.Now().Add(wsTimeout)
	s.conn.WriteControl(websocket.CloseMessage, nil, dl)
	// TODO(eaburns): Read the close response before dropping the connection.
	return s.conn.Close()
}

// Next returns the next ChangeList from the stream.
func (s *ChangeStream) Next() (ChangeList, error) {
	var cl ChangeList
	return cl, s.conn.ReadJSON(&cl)
}

// Changes returns a ChangeStream that reads changes made to a buffer.
// The URL is expected to point at the changes file of a buffer.
// Note that the changes file is a websocket, and must use a ws scheme:
// 	ws://host:port/buffer/<ID>/changes
func Changes(URL *url.URL) (*ChangeStream, error) {
	conn, resp, err := websocket.DefaultDialer.Dial(URL.String(), make(http.Header))
	switch {
	case err == websocket.ErrBadHandshake:
		if resp.StatusCode != http.StatusOK {
			return nil, responseError(resp)
		}
		fallthrough
	case err != nil:
		return nil, err
	}
	return &ChangeStream{conn: conn}, nil
}

// NewEditor does a PUT and returns an Editor from the response body.
// The URL is expected to point at a buffer path.
func NewEditor(URL *url.URL) (Editor, error) {
	var ed Editor
	if err := request(URL, http.MethodPut, nil, &ed); err != nil {
		return Editor{}, err
	}
	return ed, nil
}

// EditorInfo does a GET and returns an Editor from the response body.
// The URL is expected to point at an editor path.
func EditorInfo(URL *url.URL) (Editor, error) {
	var ed Editor
	if err := request(URL, http.MethodGet, nil, &ed); err != nil {
		return Editor{}, err
	}
	return ed, nil
}

// Reader returns an io.ReadCloser that reads the text from a given Address.
// If non-nil, the returned io.ReadCloser must be closed by the caller.
// If the Address is non-nil, it is set as the value of the addr URL parameter.
// The URL is expected to point at an editor's text path.
func Reader(URL *url.URL, addr edit.Address) (io.ReadCloser, error) {
	urlCopy := *URL
	if addr != nil {
		vals := make(url.Values)
		vals["addr"] = []string{addr.String()}
		urlCopy.RawQuery += "&" + vals.Encode()
	}

	httpResp, err := http.Get(urlCopy.String())
	if err != nil {
		return nil, err
	}
	if httpResp.StatusCode != http.StatusOK {
		defer httpResp.Body.Close()
		return nil, responseError(httpResp)
	}
	return httpResp.Body, nil
}

// Do POSTs a sequence of edits and returns a list of the EditResults
// from the response body.
// The URL is expected to point at an editor path.
func Do(URL *url.URL, edits ...edit.Edit) ([]EditResult, error) {
	var eds []editRequest
	for _, ed := range edits {
		eds = append(eds, editRequest{ed})
	}
	body := bytes.NewBuffer(nil)
	if err := json.NewEncoder(body).Encode(eds); err != nil {
		return nil, err
	}
	var results []EditResult
	if err := request(URL, http.MethodPost, body, &results); err != nil {
		return nil, err
	}
	return results, nil
}

func responseError(resp *http.Response) error {
	switch resp.StatusCode {
	case http.StatusNotFound:
		return ErrNotFound
	case http.StatusRequestedRangeNotSatisfiable:
		return ErrRange
	default:
		data, _ := ioutil.ReadAll(resp.Body)
		return errors.New(resp.Status + ": " + string(data))
	}
}
<|endoftext|>


<commit_before>package editor

import (
	"github.com/elpinal/coco3/editor/register"
	"github.com/elpinal/coco3/screen"
)

type visual struct {
	nvCommon

	start int
}

func newVisual(s streamSet, e *editor) *visual {
	return &visual{
		nvCommon: nvCommon{
			streamSet: s,
			editor:    e,
		},

		start: e.pos,
	}
}

func (v *visual) Mode() mode {
	return modeVisual
}

func (v *visual) Runes() []rune {
	return v.buf
}

func (v *visual) Position() int {
	return v.pos
}

func (v *visual) Message() []rune {
	return []rune("-- VISUAL --")
}

func (v *visual) Highlight() *screen.Hi {
	return &screen.Hi{
		Left:  min(v.start, v.pos),
		Right: constrain(max(v.start, v.pos)+1, 0, len(v.buf)),
	}
}

func (v *visual) Run() (end continuity, next modeChanger, err error) {
	r, _, err := v.in.ReadRune()
	if err != nil {
		return end, next, err
	}
	for ('1' <= r && r <= '9') || (v.count != 0 && r == '0') {
		v.count = v.count*10 + int(r-'0')
		r1, _, err := v.streamSet.in.ReadRune()
		if err != nil {
			return end, next, err
		}
		r = r1
	}
	if v.count == 0 {
		v.count = 1
	}
	cmd, ok := visualCommands[r]
	if !ok {
		return
	}
	if m := cmd(v, r); m != nil {
		next = m
	}
	if v.pos == len(v.buf) {
		v.move(v.pos - 1)
	}
	v.count = 0
	return
}

type visualCommand = func(*visual, rune) modeChanger

var visualCommands = map[rune]visualCommand{
	CharEscape: (*visual).escape,
	CharCtrlC:  (*visual).escape,
	'$':        (*visual).endline,
	'0':        (*visual).beginline,
	'B':        (*visual).wordBack,
	'E':        (*visual).word,
	'F':        (*visual).searchCharacterBackward,
	'U':        (*visual).toUpper,
	'W':        (*visual).word,
	'b':        (*visual).wordBack,
	'c':        (*visual).change,
	'd':        (*visual).delete,
	'e':        (*visual).word,
	'f':        (*visual).searchCharacter,
	'h':        (*visual).left,
	'l':        (*visual).right,
	'r':        (*visual).replace,
	'o':        (*visual).swap,
	'u':        (*visual).toLower,
	'v':        (*visual).escape,
	'w':        (*visual).word,
	'y':        (*visual).yank,
}

func (v *visual) escape(_ rune) modeChanger {
	return norm()
}

func (v *visual) delete(_ rune) modeChanger {
	hi := v.Highlight()
	v.nvCommon.delete(hi.Left, hi.Right)
	return norm()
}

func (v *visual) change(r rune) modeChanger {
	_ = v.delete(r)
	return ins(v.pos == len(v.buf))
}

func (v *visual) swap(_ rune) (_ modeChanger) {
	v.start, v.pos = v.pos, v.start
	return
}

func (v *visual) yank(_ rune) modeChanger {
	hi := v.Highlight()
	v.nvCommon.yank(register.Unnamed, hi.Left, hi.Right)
	v.move(hi.Left)
	return norm()
}

func (v *visual) replace(_ rune) modeChanger {
	r, _, _ := v.in.ReadRune()
	hi := v.Highlight()
	rs := make([]rune, hi.Right-hi.Left)
	for i := range rs {
		rs[i] = r
	}
	v.nvCommon.replace(rs, hi.Left)
	return norm()
}

func (v *visual) toUpper(_ rune) modeChanger {
	hi := v.Highlight()
	v.nvCommon.toUpper(hi.Left, hi.Right)
	return norm()
}

func (v *visual) toLower(_ rune) modeChanger {
	hi := v.Highlight()
	v.nvCommon.toLower(hi.Left, hi.Right)
	return norm()
}

func (v *visual) word(r rune) (_ modeChanger) {
	var f func()
	switch r {
	case 'w':
		f = v.nvCommon.wordForward
	case 'W':
		f = v.nvCommon.wordForwardNonBlank
	case 'e':
		f = v.nvCommon.wordEnd
	case 'E':
		f = v.nvCommon.wordEndNonBlank
	}
	for i := 0; i < v.count; i++ {
		f()
	}
	return
}
<commit_msg>Use '_' instead of 'r'<commit_after>package editor

import (
	"github.com/elpinal/coco3/editor/register"
	"github.com/elpinal/coco3/screen"
)

type visual struct {
	nvCommon

	start int
}

func newVisual(s streamSet, e *editor) *visual {
	return &visual{
		nvCommon: nvCommon{
			streamSet: s,
			editor:    e,
		},

		start: e.pos,
	}
}

func (v *visual) Mode() mode {
	return modeVisual
}

func (v *visual) Runes() []rune {
	return v.buf
}

func (v *visual) Position() int {
	return v.pos
}

func (v *visual) Message() []rune {
	return []rune("-- VISUAL --")
}

func (v *visual) Highlight() *screen.Hi {
	return &screen.Hi{
		Left:  min(v.start, v.pos),
		Right: constrain(max(v.start, v.pos)+1, 0, len(v.buf)),
	}
}

func (v *visual) Run() (end continuity, next modeChanger, err error) {
	r, _, err := v.in.ReadRune()
	if err != nil {
		return end, next, err
	}
	for ('1' <= r && r <= '9') || (v.count != 0 && r == '0') {
		v.count = v.count*10 + int(r-'0')
		r1, _, err := v.streamSet.in.ReadRune()
		if err != nil {
			return end, next, err
		}
		r = r1
	}
	if v.count == 0 {
		v.count = 1
	}
	cmd, ok := visualCommands[r]
	if !ok {
		return
	}
	if m := cmd(v, r); m != nil {
		next = m
	}
	if v.pos == len(v.buf) {
		v.move(v.pos - 1)
	}
	v.count = 0
	return
}

type visualCommand = func(*visual, rune) modeChanger

var visualCommands = map[rune]visualCommand{
	CharEscape: (*visual).escape,
	CharCtrlC:  (*visual).escape,
	'$':        (*visual).endline,
	'0':        (*visual).beginline,
	'B':        (*visual).wordBack,
	'E':        (*visual).word,
	'F':        (*visual).searchCharacterBackward,
	'U':        (*visual).toUpper,
	'W':        (*visual).word,
	'b':        (*visual).wordBack,
	'c':        (*visual).change,
	'd':        (*visual).delete,
	'e':        (*visual).word,
	'f':        (*visual).searchCharacter,
	'h':        (*visual).left,
	'l':        (*visual).right,
	'r':        (*visual).replace,
	'o':        (*visual).swap,
	'u':        (*visual).toLower,
	'v':        (*visual).escape,
	'w':        (*visual).word,
	'y':        (*visual).yank,
}

func (v *visual) escape(_ rune) modeChanger {
	return norm()
}

func (v *visual) delete(_ rune) modeChanger {
	hi := v.Highlight()
	v.nvCommon.delete(hi.Left, hi.Right)
	return norm()
}

func (v *visual) change(_ rune) modeChanger {
	_ = v.delete(0)
	return ins(v.pos == len(v.buf))
}

func (v *visual) swap(_ rune) (_ modeChanger) {
	v.start, v.pos = v.pos, v.start
	return
}

func (v *visual) yank(_ rune) modeChanger {
	hi := v.Highlight()
	v.nvCommon.yank(register.Unnamed, hi.Left, hi.Right)
	v.move(hi.Left)
	return norm()
}

func (v *visual) replace(_ rune) modeChanger {
	r, _, _ := v.in.ReadRune()
	hi := v.Highlight()
	rs := make([]rune, hi.Right-hi.Left)
	for i := range rs {
		rs[i] = r
	}
	v.nvCommon.replace(rs, hi.Left)
	return norm()
}

func (v *visual) toUpper(_ rune) modeChanger {
	hi := v.Highlight()
	v.nvCommon.toUpper(hi.Left, hi.Right)
	return norm()
}

func (v *visual) toLower(_ rune) modeChanger {
	hi := v.Highlight()
	v.nvCommon.toLower(hi.Left, hi.Right)
	return norm()
}

func (v *visual) word(r rune) (_ modeChanger) {
	var f func()
	switch r {
	case 'w':
		f = v.nvCommon.wordForward
	case 'W':
		f = v.nvCommon.wordForwardNonBlank
	case 'e':
		f = v.nvCommon.wordEnd
	case 'E':
		f = v.nvCommon.wordEndNonBlank
	}
	for i := 0; i < v.count; i++ {
		f()
	}
	return
}
<|endoftext|>


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

package goftp

import (
	"fmt"
	"os"
	"path"
	"path/filepath"
	"strings"
	"sync/atomic"
)

// Just for fun, walk an ftp server in parallel. I make no claim that this is
// correct or a good idea.
func ExampleClient_ReadDir_parallelWalk() {
	client, err := Dial("ftp.hq.nasa.gov")
	if err != nil {
		panic(err)
	}

	Walk(client, "", func(dir string, info os.FileInfo, err error) error {
		if err != nil {
			// no permissions is okay, keep walking
			if strings.Contains(err.Error(), "550") {
				return nil
			}
			return err
		}

		fmt.Println(path.Join(dir, info.Name()))

		return nil
	})
}

// Walk a FTP file tree in parallel with prunability and error handling.
// See http://golang.org/pkg/path/filepath/#Walk for interface details.
func Walk(client *Client, root string, walkFn filepath.WalkFunc) (ret error) {
	dirsToCheck := make(chan string, 100)

	var workCount int32 = 1
	dirsToCheck <- root

	for dir := range dirsToCheck {
		go func(dir string) {
			files, err := client.ReadDir(dir)

			if err != nil {
				if err = walkFn(dir, nil, err); err != nil && err != filepath.SkipDir {
					ret = err
					close(dirsToCheck)
					return
				}
			}

			for _, file := range files {
				if err = walkFn(dir, file, nil); err != nil {
					if file.IsDir() && err == filepath.SkipDir {
						continue
					}
					ret = err
					close(dirsToCheck)
					return
				}

				if file.IsDir() {
					atomic.AddInt32(&workCount, 1)
					dirsToCheck <- path.Join(dir, file.Name())
				}
			}

			atomic.AddInt32(&workCount, -1)
			if workCount == 0 {
				close(dirsToCheck)
			}
		}(dir)
	}

	return ret
}
<commit_msg>Update parallel walk example.<commit_after>// Copyright 2015 Muir Manders.  All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package goftp

import (
	"fmt"
	"os"
	"path"
	"path/filepath"
	"sync/atomic"
)

// Just for fun, walk an ftp server in parallel. I make no claim that this is
// correct or a good idea.
func ExampleClient_ReadDir_parallelWalk() {
	client, err := Dial("ftp.hq.nasa.gov")
	if err != nil {
		panic(err)
	}

	Walk(client, "", func(fullPath string, info os.FileInfo, err error) error {
		if err != nil {
			// no permissions is okay, keep walking
			if err.(Error).Code() == 550 {
				return nil
			}
			return err
		}

		fmt.Println(fullPath)

		return nil
	})
}

// Walk a FTP file tree in parallel with prunability and error handling.
// See http://golang.org/pkg/path/filepath/#Walk for interface details.
func Walk(client *Client, root string, walkFn filepath.WalkFunc) (ret error) {
	dirsToCheck := make(chan string, 100)

	var workCount int32 = 1
	dirsToCheck <- root

	for dir := range dirsToCheck {
		go func(dir string) {
			files, err := client.ReadDir(dir)

			if err != nil {
				if err = walkFn(dir, nil, err); err != nil && err != filepath.SkipDir {
					ret = err
					close(dirsToCheck)
					return
				}
			}

			for _, file := range files {
				if err = walkFn(path.Join(dir, file.Name()), file, nil); err != nil {
					if file.IsDir() && err == filepath.SkipDir {
						continue
					}
					ret = err
					close(dirsToCheck)
					return
				}

				if file.IsDir() {
					atomic.AddInt32(&workCount, 1)
					dirsToCheck <- path.Join(dir, file.Name())
				}
			}

			atomic.AddInt32(&workCount, -1)
			if workCount == 0 {
				close(dirsToCheck)
			}
		}(dir)
	}

	return ret
}
<|endoftext|>


<commit_before>package parser

import (
  "fmt"
  "reflect"
  "testing"
)

func TestLexer(t *testing.T) {
  tests := map[string][]tokenInfo{
    "foo": []tokenInfo{
      {"foo", tokIdentifier},
    },
    "(foo)": []tokenInfo{
      {"(", tokOpen},
      {"foo", tokIdentifier},
      {")", tokClose},
    },
    " (  foo ) ": []tokenInfo{
      {"(", tokOpen},
      {"foo", tokIdentifier},
      {")", tokClose},
    },
  }

  for input, expected := range tests {
    l := newLexer(input)

    tokens := []tokenInfo{}
    for t := range l.tokens {
      tokens = append(tokens, t)
    }
    if len(tokens) != len(expected) {
      t.Fatalf("Invalid number of tokens found; expected %v, found %v", expected, tokens)
    }
    for i, token := range tokens {
      if token != expected[i] {
        t.Errorf("Expression %q - expected %v, got %v", input, expected[i], token)
      }
    }
  }
}

func TestParsing(t *testing.T) {
  tests := map[string]bool{
    "foo": true,
    "a(b": false,
    "()": true,
    "(foo)": true,
    "(a b)": true,
    "(a (b c))": true,
    "(a (b c) d (e f))": true,
  }

  for input, valid := range tests {
    l := newLexer(input)
    yyParse(l)

    if valid && len(l.errors) != 0 {
      t.Errorf("Input %q - parsing errors: %v", input, l.errors)
    }

    if !valid && len(l.errors) == 0 {
      t.Errorf("Input %q parsed instead of generating error", input)
    }
  }
}
<commit_msg>Check content of the first level of expressions<commit_after>package parser

import (
  "testing"
)

func TestLexer(t *testing.T) {
  tests := map[string][]tokenInfo{
    "foo": []tokenInfo{
      {"foo", tokIdentifier},
    },
    "(foo)": []tokenInfo{
      {"(", tokOpen},
      {"foo", tokIdentifier},
      {")", tokClose},
    },
    " (  foo ) ": []tokenInfo{
      {"(", tokOpen},
      {"foo", tokIdentifier},
      {")", tokClose},
    },
  }

  for input, expected := range tests {
    l := newLexer(input)

    tokens := []tokenInfo{}
    for t := range l.tokens {
      tokens = append(tokens, t)
    }
    if len(tokens) != len(expected) {
      t.Fatalf("Invalid number of tokens found; expected %v, found %v", expected, tokens)
    }
    for i, token := range tokens {
      if token != expected[i] {
        t.Errorf("Expression %q - expected %v, got %v", input, expected[i], token)
      }
    }
  }
}

func TestParsing(t *testing.T) {
  tests := map[string]int{
    "foo": 1,
    "a(b": -1,
    "()": 0,
    "(foo)": 1,
    "(a b)": 2,
    "(a (b c))": 2,
    "(a (b c) d (e f))": 4,
  }

  for input, count := range tests {
    l := newLexer(input)
    yyParse(l)

    if count < 0 {
      if len(l.errors) == 0 {
        t.Errorf("Input %q parsed instead of generating error", input)
      }
      continue
    }

    if len(l.errors) != 0 {
      t.Errorf("Input %q - parsing errors: %v", input, l.errors)
    }

    if len(l.program.Children()) != count {
      t.Errorf("Input %q - expecting %d children, got %d: %v", input, count, len(l.program.Children()), l.program.Children())
    }
  }
}
<|endoftext|>


<commit_before>package parser

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"testing"
)

import (
	"fmt"
	"github.com/rafecolton/bob/builderfile"
	"github.com/rafecolton/bob/log"
	"os"
	"os/exec"
)

func TestBuilder(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "Parser Specs")
}

var _ = Describe("Parse", func() {

	var (
		subject                 *Parser
		validFile               string
		invalidFile             string
		top                     = os.ExpandEnv("${PWD}")
		expectedCommandSequence = &CommandSequence{
			commands: []exec.Cmd{
				*&exec.Cmd{
					Path: "docker",
					Args: []string{"docker", "build", "-t", "quay.io/modcloth/style-gallery:035c4ea0-d73b-5bde-7d6f-c806b04f2ec3", "--rm", "--no-cache", "."},
				},
				*&exec.Cmd{
					Path: "docker",
					Args: []string{"docker", "tag", "abcdef0123456789", "quay.io/modcloth/style-gallery:<TAG>"},
				},
				*&exec.Cmd{
					Path: "docker",
					Args: []string{"docker", "push", "quay.io/modcloth/style-gallery"},
				},
				*&exec.Cmd{
					Path: "docker",
					Args: []string{"docker", "build", "-t", "quay.io/modcloth/style-gallery:035c4ea0-d73b-5bde-7d6f-c806b04f2ec3", "--rm", "--no-cache", "."},
				},
				*&exec.Cmd{
					Path: "docker",
					Args: []string{"docker", "tag", "abcdef0123456789", "quay.io/modcloth/style-gallery:<TAG>"},
				},
				*&exec.Cmd{
					Path: "docker",
					Args: []string{"docker", "tag", "abcdef0123456789", "quay.io/modcloth/style-gallery:<TAG>"},
				},
				*&exec.Cmd{
					Path: "docker",
					Args: []string{"docker", "tag", "abcdef0123456789", "quay.io/modcloth/style-gallery:<TAG>"},
				},
				*&exec.Cmd{
					Path: "docker",
					Args: []string{"docker", "push", "quay.io/modcloth/style-gallery"},
				},
			},
		}
		expectedInstructionSet = &InstructionSet{
			DockerBuildOpts: []string{"--rm", "--no-cache"},
			DockerTagOpts:   []string{},
			Containers: map[string]builderfile.ContainerSection{
				"base": *&builderfile.ContainerSection{
					Dockerfile: "Dockerfile.base",
					Included:   []string{},
					Excluded: []string{
						"spec",
						"tmp",
					},
					Registry: "quay.io/modcloth",
					Project:  "style-gallery",
					Tags: []string{
						"base",
					},
				},
				"app": *&builderfile.ContainerSection{
					Dockerfile: "Dockerfile",
					Included:   []string{},
					Excluded: []string{
						"spec",
						"tmp",
					},
					Registry: "quay.io/modcloth",
					Project:  "style-gallery",
					Tags: []string{
						"git describe --always",
						"git rev-parse -q --abbrev-ref HEAD",
						"git rev-parse -q HEAD",
					},
				},
			},
		}
		expectedBuilderfile = &builderfile.Builderfile{
			Docker: *&builderfile.Docker{
				BuildOpts: []string{"--rm", "--no-cache"},
				TagOpts:   []string{},
			},
			Containers: map[string]builderfile.ContainerSection{
				"global": *&builderfile.ContainerSection{
					Dockerfile: "",
					Included:   []string{},
					Excluded:   []string{"spec", "tmp"},
					Registry:   "quay.io/modcloth",
					Project:    "style-gallery",
					Tags: []string{
						"git describe --always",
						"git rev-parse -q --abbrev-ref HEAD",
						"git rev-parse -q HEAD",
					},
				},
				"base": *&builderfile.ContainerSection{
					Dockerfile: "Dockerfile.base",
					Included:   []string{},
					Excluded:   []string{},
					Registry:   "",
					Project:    "",
					Tags:       []string{"base"},
				},
				"app": *&builderfile.ContainerSection{
					Dockerfile: "Dockerfile",
					Included:   []string{},
					Excluded:   []string{},
					Registry:   "",
					Project:    "",
					Tags:       nil,
				},
			},
		}
	)

	BeforeEach(func() {
		validFile = fmt.Sprintf("%s/spec/fixtures/Builderfile", top)
		invalidFile = fmt.Sprintf("%s/specs/fixtures/foodoesnotexist", top)
		subject = nil
	})

	Context("with a valid Builderfile", func() {

		It("produces an openable file", func() {
			subject, _ := NewParser(validFile, &log.NullLogger{})
			Expect(subject.IsOpenable()).To(Equal(true))
		})

		It("returns a non empty string and a nil error as raw data", func() {
			subject, _ := NewParser(validFile, &log.NullLogger{})
			raw, err := subject.getRaw()
			Expect(len(raw)).ToNot(Equal(0))
			Expect(err).To(BeNil())
		})

		It("returns a fully parsed Builderfile", func() {
			subject, _ := NewParser(validFile, &log.NullLogger{})
			actual, err := subject.rawToStruct()
			Expect(expectedBuilderfile).To(Equal(actual))
			Expect(err).To(BeNil())
		})

		It("further processes the Builderfile into an InstructionSet", func() {
			subject, _ := NewParser(validFile, &log.NullLogger{})
			actual, err := subject.structToInstructionSet()
			Expect(expectedInstructionSet).To(Equal(actual))
			Expect(err).To(BeNil())
		})

		It("further processes the InstructionSet into an CommandSequence", func() {
			subject, _ := NewParser(validFile, &log.NullLogger{})
			subject.SeedUUIDGenerator()
			actual, err := subject.instructionSetToCommandSequence()
			Expect(expectedCommandSequence).To(Equal(actual))
			Expect(err).To(BeNil())
		})
	})

	Context("with an invalid Builderfile", func() {
		It("returns an empty string and error as raw data", func() {
			subject, _ := NewParser(invalidFile, &log.NullLogger{})
			raw, err := subject.getRaw()
			Expect(raw).To(Equal(""))
			Expect(err).ToNot(BeNil())
		})
	})
})
<commit_msg>Updating parser spec to reflect new tag syntax<commit_after>package parser

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"testing"
)

import (
	"fmt"
	"github.com/rafecolton/bob/builderfile"
	"github.com/rafecolton/bob/log"
	"os"
	"os/exec"
)

func TestBuilder(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "Parser Specs")
}

var _ = Describe("Parse", func() {

	var (
		subject                 *Parser
		validFile               string
		invalidFile             string
		top                     = os.ExpandEnv("${PWD}")
		expectedCommandSequence = &CommandSequence{
			commands: []exec.Cmd{
				*&exec.Cmd{
					Path: "docker",
					Args: []string{"docker", "build", "-t", "quay.io/modcloth/style-gallery:035c4ea0-d73b-5bde-7d6f-c806b04f2ec3", "--rm", "--no-cache", "."},
				},
				*&exec.Cmd{
					Path: "docker",
					Args: []string{"docker", "tag", "abcdef0123456789", "quay.io/modcloth/style-gallery:<TAG>"},
				},
				*&exec.Cmd{
					Path: "docker",
					Args: []string{"docker", "push", "quay.io/modcloth/style-gallery"},
				},
				*&exec.Cmd{
					Path: "docker",
					Args: []string{"docker", "build", "-t", "quay.io/modcloth/style-gallery:035c4ea0-d73b-5bde-7d6f-c806b04f2ec3", "--rm", "--no-cache", "."},
				},
				*&exec.Cmd{
					Path: "docker",
					Args: []string{"docker", "tag", "abcdef0123456789", "quay.io/modcloth/style-gallery:<TAG>"},
				},
				*&exec.Cmd{
					Path: "docker",
					Args: []string{"docker", "tag", "abcdef0123456789", "quay.io/modcloth/style-gallery:<TAG>"},
				},
				*&exec.Cmd{
					Path: "docker",
					Args: []string{"docker", "tag", "abcdef0123456789", "quay.io/modcloth/style-gallery:<TAG>"},
				},
				*&exec.Cmd{
					Path: "docker",
					Args: []string{"docker", "push", "quay.io/modcloth/style-gallery"},
				},
			},
		}
		expectedInstructionSet = &InstructionSet{
			DockerBuildOpts: []string{"--rm", "--no-cache"},
			DockerTagOpts:   []string{},
			Containers: map[string]builderfile.ContainerSection{
				"base": *&builderfile.ContainerSection{
					Dockerfile: "Dockerfile.base",
					Included:   []string{},
					Excluded: []string{
						"spec",
						"tmp",
					},
					Registry: "quay.io/modcloth",
					Project:  "style-gallery",
					Tags: []string{
						"base",
					},
				},
				"app": *&builderfile.ContainerSection{
					Dockerfile: "Dockerfile",
					Included:   []string{},
					Excluded: []string{
						"spec",
						"tmp",
					},
					Registry: "quay.io/modcloth",
					Project:  "style-gallery",
					Tags: []string{
						"git:branch",
						"git:rev",
						"git:short",
					},
				},
			},
		}
		expectedBuilderfile = &builderfile.Builderfile{
			Docker: *&builderfile.Docker{
				BuildOpts: []string{"--rm", "--no-cache"},
				TagOpts:   []string{},
			},
			Containers: map[string]builderfile.ContainerSection{
				"global": *&builderfile.ContainerSection{
					Dockerfile: "",
					Included:   []string{},
					Excluded:   []string{"spec", "tmp"},
					Registry:   "quay.io/modcloth",
					Project:    "style-gallery",
					Tags: []string{
						"git:branch",
						"git:rev",
						"git:short",
					},
				},
				"base": *&builderfile.ContainerSection{
					Dockerfile: "Dockerfile.base",
					Included:   []string{},
					Excluded:   []string{},
					Registry:   "",
					Project:    "",
					Tags:       []string{"base"},
				},
				"app": *&builderfile.ContainerSection{
					Dockerfile: "Dockerfile",
					Included:   []string{},
					Excluded:   []string{},
					Registry:   "",
					Project:    "",
					Tags:       nil,
				},
			},
		}
	)

	BeforeEach(func() {
		validFile = fmt.Sprintf("%s/spec/fixtures/Builderfile", top)
		invalidFile = fmt.Sprintf("%s/specs/fixtures/foodoesnotexist", top)
		subject = nil
	})

	Context("with a valid Builderfile", func() {

		It("produces an openable file", func() {
			subject, _ := NewParser(validFile, &log.NullLogger{})
			Expect(subject.IsOpenable()).To(Equal(true))
		})

		It("returns a non empty string and a nil error as raw data", func() {
			subject, _ := NewParser(validFile, &log.NullLogger{})
			raw, err := subject.getRaw()
			Expect(len(raw)).ToNot(Equal(0))
			Expect(err).To(BeNil())
		})

		It("returns a fully parsed Builderfile", func() {
			subject, _ := NewParser(validFile, &log.NullLogger{})
			actual, err := subject.rawToStruct()
			Expect(expectedBuilderfile).To(Equal(actual))
			Expect(err).To(BeNil())
		})

		It("further processes the Builderfile into an InstructionSet", func() {
			subject, _ := NewParser(validFile, &log.NullLogger{})
			actual, err := subject.structToInstructionSet()
			Expect(expectedInstructionSet).To(Equal(actual))
			Expect(err).To(BeNil())
		})

		It("further processes the InstructionSet into an CommandSequence", func() {
			subject, _ := NewParser(validFile, &log.NullLogger{})
			subject.SeedUUIDGenerator()
			actual, err := subject.instructionSetToCommandSequence()
			Expect(expectedCommandSequence).To(Equal(actual))
			Expect(err).To(BeNil())
		})
	})

	Context("with an invalid Builderfile", func() {
		It("returns an empty string and error as raw data", func() {
			subject, _ := NewParser(invalidFile, &log.NullLogger{})
			raw, err := subject.getRaw()
			Expect(raw).To(Equal(""))
			Expect(err).ToNot(BeNil())
		})
	})
})
<|endoftext|>


<commit_before>// Generated file, do not edit.

package wrapbuiltin

import (
	"reflect"

	"neugram.io/ng/eval/gowrap"

	math "math"
)

var wrap_math = &gowrap.Pkg{
	Exports: map[string]reflect.Value{

		"Abs":             reflect.ValueOf(math.Abs),
		"Acos":            reflect.ValueOf(math.Acos),
		"Acosh":           reflect.ValueOf(math.Acosh),
		"Asin":            reflect.ValueOf(math.Asin),
		"Asinh":           reflect.ValueOf(math.Asinh),
		"Atan":            reflect.ValueOf(math.Atan),
		"Atan2":           reflect.ValueOf(math.Atan2),
		"Atanh":           reflect.ValueOf(math.Atanh),
		"Cbrt":            reflect.ValueOf(math.Cbrt),
		"Ceil":            reflect.ValueOf(math.Ceil),
		"Copysign":        reflect.ValueOf(math.Copysign),
		"Cos":             reflect.ValueOf(math.Cos),
		"Cosh":            reflect.ValueOf(math.Cosh),
		"Dim":             reflect.ValueOf(math.Dim),
		"E":               reflect.ValueOf(math.E),
		"Erf":             reflect.ValueOf(math.Erf),
		"Erfc":            reflect.ValueOf(math.Erfc),
		"Erfcinv":         reflect.ValueOf(math.Erfcinv),
		"Erfinv":          reflect.ValueOf(math.Erfinv),
		"Exp":             reflect.ValueOf(math.Exp),
		"Exp2":            reflect.ValueOf(math.Exp2),
		"Expm1":           reflect.ValueOf(math.Expm1),
		"Float32bits":     reflect.ValueOf(math.Float32bits),
		"Float32frombits": reflect.ValueOf(math.Float32frombits),
		"Float64bits":     reflect.ValueOf(math.Float64bits),
		"Float64frombits": reflect.ValueOf(math.Float64frombits),
		"Floor":           reflect.ValueOf(math.Floor),
		"Frexp":           reflect.ValueOf(math.Frexp),
		"Gamma":           reflect.ValueOf(math.Gamma),
		"Hypot":           reflect.ValueOf(math.Hypot),
		"Ilogb":           reflect.ValueOf(math.Ilogb),
		"Inf":             reflect.ValueOf(math.Inf),
		"IsInf":           reflect.ValueOf(math.IsInf),
		"IsNaN":           reflect.ValueOf(math.IsNaN),
		"J0":              reflect.ValueOf(math.J0),
		"J1":              reflect.ValueOf(math.J1),
		"Jn":              reflect.ValueOf(math.Jn),
		"Ldexp":           reflect.ValueOf(math.Ldexp),
		"Lgamma":          reflect.ValueOf(math.Lgamma),
		"Ln10":            reflect.ValueOf(math.Ln10),
		"Ln2":             reflect.ValueOf(math.Ln2),
		"Log":             reflect.ValueOf(math.Log),
		"Log10":           reflect.ValueOf(math.Log10),
		"Log10E":          reflect.ValueOf(math.Log10E),
		"Log1p":           reflect.ValueOf(math.Log1p),
		"Log2":            reflect.ValueOf(math.Log2),
		"Log2E":           reflect.ValueOf(math.Log2E),
		"Logb":            reflect.ValueOf(math.Logb),
		"Max":             reflect.ValueOf(math.Max),
		"MaxFloat32":      reflect.ValueOf(math.MaxFloat32),
		"MaxFloat64":      reflect.ValueOf(math.MaxFloat64),
		"MaxInt16":        reflect.ValueOf(math.MaxInt16),
		"MaxInt32":        reflect.ValueOf(math.MaxInt32),
		"MaxInt64":        reflect.ValueOf(math.MaxInt64),
		"MaxInt8":         reflect.ValueOf(math.MaxInt8),
		"MaxUint16":       reflect.ValueOf(math.MaxUint16),
		"MaxUint32":       reflect.ValueOf(math.MaxUint32),
		"MaxUint64":       reflect.ValueOf(uint64(math.MaxUint64)),
		"MaxUint8":        reflect.ValueOf(math.MaxUint8),
		"Min":             reflect.ValueOf(math.Min),
		"MinInt16":        reflect.ValueOf(math.MinInt16),
		"MinInt32":        reflect.ValueOf(math.MinInt32),
		"MinInt64":        reflect.ValueOf(math.MinInt64),
		"MinInt8":         reflect.ValueOf(math.MinInt8),
		"Mod":             reflect.ValueOf(math.Mod),
		"Modf":            reflect.ValueOf(math.Modf),
		"NaN":             reflect.ValueOf(math.NaN),
		"Nextafter":       reflect.ValueOf(math.Nextafter),
		"Nextafter32":     reflect.ValueOf(math.Nextafter32),
		"Phi":             reflect.ValueOf(math.Phi),
		"Pi":              reflect.ValueOf(math.Pi),
		"Pow":             reflect.ValueOf(math.Pow),
		"Pow10":           reflect.ValueOf(math.Pow10),
		"Remainder":       reflect.ValueOf(math.Remainder),
		"Round":           reflect.ValueOf(math.Round),
		"Signbit":         reflect.ValueOf(math.Signbit),
		"Sin":             reflect.ValueOf(math.Sin),
		"Sincos":          reflect.ValueOf(math.Sincos),
		"Sinh":            reflect.ValueOf(math.Sinh),
		"SmallestNonzeroFloat32": reflect.ValueOf(math.SmallestNonzeroFloat32),
		"SmallestNonzeroFloat64": reflect.ValueOf(math.SmallestNonzeroFloat64),
		"Sqrt":    reflect.ValueOf(math.Sqrt),
		"Sqrt2":   reflect.ValueOf(math.Sqrt2),
		"SqrtE":   reflect.ValueOf(math.SqrtE),
		"SqrtPhi": reflect.ValueOf(math.SqrtPhi),
		"SqrtPi":  reflect.ValueOf(math.SqrtPi),
		"Tan":     reflect.ValueOf(math.Tan),
		"Tanh":    reflect.ValueOf(math.Tanh),
		"Trunc":   reflect.ValueOf(math.Trunc),
		"Y0":      reflect.ValueOf(math.Y0),
		"Y1":      reflect.ValueOf(math.Y1),
		"Yn":      reflect.ValueOf(math.Yn),
	},
}

func init() {
	gowrap.Pkgs["math"] = wrap_math
}
<commit_msg>evaal/gowrap: build with go1.9<commit_after>// Generated file, do not edit.

package wrapbuiltin

import (
	"reflect"

	"neugram.io/ng/eval/gowrap"

	math "math"
)

var wrap_math = &gowrap.Pkg{
	Exports: map[string]reflect.Value{

		"Abs":             reflect.ValueOf(math.Abs),
		"Acos":            reflect.ValueOf(math.Acos),
		"Acosh":           reflect.ValueOf(math.Acosh),
		"Asin":            reflect.ValueOf(math.Asin),
		"Asinh":           reflect.ValueOf(math.Asinh),
		"Atan":            reflect.ValueOf(math.Atan),
		"Atan2":           reflect.ValueOf(math.Atan2),
		"Atanh":           reflect.ValueOf(math.Atanh),
		"Cbrt":            reflect.ValueOf(math.Cbrt),
		"Ceil":            reflect.ValueOf(math.Ceil),
		"Copysign":        reflect.ValueOf(math.Copysign),
		"Cos":             reflect.ValueOf(math.Cos),
		"Cosh":            reflect.ValueOf(math.Cosh),
		"Dim":             reflect.ValueOf(math.Dim),
		"E":               reflect.ValueOf(math.E),
		"Erf":             reflect.ValueOf(math.Erf),
		"Erfc":            reflect.ValueOf(math.Erfc),
		"Exp":             reflect.ValueOf(math.Exp),
		"Exp2":            reflect.ValueOf(math.Exp2),
		"Expm1":           reflect.ValueOf(math.Expm1),
		"Float32bits":     reflect.ValueOf(math.Float32bits),
		"Float32frombits": reflect.ValueOf(math.Float32frombits),
		"Float64bits":     reflect.ValueOf(math.Float64bits),
		"Float64frombits": reflect.ValueOf(math.Float64frombits),
		"Floor":           reflect.ValueOf(math.Floor),
		"Frexp":           reflect.ValueOf(math.Frexp),
		"Gamma":           reflect.ValueOf(math.Gamma),
		"Hypot":           reflect.ValueOf(math.Hypot),
		"Ilogb":           reflect.ValueOf(math.Ilogb),
		"Inf":             reflect.ValueOf(math.Inf),
		"IsInf":           reflect.ValueOf(math.IsInf),
		"IsNaN":           reflect.ValueOf(math.IsNaN),
		"J0":              reflect.ValueOf(math.J0),
		"J1":              reflect.ValueOf(math.J1),
		"Jn":              reflect.ValueOf(math.Jn),
		"Ldexp":           reflect.ValueOf(math.Ldexp),
		"Lgamma":          reflect.ValueOf(math.Lgamma),
		"Ln10":            reflect.ValueOf(math.Ln10),
		"Ln2":             reflect.ValueOf(math.Ln2),
		"Log":             reflect.ValueOf(math.Log),
		"Log10":           reflect.ValueOf(math.Log10),
		"Log10E":          reflect.ValueOf(math.Log10E),
		"Log1p":           reflect.ValueOf(math.Log1p),
		"Log2":            reflect.ValueOf(math.Log2),
		"Log2E":           reflect.ValueOf(math.Log2E),
		"Logb":            reflect.ValueOf(math.Logb),
		"Max":             reflect.ValueOf(math.Max),
		"MaxFloat32":      reflect.ValueOf(math.MaxFloat32),
		"MaxFloat64":      reflect.ValueOf(math.MaxFloat64),
		"MaxInt16":        reflect.ValueOf(math.MaxInt16),
		"MaxInt32":        reflect.ValueOf(math.MaxInt32),
		"MaxInt64":        reflect.ValueOf(math.MaxInt64),
		"MaxInt8":         reflect.ValueOf(math.MaxInt8),
		"MaxUint16":       reflect.ValueOf(math.MaxUint16),
		"MaxUint32":       reflect.ValueOf(math.MaxUint32),
		"MaxUint64":       reflect.ValueOf(uint64(math.MaxUint64)),
		"MaxUint8":        reflect.ValueOf(math.MaxUint8),
		"Min":             reflect.ValueOf(math.Min),
		"MinInt16":        reflect.ValueOf(math.MinInt16),
		"MinInt32":        reflect.ValueOf(math.MinInt32),
		"MinInt64":        reflect.ValueOf(math.MinInt64),
		"MinInt8":         reflect.ValueOf(math.MinInt8),
		"Mod":             reflect.ValueOf(math.Mod),
		"Modf":            reflect.ValueOf(math.Modf),
		"NaN":             reflect.ValueOf(math.NaN),
		"Nextafter":       reflect.ValueOf(math.Nextafter),
		"Nextafter32":     reflect.ValueOf(math.Nextafter32),
		"Phi":             reflect.ValueOf(math.Phi),
		"Pi":              reflect.ValueOf(math.Pi),
		"Pow":             reflect.ValueOf(math.Pow),
		"Pow10":           reflect.ValueOf(math.Pow10),
		"Remainder":       reflect.ValueOf(math.Remainder),
		"Signbit":         reflect.ValueOf(math.Signbit),
		"Sin":             reflect.ValueOf(math.Sin),
		"Sincos":          reflect.ValueOf(math.Sincos),
		"Sinh":            reflect.ValueOf(math.Sinh),
		"SmallestNonzeroFloat32": reflect.ValueOf(math.SmallestNonzeroFloat32),
		"SmallestNonzeroFloat64": reflect.ValueOf(math.SmallestNonzeroFloat64),
		"Sqrt":    reflect.ValueOf(math.Sqrt),
		"Sqrt2":   reflect.ValueOf(math.Sqrt2),
		"SqrtE":   reflect.ValueOf(math.SqrtE),
		"SqrtPhi": reflect.ValueOf(math.SqrtPhi),
		"SqrtPi":  reflect.ValueOf(math.SqrtPi),
		"Tan":     reflect.ValueOf(math.Tan),
		"Tanh":    reflect.ValueOf(math.Tanh),
		"Trunc":   reflect.ValueOf(math.Trunc),
		"Y0":      reflect.ValueOf(math.Y0),
		"Y1":      reflect.ValueOf(math.Y1),
		"Yn":      reflect.ValueOf(math.Yn),
	},
}

func init() {
	gowrap.Pkgs["math"] = wrap_math
}
<|endoftext|>


<commit_before>
package main

import (
	"fmt"
	"strings"
	"strconv"
	"errors"
	"encoding/json"
	"github.com/hyperledger/fabric/core/chaincode/shim"
)

// SimpleChaincode example simple Chaincode implementation
type SimpleChaincode struct {
}

type Employee struct {
	Name string `json:"name"`
	EmployeeId int `json:"employeeId"`
	Project string `json:"project"`
}

type Customer struct {
	Name string `json:"name"`
	CustomerId int `json:"customerId"`
}
type Project struct {
	Name string `json:"name"`
	ProjectId int `json:"projectId"`
	CustomerOf string `json:"customerOf"`
	StartTime string `json:"startDate"`
	EndTime string `json:"endDate"`
}

type EmployeeEfforts struct{
	Efforts string
	Project string
}

type ProjectEfforts struct{
	Efforts string
	Employee string
}

type EmployeeInvoice struct{
	List []EmployeeEfforts
}
type ProjectInvoice struct{
	List []ProjectEfforts
}

func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte,error) {
    fmt.Println("Init is running " + function)
    return nil,nil
}

func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte,error) {

    fmt.Println("Invoke is running " + function)

    if function =="initEmployee"{
		return t.initEmployee(stub,args)
	}else if function =="getEmployee"{
		return t.getEmployee(stub,args)
	}else if function =="initCustomer"{
		return t.initCustomer(stub,args)
	}else if function =="getCustomer"{
		return t.getCustomer(stub,args)
	}else if function =="initProject"{
		return t.initProject(stub,args)
	}else if function =="getProject"{
		return t.getProject(stub,args)
	}else if function =="changeProject"{
		return t.changeProject(stub,args)
	}else if function =="submitEfforts"{
		return t.submitEfforts(stub,args)
	}
	return nil,errors.New("Received unknown function invocation")
}

func (t *SimpleChaincode) submitEfforts(stub shim.ChaincodeStubInterface, args []string)([]byte,error){
	if len(args)!=4{
		return nil,errors.New("Incorrect Number of arguments. Expecting 4")
	}
	fmt.Println("- start submitEfforts -")
	employeeId := args[0]
	timestamp := args[1]
	employeeIdAndTimestamp := args[2]
	efforts := args[3]
	employeeJSONasBytes,err := stub.GetState(employeeId)

	if err != nil {
		return nil,err
	}
	var e Employee
	json.Unmarshal(employeeJSONasBytes,&e)

	var ei EmployeeInvoice
	var pi ProjectInvoice

	employeeInvoiceAsBytes,err := stub.GetState(employeeIdAndTimestamp)

	if err != nil{
		return nil,err
	}
	json.Unmarshal(employeeInvoiceAsBytes,&ei)

	var ef EmployeeEfforts
	ef = EmployeeEfforts{efforts,e.Project}
	ei.List = append(ei.List,ef)

	employeeInvoiceAsBytes,err = json.Marshal(ei)
	if err!= nil{
		return nil,err
	}
	err = stub.PutState(employeeIdAndTimestamp,employeeInvoiceAsBytes)
	if err !=nil{
		return nil,err
	}

	var projectIdAndTimestamp string
	projectIdAndTimestamp = e.Project+""+timestamp

	projectInvoiceAsBytes,err := stub.GetState(projectIdAndTimestamp)

	json.Unmarshal(projectInvoiceAsBytes,&pi)

	var pf ProjectEfforts
	pf = ProjectEfforts{efforts,e.EmployeeId}
	pi.List = append(pi.List,pf)

	projectInvoiceAsBytes,err = json.Marshal(pi)

	if err!= nil{
		return nil,err
	}

	err = stub.PutState(projectIdAndTimestamp,projectInvoiceAsBytes)

	if err!= nil{
		return nil,err
	}

	return nil,nil
}
func (t *SimpleChaincode) changeProject(stub shim.ChaincodeStubInterface, args []string)([]byte,error){
	if len(args)!=2 {
		return nil,errors.New("Incorrect Number of arguments. Expecting 2")
	}
	// ==== Input sanitation ====
	fmt.Println("- start changeProject")
	if len(args[0]) <= 0 {
		return nil,errors.New("1st argument must be a non-empty string")
	}
	if len(args[1]) <= 0 {
		return nil,errors.New("2nd argument must be a non-empty string")
	}
	employeeId := args[0]
	project := strings.ToLower(args[1])
	_, err := strconv.Atoi(project)

	if err != nil {
		return nil,errors.New("2nd argument must be a numeric string")
	}
	_, err = strconv.Atoi(employeeId)

	if err != nil {
		return nil,errors.New("1st argument must be a numeric string")
	}

	_, err = stub.GetState(project)
	if err != nil {
		return nil,err
	}

	employee, err := stub.GetState(employeeId)
	if err != nil {
		return nil,err
	}

	var e Employee

	json.Unmarshal(employee,&e)
	e.Project = project
	fmt.Println(e)

	employeeJSONasBytes, err := json.Marshal(e)
	fmt.Println(employeeJSONasBytes)
	if err != nil {
		return nil,err
	}
	err = stub.PutState(employeeId, employeeJSONasBytes)

	if err != nil {
		return nil,err
	}
	return nil,nil
}
func (t *SimpleChaincode) initProject(stub shim.ChaincodeStubInterface, args []string) ([]byte,error){

	if len(args) != 5 {
		return nil,errors.New("Incorrect number of arguments. Expecting 5")
	}
	// ==== Input sanitation ====
	fmt.Println("- start initProject")
	if len(args[0]) <= 0 {
		return nil,errors.New("1st argument must be a non-empty string")
	}
	if len(args[1]) <= 0 {
		return nil,errors.New("2nd argument must be a non-empty string")
	}
	if len(args[2]) <= 0 {
		return nil,errors.New("3rd argument must be a non-empty string")
	}
	if len(args[3]) <= 0 {
		return nil,errors.New("4th argument must be a non-empty string")
	}
	if len(args[4]) <= 0 {
		return nil,errors.New("5th argument must be a non-empty string")
	}

	projectName := args[0]
	customerOf := strings.ToLower(args[2])
	projectId, err := strconv.Atoi(args[1])
	projectIdAsString := args[1]
	startDate:= args[3]
	endDate:= args[4]
	if err != nil {
		return nil,errors.New("2nd argument must be a numeric string")
	}

	projectAsBytes, err := stub.GetState(projectIdAsString)
	if err != nil {
		return nil,err
	} else if projectAsBytes != nil {
		fmt.Println("This project already exists: " + projectIdAsString)
		return nil, errors.New("This project already exists "+projectIdAsString)
	}

	project:= Project{projectName,projectId,customerOf,startDate,endDate}

	projectJSONasBytes, err := json.Marshal(project)

	if err != nil {
		return nil,err
	}
	err = stub.PutState(projectIdAsString, projectJSONasBytes)

	if err != nil {
		return nil,err
	}

	// composite key creation for searching projects according to customer
	/*
	indexName := "customerOf"
	customerOfIndexKey, err := stub.CreateCompositeKey(indexName, []string{customerOf, projectIdAsString})
	if err != nil {
		return nil,err
	}

	value := []byte{0x00}
	stub.PutState(customerOfIndexKey, value)
    */
	fmt.Println("- end initProject")
	return nil,nil
}

func (t *SimpleChaincode) getProject(stub shim.ChaincodeStubInterface, args []string) ([]byte,error){
	if len(args) !=1{
		return nil,errors.New("Incorrect number of arguments. Expecting 1")
	}
	projectId := args[0]
	project, err := stub.GetState(projectId)
	if err != nil {
		return nil,err
	}

	return project,nil
}

func (t *SimpleChaincode) getCustomer(stub shim.ChaincodeStubInterface, args []string) ([]byte,error){
	if len(args) !=1{
		return nil,errors.New("Incorrect number of arguments. Expecting 1")
	}
	customerId := args[0]
	customer, err := stub.GetState(customerId)
	if err != nil {
		return nil,err
	}

	return customer,nil
}

func (t *SimpleChaincode) initCustomer(stub shim.ChaincodeStubInterface,args []string) ([]byte,error) {
		if len(args) != 2{
			return nil,errors.New("Incorrect number of arguments. Expecting 2")
		}
			// ==== Input sanitation ====
		fmt.Println("- start initCustomer")
		if len(args[0]) <= 0 {
			return nil,errors.New("1st argument must be a non-empty string")
		}
		if len(args[1]) <= 0 {
			return nil,errors.New("2nd argument must be a non-empty string")
		}

		customerName := args[0]
		customerId, err := strconv.Atoi(args[1])
		customerIdAsString := args[1]
		if err != nil {
			return nil,errors.New("2nd argument must be a numeric string")
		}
		customerAsBytes, err := stub.GetState(customerIdAsString)
		if err != nil {
			 return nil,err
		} else if customerAsBytes != nil {
			fmt.Println("This customer already exists: " + customerIdAsString)
			return nil,errors.New("This customer already exists: "+customerIdAsString)
		}

		customer:= Customer{customerName,customerId}

		customerJSONasBytes, err := json.Marshal(customer)

		if err != nil {
			return nil,err
		}
		err = stub.PutState(customerIdAsString, customerJSONasBytes)

		if err != nil {
			return nil,err
		}

		fmt.Println("- end initCustomer")
		return nil,nil
}

func (t *SimpleChaincode) initEmployee(stub shim.ChaincodeStubInterface, args []string) ([]byte,error){

	if len(args) != 3 {
		return nil,errors.New("Incorrect number of arguments. Expecting 3")
	}
	// ==== Input sanitation ====
	fmt.Println("- start initEmployee")
	if len(args[0]) <= 0 {
		return nil,errors.New("1st argument must be a non-empty string")
	}
	if len(args[1]) <= 0 {
		return nil,errors.New("2nd argument must be a non-empty string")
	}
	if len(args[2]) <= 0 {
		return nil,errors.New("3rd argument must be a non-empty string")
	}

	employeeName := args[0]
	project := strings.ToLower(args[2])
	employeeId, err := strconv.Atoi(args[1])
	employeeIdAsString := args[1]
	if err != nil {
		return nil,errors.New("2nd argument must be a numeric string")
	}

	employeeAsBytes, err := stub.GetState(employeeIdAsString)
	if err != nil {
		return nil,err
	} else if employeeAsBytes != nil {
		fmt.Println("This employee already exists: " + employeeIdAsString)
		return []byte("duplicate"),errors.New("This employee already exists: "+employeeIdAsString)
	}

	employee:= Employee{employeeName,employeeId,project}
	fmt.Println(employee)
	employeeJSONasBytes, err := json.Marshal(employee)
	fmt.Println(employeeJSONasBytes)
	if err != nil {
		return nil,err
	}
	err = stub.PutState(employeeIdAsString, employeeJSONasBytes)

	if err != nil {
		return nil,err
	}
	employee_temp,_ := stub.GetState(employeeIdAsString)
	fmt.Println(employee_temp)
	// composite key to get employees by project

	/*
	indexName := "project"
	projectIndexKey, err := stub.CreateCompositeKey(indexName, []string{project, employeeIdAsString})
	if err != nil {
		return nil,err
	}

	value := []byte{0x00}
	stub.PutState(projectIndexKey, value)
	*/
	fmt.Println("- end initEmployee")
	return nil,nil
}

func (t *SimpleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte,error) {
    fmt.Println("Query is running " + function)

    if function =="getEmployee"{
		return t.getEmployee(stub,args)
	}else if function =="getCustomer"{
		return t.getCustomer(stub,args)
	}else if function =="getProject"{
		return t.getProject(stub,args)
	}else if function == "getEfforts"{
		return t.getEfforts(stub,args)
	}

	return nil,errors.New("Received unknown function query")
}
func (t *SimpleChaincode) getEfforts(stub shim.ChaincodeStubInterface, args []string) ([]byte,error){
	fmt.Printf("getEfforts called")
	if len(args) !=1{
		return nil,errors.New("Incorrect number of arguments. Expecting 1")
	}
	idAndTimestamp := args[0]
	invoice, err := stub.GetState(idAndTimestamp)
	fmt.Println(invoice)
	if err != nil {
		return nil,err
	}

	return invoice,nil
}
func (t *SimpleChaincode) getEmployee(stub shim.ChaincodeStubInterface, args []string) ([]byte,error){
	fmt.Printf("getEmployee called")
	if len(args) !=1{
		return nil,errors.New("Incorrect number of arguments. Expecting 1")
	}
	employeeId := args[0]
	employee, err := stub.GetState(employeeId)
	fmt.Println(employee)
	if err != nil {
		return nil,err
	}

	return employee,nil
}

func main() {
    	err := shim.Start(new(SimpleChaincode))
    if err != nil {
        fmt.Printf("Error starting Simple chaincode: %s", err)
    }
}
<commit_msg>project employee correction<commit_after>
package main

import (
	"fmt"
	"strings"
	"strconv"
	"errors"
	"encoding/json"
	"github.com/hyperledger/fabric/core/chaincode/shim"
)

// SimpleChaincode example simple Chaincode implementation
type SimpleChaincode struct {
}

type Employee struct {
	Name string `json:"name"`
	EmployeeId int `json:"employeeId"`
	Project string `json:"project"`
}

type Customer struct {
	Name string `json:"name"`
	CustomerId int `json:"customerId"`
}
type Project struct {
	Name string `json:"name"`
	ProjectId int `json:"projectId"`
	CustomerOf string `json:"customerOf"`
	StartTime string `json:"startDate"`
	EndTime string `json:"endDate"`
}

type EmployeeEfforts struct{
	Efforts string
	Project string
}

type ProjectEfforts struct{
	Efforts string
	Employee string
}

type EmployeeInvoice struct{
	List []EmployeeEfforts
}
type ProjectInvoice struct{
	List []ProjectEfforts
}

func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte,error) {
    fmt.Println("Init is running " + function)
    return nil,nil
}

func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte,error) {

    fmt.Println("Invoke is running " + function)

    if function =="initEmployee"{
		return t.initEmployee(stub,args)
	}else if function =="getEmployee"{
		return t.getEmployee(stub,args)
	}else if function =="initCustomer"{
		return t.initCustomer(stub,args)
	}else if function =="getCustomer"{
		return t.getCustomer(stub,args)
	}else if function =="initProject"{
		return t.initProject(stub,args)
	}else if function =="getProject"{
		return t.getProject(stub,args)
	}else if function =="changeProject"{
		return t.changeProject(stub,args)
	}else if function =="submitEfforts"{
		return t.submitEfforts(stub,args)
	}
	return nil,errors.New("Received unknown function invocation")
}

func (t *SimpleChaincode) submitEfforts(stub shim.ChaincodeStubInterface, args []string)([]byte,error){
	if len(args)!=4{
		return nil,errors.New("Incorrect Number of arguments. Expecting 4")
	}
	fmt.Println("- start submitEfforts -")
	employeeId := args[0]
	timestamp := args[1]
	employeeIdAndTimestamp := args[2]
	efforts := args[3]
	employeeJSONasBytes,err := stub.GetState(employeeId)

	if err != nil {
		return nil,err
	}
	var e Employee
	json.Unmarshal(employeeJSONasBytes,&e)

	var ei EmployeeInvoice
	var pi ProjectInvoice

	employeeInvoiceAsBytes,err := stub.GetState(employeeIdAndTimestamp)

	if err != nil{
		return nil,err
	}
	json.Unmarshal(employeeInvoiceAsBytes,&ei)

	var ef EmployeeEfforts
	ef = EmployeeEfforts{efforts,e.Project}
	ei.List = append(ei.List,ef)

	employeeInvoiceAsBytes,err = json.Marshal(ei)
	if err!= nil{
		return nil,err
	}
	err = stub.PutState(employeeIdAndTimestamp,employeeInvoiceAsBytes)
	if err !=nil{
		return nil,err
	}

	var projectIdAndTimestamp string
	projectIdAndTimestamp = e.Project+""+timestamp

	projectInvoiceAsBytes,err := stub.GetState(projectIdAndTimestamp)

	json.Unmarshal(projectInvoiceAsBytes,&pi)

	var pf ProjectEfforts
	pf = ProjectEfforts{efforts,employeeId}
	pi.List = append(pi.List,pf)

	projectInvoiceAsBytes,err = json.Marshal(pi)

	if err!= nil{
		return nil,err
	}

	err = stub.PutState(projectIdAndTimestamp,projectInvoiceAsBytes)

	if err!= nil{
		return nil,err
	}

	return nil,nil
}
func (t *SimpleChaincode) changeProject(stub shim.ChaincodeStubInterface, args []string)([]byte,error){
	if len(args)!=2 {
		return nil,errors.New("Incorrect Number of arguments. Expecting 2")
	}
	// ==== Input sanitation ====
	fmt.Println("- start changeProject")
	if len(args[0]) <= 0 {
		return nil,errors.New("1st argument must be a non-empty string")
	}
	if len(args[1]) <= 0 {
		return nil,errors.New("2nd argument must be a non-empty string")
	}
	employeeId := args[0]
	project := strings.ToLower(args[1])
	_, err := strconv.Atoi(project)

	if err != nil {
		return nil,errors.New("2nd argument must be a numeric string")
	}
	_, err = strconv.Atoi(employeeId)

	if err != nil {
		return nil,errors.New("1st argument must be a numeric string")
	}

	_, err = stub.GetState(project)
	if err != nil {
		return nil,err
	}

	employee, err := stub.GetState(employeeId)
	if err != nil {
		return nil,err
	}

	var e Employee

	json.Unmarshal(employee,&e)
	e.Project = project
	fmt.Println(e)

	employeeJSONasBytes, err := json.Marshal(e)
	fmt.Println(employeeJSONasBytes)
	if err != nil {
		return nil,err
	}
	err = stub.PutState(employeeId, employeeJSONasBytes)

	if err != nil {
		return nil,err
	}
	return nil,nil
}
func (t *SimpleChaincode) initProject(stub shim.ChaincodeStubInterface, args []string) ([]byte,error){

	if len(args) != 5 {
		return nil,errors.New("Incorrect number of arguments. Expecting 5")
	}
	// ==== Input sanitation ====
	fmt.Println("- start initProject")
	if len(args[0]) <= 0 {
		return nil,errors.New("1st argument must be a non-empty string")
	}
	if len(args[1]) <= 0 {
		return nil,errors.New("2nd argument must be a non-empty string")
	}
	if len(args[2]) <= 0 {
		return nil,errors.New("3rd argument must be a non-empty string")
	}
	if len(args[3]) <= 0 {
		return nil,errors.New("4th argument must be a non-empty string")
	}
	if len(args[4]) <= 0 {
		return nil,errors.New("5th argument must be a non-empty string")
	}

	projectName := args[0]
	customerOf := strings.ToLower(args[2])
	projectId, err := strconv.Atoi(args[1])
	projectIdAsString := args[1]
	startDate:= args[3]
	endDate:= args[4]
	if err != nil {
		return nil,errors.New("2nd argument must be a numeric string")
	}

	projectAsBytes, err := stub.GetState(projectIdAsString)
	if err != nil {
		return nil,err
	} else if projectAsBytes != nil {
		fmt.Println("This project already exists: " + projectIdAsString)
		return nil, errors.New("This project already exists "+projectIdAsString)
	}

	project:= Project{projectName,projectId,customerOf,startDate,endDate}

	projectJSONasBytes, err := json.Marshal(project)

	if err != nil {
		return nil,err
	}
	err = stub.PutState(projectIdAsString, projectJSONasBytes)

	if err != nil {
		return nil,err
	}

	// composite key creation for searching projects according to customer
	/*
	indexName := "customerOf"
	customerOfIndexKey, err := stub.CreateCompositeKey(indexName, []string{customerOf, projectIdAsString})
	if err != nil {
		return nil,err
	}

	value := []byte{0x00}
	stub.PutState(customerOfIndexKey, value)
    */
	fmt.Println("- end initProject")
	return nil,nil
}

func (t *SimpleChaincode) getProject(stub shim.ChaincodeStubInterface, args []string) ([]byte,error){
	if len(args) !=1{
		return nil,errors.New("Incorrect number of arguments. Expecting 1")
	}
	projectId := args[0]
	project, err := stub.GetState(projectId)
	if err != nil {
		return nil,err
	}

	return project,nil
}

func (t *SimpleChaincode) getCustomer(stub shim.ChaincodeStubInterface, args []string) ([]byte,error){
	if len(args) !=1{
		return nil,errors.New("Incorrect number of arguments. Expecting 1")
	}
	customerId := args[0]
	customer, err := stub.GetState(customerId)
	if err != nil {
		return nil,err
	}

	return customer,nil
}

func (t *SimpleChaincode) initCustomer(stub shim.ChaincodeStubInterface,args []string) ([]byte,error) {
		if len(args) != 2{
			return nil,errors.New("Incorrect number of arguments. Expecting 2")
		}
			// ==== Input sanitation ====
		fmt.Println("- start initCustomer")
		if len(args[0]) <= 0 {
			return nil,errors.New("1st argument must be a non-empty string")
		}
		if len(args[1]) <= 0 {
			return nil,errors.New("2nd argument must be a non-empty string")
		}

		customerName := args[0]
		customerId, err := strconv.Atoi(args[1])
		customerIdAsString := args[1]
		if err != nil {
			return nil,errors.New("2nd argument must be a numeric string")
		}
		customerAsBytes, err := stub.GetState(customerIdAsString)
		if err != nil {
			 return nil,err
		} else if customerAsBytes != nil {
			fmt.Println("This customer already exists: " + customerIdAsString)
			return nil,errors.New("This customer already exists: "+customerIdAsString)
		}

		customer:= Customer{customerName,customerId}

		customerJSONasBytes, err := json.Marshal(customer)

		if err != nil {
			return nil,err
		}
		err = stub.PutState(customerIdAsString, customerJSONasBytes)

		if err != nil {
			return nil,err
		}

		fmt.Println("- end initCustomer")
		return nil,nil
}

func (t *SimpleChaincode) initEmployee(stub shim.ChaincodeStubInterface, args []string) ([]byte,error){

	if len(args) != 3 {
		return nil,errors.New("Incorrect number of arguments. Expecting 3")
	}
	// ==== Input sanitation ====
	fmt.Println("- start initEmployee")
	if len(args[0]) <= 0 {
		return nil,errors.New("1st argument must be a non-empty string")
	}
	if len(args[1]) <= 0 {
		return nil,errors.New("2nd argument must be a non-empty string")
	}
	if len(args[2]) <= 0 {
		return nil,errors.New("3rd argument must be a non-empty string")
	}

	employeeName := args[0]
	project := strings.ToLower(args[2])
	employeeId, err := strconv.Atoi(args[1])
	employeeIdAsString := args[1]
	if err != nil {
		return nil,errors.New("2nd argument must be a numeric string")
	}

	employeeAsBytes, err := stub.GetState(employeeIdAsString)
	if err != nil {
		return nil,err
	} else if employeeAsBytes != nil {
		fmt.Println("This employee already exists: " + employeeIdAsString)
		return []byte("duplicate"),errors.New("This employee already exists: "+employeeIdAsString)
	}

	employee:= Employee{employeeName,employeeId,project}
	fmt.Println(employee)
	employeeJSONasBytes, err := json.Marshal(employee)
	fmt.Println(employeeJSONasBytes)
	if err != nil {
		return nil,err
	}
	err = stub.PutState(employeeIdAsString, employeeJSONasBytes)

	if err != nil {
		return nil,err
	}
	employee_temp,_ := stub.GetState(employeeIdAsString)
	fmt.Println(employee_temp)
	// composite key to get employees by project

	/*
	indexName := "project"
	projectIndexKey, err := stub.CreateCompositeKey(indexName, []string{project, employeeIdAsString})
	if err != nil {
		return nil,err
	}

	value := []byte{0x00}
	stub.PutState(projectIndexKey, value)
	*/
	fmt.Println("- end initEmployee")
	return nil,nil
}

func (t *SimpleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte,error) {
    fmt.Println("Query is running " + function)

    if function =="getEmployee"{
		return t.getEmployee(stub,args)
	}else if function =="getCustomer"{
		return t.getCustomer(stub,args)
	}else if function =="getProject"{
		return t.getProject(stub,args)
	}else if function == "getEfforts"{
		return t.getEfforts(stub,args)
	}

	return nil,errors.New("Received unknown function query")
}
func (t *SimpleChaincode) getEfforts(stub shim.ChaincodeStubInterface, args []string) ([]byte,error){
	fmt.Printf("getEfforts called")
	if len(args) !=1{
		return nil,errors.New("Incorrect number of arguments. Expecting 1")
	}
	idAndTimestamp := args[0]
	invoice, err := stub.GetState(idAndTimestamp)
	fmt.Println(invoice)
	if err != nil {
		return nil,err
	}

	return invoice,nil
}
func (t *SimpleChaincode) getEmployee(stub shim.ChaincodeStubInterface, args []string) ([]byte,error){
	fmt.Printf("getEmployee called")
	if len(args) !=1{
		return nil,errors.New("Incorrect number of arguments. Expecting 1")
	}
	employeeId := args[0]
	employee, err := stub.GetState(employeeId)
	fmt.Println(employee)
	if err != nil {
		return nil,err
	}

	return employee,nil
}

func main() {
    	err := shim.Start(new(SimpleChaincode))
    if err != nil {
        fmt.Printf("Error starting Simple chaincode: %s", err)
    }
}
<|endoftext|>


<commit_before>package main

import (
	"context"
	"flag"
	"fmt"
	"os"
	"strconv"
	"text/tabwriter"
	"time"

	"google.golang.org/grpc"

	"github.com/apache/thrift/lib/go/thrift"
	lightstep "github.com/lightstep/lightstep-tracer-go"
	stdopentracing "github.com/opentracing/opentracing-go"
	zipkin "github.com/openzipkin/zipkin-go"
	zipkinot "github.com/openzipkin/zipkin-go-opentracing"
	zipkinhttp "github.com/openzipkin/zipkin-go/reporter/http"
	"sourcegraph.com/sourcegraph/appdash"
	appdashot "sourcegraph.com/sourcegraph/appdash/opentracing"

	"github.com/go-kit/kit/log"

	"github.com/go-kit/kit/examples/addsvc/pkg/addservice"
	"github.com/go-kit/kit/examples/addsvc/pkg/addtransport"
	addthrift "github.com/go-kit/kit/examples/addsvc/thrift/gen-go/addsvc"
)

func main() {
	// The addcli presumes no service discovery system, and expects users to
	// provide the direct address of an addsvc. This presumption is reflected in
	// the addcli binary and the client packages: the -transport.addr flags
	// and various client constructors both expect host:port strings. For an
	// example service with a client built on top of a service discovery system,
	// see profilesvc.
	fs := flag.NewFlagSet("addcli", flag.ExitOnError)
	var (
		httpAddr       = fs.String("http-addr", "", "HTTP address of addsvc")
		grpcAddr       = fs.String("grpc-addr", "", "gRPC address of addsvc")
		thriftAddr     = fs.String("thrift-addr", "", "Thrift address of addsvc")
		jsonRPCAddr    = fs.String("jsonrpc-addr", "", "JSON RPC address of addsvc")
		thriftProtocol = fs.String("thrift-protocol", "binary", "binary, compact, json, simplejson")
		thriftBuffer   = fs.Int("thrift-buffer", 0, "0 for unbuffered")
		thriftFramed   = fs.Bool("thrift-framed", false, "true to enable framing")
		zipkinV2URL    = fs.String("zipkin-url", "", "Enable Zipkin v2 tracing (zipkin-go) via HTTP Reporter URL e.g. http://localhost:94111/api/v2/spans")
		zipkinV1URL    = fs.String("zipkin-v1-url", "", "Enable Zipkin v1 tracing (zipkin-go-opentracing) via a collector URL e.g. http://localhost:9411/api/v1/spans")
		lightstepToken = fs.String("lightstep-token", "", "Enable LightStep tracing via a LightStep access token")
		appdashAddr    = fs.String("appdash-addr", "", "Enable Appdash tracing via an Appdash server host:port")
		method         = fs.String("method", "sum", "sum, concat")
	)
	fs.Usage = usageFor(fs, os.Args[0]+" [flags] <a> <b>")
	fs.Parse(os.Args[1:])
	if len(fs.Args()) != 2 {
		fs.Usage()
		os.Exit(1)
	}

	// This is a demonstration client, which supports multiple tracers.
	// Your clients will probably just use one tracer.
	var otTracer stdopentracing.Tracer
	{
		if *zipkinV1URL != "" && *zipkinV2URL == "" {
			collector, err := zipkinot.NewHTTPCollector(*zipkinV1URL)
			if err != nil {
				fmt.Fprintln(os.Stderr, err.Error())
				os.Exit(1)
			}
			defer collector.Close()
			var (
				debug       = false
				hostPort    = "localhost:0"
				serviceName = "addsvc-cli"
			)
			recorder := zipkinot.NewRecorder(collector, debug, hostPort, serviceName)
			otTracer, err = zipkinot.NewTracer(recorder)
			if err != nil {
				fmt.Fprintln(os.Stderr, err.Error())
				os.Exit(1)
			}
		} else if *lightstepToken != "" {
			otTracer = lightstep.NewTracer(lightstep.Options{
				AccessToken: *lightstepToken,
			})
			defer lightstep.FlushLightStepTracer(otTracer)
		} else if *appdashAddr != "" {
			otTracer = appdashot.NewTracer(appdash.NewRemoteCollector(*appdashAddr))
		} else {
			otTracer = stdopentracing.GlobalTracer() // no-op
		}
	}

	// This is a demonstration of the native Zipkin tracing client. If using
	// Zipkin this is the more idiomatic client over OpenTracing.
	var zipkinTracer *zipkin.Tracer
	{
		var (
			err           error
			hostPort      = "" // if host:port is unknown we can keep this empty
			serviceName   = "addsvc-cli"
			useNoopTracer = (*zipkinV2URL == "")
			reporter      = zipkinhttp.NewReporter(*zipkinV2URL)
		)
		defer reporter.Close()
		zEP, _ := zipkin.NewEndpoint(serviceName, hostPort)
		zipkinTracer, err = zipkin.NewTracer(
			reporter, zipkin.WithLocalEndpoint(zEP), zipkin.WithNoopTracer(useNoopTracer),
		)
		if err != nil {
			fmt.Fprintf(os.Stderr, "unable to create zipkin tracer: %s\n", err.Error())
			os.Exit(1)
		}
	}

	// This is a demonstration client, which supports multiple transports.
	// Your clients will probably just define and stick with 1 transport.
	var (
		svc addservice.Service
		err error
	)
	if *httpAddr != "" {
		svc, err = addtransport.NewHTTPClient(*httpAddr, otTracer, zipkinTracer, log.NewNopLogger())
	} else if *grpcAddr != "" {
		conn, err := grpc.Dial(*grpcAddr, grpc.WithInsecure(), grpc.WithTimeout(time.Second))
		if err != nil {
			fmt.Fprintf(os.Stderr, "error: %v", err)
			os.Exit(1)
		}
		defer conn.Close()
		svc = addtransport.NewGRPCClient(conn, otTracer, zipkinTracer, log.NewNopLogger())
	} else if *jsonRPCAddr != "" {
		svc, err = addtransport.NewJSONRPCClient(*jsonRPCAddr, otTracer, log.NewNopLogger())
	} else if *thriftAddr != "" {
		// It's necessary to do all of this construction in the func main,
		// because (among other reasons) we need to control the lifecycle of the
		// Thrift transport, i.e. close it eventually.
		var protocolFactory thrift.TProtocolFactory
		switch *thriftProtocol {
		case "compact":
			protocolFactory = thrift.NewTCompactProtocolFactory()
		case "simplejson":
			protocolFactory = thrift.NewTSimpleJSONProtocolFactory()
		case "json":
			protocolFactory = thrift.NewTJSONProtocolFactory()
		case "binary", "":
			protocolFactory = thrift.NewTBinaryProtocolFactoryDefault()
		default:
			fmt.Fprintf(os.Stderr, "error: invalid protocol %q\n", *thriftProtocol)
			os.Exit(1)
		}
		var transportFactory thrift.TTransportFactory
		if *thriftBuffer > 0 {
			transportFactory = thrift.NewTBufferedTransportFactory(*thriftBuffer)
		} else {
			transportFactory = thrift.NewTTransportFactory()
		}
		if *thriftFramed {
			transportFactory = thrift.NewTFramedTransportFactory(transportFactory)
		}
		transportSocket, err := thrift.NewTSocket(*thriftAddr)
		if err != nil {
			fmt.Fprintf(os.Stderr, "error: %v\n", err)
			os.Exit(1)
		}
		transport, err := transportFactory.GetTransport(transportSocket)
		if err != nil {
			fmt.Fprintf(os.Stderr, "error: %v\n", err)
			os.Exit(1)
		}
		if err := transport.Open(); err != nil {
			fmt.Fprintf(os.Stderr, "error: %v\n", err)
			os.Exit(1)
		}
		defer transport.Close()
		client := addthrift.NewAddServiceClientFactory(transport, protocolFactory)
		svc = addtransport.NewThriftClient(client)
	} else {
		fmt.Fprintf(os.Stderr, "error: no remote address specified\n")
		os.Exit(1)
	}
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %v\n", err)
		os.Exit(1)
	}

	switch *method {
	case "sum":
		a, _ := strconv.ParseInt(fs.Args()[0], 10, 64)
		b, _ := strconv.ParseInt(fs.Args()[1], 10, 64)
		v, err := svc.Sum(context.Background(), int(a), int(b))
		if err != nil {
			fmt.Fprintf(os.Stderr, "error: %v\n", err)
			os.Exit(1)
		}
		fmt.Fprintf(os.Stdout, "%d + %d = %d\n", a, b, v)

	case "concat":
		a := fs.Args()[0]
		b := fs.Args()[1]
		v, err := svc.Concat(context.Background(), a, b)
		if err != nil {
			fmt.Fprintf(os.Stderr, "error: %v\n", err)
			os.Exit(1)
		}
		fmt.Fprintf(os.Stdout, "%q + %q = %q\n", a, b, v)

	default:
		fmt.Fprintf(os.Stderr, "error: invalid method %q\n", method)
		os.Exit(1)
	}
}

func usageFor(fs *flag.FlagSet, short string) func() {
	return func() {
		fmt.Fprintf(os.Stderr, "USAGE\n")
		fmt.Fprintf(os.Stderr, "  %s\n", short)
		fmt.Fprintf(os.Stderr, "\n")
		fmt.Fprintf(os.Stderr, "FLAGS\n")
		w := tabwriter.NewWriter(os.Stderr, 0, 2, 2, ' ', 0)
		fs.VisitAll(func(f *flag.Flag) {
			fmt.Fprintf(w, "\t-%s %s\t%s\n", f.Name, f.DefValue, f.Usage)
		})
		w.Flush()
		fmt.Fprintf(os.Stderr, "\n")
	}
}
<commit_msg>silence wrong type error<commit_after>package main

import (
	"context"
	"flag"
	"fmt"
	"os"
	"strconv"
	"text/tabwriter"
	"time"

	"google.golang.org/grpc"

	"github.com/apache/thrift/lib/go/thrift"
	lightstep "github.com/lightstep/lightstep-tracer-go"
	stdopentracing "github.com/opentracing/opentracing-go"
	zipkin "github.com/openzipkin/zipkin-go"
	zipkinot "github.com/openzipkin/zipkin-go-opentracing"
	zipkinhttp "github.com/openzipkin/zipkin-go/reporter/http"
	"sourcegraph.com/sourcegraph/appdash"
	appdashot "sourcegraph.com/sourcegraph/appdash/opentracing"

	"github.com/go-kit/kit/log"

	"github.com/go-kit/kit/examples/addsvc/pkg/addservice"
	"github.com/go-kit/kit/examples/addsvc/pkg/addtransport"
	addthrift "github.com/go-kit/kit/examples/addsvc/thrift/gen-go/addsvc"
)

func main() {
	// The addcli presumes no service discovery system, and expects users to
	// provide the direct address of an addsvc. This presumption is reflected in
	// the addcli binary and the client packages: the -transport.addr flags
	// and various client constructors both expect host:port strings. For an
	// example service with a client built on top of a service discovery system,
	// see profilesvc.
	fs := flag.NewFlagSet("addcli", flag.ExitOnError)
	var (
		httpAddr       = fs.String("http-addr", "", "HTTP address of addsvc")
		grpcAddr       = fs.String("grpc-addr", "", "gRPC address of addsvc")
		thriftAddr     = fs.String("thrift-addr", "", "Thrift address of addsvc")
		jsonRPCAddr    = fs.String("jsonrpc-addr", "", "JSON RPC address of addsvc")
		thriftProtocol = fs.String("thrift-protocol", "binary", "binary, compact, json, simplejson")
		thriftBuffer   = fs.Int("thrift-buffer", 0, "0 for unbuffered")
		thriftFramed   = fs.Bool("thrift-framed", false, "true to enable framing")
		zipkinV2URL    = fs.String("zipkin-url", "", "Enable Zipkin v2 tracing (zipkin-go) via HTTP Reporter URL e.g. http://localhost:94111/api/v2/spans")
		zipkinV1URL    = fs.String("zipkin-v1-url", "", "Enable Zipkin v1 tracing (zipkin-go-opentracing) via a collector URL e.g. http://localhost:9411/api/v1/spans")
		lightstepToken = fs.String("lightstep-token", "", "Enable LightStep tracing via a LightStep access token")
		appdashAddr    = fs.String("appdash-addr", "", "Enable Appdash tracing via an Appdash server host:port")
		method         = fs.String("method", "sum", "sum, concat")
	)
	fs.Usage = usageFor(fs, os.Args[0]+" [flags] <a> <b>")
	fs.Parse(os.Args[1:])
	if len(fs.Args()) != 2 {
		fs.Usage()
		os.Exit(1)
	}

	// This is a demonstration client, which supports multiple tracers.
	// Your clients will probably just use one tracer.
	var otTracer stdopentracing.Tracer
	{
		if *zipkinV1URL != "" && *zipkinV2URL == "" {
			collector, err := zipkinot.NewHTTPCollector(*zipkinV1URL)
			if err != nil {
				fmt.Fprintln(os.Stderr, err.Error())
				os.Exit(1)
			}
			defer collector.Close()
			var (
				debug       = false
				hostPort    = "localhost:0"
				serviceName = "addsvc-cli"
			)
			recorder := zipkinot.NewRecorder(collector, debug, hostPort, serviceName)
			otTracer, err = zipkinot.NewTracer(recorder)
			if err != nil {
				fmt.Fprintln(os.Stderr, err.Error())
				os.Exit(1)
			}
		} else if *lightstepToken != "" {
			otTracer = lightstep.NewTracer(lightstep.Options{
				AccessToken: *lightstepToken,
			})
			defer lightstep.FlushLightStepTracer(otTracer)
		} else if *appdashAddr != "" {
			otTracer = appdashot.NewTracer(appdash.NewRemoteCollector(*appdashAddr))
		} else {
			otTracer = stdopentracing.GlobalTracer() // no-op
		}
	}

	// This is a demonstration of the native Zipkin tracing client. If using
	// Zipkin this is the more idiomatic client over OpenTracing.
	var zipkinTracer *zipkin.Tracer
	{
		var (
			err           error
			hostPort      = "" // if host:port is unknown we can keep this empty
			serviceName   = "addsvc-cli"
			useNoopTracer = (*zipkinV2URL == "")
			reporter      = zipkinhttp.NewReporter(*zipkinV2URL)
		)
		defer reporter.Close()
		zEP, _ := zipkin.NewEndpoint(serviceName, hostPort)
		zipkinTracer, err = zipkin.NewTracer(
			reporter, zipkin.WithLocalEndpoint(zEP), zipkin.WithNoopTracer(useNoopTracer),
		)
		if err != nil {
			fmt.Fprintf(os.Stderr, "unable to create zipkin tracer: %s\n", err.Error())
			os.Exit(1)
		}
	}

	// This is a demonstration client, which supports multiple transports.
	// Your clients will probably just define and stick with 1 transport.
	var (
		svc addservice.Service
		err error
	)
	if *httpAddr != "" {
		svc, err = addtransport.NewHTTPClient(*httpAddr, otTracer, zipkinTracer, log.NewNopLogger())
	} else if *grpcAddr != "" {
		conn, err := grpc.Dial(*grpcAddr, grpc.WithInsecure(), grpc.WithTimeout(time.Second))
		if err != nil {
			fmt.Fprintf(os.Stderr, "error: %v", err)
			os.Exit(1)
		}
		defer conn.Close()
		svc = addtransport.NewGRPCClient(conn, otTracer, zipkinTracer, log.NewNopLogger())
	} else if *jsonRPCAddr != "" {
		svc, err = addtransport.NewJSONRPCClient(*jsonRPCAddr, otTracer, log.NewNopLogger())
	} else if *thriftAddr != "" {
		// It's necessary to do all of this construction in the func main,
		// because (among other reasons) we need to control the lifecycle of the
		// Thrift transport, i.e. close it eventually.
		var protocolFactory thrift.TProtocolFactory
		switch *thriftProtocol {
		case "compact":
			protocolFactory = thrift.NewTCompactProtocolFactory()
		case "simplejson":
			protocolFactory = thrift.NewTSimpleJSONProtocolFactory()
		case "json":
			protocolFactory = thrift.NewTJSONProtocolFactory()
		case "binary", "":
			protocolFactory = thrift.NewTBinaryProtocolFactoryDefault()
		default:
			fmt.Fprintf(os.Stderr, "error: invalid protocol %q\n", *thriftProtocol)
			os.Exit(1)
		}
		var transportFactory thrift.TTransportFactory
		if *thriftBuffer > 0 {
			transportFactory = thrift.NewTBufferedTransportFactory(*thriftBuffer)
		} else {
			transportFactory = thrift.NewTTransportFactory()
		}
		if *thriftFramed {
			transportFactory = thrift.NewTFramedTransportFactory(transportFactory)
		}
		transportSocket, err := thrift.NewTSocket(*thriftAddr)
		if err != nil {
			fmt.Fprintf(os.Stderr, "error: %v\n", err)
			os.Exit(1)
		}
		transport, err := transportFactory.GetTransport(transportSocket)
		if err != nil {
			fmt.Fprintf(os.Stderr, "error: %v\n", err)
			os.Exit(1)
		}
		if err := transport.Open(); err != nil {
			fmt.Fprintf(os.Stderr, "error: %v\n", err)
			os.Exit(1)
		}
		defer transport.Close()
		client := addthrift.NewAddServiceClientFactory(transport, protocolFactory)
		svc = addtransport.NewThriftClient(client)
	} else {
		fmt.Fprintf(os.Stderr, "error: no remote address specified\n")
		os.Exit(1)
	}
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %v\n", err)
		os.Exit(1)
	}

	switch *method {
	case "sum":
		a, _ := strconv.ParseInt(fs.Args()[0], 10, 64)
		b, _ := strconv.ParseInt(fs.Args()[1], 10, 64)
		v, err := svc.Sum(context.Background(), int(a), int(b))
		if err != nil {
			fmt.Fprintf(os.Stderr, "error: %v\n", err)
			os.Exit(1)
		}
		fmt.Fprintf(os.Stdout, "%d + %d = %d\n", a, b, v)

	case "concat":
		a := fs.Args()[0]
		b := fs.Args()[1]
		v, err := svc.Concat(context.Background(), a, b)
		if err != nil {
			fmt.Fprintf(os.Stderr, "error: %v\n", err)
			os.Exit(1)
		}
		fmt.Fprintf(os.Stdout, "%q + %q = %q\n", a, b, v)

	default:
		fmt.Fprintf(os.Stderr, "error: invalid method %q\n", *method)
		os.Exit(1)
	}
}

func usageFor(fs *flag.FlagSet, short string) func() {
	return func() {
		fmt.Fprintf(os.Stderr, "USAGE\n")
		fmt.Fprintf(os.Stderr, "  %s\n", short)
		fmt.Fprintf(os.Stderr, "\n")
		fmt.Fprintf(os.Stderr, "FLAGS\n")
		w := tabwriter.NewWriter(os.Stderr, 0, 2, 2, ' ', 0)
		fs.VisitAll(func(f *flag.Flag) {
			fmt.Fprintf(w, "\t-%s %s\t%s\n", f.Name, f.DefValue, f.Usage)
		})
		w.Flush()
		fmt.Fprintf(os.Stderr, "\n")
	}
}
<|endoftext|>