<commit_before>//  Copyright (c) 2014 Couchbase, 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 bleve

import (
	"encoding/json"
	"fmt"

	"github.com/couchbaselabs/bleve/document"
	"github.com/couchbaselabs/bleve/index"
	"github.com/couchbaselabs/bleve/index/store"
	"github.com/couchbaselabs/bleve/index/store/leveldb"
	"github.com/couchbaselabs/bleve/index/upside_down"
	"github.com/couchbaselabs/bleve/search"
)

type indexImpl struct {
	s store.KVStore
	i index.Index
	m *IndexMapping
}

func newIndex(path string, mapping *IndexMapping) (*indexImpl, error) {
	store, err := leveldb.Open(path)
	if err != nil {
		return nil, err
	}
	idx := upside_down.NewUpsideDownCouch(store)
	err = idx.Open()
	if err != nil {
		return nil, err
	}
	return &indexImpl{
		s: store,
		i: idx,
		m: mapping,
	}, nil
}

// Index the provided data.
func (i *indexImpl) Index(data interface{}) error {
	id, ok := i.determineID(data)
	if ok {
		return i.IndexID(id, data)
	}

	return ERROR_NO_ID
}

func (i *indexImpl) IndexID(id string, data interface{}) error {
	doc := document.NewDocument(id)
	err := i.m.MapDocument(doc, data)
	if err != nil {
		return err
	}
	err = i.i.Update(doc)
	if err != nil {
		return err
	}
	return nil
}

func (i *indexImpl) IndexJSON(data []byte) error {
	var obj interface{}
	err := json.Unmarshal(data, &obj)
	if err != nil {
		return err
	}
	return i.Index(obj)
}

func (i *indexImpl) IndexJSONID(id string, data []byte) error {
	var obj interface{}
	err := json.Unmarshal(data, &obj)
	if err != nil {
		return err
	}
	return i.IndexID(id, obj)
}

func (i *indexImpl) Delete(data interface{}) error {
	id, ok := i.determineID(data)
	if ok {
		return i.DeleteID(id)
	}

	return ERROR_NO_ID
}

func (i *indexImpl) DeleteID(id string) error {
	err := i.i.Delete(id)
	if err != nil {
		return err
	}
	return nil
}

func (i *indexImpl) Document(id string) (*document.Document, error) {
	return i.i.Document(id)
}

func (i *indexImpl) DocCount() uint64 {
	return i.i.DocCount()
}

func (i *indexImpl) Search(req *SearchRequest) (*SearchResult, error) {
	collector := search.NewTopScorerSkipCollector(req.Size, req.From)
	searcher, err := req.Query.Searcher(i, req.Explain)
	if err != nil {
		return nil, err
	}
	err = collector.Collect(searcher)
	if err != nil {
		return nil, err
	}

	hits := collector.Results()

	if req.Highlight != nil {
		// get the right highlighter
		highlighter := config.Highlight.Highlighters[*config.DefaultHighlighter]
		if req.Highlight.Style != nil {
			highlighter = config.Highlight.Highlighters[*req.Highlight.Style]
			if highlighter == nil {
				return nil, fmt.Errorf("no highlighter named `%s` registered", req.Highlight.Style)
			}
		}

		for _, hit := range hits {
			doc, err := i.Document(hit.ID)
			if err == nil {
				highlightFields := req.Highlight.Fields
				if highlightFields == nil {
					// add all fields with matches
					highlightFields = make([]string, 0, len(hit.Locations))
					for k, _ := range hit.Locations {
						highlightFields = append(highlightFields, k)
					}
				}

				for _, hf := range highlightFields {
					highlighter.BestFragmentsInField(hit, doc, hf, 3)
				}
			}
		}
	}

	return &SearchResult{
		Request:  req,
		Hits:     hits,
		Total:    collector.Total(),
		MaxScore: collector.MaxScore(),
		Took:     collector.Took(),
	}, nil
}

func (i *indexImpl) DumpDoc(id string) ([]interface{}, error) {
	return i.i.DumpDoc(id)
}

func (i *indexImpl) Close() {
	i.i.Close()
}

func (i *indexImpl) determineID(data interface{}) (string, bool) {
	// first see if the object implements Identifier
	identifier, ok := data.(Identifier)
	if ok {
		return identifier.ID(), true
	}

	// now see if we can find an ID using the mapping
	if i.m.IdField != nil {
		id, ok := mustString(lookupPropertyPath(data, *i.m.IdField))
		if ok {
			return id, true
		}
	}

	return "", false
}
<commit_msg>fix go vet issue<commit_after>//  Copyright (c) 2014 Couchbase, 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 bleve

import (
	"encoding/json"
	"fmt"

	"github.com/couchbaselabs/bleve/document"
	"github.com/couchbaselabs/bleve/index"
	"github.com/couchbaselabs/bleve/index/store"
	"github.com/couchbaselabs/bleve/index/store/leveldb"
	"github.com/couchbaselabs/bleve/index/upside_down"
	"github.com/couchbaselabs/bleve/search"
)

type indexImpl struct {
	s store.KVStore
	i index.Index
	m *IndexMapping
}

func newIndex(path string, mapping *IndexMapping) (*indexImpl, error) {
	store, err := leveldb.Open(path)
	if err != nil {
		return nil, err
	}
	idx := upside_down.NewUpsideDownCouch(store)
	err = idx.Open()
	if err != nil {
		return nil, err
	}
	return &indexImpl{
		s: store,
		i: idx,
		m: mapping,
	}, nil
}

// Index the provided data.
func (i *indexImpl) Index(data interface{}) error {
	id, ok := i.determineID(data)
	if ok {
		return i.IndexID(id, data)
	}

	return ERROR_NO_ID
}

func (i *indexImpl) IndexID(id string, data interface{}) error {
	doc := document.NewDocument(id)
	err := i.m.MapDocument(doc, data)
	if err != nil {
		return err
	}
	err = i.i.Update(doc)
	if err != nil {
		return err
	}
	return nil
}

func (i *indexImpl) IndexJSON(data []byte) error {
	var obj interface{}
	err := json.Unmarshal(data, &obj)
	if err != nil {
		return err
	}
	return i.Index(obj)
}

func (i *indexImpl) IndexJSONID(id string, data []byte) error {
	var obj interface{}
	err := json.Unmarshal(data, &obj)
	if err != nil {
		return err
	}
	return i.IndexID(id, obj)
}

func (i *indexImpl) Delete(data interface{}) error {
	id, ok := i.determineID(data)
	if ok {
		return i.DeleteID(id)
	}

	return ERROR_NO_ID
}

func (i *indexImpl) DeleteID(id string) error {
	err := i.i.Delete(id)
	if err != nil {
		return err
	}
	return nil
}

func (i *indexImpl) Document(id string) (*document.Document, error) {
	return i.i.Document(id)
}

func (i *indexImpl) DocCount() uint64 {
	return i.i.DocCount()
}

func (i *indexImpl) Search(req *SearchRequest) (*SearchResult, error) {
	collector := search.NewTopScorerSkipCollector(req.Size, req.From)
	searcher, err := req.Query.Searcher(i, req.Explain)
	if err != nil {
		return nil, err
	}
	err = collector.Collect(searcher)
	if err != nil {
		return nil, err
	}

	hits := collector.Results()

	if req.Highlight != nil {
		// get the right highlighter
		highlighter := config.Highlight.Highlighters[*config.DefaultHighlighter]
		if req.Highlight.Style != nil {
			highlighter = config.Highlight.Highlighters[*req.Highlight.Style]
			if highlighter == nil {
				return nil, fmt.Errorf("no highlighter named `%s` registered", *req.Highlight.Style)
			}
		}

		for _, hit := range hits {
			doc, err := i.Document(hit.ID)
			if err == nil {
				highlightFields := req.Highlight.Fields
				if highlightFields == nil {
					// add all fields with matches
					highlightFields = make([]string, 0, len(hit.Locations))
					for k, _ := range hit.Locations {
						highlightFields = append(highlightFields, k)
					}
				}

				for _, hf := range highlightFields {
					highlighter.BestFragmentsInField(hit, doc, hf, 3)
				}
			}
		}
	}

	return &SearchResult{
		Request:  req,
		Hits:     hits,
		Total:    collector.Total(),
		MaxScore: collector.MaxScore(),
		Took:     collector.Took(),
	}, nil
}

func (i *indexImpl) DumpDoc(id string) ([]interface{}, error) {
	return i.i.DumpDoc(id)
}

func (i *indexImpl) Close() {
	i.i.Close()
}

func (i *indexImpl) determineID(data interface{}) (string, bool) {
	// first see if the object implements Identifier
	identifier, ok := data.(Identifier)
	if ok {
		return identifier.ID(), true
	}

	// now see if we can find an ID using the mapping
	if i.m.IdField != nil {
		id, ok := mustString(lookupPropertyPath(data, *i.m.IdField))
		if ok {
			return id, true
		}
	}

	return "", false
}
<|endoftext|>


<commit_before>/*
Smart Contract for PoC - Track & Trace Use Case
*/
package main

import (
	"errors"
	"fmt"
	//"strconv"
	"encoding/json"

	"github.com/hyperledger/fabric/core/chaincode/shim"
	//"github.com/hyperledger/fabric/core/crypto/primitives"
)

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

//iQOS Changes starts ----------------------------------------------------------------
// Assembly comprises of one Serial ID and multiple Batch IDs
type AssemblyLine struct{
	AssemblyLineId string `json:"assemblyLineId"`
	SerialId string `json:"serialId"`
	OriginalFilamentBatchId string `json:"originalFilamentBatchId"`
	OriginalLedBatchId string `json:"originalLedBatchId"`
	OriginalCircuitBoardBatchId string `json:"originalCircuitBoardBatchId"`
	OriginalWireBatchId string `json:"originalWireBatchId"`
	OriginalCasingBatchId string `json:"originalCasingBatchId"`
	OriginalAdaptorBatchId string `json:"originalAdaptorBatchId"`
	OriginalStickPodBatchId string `json:"originalStickPodBatchId"`
	AssemblyLineStatus string `json:"assemblyLineStatus"`
	}

// GetAssemblyLineStatus is for storing retreived Assembly Line Status
type GetAssemblyLineStatus struct{
	AssemblyLineStatus string `json:"assemblyLineStatus"`
}

//iQOS Changes ends ----------------------------------------------------------------

func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	fmt.Printf("Init called, initializing chaincode")

	/*
	// Check if table already exists
	_, err = stub.GetTable("AssemblyLine")
	if err == nil {
		// Table already exists; do not recreate
		return nil, nil
	}
   */
	// Create application Table
	err := stub.CreateTable("AssemblyLine", []*shim.ColumnDefinition{
		&shim.ColumnDefinition{Name: "assemblyLineId", Type: shim.ColumnDefinition_STRING, Key: true},
		&shim.ColumnDefinition{Name: "serialId", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "originalFilamentBatchId", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "originalLedBatchId", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "originalCircuitBoardBatchId", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "originalWireBatchId", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "originalCasingBatchId", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "originalAdaptorBatchId", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "originalStickPodBatchId", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "assemblyLineStatus", Type: shim.ColumnDefinition_STRING, Key: false},

	})
	if err != nil {
		return nil, errors.New("Failed creating AssemblyLine.")
	}

	return nil, nil
}

//startAssemblyLine to start an Assemblyline
func (t *SimpleChaincode) startAssemblyLine(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
if len(args) != 9 {
			return nil, fmt.Errorf("Incorrect number of arguments. Expecting 9. Got: %d.", len(args))
		}

		assemblyLineId:=args[0]
		serialId:=args[1]
		originalFilamentBatchId:=args[2]
		originalLedBatchId:=args[3]
		originalCircuitBoardBatchId:=args[4]
		originalWireBatchId:=args[5]
		originalCasingBatchId:=args[6]
		originalAdaptorBatchId:=args[7]
		originalStickPodBatchId:=args[8]
		assemblyLineStatus:= "InProgress"

		// Insert a row
		ok, err := stub.InsertRow("AssemblyLine", shim.Row{
			Columns: []*shim.Column{
				&shim.Column{Value: &shim.Column_String_{String_: assemblyLineId}},
				&shim.Column{Value: &shim.Column_String_{String_: serialId}},
				&shim.Column{Value: &shim.Column_String_{String_: originalFilamentBatchId}},
				&shim.Column{Value: &shim.Column_String_{String_: originalLedBatchId}},
				&shim.Column{Value: &shim.Column_String_{String_: originalCircuitBoardBatchId}},
				&shim.Column{Value: &shim.Column_String_{String_: originalWireBatchId}},
				&shim.Column{Value: &shim.Column_String_{String_: originalCasingBatchId}},
				&shim.Column{Value: &shim.Column_String_{String_: originalAdaptorBatchId}},
				&shim.Column{Value: &shim.Column_String_{String_: originalStickPodBatchId}},
				&shim.Column{Value: &shim.Column_String_{String_: assemblyLineStatus}},
			}})

		if err != nil {
			return nil, err
		}
		if !ok && err == nil {
			return nil, errors.New("Row already exists.")
		}

		return nil, nil

}

//Update AssemblyLine status
func (t *SimpleChaincode) updateAssemblyLineStatus(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {

	if len(args) != 2 {
		return nil, errors.New("Incorrect number of arguments. Expecting 2.")
	}
	//else {
	//	return nil, errors.New("Correct number of arguments. Got 2.")
	//}

	assemblyLineId := args[0]
	assemblyLineStatus := args[1]

	// Get the row pertaining to this AssemblyLineId
	var columns []shim.Column
	col1 := shim.Column{Value: &shim.Column_String_{String_: assemblyLineId}}
	columns = append(columns, col1)

	row, err := stub.GetRow("AssemblyLine", columns)
	if err != nil {
		return nil, fmt.Errorf("Error: Failed retrieving AssemblyLine with assemblyLineId %s. Error %s", assemblyLineId, err.Error())
	}

	// GetRows returns empty message if key does not exist
	if len(row.Columns) == 0 {
		return nil, nil
	}

	// Delete the row pertaining to this assemblyLineId
	err = stub.DeleteRow(
		"Assemblyline",
		columns,
	)
	if err != nil {
		return nil, errors.New("Failed deleting row.")
	}

		//assemblyLineId:=row.Columns[0].GetString_()
		serialId:=row.Columns[1].GetString_()
		originalFilamentBatchId:=row.Columns[2].GetString_()
		originalLedBatchId:=row.Columns[3].GetString_()
		originalCircuitBoardBatchId:=row.Columns[4].GetString_()
		originalWireBatchId:=row.Columns[5].GetString_()
		originalCasingBatchId:=row.Columns[6].GetString_()
		originalAdaptorBatchId:=row.Columns[7].GetString_()
		originalStickPodBatchId:=row.Columns[8].GetString_()
		//assemblyLineStatus:= assemblyLineStatus

		// Insert a row
		ok, err := stub.InsertRow("AssemblyLine", shim.Row{
			Columns: []*shim.Column{
				&shim.Column{Value: &shim.Column_String_{String_: assemblyLineId}},
				&shim.Column{Value: &shim.Column_String_{String_: serialId}},
				&shim.Column{Value: &shim.Column_String_{String_: originalFilamentBatchId}},
				&shim.Column{Value: &shim.Column_String_{String_: originalLedBatchId}},
				&shim.Column{Value: &shim.Column_String_{String_: originalCircuitBoardBatchId}},
				&shim.Column{Value: &shim.Column_String_{String_: originalWireBatchId}},
				&shim.Column{Value: &shim.Column_String_{String_: originalCasingBatchId}},
				&shim.Column{Value: &shim.Column_String_{String_: originalAdaptorBatchId}},
				&shim.Column{Value: &shim.Column_String_{String_: originalStickPodBatchId}},
				&shim.Column{Value: &shim.Column_String_{String_: assemblyLineStatus}},
			}})

		if err != nil {
			return nil, err
		}
		if !ok && err == nil {
			return nil, errors.New("Row already exists in Assemblyline.")
		}

	return nil, nil

}

// Invoke callback representing the invocation of a chaincode
// This chaincode will manage two accounts A and B and will transfer X units from A to B upon invoke
func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	fmt.Printf("Invoke called, determining function")

	// Handle different functions
	if function == "init" {
		fmt.Printf("Function is init")
		return t.Init(stub, function, args)
	} else if function == "startAssemblyLine" {
		fmt.Printf("Function is startAssemblyLine")
		return t.startAssemblyLine(stub, args)
	} else if function == "updateAssemblyLineStatus" {
		fmt.Printf("Function is updateAssemblyLineStatus")
		return t.updateAssemblyLineStatus(stub, args)
	}

	return nil, errors.New("Received unknown function invocation")
}

func (t* SimpleChaincode) Run(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	fmt.Printf("Run called, passing through to Invoke (same function)")

	// Handle different functions
	if function == "startAssemblyLine" {
		fmt.Printf("Function is startAssemblyLine")
		return t.startAssemblyLine(stub, args)
	}  else if function == "updateAssemblyLineStatus" {
		fmt.Printf("Function is updateAssemblyLineStatus")
		return t.updateAssemblyLineStatus(stub, args)
	} else if function == "init" {
		fmt.Printf("Function is init")
		return t.Init(stub, function, args)
	}

	return nil, errors.New("Received unknown function invocation")
}

//get the AssemblyLine against ID
func (t *SimpleChaincode) getAssemblyLineByID(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {

	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting AssemblyLineID to query")
	}

	assemblyLineID := args[0]

	// Get the row pertaining to this assemblyLineID
	var columns []shim.Column
	col1 := shim.Column{Value: &shim.Column_String_{String_: assemblyLineID}}
	columns = append(columns, col1)

	row, err := stub.GetRow("AssemblyLine", columns)
	if err != nil {
		jsonResp := "{\"Error\":\"Failed to get the data for the assemblyLineID " + assemblyLineID + "\"}"
		return nil, errors.New(jsonResp)
	}

	// GetRows returns empty message if key does not exist
	if len(row.Columns) == 0 {
		jsonResp := "{\"Error\":\"Failed to get the data for the assemblyLineID " + assemblyLineID + "\"}"
		return nil, errors.New(jsonResp)
	}

	//return []byte (row), nil
	 mapB, _ := json.Marshal(row)
    fmt.Println(string(mapB))

	return mapB, nil

}

//get the status against the AssemblyLineID
func (t *SimpleChaincode) getAssemblyLineStatus(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {

	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting AssemblyLineID to query")
	}

	assemblyLineID := args[0]

	// Get the row pertaining to this assemblyLineID
	var columns []shim.Column
	col1 := shim.Column{Value: &shim.Column_String_{String_: assemblyLineID}}
	columns = append(columns, col1)

	row, err := stub.GetRow("AssemblyLine", columns)
	if err != nil {
		jsonResp := "{\"Error\":\"Failed to get the data for the assemblyLineID " + assemblyLineID + "\"}"
		return nil, errors.New(jsonResp)
	}

	// GetRows returns empty message if key does not exist
	if len(row.Columns) == 0 {
		jsonResp := "{\"Error\":\"Failed to get the data for the assemblyLineID " + assemblyLineID + "\"}"
		return nil, errors.New(jsonResp)
	}

	res2E := GetAssemblyLineStatus{}

	res2E.AssemblyLineStatus = row.Columns[9].GetString_()

  /*
    mapB, _ := json.Marshal(res2E)
    fmt.Println(string(mapB))
	return mapB, nil
  */

    return []byte (res2E.AssemblyLineStatus), nil

}

//get all AssemblyLines
func (t *SimpleChaincode) getAllAssemblyLines(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var columns []shim.Column

	rows, err := stub.GetRows("AssemblyLine", columns)
	if err != nil {
		return nil, fmt.Errorf("Failed to retrieve row")
	}

	res2E:= []*AssemblyLine{}

	for row := range rows {
		newApp:= new(AssemblyLine)
		newApp.AssemblyLineId = row.Columns[0].GetString_()
		newApp.SerialId = row.Columns[1].GetString_()
		newApp.OriginalFilamentBatchId = row.Columns[2].GetString_()
		newApp.OriginalLedBatchId = row.Columns[3].GetString_()
		newApp.OriginalCircuitBoardBatchId = row.Columns[4].GetString_()
		newApp.OriginalWireBatchId = row.Columns[5].GetString_()
		newApp.OriginalCasingBatchId = row.Columns[6].GetString_()
		newApp.OriginalAdaptorBatchId = row.Columns[7].GetString_()
		newApp.OriginalStickPodBatchId = row.Columns[8].GetString_()
		newApp.AssemblyLineStatus = row.Columns[9].GetString_()

		if len(newApp.AssemblyLineId) > 0{
		res2E=append(res2E,newApp)
		}
	}

    mapB, _ := json.Marshal(res2E)
    fmt.Println(string(mapB))

	return mapB, nil

}

// query queries the chaincode
func (t *SimpleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	fmt.Printf("Query called, determining function")

	if function == "getAssemblyLineStatus" {
		t := SimpleChaincode{}
		return t.getAssemblyLineStatus(stub, args)
	} else if function == "getAssemblyLineByID" {
		t := SimpleChaincode{}
		return t.getAssemblyLineByID(stub, args)
	} else if function == "getAllAssemblyLines" {
		t := SimpleChaincode{}
		return t.getAllAssemblyLines(stub, args)
	}

	return nil, errors.New("Received unknown function query")
}
//iQOS Changes ends------------------------------------------------------------------------------------------

func main() {
	err := shim.Start(new(SimpleChaincode))
	if err != nil {
		fmt.Printf("Error starting Simple chaincode: %s", err)
	}
}
<commit_msg>May15-3<commit_after>/*
Smart Contract for PoC - Track & Trace Use Case
*/
package main

import (
	"errors"
	"fmt"
	//"strconv"
	"encoding/json"

	"github.com/hyperledger/fabric/core/chaincode/shim"
	//"github.com/hyperledger/fabric/core/crypto/primitives"
)

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

//iQOS Changes starts ----------------------------------------------------------------
// Assembly comprises of one Serial ID and multiple Batch IDs
type AssemblyLine struct{
	AssemblyLineId string `json:"assemblyLineId"`
	SerialId string `json:"serialId"`
	OriginalFilamentBatchId string `json:"originalFilamentBatchId"`
	OriginalLedBatchId string `json:"originalLedBatchId"`
	OriginalCircuitBoardBatchId string `json:"originalCircuitBoardBatchId"`
	OriginalWireBatchId string `json:"originalWireBatchId"`
	OriginalCasingBatchId string `json:"originalCasingBatchId"`
	OriginalAdaptorBatchId string `json:"originalAdaptorBatchId"`
	OriginalStickPodBatchId string `json:"originalStickPodBatchId"`
	AssemblyLineStatus string `json:"assemblyLineStatus"`
	}

// GetAssemblyLineStatus is for storing retreived Assembly Line Status
type GetAssemblyLineStatus struct{
	AssemblyLineStatus string `json:"assemblyLineStatus"`
}

//iQOS Changes ends ----------------------------------------------------------------

func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	fmt.Printf("Init called, initializing chaincode for testing")

	// Check if table already exists
	_, err := stub.GetTable("AssemblyLine")
	if err == nil {
		// Table already exists; do not recreate
		return nil, nil
	}

	// Create application Table
	err = stub.CreateTable("AssemblyLine", []*shim.ColumnDefinition{
		&shim.ColumnDefinition{Name: "assemblyLineId", Type: shim.ColumnDefinition_STRING, Key: true},
		&shim.ColumnDefinition{Name: "serialId", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "originalFilamentBatchId", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "originalLedBatchId", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "originalCircuitBoardBatchId", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "originalWireBatchId", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "originalCasingBatchId", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "originalAdaptorBatchId", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "originalStickPodBatchId", Type: shim.ColumnDefinition_STRING, Key: false},
		&shim.ColumnDefinition{Name: "assemblyLineStatus", Type: shim.ColumnDefinition_STRING, Key: false},

	})
	if err != nil {
		return nil, errors.New("Failed creating AssemblyLine.")
	}

	return nil, nil
}

//startAssemblyLine to start an Assemblyline
func (t *SimpleChaincode) startAssemblyLine(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
if len(args) != 9 {
			return nil, fmt.Errorf("Incorrect number of arguments. Expecting 9. Got: %d.", len(args))
		}

		assemblyLineId:=args[0]
		serialId:=args[1]
		originalFilamentBatchId:=args[2]
		originalLedBatchId:=args[3]
		originalCircuitBoardBatchId:=args[4]
		originalWireBatchId:=args[5]
		originalCasingBatchId:=args[6]
		originalAdaptorBatchId:=args[7]
		originalStickPodBatchId:=args[8]
		assemblyLineStatus:= "InProgress"

		// Insert a row
		ok, err := stub.InsertRow("AssemblyLine", shim.Row{
			Columns: []*shim.Column{
				&shim.Column{Value: &shim.Column_String_{String_: assemblyLineId}},
				&shim.Column{Value: &shim.Column_String_{String_: serialId}},
				&shim.Column{Value: &shim.Column_String_{String_: originalFilamentBatchId}},
				&shim.Column{Value: &shim.Column_String_{String_: originalLedBatchId}},
				&shim.Column{Value: &shim.Column_String_{String_: originalCircuitBoardBatchId}},
				&shim.Column{Value: &shim.Column_String_{String_: originalWireBatchId}},
				&shim.Column{Value: &shim.Column_String_{String_: originalCasingBatchId}},
				&shim.Column{Value: &shim.Column_String_{String_: originalAdaptorBatchId}},
				&shim.Column{Value: &shim.Column_String_{String_: originalStickPodBatchId}},
				&shim.Column{Value: &shim.Column_String_{String_: assemblyLineStatus}},
			}})

		if err != nil {
			return nil, err
		}
		if !ok && err == nil {
			return nil, errors.New("Row already exists.")
		}

		return nil, nil

}

//Update AssemblyLine status
func (t *SimpleChaincode) updateAssemblyLineStatus(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {

	if len(args) != 2 {
		return nil, errors.New("Incorrect number of arguments. Expecting 2.")
	}
	//else {
	//	return nil, errors.New("Correct number of arguments. Got 2.")
	//}

	assemblyLineId := args[0]
	assemblyLineStatus := args[1]

	// Get the row pertaining to this AssemblyLineId
	var columns []shim.Column
	col1 := shim.Column{Value: &shim.Column_String_{String_: assemblyLineId}}
	columns = append(columns, col1)

	row, err := stub.GetRow("AssemblyLine", columns)
	if err != nil {
		return nil, fmt.Errorf("Error: Failed retrieving AssemblyLine with assemblyLineId %s. Error %s", assemblyLineId, err.Error())
	}

	// GetRows returns empty message if key does not exist
	if len(row.Columns) == 0 {
		return nil, nil
	}

	// Delete the row pertaining to this assemblyLineId
	err = stub.DeleteRow(
		"Assemblyline",
		columns,
	)
	if err != nil {
		return nil, errors.New("Failed deleting row.")
	}

		//assemblyLineId:=row.Columns[0].GetString_()
		serialId:=row.Columns[1].GetString_()
		originalFilamentBatchId:=row.Columns[2].GetString_()
		originalLedBatchId:=row.Columns[3].GetString_()
		originalCircuitBoardBatchId:=row.Columns[4].GetString_()
		originalWireBatchId:=row.Columns[5].GetString_()
		originalCasingBatchId:=row.Columns[6].GetString_()
		originalAdaptorBatchId:=row.Columns[7].GetString_()
		originalStickPodBatchId:=row.Columns[8].GetString_()
		//assemblyLineStatus:= assemblyLineStatus

		// Insert a row
		ok, err := stub.InsertRow("AssemblyLine", shim.Row{
			Columns: []*shim.Column{
				&shim.Column{Value: &shim.Column_String_{String_: assemblyLineId}},
				&shim.Column{Value: &shim.Column_String_{String_: serialId}},
				&shim.Column{Value: &shim.Column_String_{String_: originalFilamentBatchId}},
				&shim.Column{Value: &shim.Column_String_{String_: originalLedBatchId}},
				&shim.Column{Value: &shim.Column_String_{String_: originalCircuitBoardBatchId}},
				&shim.Column{Value: &shim.Column_String_{String_: originalWireBatchId}},
				&shim.Column{Value: &shim.Column_String_{String_: originalCasingBatchId}},
				&shim.Column{Value: &shim.Column_String_{String_: originalAdaptorBatchId}},
				&shim.Column{Value: &shim.Column_String_{String_: originalStickPodBatchId}},
				&shim.Column{Value: &shim.Column_String_{String_: assemblyLineStatus}},
			}})

		if err != nil {
			return nil, err
		}
		if !ok && err == nil {
			return nil, errors.New("Row already exists in Assemblyline.")
		}

	return nil, nil

}

// Invoke callback representing the invocation of a chaincode
// This chaincode will manage two accounts A and B and will transfer X units from A to B upon invoke
func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	fmt.Printf("Invoke called, determining function")

	// Handle different functions
	if function == "init" {
		fmt.Printf("Function is init")
		return t.Init(stub, function, args)
	} else if function == "startAssemblyLine" {
		fmt.Printf("Function is startAssemblyLine")
		return t.startAssemblyLine(stub, args)
	} else if function == "updateAssemblyLineStatus" {
		fmt.Printf("Function is updateAssemblyLineStatus")
		return t.updateAssemblyLineStatus(stub, args)
	}

	return nil, errors.New("Received unknown function invocation")
}

func (t* SimpleChaincode) Run(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	fmt.Printf("Run called, passing through to Invoke (same function)")

	// Handle different functions
	if function == "startAssemblyLine" {
		fmt.Printf("Function is startAssemblyLine")
		return t.startAssemblyLine(stub, args)
	}  else if function == "updateAssemblyLineStatus" {
		fmt.Printf("Function is updateAssemblyLineStatus")
		return t.updateAssemblyLineStatus(stub, args)
	} else if function == "init" {
		fmt.Printf("Function is init")
		return t.Init(stub, function, args)
	}

	return nil, errors.New("Received unknown function invocation")
}

//get the AssemblyLine against ID
func (t *SimpleChaincode) getAssemblyLineByID(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {

	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting AssemblyLineID to query")
	}

	assemblyLineID := args[0]

	// Get the row pertaining to this assemblyLineID
	var columns []shim.Column
	col1 := shim.Column{Value: &shim.Column_String_{String_: assemblyLineID}}
	columns = append(columns, col1)

	row, err := stub.GetRow("AssemblyLine", columns)
	if err != nil {
		jsonResp := "{\"Error\":\"Failed to get the data for the assemblyLineID " + assemblyLineID + "\"}"
		return nil, errors.New(jsonResp)
	}

	// GetRows returns empty message if key does not exist
	if len(row.Columns) == 0 {
		jsonResp := "{\"Error\":\"Failed to get the data for the assemblyLineID " + assemblyLineID + "\"}"
		return nil, errors.New(jsonResp)
	}

	//return []byte (row), nil
	 mapB, _ := json.Marshal(row)
    fmt.Println(string(mapB))

	return mapB, nil

}

//get the status against the AssemblyLineID
func (t *SimpleChaincode) getAssemblyLineStatus(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {

	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting AssemblyLineID to query")
	}

	assemblyLineID := args[0]

	// Get the row pertaining to this assemblyLineID
	var columns []shim.Column
	col1 := shim.Column{Value: &shim.Column_String_{String_: assemblyLineID}}
	columns = append(columns, col1)

	row, err := stub.GetRow("AssemblyLine", columns)
	if err != nil {
		jsonResp := "{\"Error\":\"Failed to get the data for the assemblyLineID " + assemblyLineID + "\"}"
		return nil, errors.New(jsonResp)
	}

	// GetRows returns empty message if key does not exist
	if len(row.Columns) == 0 {
		jsonResp := "{\"Error\":\"Failed to get the data for the assemblyLineID " + assemblyLineID + "\"}"
		return nil, errors.New(jsonResp)
	}

	res2E := GetAssemblyLineStatus{}

	res2E.AssemblyLineStatus = row.Columns[9].GetString_()

  /*
    mapB, _ := json.Marshal(res2E)
    fmt.Println(string(mapB))
	return mapB, nil
  */

    return []byte (res2E.AssemblyLineStatus), nil

}

//get all AssemblyLines
func (t *SimpleChaincode) getAllAssemblyLines(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
var columns []shim.Column

	rows, err := stub.GetRows("AssemblyLine", columns)
	if err != nil {
		return nil, fmt.Errorf("Failed to retrieve row")
	}

	res2E:= []*AssemblyLine{}

	for row := range rows {
		newApp:= new(AssemblyLine)
		newApp.AssemblyLineId = row.Columns[0].GetString_()
		newApp.SerialId = row.Columns[1].GetString_()
		newApp.OriginalFilamentBatchId = row.Columns[2].GetString_()
		newApp.OriginalLedBatchId = row.Columns[3].GetString_()
		newApp.OriginalCircuitBoardBatchId = row.Columns[4].GetString_()
		newApp.OriginalWireBatchId = row.Columns[5].GetString_()
		newApp.OriginalCasingBatchId = row.Columns[6].GetString_()
		newApp.OriginalAdaptorBatchId = row.Columns[7].GetString_()
		newApp.OriginalStickPodBatchId = row.Columns[8].GetString_()
		newApp.AssemblyLineStatus = row.Columns[9].GetString_()

		if len(newApp.AssemblyLineId) > 0{
		res2E=append(res2E,newApp)
		}
	}

    mapB, _ := json.Marshal(res2E)
    fmt.Println(string(mapB))

	return mapB, nil

}

// query queries the chaincode
func (t *SimpleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	fmt.Printf("Query called, determining function")

	if function == "getAssemblyLineStatus" {
		t := SimpleChaincode{}
		return t.getAssemblyLineStatus(stub, args)
	} else if function == "getAssemblyLineByID" {
		t := SimpleChaincode{}
		return t.getAssemblyLineByID(stub, args)
	} else if function == "getAllAssemblyLines" {
		t := SimpleChaincode{}
		return t.getAllAssemblyLines(stub, args)
	}

	return nil, errors.New("Received unknown function query")
}
//iQOS Changes ends------------------------------------------------------------------------------------------

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


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

package rafttest

import (
	"context"
	"log"
	"sync"
	"time"

	"go.etcd.io/etcd/raft"
	"go.etcd.io/etcd/raft/raftpb"
)

type node struct {
	raft.Node
	id     uint64
	iface  iface
	stopc  chan struct{}
	pausec chan bool

	// stable
	storage *raft.MemoryStorage

	mu    sync.Mutex // guards state
	state raftpb.HardState
}

func startNode(id uint64, peers []raft.Peer, iface iface) *node {
	st := raft.NewMemoryStorage()
	c := &raft.Config{
		ID:                        id,
		ElectionTick:              10,
		HeartbeatTick:             1,
		Storage:                   st,
		MaxSizePerMsg:             1024 * 1024,
		MaxInflightMsgs:           256,
		MaxUncommittedEntriesSize: 1 << 30,
	}
	rn := raft.StartNode(c, peers)
	n := &node{
		Node:    rn,
		id:      id,
		storage: st,
		iface:   iface,
		pausec:  make(chan bool),
	}
	n.start()
	return n
}

func (n *node) start() {
	n.stopc = make(chan struct{})
	ticker := time.Tick(5 * time.Millisecond)

	go func() {
		for {
			select {
			case <-ticker:
				n.Tick()
			case rd := <-n.Ready():
				if !raft.IsEmptyHardState(rd.HardState) {
					n.mu.Lock()
					n.state = rd.HardState
					n.mu.Unlock()
					n.storage.SetHardState(n.state)
				}
				n.storage.Append(rd.Entries)
				time.Sleep(time.Millisecond)
				// TODO: make send async, more like real world...
				for _, m := range rd.Messages {
					n.iface.send(m)
				}
				n.Advance()
			case m := <-n.iface.recv():
				go n.Step(context.TODO(), m)
			case <-n.stopc:
				n.Stop()
				log.Printf("raft.%d: stop", n.id)
				n.Node = nil
				close(n.stopc)
				return
			case p := <-n.pausec:
				recvms := make([]raftpb.Message, 0)
				for p {
					select {
					case m := <-n.iface.recv():
						recvms = append(recvms, m)
					case p = <-n.pausec:
					}
				}
				// step all pending messages
				for _, m := range recvms {
					n.Step(context.TODO(), m)
				}
			}
		}
	}()
}

// stop stops the node. stop a stopped node might panic.
// All in memory state of node is discarded.
// All stable MUST be unchanged.
func (n *node) stop() {
	n.iface.disconnect()
	n.stopc <- struct{}{}
	// wait for the shutdown
	<-n.stopc
}

// restart restarts the node. restart a started node
// blocks and might affect the future stop operation.
func (n *node) restart() {
	// wait for the shutdown
	<-n.stopc
	c := &raft.Config{
		ID:                        n.id,
		ElectionTick:              10,
		HeartbeatTick:             1,
		Storage:                   n.storage,
		MaxSizePerMsg:             1024 * 1024,
		MaxInflightMsgs:           256,
		MaxUncommittedEntriesSize: 1 << 30,
	}
	n.Node = raft.RestartNode(c)
	n.start()
	n.iface.connect()
}

// pause pauses the node.
// The paused node buffers the received messages and replies
// all of them when it resumes.
func (n *node) pause() {
	n.pausec <- true
}

// resume resumes the paused node.
func (n *node) resume() {
	n.pausec <- false
}
<commit_msg>raft/rafttest: simulate async send in node test<commit_after>// Copyright 2015 The etcd Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package rafttest

import (
	"context"
	"log"
	"math/rand"
	"sync"
	"time"

	"go.etcd.io/etcd/raft"
	"go.etcd.io/etcd/raft/raftpb"
)

type node struct {
	raft.Node
	id     uint64
	iface  iface
	stopc  chan struct{}
	pausec chan bool

	// stable
	storage *raft.MemoryStorage

	mu    sync.Mutex // guards state
	state raftpb.HardState
}

func startNode(id uint64, peers []raft.Peer, iface iface) *node {
	st := raft.NewMemoryStorage()
	c := &raft.Config{
		ID:                        id,
		ElectionTick:              10,
		HeartbeatTick:             1,
		Storage:                   st,
		MaxSizePerMsg:             1024 * 1024,
		MaxInflightMsgs:           256,
		MaxUncommittedEntriesSize: 1 << 30,
	}
	rn := raft.StartNode(c, peers)
	n := &node{
		Node:    rn,
		id:      id,
		storage: st,
		iface:   iface,
		pausec:  make(chan bool),
	}
	n.start()
	return n
}

func (n *node) start() {
	n.stopc = make(chan struct{})
	ticker := time.Tick(5 * time.Millisecond)

	go func() {
		for {
			select {
			case <-ticker:
				n.Tick()
			case rd := <-n.Ready():
				if !raft.IsEmptyHardState(rd.HardState) {
					n.mu.Lock()
					n.state = rd.HardState
					n.mu.Unlock()
					n.storage.SetHardState(n.state)
				}
				n.storage.Append(rd.Entries)
				time.Sleep(time.Millisecond)

				// simulate async send, more like real world...
				for _, m := range rd.Messages {
					mlocal := m
					go func() {
						time.Sleep(time.Duration(rand.Int63n(10)) * time.Millisecond)
						n.iface.send(mlocal)
					}()
				}
				n.Advance()
			case m := <-n.iface.recv():
				go n.Step(context.TODO(), m)
			case <-n.stopc:
				n.Stop()
				log.Printf("raft.%d: stop", n.id)
				n.Node = nil
				close(n.stopc)
				return
			case p := <-n.pausec:
				recvms := make([]raftpb.Message, 0)
				for p {
					select {
					case m := <-n.iface.recv():
						recvms = append(recvms, m)
					case p = <-n.pausec:
					}
				}
				// step all pending messages
				for _, m := range recvms {
					n.Step(context.TODO(), m)
				}
			}
		}
	}()
}

// stop stops the node. stop a stopped node might panic.
// All in memory state of node is discarded.
// All stable MUST be unchanged.
func (n *node) stop() {
	n.iface.disconnect()
	n.stopc <- struct{}{}
	// wait for the shutdown
	<-n.stopc
}

// restart restarts the node. restart a started node
// blocks and might affect the future stop operation.
func (n *node) restart() {
	// wait for the shutdown
	<-n.stopc
	c := &raft.Config{
		ID:                        n.id,
		ElectionTick:              10,
		HeartbeatTick:             1,
		Storage:                   n.storage,
		MaxSizePerMsg:             1024 * 1024,
		MaxInflightMsgs:           256,
		MaxUncommittedEntriesSize: 1 << 30,
	}
	n.Node = raft.RestartNode(c)
	n.start()
	n.iface.connect()
}

// pause pauses the node.
// The paused node buffers the received messages and replies
// all of them when it resumes.
func (n *node) pause() {
	n.pausec <- true
}

// resume resumes the paused node.
func (n *node) resume() {
	n.pausec <- false
}
<|endoftext|>


<commit_before>package node

import (
	"encoding/hex"
	"io"
)

type NodeAddress string

func (n NodeAddress) MarshalText() ([]byte, error) {
	s := hex.EncodeToString([]byte(n))
	return []byte(s), nil
}
func (n *NodeAddress) UnmarshalText(b []byte) error {
	s, err := hex.DecodeString(string(b))
	*n = NodeAddress(string(s))
	return err
}

type PacketHash string

// Layer three interfaces for network control traffic
type MapConnection interface {
	SendMap(BloomReachabilityMap) error
	ReachabilityMaps() <-chan BloomReachabilityMap
}
type ReceiptConnection interface {
	SendReceipt(PacketReceipt) error
	PacketReceipts() <-chan PacketReceipt
}
type PaymentConnection interface {
	SendPayment(PaymentHash) error
	Payments() <-chan PaymentHash
}

// While the two connections use different messages, a working ControlConnection has both interfaces
type ControlConnection interface {
	MapConnection
	ReceiptConnection
	PaymentConnection
}

// The actual data connection. Should be done at the layer two level in order to be able to send congestion signals
type DataConnection interface {
	SendPacket(Packet) error
	Packets() <-chan Packet
}

type Connection interface {
	ControlConnection
	DataConnection
	Key() PublicKey
	io.Closer
}
<commit_msg>Make packet hash marshall correctly<commit_after>package node

import (
	"encoding/hex"
	"io"
)

type NodeAddress string

func (n NodeAddress) MarshalText() ([]byte, error) {
	s := hex.EncodeToString([]byte(n))
	return []byte(s), nil
}
func (n *NodeAddress) UnmarshalText(b []byte) error {
	s, err := hex.DecodeString(string(b))
	*n = NodeAddress(string(s))
	return err
}

type PacketHash string

func (n PacketHash) MarshalText() ([]byte, error) {
	s := hex.EncodeToString([]byte(n))
	return []byte(s), nil
}
func (n *PacketHash) UnmarshalText(b []byte) error {
	s, err := hex.DecodeString(string(b))
	*n = PacketHash(string(s))
	return err
}

// Layer three interfaces for network control traffic
type MapConnection interface {
	SendMap(BloomReachabilityMap) error
	ReachabilityMaps() <-chan BloomReachabilityMap
}
type ReceiptConnection interface {
	SendReceipt(PacketReceipt) error
	PacketReceipts() <-chan PacketReceipt
}
type PaymentConnection interface {
	SendPayment(PaymentHash) error
	Payments() <-chan PaymentHash
}

// While the two connections use different messages, a working ControlConnection has both interfaces
type ControlConnection interface {
	MapConnection
	ReceiptConnection
	PaymentConnection
}

// The actual data connection. Should be done at the layer two level in order to be able to send congestion signals
type DataConnection interface {
	SendPacket(Packet) error
	Packets() <-chan Packet
}

type Connection interface {
	ControlConnection
	DataConnection
	Key() PublicKey
	io.Closer
}
<|endoftext|>


<commit_before>package mocks

import (
	"net/http"

	"github.com/drone/drone/model"
	"github.com/stretchr/testify/mock"
)

// Remote is an autogenerated mock type for the Remote type
type Remote struct {
	mock.Mock
}

// Activate provides a mock function with given fields: u, r, link
func (_m *Remote) Activate(u *model.User, r *model.Repo, link string) error {
	ret := _m.Called(u, r, link)

	var r0 error
	if rf, ok := ret.Get(0).(func(*model.User, *model.Repo, string) error); ok {
		r0 = rf(u, r, link)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}

// Auth provides a mock function with given fields: token, secret
func (_m *Remote) Auth(token string, secret string) (string, error) {
	ret := _m.Called(token, secret)

	var r0 string
	if rf, ok := ret.Get(0).(func(string, string) string); ok {
		r0 = rf(token, secret)
	} else {
		r0 = ret.Get(0).(string)
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(string, string) error); ok {
		r1 = rf(token, secret)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

// Deactivate provides a mock function with given fields: u, r, link
func (_m *Remote) Deactivate(u *model.User, r *model.Repo, link string) error {
	ret := _m.Called(u, r, link)

	var r0 error
	if rf, ok := ret.Get(0).(func(*model.User, *model.Repo, string) error); ok {
		r0 = rf(u, r, link)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}

// File provides a mock function with given fields: u, r, b, f
func (_m *Remote) File(u *model.User, r *model.Repo, b *model.Build, f string) ([]byte, error) {
	ret := _m.Called(u, r, b, f)

	var r0 []byte
	if rf, ok := ret.Get(0).(func(*model.User, *model.Repo, *model.Build, string) []byte); ok {
		r0 = rf(u, r, b, f)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).([]byte)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(*model.User, *model.Repo, *model.Build, string) error); ok {
		r1 = rf(u, r, b, f)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

// FileRef provides a mock function with given fields: u, r, ref, f
func (_m *Remote) FileRef(u *model.User, r *model.Repo, ref string, f string) ([]byte, error) {
	ret := _m.Called(u, r, ref, f)

	var r0 []byte
	if rf, ok := ret.Get(0).(func(*model.User, *model.Repo, string, string) []byte); ok {
		r0 = rf(u, r, ref, f)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).([]byte)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(*model.User, *model.Repo, string, string) error); ok {
		r1 = rf(u, r, ref, f)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

// Hook provides a mock function with given fields: r
func (_m *Remote) Hook(r *http.Request) (*model.Repo, *model.Build, error) {
	ret := _m.Called(r)

	var r0 *model.Repo
	if rf, ok := ret.Get(0).(func(*http.Request) *model.Repo); ok {
		r0 = rf(r)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(*model.Repo)
		}
	}

	var r1 *model.Build
	if rf, ok := ret.Get(1).(func(*http.Request) *model.Build); ok {
		r1 = rf(r)
	} else {
		if ret.Get(1) != nil {
			r1 = ret.Get(1).(*model.Build)
		}
	}

	var r2 error
	if rf, ok := ret.Get(2).(func(*http.Request) error); ok {
		r2 = rf(r)
	} else {
		r2 = ret.Error(2)
	}

	return r0, r1, r2
}

// Login provides a mock function with given fields: w, r
func (_m *Remote) Login(w http.ResponseWriter, r *http.Request) (*model.User, error) {
	ret := _m.Called(w, r)

	var r0 *model.User
	if rf, ok := ret.Get(0).(func(http.ResponseWriter, *http.Request) *model.User); ok {
		r0 = rf(w, r)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(*model.User)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(http.ResponseWriter, *http.Request) error); ok {
		r1 = rf(w, r)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

// Netrc provides a mock function with given fields: u, r
func (_m *Remote) Netrc(u *model.User, r *model.Repo) (*model.Netrc, error) {
	ret := _m.Called(u, r)

	var r0 *model.Netrc
	if rf, ok := ret.Get(0).(func(*model.User, *model.Repo) *model.Netrc); ok {
		r0 = rf(u, r)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(*model.Netrc)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(*model.User, *model.Repo) error); ok {
		r1 = rf(u, r)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

// Perm provides a mock function with given fields: u, owner, repo
func (_m *Remote) Perm(u *model.User, owner string, repo string) (*model.Perm, error) {
	ret := _m.Called(u, owner, repo)

	var r0 *model.Perm
	if rf, ok := ret.Get(0).(func(*model.User, string, string) *model.Perm); ok {
		r0 = rf(u, owner, repo)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(*model.Perm)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(*model.User, string, string) error); ok {
		r1 = rf(u, owner, repo)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

// Repo provides a mock function with given fields: u, owner, repo
func (_m *Remote) Repo(u *model.User, owner string, repo string) (*model.Repo, error) {
	ret := _m.Called(u, owner, repo)

	var r0 *model.Repo
	if rf, ok := ret.Get(0).(func(*model.User, string, string) *model.Repo); ok {
		r0 = rf(u, owner, repo)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(*model.Repo)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(*model.User, string, string) error); ok {
		r1 = rf(u, owner, repo)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

// Repos provides a mock function with given fields: u
func (_m *Remote) Repos(u *model.User) ([]*model.RepoLite, error) {
	ret := _m.Called(u)

	var r0 []*model.RepoLite
	if rf, ok := ret.Get(0).(func(*model.User) []*model.RepoLite); ok {
		r0 = rf(u)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).([]*model.RepoLite)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(*model.User) error); ok {
		r1 = rf(u)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

// Status provides a mock function with given fields: u, r, b, link
func (_m *Remote) Status(u *model.User, r *model.Repo, b *model.Build, link string) error {
	ret := _m.Called(u, r, b, link)

	var r0 error
	if rf, ok := ret.Get(0).(func(*model.User, *model.Repo, *model.Build, string) error); ok {
		r0 = rf(u, r, b, link)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}

// TeamPerm provides a mock function with given fields: u, org
func (_m *Remote) TeamPerm(u *model.User, org string) (*model.Perm, error) {
	ret := _m.Called(u, org)

	var r0 *model.Perm
	if rf, ok := ret.Get(0).(func(*model.User, string) *model.Perm); ok {
		r0 = rf(u, org)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(*model.Perm)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(*model.User, string) error); ok {
		r1 = rf(u, org)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

// Teams provides a mock function with given fields: u
func (_m *Remote) Teams(u *model.User) ([]*model.Team, error) {
	ret := _m.Called(u)

	var r0 []*model.Team
	if rf, ok := ret.Get(0).(func(*model.User) []*model.Team); ok {
		r0 = rf(u)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).([]*model.Team)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(*model.User) error); ok {
		r1 = rf(u)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
<commit_msg>fix mock package name<commit_after>package mock

import (
	"net/http"

	"github.com/drone/drone/model"
	"github.com/stretchr/testify/mock"
)

// Remote is an autogenerated mock type for the Remote type
type Remote struct {
	mock.Mock
}

// Activate provides a mock function with given fields: u, r, link
func (_m *Remote) Activate(u *model.User, r *model.Repo, link string) error {
	ret := _m.Called(u, r, link)

	var r0 error
	if rf, ok := ret.Get(0).(func(*model.User, *model.Repo, string) error); ok {
		r0 = rf(u, r, link)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}

// Auth provides a mock function with given fields: token, secret
func (_m *Remote) Auth(token string, secret string) (string, error) {
	ret := _m.Called(token, secret)

	var r0 string
	if rf, ok := ret.Get(0).(func(string, string) string); ok {
		r0 = rf(token, secret)
	} else {
		r0 = ret.Get(0).(string)
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(string, string) error); ok {
		r1 = rf(token, secret)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

// Deactivate provides a mock function with given fields: u, r, link
func (_m *Remote) Deactivate(u *model.User, r *model.Repo, link string) error {
	ret := _m.Called(u, r, link)

	var r0 error
	if rf, ok := ret.Get(0).(func(*model.User, *model.Repo, string) error); ok {
		r0 = rf(u, r, link)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}

// File provides a mock function with given fields: u, r, b, f
func (_m *Remote) File(u *model.User, r *model.Repo, b *model.Build, f string) ([]byte, error) {
	ret := _m.Called(u, r, b, f)

	var r0 []byte
	if rf, ok := ret.Get(0).(func(*model.User, *model.Repo, *model.Build, string) []byte); ok {
		r0 = rf(u, r, b, f)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).([]byte)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(*model.User, *model.Repo, *model.Build, string) error); ok {
		r1 = rf(u, r, b, f)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

// FileRef provides a mock function with given fields: u, r, ref, f
func (_m *Remote) FileRef(u *model.User, r *model.Repo, ref string, f string) ([]byte, error) {
	ret := _m.Called(u, r, ref, f)

	var r0 []byte
	if rf, ok := ret.Get(0).(func(*model.User, *model.Repo, string, string) []byte); ok {
		r0 = rf(u, r, ref, f)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).([]byte)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(*model.User, *model.Repo, string, string) error); ok {
		r1 = rf(u, r, ref, f)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

// Hook provides a mock function with given fields: r
func (_m *Remote) Hook(r *http.Request) (*model.Repo, *model.Build, error) {
	ret := _m.Called(r)

	var r0 *model.Repo
	if rf, ok := ret.Get(0).(func(*http.Request) *model.Repo); ok {
		r0 = rf(r)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(*model.Repo)
		}
	}

	var r1 *model.Build
	if rf, ok := ret.Get(1).(func(*http.Request) *model.Build); ok {
		r1 = rf(r)
	} else {
		if ret.Get(1) != nil {
			r1 = ret.Get(1).(*model.Build)
		}
	}

	var r2 error
	if rf, ok := ret.Get(2).(func(*http.Request) error); ok {
		r2 = rf(r)
	} else {
		r2 = ret.Error(2)
	}

	return r0, r1, r2
}

// Login provides a mock function with given fields: w, r
func (_m *Remote) Login(w http.ResponseWriter, r *http.Request) (*model.User, error) {
	ret := _m.Called(w, r)

	var r0 *model.User
	if rf, ok := ret.Get(0).(func(http.ResponseWriter, *http.Request) *model.User); ok {
		r0 = rf(w, r)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(*model.User)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(http.ResponseWriter, *http.Request) error); ok {
		r1 = rf(w, r)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

// Netrc provides a mock function with given fields: u, r
func (_m *Remote) Netrc(u *model.User, r *model.Repo) (*model.Netrc, error) {
	ret := _m.Called(u, r)

	var r0 *model.Netrc
	if rf, ok := ret.Get(0).(func(*model.User, *model.Repo) *model.Netrc); ok {
		r0 = rf(u, r)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(*model.Netrc)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(*model.User, *model.Repo) error); ok {
		r1 = rf(u, r)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

// Perm provides a mock function with given fields: u, owner, repo
func (_m *Remote) Perm(u *model.User, owner string, repo string) (*model.Perm, error) {
	ret := _m.Called(u, owner, repo)

	var r0 *model.Perm
	if rf, ok := ret.Get(0).(func(*model.User, string, string) *model.Perm); ok {
		r0 = rf(u, owner, repo)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(*model.Perm)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(*model.User, string, string) error); ok {
		r1 = rf(u, owner, repo)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

// Repo provides a mock function with given fields: u, owner, repo
func (_m *Remote) Repo(u *model.User, owner string, repo string) (*model.Repo, error) {
	ret := _m.Called(u, owner, repo)

	var r0 *model.Repo
	if rf, ok := ret.Get(0).(func(*model.User, string, string) *model.Repo); ok {
		r0 = rf(u, owner, repo)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(*model.Repo)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(*model.User, string, string) error); ok {
		r1 = rf(u, owner, repo)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

// Repos provides a mock function with given fields: u
func (_m *Remote) Repos(u *model.User) ([]*model.RepoLite, error) {
	ret := _m.Called(u)

	var r0 []*model.RepoLite
	if rf, ok := ret.Get(0).(func(*model.User) []*model.RepoLite); ok {
		r0 = rf(u)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).([]*model.RepoLite)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(*model.User) error); ok {
		r1 = rf(u)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

// Status provides a mock function with given fields: u, r, b, link
func (_m *Remote) Status(u *model.User, r *model.Repo, b *model.Build, link string) error {
	ret := _m.Called(u, r, b, link)

	var r0 error
	if rf, ok := ret.Get(0).(func(*model.User, *model.Repo, *model.Build, string) error); ok {
		r0 = rf(u, r, b, link)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}

// TeamPerm provides a mock function with given fields: u, org
func (_m *Remote) TeamPerm(u *model.User, org string) (*model.Perm, error) {
	ret := _m.Called(u, org)

	var r0 *model.Perm
	if rf, ok := ret.Get(0).(func(*model.User, string) *model.Perm); ok {
		r0 = rf(u, org)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(*model.Perm)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(*model.User, string) error); ok {
		r1 = rf(u, org)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

// Teams provides a mock function with given fields: u
func (_m *Remote) Teams(u *model.User) ([]*model.Team, error) {
	ret := _m.Called(u)

	var r0 []*model.Team
	if rf, ok := ret.Get(0).(func(*model.User) []*model.Team); ok {
		r0 = rf(u)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).([]*model.Team)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(*model.User) error); ok {
		r1 = rf(u)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
<|endoftext|>


<commit_before>package repository

import (
	"errors"
	"io/ioutil"
	"os"
	"path/filepath"
)

// Manager keeps track of indivudal repositories.
type Manager struct {
	basePath string
}

// NewManager returns a new manager instance.
func NewManager(basePath string) (*Manager, error) {
	stat, err := os.Stat(basePath)
	if err != nil {
		return nil, err
	}
	if !stat.IsDir() {
		return nil, errors.New("not a directory")
	}
	return &Manager{basePath: basePath}, nil
}

// ListNames returns the names of all registered repositories.
func (m *Manager) ListNames() ([]string, error) {
	entries, err := ioutil.ReadDir(m.basePath)
	if err != nil {
		return nil, err
	}
	res := make([]string, 0)
	for _, e := range entries {
		if !e.IsDir() {
			continue
		}
		res = append(res, e.Name())
	}
	return res, nil
}

// Create registers a new repository.
func (m *Manager) Create(name string, pubKey []byte) error {
	r := &Repository{Path: filepath.Join(m.basePath, name)}
	err := r.Create()
	if err != nil {
		return err
	}
	return r.SetAuthPubkey(pubKey)
}

// Open returns a handle for the given existing repository.
func (m *Manager) Open(name string) (*Repository, error) {
	absPath := filepath.Join(m.basePath, name)
	r := &Repository{Path: absPath}
	s, err := os.Stat(absPath)
	if err != nil {
		return nil, err
	}
	if !s.IsDir() {
		return nil, errors.New("not a directory")
	}
	return r, nil
}

// Returns if the repository with the given name exists
func (m *Manager) Exists(name string) bool {
	r, _ := m.Open(name)
	return r != nil
}
<commit_msg>repository: fix golint warning<commit_after>package repository

import (
	"errors"
	"io/ioutil"
	"os"
	"path/filepath"
)

// Manager keeps track of indivudal repositories.
type Manager struct {
	basePath string
}

// NewManager returns a new manager instance.
func NewManager(basePath string) (*Manager, error) {
	stat, err := os.Stat(basePath)
	if err != nil {
		return nil, err
	}
	if !stat.IsDir() {
		return nil, errors.New("not a directory")
	}
	return &Manager{basePath: basePath}, nil
}

// ListNames returns the names of all registered repositories.
func (m *Manager) ListNames() ([]string, error) {
	entries, err := ioutil.ReadDir(m.basePath)
	if err != nil {
		return nil, err
	}
	res := []string{}
	for _, e := range entries {
		if !e.IsDir() {
			continue
		}
		res = append(res, e.Name())
	}
	return res, nil
}

// Create registers a new repository.
func (m *Manager) Create(name string, pubKey []byte) error {
	r := &Repository{Path: filepath.Join(m.basePath, name)}
	err := r.Create()
	if err != nil {
		return err
	}
	return r.SetAuthPubkey(pubKey)
}

// Open returns a handle for the given existing repository.
func (m *Manager) Open(name string) (*Repository, error) {
	absPath := filepath.Join(m.basePath, name)
	r := &Repository{Path: absPath}
	s, err := os.Stat(absPath)
	if err != nil {
		return nil, err
	}
	if !s.IsDir() {
		return nil, errors.New("not a directory")
	}
	return r, nil
}

// Returns if the repository with the given name exists
func (m *Manager) Exists(name string) bool {
	r, _ := m.Open(name)
	return r != nil
}
<|endoftext|>


<commit_before>package main

import (
	"errors"
	"fmt"
	"strconv"

	"time"

	"github.com/hyperledger/fabric/core/chaincode/shim"
)

var account map[string]int

var logger = shim.NewLogger("ftLogger")

// SampleChaincode struct required to implement the shim.Chaincode interface
type SampleChaincode struct {
}

// Init method is called when the chaincode is first deployed onto the blockchain network
func (t *SampleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	var customerName string // Name of the customer
	var currentBalance int  // Current account balance of the customer
	var err error

	account = make(map[string]int)

	if len(args) != 2 {
		return nil, errors.New("Incorrect number of arguments. Expecting 2")
	}

	// Initialize the chaincode
	customerName = args[0]
	currentBalance, err = strconv.Atoi(args[1])
	if err != nil {
		return nil, errors.New("Expecting integer value for customer account balance: " + err.Error())
	}

	logger.Info("Customer: %s, Available Balance: %d", customerName, currentBalance)

	// Save the Customer info
	account[customerName] = currentBalance

	// Write the state to the ledger
	err = stub.PutState("IBI-CC[init]: "+time.Now().String(), []byte(args[0]))
	if err != nil {
		return nil, err
	}

	return nil, nil
}

// Query method is invoked whenever any read/get/query operation needs to be performed on the blockchain state.
func (t *SampleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	logger.Info("Query is running: " + function)

	// Handle different functions
	if function == "GetAccountBalance" { //read a variable
		return t.getAccountBalance(stub, args)
	}
	logger.Error("Query did not find func: " + function)

	return nil, errors.New("Received unknown function query")
}

// Invoke method is invoked whenever the state of the blockchain is to be modified.
func (t *SampleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	logger.Info("Invoke is running: " + function)

	// Handle different functions
	switch function {
	case "Init":
		return t.Init(stub, "init", args)
	case "Deposit":
		return t.depositFund(stub, args)
	case "Withdraw":
		return t.withdrawFund(stub, args)
	default:
		logger.Error("Invoke did not find func: " + function)
	}

	return nil, errors.New("Received unknown function invocation")
}

func (t *SampleChaincode) getAccountBalance(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
	logger.Info("Running getAccountBalance")
	var name, jsonResp string
	var err error

	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting name of the var to query")
	}

	name = args[0]

	valAsbytes := []byte(strconv.Itoa(account[name]))
	if err != nil {
		jsonResp = "{\"Error\":\"Failed to get account balance for " + name + err.Error() + "\"}"
		return nil, errors.New(jsonResp)
	}

	return valAsbytes, nil
}

func (t *SampleChaincode) depositFund(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
	logger.Info("Running depositFund")

	var name, jsonResp string
	var value, currentBalance, newBalance int
	var err error

	if len(args) != 2 {
		return nil, errors.New("Incorrect number of arguments. Expecting 2. name of the customer and value to set")
	}

	name = args[0]
	value, err = strconv.Atoi(args[1])
	if err != nil {
		jsonResp = "{\"Error\":\"Invalid input argument for deposit amount: " + err.Error() + "\"}"
		return nil, errors.New(jsonResp)
	}

	currentBalance = account[name]
	newBalance = value + currentBalance

	account[name] = newBalance

	return nil, nil
}

func (t *SampleChaincode) withdrawFund(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
	logger.Info("Running withdrawFund")

	var name, jsonResp string
	var value, currentBalance, newBalance int
	var err error

	if len(args) != 2 {
		return nil, errors.New("Incorrect number of arguments. Expecting 2. name of the customer and value to set")
	}

	name = args[0]
	value, err = strconv.Atoi(args[1])
	if err != nil {
		jsonResp = "{\"Error\":\"Invalid input argument for withdraw amount: " + err.Error() + "\"}"
		return nil, errors.New(jsonResp)
	}

	currentBalance = account[name]

	if value > currentBalance {
		jsonResp = "{\"Error\":\"Insufficient Fund in account. Aborting...\"}"
		logger.Error(jsonResp)
		return nil, errors.New(jsonResp)
	}

	newBalance = currentBalance - value

	account[name] = newBalance

	return nil, nil
}

func main() {
	var err error
	lld, _ := shim.LogLevel("DEBUG")
	fmt.Println(lld)

	logger.SetLevel(lld)
	fmt.Println(logger.IsEnabledFor(lld))

	err = shim.Start(new(SampleChaincode))
	if err != nil {
		fmt.Println("Could not start SampleChaincode")
	} else {
		fmt.Println("SampleChaincode successfully started")
	}
}
<commit_msg>fixed a bug<commit_after>package main

import (
	"errors"
	"fmt"
	"strconv"

	"time"

	"github.com/hyperledger/fabric/core/chaincode/shim"
)

var account = make(map[string]int)

var logger = shim.NewLogger("ftLogger")

// SampleChaincode struct required to implement the shim.Chaincode interface
type SampleChaincode struct {
}

// Init method is called when the chaincode is first deployed onto the blockchain network
func (t *SampleChaincode) Init(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	var customerName string // Name of the customer
	var currentBalance int  // Current account balance of the customer
	var err error

	if len(args) != 2 {
		return nil, errors.New("Incorrect number of arguments. Expecting 2")
	}

	// Initialize the chaincode
	customerName = args[0]
	currentBalance, err = strconv.Atoi(args[1])
	if err != nil {
		return nil, errors.New("Expecting integer value for customer account balance: " + err.Error())
	}

	logger.Info("Customer: %s, Available Balance: %d", customerName, currentBalance)

	// Save the Customer info
	account[customerName] = currentBalance

	// Write the state to the ledger
	err = stub.PutState("IBI-CC[init]: "+time.Now().String(), []byte(args[0]))
	if err != nil {
		return nil, err
	}

	return nil, nil
}

// Query method is invoked whenever any read/get/query operation needs to be performed on the blockchain state.
func (t *SampleChaincode) Query(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	logger.Info("Query is running: " + function)

	// Handle different functions
	if function == "GetAccountBalance" { //read a variable
		return t.getAccountBalance(stub, args)
	}
	logger.Error("Query did not find func: " + function)

	return nil, errors.New("Received unknown function query")
}

// Invoke method is invoked whenever the state of the blockchain is to be modified.
func (t *SampleChaincode) Invoke(stub shim.ChaincodeStubInterface, function string, args []string) ([]byte, error) {
	logger.Info("Invoke is running: " + function)

	// Handle different functions
	switch function {
	case "Init":
		return t.Init(stub, "init", args)
	case "Deposit":
		return t.depositFund(stub, args)
	case "Withdraw":
		return t.withdrawFund(stub, args)
	default:
		logger.Error("Invoke did not find func: " + function)
	}

	return nil, errors.New("Received unknown function invocation")
}

func (t *SampleChaincode) getAccountBalance(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
	logger.Info("Running getAccountBalance")
	var name string

	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting name of the var to query")
	}

	name = args[0]

	valAsbytes := []byte(strconv.Itoa(account[name]))

	return valAsbytes, nil
}

func (t *SampleChaincode) depositFund(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
	logger.Info("Running depositFund")

	var name, jsonResp string
	var value, currentBalance, newBalance int
	var err error

	if len(args) != 2 {
		return nil, errors.New("Incorrect number of arguments. Expecting 2. name of the customer and value to set")
	}

	name = args[0]
	value, err = strconv.Atoi(args[1])
	if err != nil {
		jsonResp = "{\"Error\":\"Invalid input argument for deposit amount: " + err.Error() + "\"}"
		return nil, errors.New(jsonResp)
	}

	currentBalance = account[name]
	newBalance = value + currentBalance

	account[name] = newBalance

	valAsbytes := []byte(strconv.Itoa(account[name]))

	return valAsbytes, nil
}

func (t *SampleChaincode) withdrawFund(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
	logger.Info("Running withdrawFund")

	var name, jsonResp string
	var value, currentBalance, newBalance int
	var err error

	if len(args) != 2 {
		return nil, errors.New("Incorrect number of arguments. Expecting 2. name of the customer and value to set")
	}

	name = args[0]
	value, err = strconv.Atoi(args[1])
	if err != nil {
		jsonResp = "{\"Error\":\"Invalid input argument for withdraw amount: " + err.Error() + "\"}"
		return nil, errors.New(jsonResp)
	}

	currentBalance = account[name]

	if value > currentBalance {
		jsonResp = "{\"Error\":\"Insufficient Fund in account. Aborting...\"}"
		logger.Error(jsonResp)
		return nil, errors.New(jsonResp)
	}

	newBalance = currentBalance - value

	account[name] = newBalance

	valAsbytes := []byte(strconv.Itoa(account[name]))

	return valAsbytes, nil
}

func main() {
	var err error
	lld, _ := shim.LogLevel("DEBUG")
	fmt.Println(lld)

	logger.SetLevel(lld)
	fmt.Println(logger.IsEnabledFor(lld))

	err = shim.Start(new(SampleChaincode))
	if err != nil {
		fmt.Println("Could not start SampleChaincode")
	} else {
		fmt.Println("SampleChaincode successfully started")
	}
}
<|endoftext|>


<commit_before>package wuxia

import (
	"encoding/json"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"

	"github.com/gocraft/health"
	"github.com/robertkrimen/otto"
	"github.com/robertkrimen/otto/underscore"
	"github.com/spf13/afero"
	// load underscore for otto runtime.
)

var stream *health.Stream

func init() {
	stream = health.NewStream()
}

const (
	scriptsDir = "scripts"
	initDir    = "init"
	planDir    = "plan"
	configFile = "config.json"
	indexFile  = "index.js"
)

//BuildStage the step in the generation process life cycle.
type BuildStage int

// available stages offered by the generator
const (
	StageInit BuildStage = iota
	StageConfig
	StagePlan
	StageExec
)

func (s BuildStage) String() string {
	var rst string
	switch s {
	case StageInit:
		rst = "init"
	case StageConfig:
		rst = "config"
	case StagePlan:
		rst = "plan"
	case StageExec:
		rst = "exec"
	default:
		rst = "unkown stage"
	}
	return rst
}

//buildError error returned when building the static website. The error string
//returned is a json string that encodes the build stage and the message.
type buildError struct {
	Stage   string `json:"stage"`
	Message string `json:"msg"`
}

func buildErr(stage BuildStage, msg string) error {
	return &buildError{Stage: stage.String(), Message: msg}
}

func (b *buildError) Error() string {
	o, err := json.Marshal(b)
	if err != nil {
		return err.Error()
	}
	return string(o)
}

//Generator provides the static website generation capabilities.This is heavily
//integrated with the otto javascript runtime.
type Generator struct {
	vm  *otto.Otto
	sys *System
	fs  afero.Fs

	// This is the absolute path to the root of the project from which the
	// Generator will be operating.
	workDir string
	job     *health.Job

	Verbose bool

	// when the verbose option is set to true. Here is where the ;og information
	// will be written to.
	Out io.Writer
}

//NewGenerator retrunes a new  Generator.
func NewGenerator(vm *otto.Otto, sys *System, fs afero.Fs) *Generator {
	return &Generator{
		vm:  vm,
		sys: sys,
		fs:  fs,
	}
}

//Init initializes the build process. Any stages after this will have the generator
//already bootstraped.
//
// It is possible to bootstrap the generator from the project( User's side) by
// providing an entry javascript file in the default path of
// scripts/init/index.js which will be executed and you can overide the default
// entry script which is evaluated internally
//
// Initialzation is offloaded to the javascript runtine of the generator..Any
// error returned is a build error.
func (g *Generator) Init() error {
	if g.Verbose {
		g.job.Event("initializing_generator")
	}
	_ = g.vm.Set("sys", func(call otto.FunctionCall) otto.Value {
		data, err := json.Marshal(g.sys)
		if err != nil {
			panicOtto(err)
		}
		val, err := call.Otto.Call("JSON.parse", nil, string(data))
		if err != nil {
			panicOtto(err)
		}
		return val
	})
	_, err := g.vm.Eval(entryScript())
	if err != nil {
		return buildErr(StageInit, err.Error())
	}

	_ = g.vm.Set("fileTree", fileTree(g.fs, g.workDir))

	// evaluate project provided entry script if provided. We ignore if the file
	// is not provided but any errors arsing from evaluating a provided script is
	// a built error.
	entryFile := filepath.Join(scriptsDir, initDir, indexFile)
	err = g.evaluateFile(entryFile)
	if err != nil {
		if !os.IsNotExist(err) {
			return buildErr(StageInit, err.Error())
		}
	}
	if g.Verbose {
		g.job.EventKv("initializing_generator.complete",
			health.Kvs{
				"project": g.sys.Config.Name,
			})
	}
	return nil
}

//fileTree provides an array of all files found in the root( which is suppose to
//be the working directory.
//
//The file index is built only once and evaluated once too, then it is cached.
//This operates in the otto runtime.
func fileTree(fs afero.Fs, root string) func(otto.FunctionCall) otto.Value {
	var tree []string
	var v otto.Value
	return func(call otto.FunctionCall) otto.Value {
		if tree != nil {
			return v
		}
		ferr := afero.Walk(fs, "/", func(path string, info os.FileInfo, err error) error {
			if err != nil {
				return err
			}
			if !info.IsDir() {
				tree = append(tree, path)
			}
			return nil
		})
		if ferr != nil {
			tree = nil
			panicOtto(ferr.Error())
		}
		v, _ = call.Otto.ToValue(tree)
		return v
	}
}

func defaultSystem() *System {
	return &System{
		Boot: &Boot{
			ConfigiFile: configFile,
			PlanFile:    "index.js",
		},
	}
}

func defaultPlan() *Plan {
	return &Plan{}
}

// opens the file in the specified path and evaluates it withing the context of
// the javascript runtine.
//
// The evaluated javascript code can mutate the global state. Use execFile to
// execute the javascript without mutating the state of the generato'r
// javascript runtime.
//
// TODO: (gernest) implement callFile if necessary
func (g *Generator) evaluateFile(path string) error {
	f, err := g.fs.Open(path)
	if err != nil {
		return err
	}
	defer func() { _ = f.Close() }()
	data, err := ioutil.ReadAll(f)
	if err != nil {
		return err
	}
	_, err = g.vm.Eval(data)
	if err != nil {
		return err
	}
	return nil
}

func defaultVM(sys *System) *otto.Otto {
	return otto.New()
}

//Config configures the generator.
func (g *Generator) Config() error {
	// Properly set working directory/
	if g.workDir == "" {
		wd, err := os.Getwd()
		if err != nil {
			return buildErr(StageInit, err.Error())
		}
		g.workDir = wd
	}

	if g.Verbose {
		if g.Out == nil {
			g.Out = os.Stdout
		}
		if stream.Sinks == nil {
			stream.AddSink(&health.WriterSink{Writer: g.Out})
		}
		g.job = stream.NewJob("generate:" + g.workDir)
		g.job.Event("configuring_generator")
	}
	if g.sys == nil {
		g.sys = defaultSystem()
	}
	if g.vm == nil {
		g.vm = defaultVM(g.sys)
	}

	// ensure everything is relative to the working directory
	// The working directory is where the  directory in which the project to be
	// built lives.
	//
	// All file operations, happens within the diretory. So to access the
	// configuration file for example it is located in /config.json.
	g.fs = afero.NewBasePathFs(g.fs, g.workDir)
	af := afero.Afero{Fs: g.fs}
	data, err := af.ReadFile(configFile)
	if err != nil {
		return buildErr(StageInit, err.Error())
	}
	cfg := &Config{}
	err = json.Unmarshal(data, cfg)
	if err != nil {
		return buildErr(StageInit, err.Error())
	}
	g.sys.Config = cfg

	// Add reuire
	req := newRequire(g.fs, scriptsDir)
	err = g.registerBuiltin(req)
	if err != nil {
		return buildErr(StageInit, err.Error())
	}
	_ = g.vm.Set("require", req.load)
	if g.Verbose {
		g.job.EventKv("configuring__generator.complete",
			health.Kvs{
				"project": g.sys.Config.Name,
			})
	}
	return nil
}

//Plan is the planning phase of the generator. First a project specific plan
//file is evaluated, the file is loacetd in /scripts_dir/plan_fir/index.js for
//example /scripts/plan/index.js. Second the existing system plan is merged with
//default plan.
//
//TODO: Use user defined plan only when it is set, and use default plan only
//when there is no user defined plan.
//
// This is executed to prepare the Plan object, which is the blueprint on how
// the whole execution is going to take place.
func (g *Generator) Plan() error {
	pFile := filepath.Join(scriptsDir, planDir, indexFile)
	err := g.evaluateFile(pFile)
	if err != nil {
		if !os.IsNotExist(err) {
			return buildErr(StagePlan, err.Error())
		}
	}
	v, err := g.vm.Call("getCurrentSys", nil)
	if err != nil {
		return buildErr(StagePlan, err.Error())
	}
	str, err := v.ToString()
	if err != nil {
		return buildErr(StagePlan, err.Error())
	}
	sys := &System{}
	err = json.Unmarshal([]byte(str), sys)
	if err != nil {
		return buildErr(StagePlan, err.Error())
	}
	g.sys = sys
	if g.sys.Plan == nil {
		g.sys.Plan = defaultPlan()
	}
	return nil
}

//Exec executes the plans that are outilend by the Plan method. The Plan method
//should be called before this.
func (g *Generator) Exec() error {
	o, err := g.vm.Call("fileTree", nil)
	if err != nil {
		return buildErr(StageExec, err.Error())
	}
	ov, err := o.Export()
	if err != nil {
		return buildErr(StageExec, err.Error())
	}
	if ov == nil {
		// No files to mess with
	}
	files, ok := ov.([]string)
	if !ok {
		// Some fish
	}
	var list FileList
	p := g.sys.Plan
	for i := range files {
		s, err := p.FindStrategy(files[i])
		if err != nil {
			continue
		}
		f, err := g.execStrategy(files[i], s)
		if err != nil {
			return buildErr(StageExec, err.Error())
		}
		list = append(list, f)
	}
	return g.execPlan(list, p)
}

func (g *Generator) execStrategy(filePath string, s *Strategy) (*File, error) {
	return nil, nil
}

func (g *Generator) execPlan(a FileList, p *Plan) error {
	return nil
}

func (g *Generator) down() error {
	return nil
}

func (g *Generator) registerBuiltin(r *require) error {
	f := &fileSys{}
	f.Fs = g.fs
	v := f.export().ToValue(g.vm)
	r.addToCache("fs", v)
	r.addToCache("markdown", markdown().ToValue(g.vm))
	v, err := otto.New().Run(underscore.Source())
	if err != nil {
		return err
	}
	r.addToCache("underscore", v)
	return nil
}
<commit_msg>Add doc<commit_after>package wuxia

import (
	"encoding/json"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"

	"github.com/gocraft/health"
	"github.com/robertkrimen/otto"
	"github.com/robertkrimen/otto/underscore"
	"github.com/spf13/afero"
	// load underscore for otto runtime.
)

var stream *health.Stream

func init() {
	stream = health.NewStream()
}

const (
	scriptsDir = "scripts"
	initDir    = "init"
	planDir    = "plan"
	configFile = "config.json"
	indexFile  = "index.js"
)

//BuildStage the step in the generation process life cycle.
type BuildStage int

// available stages offered by the generator
const (
	StageInit BuildStage = iota
	StageConfig
	StagePlan
	StageExec
)

func (s BuildStage) String() string {
	var rst string
	switch s {
	case StageInit:
		rst = "init"
	case StageConfig:
		rst = "config"
	case StagePlan:
		rst = "plan"
	case StageExec:
		rst = "exec"
	default:
		rst = "unkown stage"
	}
	return rst
}

//buildError error returned when building the static website. The error string
//returned is a json string that encodes the build stage and the message.
type buildError struct {
	Stage   string `json:"stage"`
	Message string `json:"msg"`
}

func buildErr(stage BuildStage, msg string) error {
	return &buildError{Stage: stage.String(), Message: msg}
}

func (b *buildError) Error() string {
	o, err := json.Marshal(b)
	if err != nil {
		return err.Error()
	}
	return string(o)
}

//Generator provides the static website generation capabilities.This is heavily
//integrated with the otto javascript runtime.
type Generator struct {
	vm  *otto.Otto
	sys *System
	fs  afero.Fs

	// This is the absolute path to the root of the project from which the
	// Generator will be operating.
	workDir string
	job     *health.Job

	Verbose bool

	// when the verbose option is set to true. Here is where the ;og information
	// will be written to.
	Out io.Writer
}

//NewGenerator retrunes a new  Generator.
func NewGenerator(vm *otto.Otto, sys *System, fs afero.Fs) *Generator {
	return &Generator{
		vm:  vm,
		sys: sys,
		fs:  fs,
	}
}

//Init initializes the build process. Any stages after this will have the generator
//already bootstraped.
//
// It is possible to bootstrap the generator from the project( User's side) by
// providing an entry javascript file in the default path of
// scripts/init/index.js which will be executed and you can overide the default
// entry script which is evaluated internally
//
// Initialzation is offloaded to the javascript runtine of the generator..Any
// error returned is a build error.
func (g *Generator) Init() error {
	if g.Verbose {
		g.job.Event("initializing_generator")
	}
	_ = g.vm.Set("sys", func(call otto.FunctionCall) otto.Value {
		data, err := json.Marshal(g.sys)
		if err != nil {
			panicOtto(err)
		}
		val, err := call.Otto.Call("JSON.parse", nil, string(data))
		if err != nil {
			panicOtto(err)
		}
		return val
	})
	_, err := g.vm.Eval(entryScript())
	if err != nil {
		return buildErr(StageInit, err.Error())
	}

	_ = g.vm.Set("fileTree", fileTree(g.fs, g.workDir))

	// evaluate project provided entry script if provided. We ignore if the file
	// is not provided but any errors arsing from evaluating a provided script is
	// a built error.
	entryFile := filepath.Join(scriptsDir, initDir, indexFile)
	err = g.evaluateFile(entryFile)
	if err != nil {
		if !os.IsNotExist(err) {
			return buildErr(StageInit, err.Error())
		}
	}
	if g.Verbose {
		g.job.EventKv("initializing_generator.complete",
			health.Kvs{
				"project": g.sys.Config.Name,
			})
	}
	return nil
}

//fileTree provides an array of all files found in the root( which is suppose to
//be the working directory.
//
//The file index is built only once and evaluated once too, then it is cached.
//This operates in the otto runtime.
func fileTree(fs afero.Fs, root string) func(otto.FunctionCall) otto.Value {
	var tree []string
	var v otto.Value
	return func(call otto.FunctionCall) otto.Value {
		if tree != nil {
			return v
		}
		ferr := afero.Walk(fs, "/", func(path string, info os.FileInfo, err error) error {
			if err != nil {
				return err
			}
			if !info.IsDir() {
				tree = append(tree, path)
			}
			return nil
		})
		if ferr != nil {
			tree = nil
			panicOtto(ferr.Error())
		}
		v, _ = call.Otto.ToValue(tree)
		return v
	}
}

func defaultSystem() *System {
	return &System{
		Boot: &Boot{
			ConfigiFile: configFile,
			PlanFile:    "index.js",
		},
	}
}

func defaultPlan() *Plan {
	return &Plan{}
}

// opens the file in the specified path and evaluates it withing the context of
// the javascript runtine.
//
// The evaluated javascript code can mutate the global state. Use execFile to
// execute the javascript without mutating the state of the generato'r
// javascript runtime.
//
// TODO: (gernest) implement callFile if necessary
func (g *Generator) evaluateFile(path string) error {
	f, err := g.fs.Open(path)
	if err != nil {
		return err
	}
	defer func() { _ = f.Close() }()
	data, err := ioutil.ReadAll(f)
	if err != nil {
		return err
	}
	_, err = g.vm.Eval(data)
	if err != nil {
		return err
	}
	return nil
}

func defaultVM(sys *System) *otto.Otto {
	return otto.New()
}

//Config configures the generator.
func (g *Generator) Config() error {
	// Properly set working directory/
	if g.workDir == "" {
		wd, err := os.Getwd()
		if err != nil {
			return buildErr(StageInit, err.Error())
		}
		g.workDir = wd
	}

	if g.Verbose {
		if g.Out == nil {
			g.Out = os.Stdout
		}
		if stream.Sinks == nil {
			stream.AddSink(&health.WriterSink{Writer: g.Out})
		}
		g.job = stream.NewJob("generate:" + g.workDir)
		g.job.Event("configuring_generator")
	}
	if g.sys == nil {
		g.sys = defaultSystem()
	}
	if g.vm == nil {
		g.vm = defaultVM(g.sys)
	}

	// ensure everything is relative to the working directory
	// The working directory is where the  directory in which the project to be
	// built lives.
	//
	// All file operations, happens within the diretory. So to access the
	// configuration file for example it is located in /config.json.
	g.fs = afero.NewBasePathFs(g.fs, g.workDir)
	af := afero.Afero{Fs: g.fs}
	data, err := af.ReadFile(configFile)
	if err != nil {
		return buildErr(StageInit, err.Error())
	}
	cfg := &Config{}
	err = json.Unmarshal(data, cfg)
	if err != nil {
		return buildErr(StageInit, err.Error())
	}
	g.sys.Config = cfg

	// Add reuire
	req := newRequire(g.fs, scriptsDir)
	err = g.registerBuiltin(req)
	if err != nil {
		return buildErr(StageInit, err.Error())
	}
	_ = g.vm.Set("require", req.load)
	if g.Verbose {
		g.job.EventKv("configuring__generator.complete",
			health.Kvs{
				"project": g.sys.Config.Name,
			})
	}
	return nil
}

//Plan is the planning phase of the generator. First a project specific plan
//file is evaluated, the file is loacetd in /scripts_dir/plan_fir/index.js for
//example /scripts/plan/index.js. Second the existing system plan is merged with
//default plan.
//
//TODO: Use user defined plan only when it is set, and use default plan only
//when there is no user defined plan.
//
// This is executed to prepare the Plan object, which is the blueprint on how
// the whole execution is going to take place.
func (g *Generator) Plan() error {
	pFile := filepath.Join(scriptsDir, planDir, indexFile)
	err := g.evaluateFile(pFile)
	if err != nil {
		if !os.IsNotExist(err) {
			return buildErr(StagePlan, err.Error())
		}
	}
	v, err := g.vm.Call("getCurrentSys", nil)
	if err != nil {
		return buildErr(StagePlan, err.Error())
	}
	str, err := v.ToString()
	if err != nil {
		return buildErr(StagePlan, err.Error())
	}
	sys := &System{}
	err = json.Unmarshal([]byte(str), sys)
	if err != nil {
		return buildErr(StagePlan, err.Error())
	}
	g.sys = sys
	if g.sys.Plan == nil {
		g.sys.Plan = defaultPlan()
	}
	return nil
}

//Exec executes the plans that are outilend by the Plan method. The Plan method
//should be called before this.
//
// Execution is done in two phases. First the files are evaluated using the
// matching plans. Plans are per file. Secondly the rendering of the site is
// done.
//
// Evaluation of files is done concurrently, then the results are aggregated
// back together.
//
// Rendering is done synchronously. As there is a lot of cross refences and
// stuffs to be considered, the rendering function is provided by the plan.
func (g *Generator) Exec() error {
	o, err := g.vm.Call("fileTree", nil)
	if err != nil {
		return buildErr(StageExec, err.Error())
	}
	ov, err := o.Export()
	if err != nil {
		return buildErr(StageExec, err.Error())
	}
	if ov == nil {
		// No files to mess with
	}
	files, ok := ov.([]string)
	if !ok {
		// Some fish
	}
	var list FileList
	p := g.sys.Plan
	for i := range files {
		s, err := p.FindStrategy(files[i])
		if err != nil {
			continue
		}
		f, err := g.execStrategy(files[i], s)
		if err != nil {
			return buildErr(StageExec, err.Error())
		}
		list = append(list, f)
	}
	return g.execPlan(list, p)
}

func (g *Generator) execStrategy(filePath string, s *Strategy) (*File, error) {
	return nil, nil
}

func (g *Generator) execPlan(a FileList, p *Plan) error {
	return nil
}

func (g *Generator) down() error {
	return nil
}

func (g *Generator) registerBuiltin(r *require) error {
	f := &fileSys{}
	f.Fs = g.fs
	v := f.export().ToValue(g.vm)
	r.addToCache("fs", v)
	r.addToCache("markdown", markdown().ToValue(g.vm))
	v, err := otto.New().Run(underscore.Source())
	if err != nil {
		return err
	}
	r.addToCache("underscore", v)
	return nil
}
<|endoftext|>