repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
hyperledger/burrow
vent/sqlsol/projection.go
NewProjectionFromFolder
func NewProjectionFromFolder(specFileOrDirs ...string) (*Projection, error) { eventSpec := types.EventSpec{} const errHeader = "NewProjectionFromFolder():" for _, dir := range specFileOrDirs { err := filepath.Walk(dir, func(path string, _ os.FileInfo, err error) error { if err != nil { return fmt.Errorf("error walking event spec files location '%s': %v", dir, err) } if filepath.Ext(path) == ".json" { bs, err := readFile(path) if err != nil { return fmt.Errorf("error reading spec file '%s': %v", path, err) } err = ValidateJSONEventSpec(bs) if err != nil { return fmt.Errorf("could not validate spec file '%s': %v", path, err) } fileEventSpec := types.EventSpec{} err = json.Unmarshal(bs, &fileEventSpec) if err != nil { return fmt.Errorf("error reading spec file '%s': %v", path, err) } eventSpec = append(eventSpec, fileEventSpec...) } return nil }) if err != nil { return nil, fmt.Errorf("%s %v", errHeader, err) } } return NewProjectionFromEventSpec(eventSpec) }
go
func NewProjectionFromFolder(specFileOrDirs ...string) (*Projection, error) { eventSpec := types.EventSpec{} const errHeader = "NewProjectionFromFolder():" for _, dir := range specFileOrDirs { err := filepath.Walk(dir, func(path string, _ os.FileInfo, err error) error { if err != nil { return fmt.Errorf("error walking event spec files location '%s': %v", dir, err) } if filepath.Ext(path) == ".json" { bs, err := readFile(path) if err != nil { return fmt.Errorf("error reading spec file '%s': %v", path, err) } err = ValidateJSONEventSpec(bs) if err != nil { return fmt.Errorf("could not validate spec file '%s': %v", path, err) } fileEventSpec := types.EventSpec{} err = json.Unmarshal(bs, &fileEventSpec) if err != nil { return fmt.Errorf("error reading spec file '%s': %v", path, err) } eventSpec = append(eventSpec, fileEventSpec...) } return nil }) if err != nil { return nil, fmt.Errorf("%s %v", errHeader, err) } } return NewProjectionFromEventSpec(eventSpec) }
[ "func", "NewProjectionFromFolder", "(", "specFileOrDirs", "...", "string", ")", "(", "*", "Projection", ",", "error", ")", "{", "eventSpec", ":=", "types", ".", "EventSpec", "{", "}", "\n", "const", "errHeader", "=", "\"NewProjectionFromFolder():\"", "\n", "for", "_", ",", "dir", ":=", "range", "specFileOrDirs", "{", "err", ":=", "filepath", ".", "Walk", "(", "dir", ",", "func", "(", "path", "string", ",", "_", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"error walking event spec files location '%s': %v\"", ",", "dir", ",", "err", ")", "\n", "}", "\n", "if", "filepath", ".", "Ext", "(", "path", ")", "==", "\".json\"", "{", "bs", ",", "err", ":=", "readFile", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"error reading spec file '%s': %v\"", ",", "path", ",", "err", ")", "\n", "}", "\n", "err", "=", "ValidateJSONEventSpec", "(", "bs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"could not validate spec file '%s': %v\"", ",", "path", ",", "err", ")", "\n", "}", "\n", "fileEventSpec", ":=", "types", ".", "EventSpec", "{", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "bs", ",", "&", "fileEventSpec", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"error reading spec file '%s': %v\"", ",", "path", ",", "err", ")", "\n", "}", "\n", "eventSpec", "=", "append", "(", "eventSpec", ",", "fileEventSpec", "...", ")", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"%s %v\"", ",", "errHeader", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "NewProjectionFromEventSpec", "(", "eventSpec", ")", "\n", "}" ]
// NewProjectionFromFolder creates a Projection from a folder containing spec files
[ "NewProjectionFromFolder", "creates", "a", "Projection", "from", "a", "folder", "containing", "spec", "files" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/sqlsol/projection.go#L43-L81
train
hyperledger/burrow
vent/sqlsol/projection.go
NewProjectionFromEventSpec
func NewProjectionFromEventSpec(eventSpec types.EventSpec) (*Projection, error) { // builds abi information from specification tables := make(types.EventTables) // obtain global field mappings to add to table definitions globalFieldMappings := getGlobalFieldMappings() for _, eventClass := range eventSpec { // validate json structure if err := eventClass.Validate(); err != nil { return nil, fmt.Errorf("validation error on %v: %v", eventClass, err) } // build columns mapping var columns []*types.SQLTableColumn channels := make(map[string][]string) // Add the global mappings eventClass.FieldMappings = append(globalFieldMappings, eventClass.FieldMappings...) i := 0 for _, mapping := range eventClass.FieldMappings { sqlType, sqlTypeLength, err := getSQLType(mapping.Type, mapping.BytesToString) if err != nil { return nil, err } i++ // Update channels broadcast payload subsets with this column for _, channel := range mapping.Notify { channels[channel] = append(channels[channel], mapping.ColumnName) } columns = append(columns, &types.SQLTableColumn{ Name: mapping.ColumnName, Type: sqlType, Primary: mapping.Primary, Length: sqlTypeLength, }) } // Allow for compatible composition of tables var err error tables[eventClass.TableName], err = mergeTables(tables[eventClass.TableName], &types.SQLTable{ Name: eventClass.TableName, NotifyChannels: channels, Columns: columns, }) if err != nil { return nil, err } } // check if there are duplicated duplicated column names (for a given table) colName := make(map[string]int) for _, table := range tables { for _, column := range table.Columns { colName[table.Name+column.Name]++ if colName[table.Name+column.Name] > 1 { return nil, fmt.Errorf("duplicated column name: '%s' in table '%s'", column.Name, table.Name) } } } return &Projection{ Tables: tables, EventSpec: eventSpec, }, nil }
go
func NewProjectionFromEventSpec(eventSpec types.EventSpec) (*Projection, error) { // builds abi information from specification tables := make(types.EventTables) // obtain global field mappings to add to table definitions globalFieldMappings := getGlobalFieldMappings() for _, eventClass := range eventSpec { // validate json structure if err := eventClass.Validate(); err != nil { return nil, fmt.Errorf("validation error on %v: %v", eventClass, err) } // build columns mapping var columns []*types.SQLTableColumn channels := make(map[string][]string) // Add the global mappings eventClass.FieldMappings = append(globalFieldMappings, eventClass.FieldMappings...) i := 0 for _, mapping := range eventClass.FieldMappings { sqlType, sqlTypeLength, err := getSQLType(mapping.Type, mapping.BytesToString) if err != nil { return nil, err } i++ // Update channels broadcast payload subsets with this column for _, channel := range mapping.Notify { channels[channel] = append(channels[channel], mapping.ColumnName) } columns = append(columns, &types.SQLTableColumn{ Name: mapping.ColumnName, Type: sqlType, Primary: mapping.Primary, Length: sqlTypeLength, }) } // Allow for compatible composition of tables var err error tables[eventClass.TableName], err = mergeTables(tables[eventClass.TableName], &types.SQLTable{ Name: eventClass.TableName, NotifyChannels: channels, Columns: columns, }) if err != nil { return nil, err } } // check if there are duplicated duplicated column names (for a given table) colName := make(map[string]int) for _, table := range tables { for _, column := range table.Columns { colName[table.Name+column.Name]++ if colName[table.Name+column.Name] > 1 { return nil, fmt.Errorf("duplicated column name: '%s' in table '%s'", column.Name, table.Name) } } } return &Projection{ Tables: tables, EventSpec: eventSpec, }, nil }
[ "func", "NewProjectionFromEventSpec", "(", "eventSpec", "types", ".", "EventSpec", ")", "(", "*", "Projection", ",", "error", ")", "{", "tables", ":=", "make", "(", "types", ".", "EventTables", ")", "\n", "globalFieldMappings", ":=", "getGlobalFieldMappings", "(", ")", "\n", "for", "_", ",", "eventClass", ":=", "range", "eventSpec", "{", "if", "err", ":=", "eventClass", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"validation error on %v: %v\"", ",", "eventClass", ",", "err", ")", "\n", "}", "\n", "var", "columns", "[", "]", "*", "types", ".", "SQLTableColumn", "\n", "channels", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "string", ")", "\n", "eventClass", ".", "FieldMappings", "=", "append", "(", "globalFieldMappings", ",", "eventClass", ".", "FieldMappings", "...", ")", "\n", "i", ":=", "0", "\n", "for", "_", ",", "mapping", ":=", "range", "eventClass", ".", "FieldMappings", "{", "sqlType", ",", "sqlTypeLength", ",", "err", ":=", "getSQLType", "(", "mapping", ".", "Type", ",", "mapping", ".", "BytesToString", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "i", "++", "\n", "for", "_", ",", "channel", ":=", "range", "mapping", ".", "Notify", "{", "channels", "[", "channel", "]", "=", "append", "(", "channels", "[", "channel", "]", ",", "mapping", ".", "ColumnName", ")", "\n", "}", "\n", "columns", "=", "append", "(", "columns", ",", "&", "types", ".", "SQLTableColumn", "{", "Name", ":", "mapping", ".", "ColumnName", ",", "Type", ":", "sqlType", ",", "Primary", ":", "mapping", ".", "Primary", ",", "Length", ":", "sqlTypeLength", ",", "}", ")", "\n", "}", "\n", "var", "err", "error", "\n", "tables", "[", "eventClass", ".", "TableName", "]", ",", "err", "=", "mergeTables", "(", "tables", "[", "eventClass", ".", "TableName", "]", ",", "&", "types", ".", "SQLTable", "{", "Name", ":", "eventClass", ".", "TableName", ",", "NotifyChannels", ":", "channels", ",", "Columns", ":", "columns", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "colName", ":=", "make", "(", "map", "[", "string", "]", "int", ")", "\n", "for", "_", ",", "table", ":=", "range", "tables", "{", "for", "_", ",", "column", ":=", "range", "table", ".", "Columns", "{", "colName", "[", "table", ".", "Name", "+", "column", ".", "Name", "]", "++", "\n", "if", "colName", "[", "table", ".", "Name", "+", "column", ".", "Name", "]", ">", "1", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"duplicated column name: '%s' in table '%s'\"", ",", "column", ".", "Name", ",", "table", ".", "Name", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "&", "Projection", "{", "Tables", ":", "tables", ",", "EventSpec", ":", "eventSpec", ",", "}", ",", "nil", "\n", "}" ]
// NewProjectionFromEventSpec receives a sqlsol event specification // and returns a pointer to a filled projection structure // that contains event types mapped to SQL column types // and Event tables structures with table and columns info
[ "NewProjectionFromEventSpec", "receives", "a", "sqlsol", "event", "specification", "and", "returns", "a", "pointer", "to", "a", "filled", "projection", "structure", "that", "contains", "event", "types", "mapped", "to", "SQL", "column", "types", "and", "Event", "tables", "structures", "with", "table", "and", "columns", "info" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/sqlsol/projection.go#L87-L159
train
hyperledger/burrow
vent/sqlsol/projection.go
GetColumn
func (p *Projection) GetColumn(tableName, columnName string) (*types.SQLTableColumn, error) { if table, ok := p.Tables[tableName]; ok { column := table.GetColumn(columnName) if column == nil { return nil, fmt.Errorf("GetColumn: table '%s' has no column '%s'", tableName, columnName) } return column, nil } return nil, fmt.Errorf("GetColumn: table does not exist projection: %s ", tableName) }
go
func (p *Projection) GetColumn(tableName, columnName string) (*types.SQLTableColumn, error) { if table, ok := p.Tables[tableName]; ok { column := table.GetColumn(columnName) if column == nil { return nil, fmt.Errorf("GetColumn: table '%s' has no column '%s'", tableName, columnName) } return column, nil } return nil, fmt.Errorf("GetColumn: table does not exist projection: %s ", tableName) }
[ "func", "(", "p", "*", "Projection", ")", "GetColumn", "(", "tableName", ",", "columnName", "string", ")", "(", "*", "types", ".", "SQLTableColumn", ",", "error", ")", "{", "if", "table", ",", "ok", ":=", "p", ".", "Tables", "[", "tableName", "]", ";", "ok", "{", "column", ":=", "table", ".", "GetColumn", "(", "columnName", ")", "\n", "if", "column", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"GetColumn: table '%s' has no column '%s'\"", ",", "tableName", ",", "columnName", ")", "\n", "}", "\n", "return", "column", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"GetColumn: table does not exist projection: %s \"", ",", "tableName", ")", "\n", "}" ]
// Get the column for a particular table and column name
[ "Get", "the", "column", "for", "a", "particular", "table", "and", "column", "name" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/sqlsol/projection.go#L162-L173
train
hyperledger/burrow
vent/sqlsol/projection.go
readFile
func readFile(file string) ([]byte, error) { theFile, err := os.Open(file) if err != nil { return nil, err } defer theFile.Close() byteValue, err := ioutil.ReadAll(theFile) if err != nil { return nil, err } return byteValue, nil }
go
func readFile(file string) ([]byte, error) { theFile, err := os.Open(file) if err != nil { return nil, err } defer theFile.Close() byteValue, err := ioutil.ReadAll(theFile) if err != nil { return nil, err } return byteValue, nil }
[ "func", "readFile", "(", "file", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "theFile", ",", "err", ":=", "os", ".", "Open", "(", "file", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "theFile", ".", "Close", "(", ")", "\n", "byteValue", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "theFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "byteValue", ",", "nil", "\n", "}" ]
// readFile opens a given file and reads it contents into a stream of bytes
[ "readFile", "opens", "a", "given", "file", "and", "reads", "it", "contents", "into", "a", "stream", "of", "bytes" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/sqlsol/projection.go#L194-L207
train
hyperledger/burrow
vent/sqlsol/projection.go
getSQLType
func getSQLType(evmSignature string, bytesToString bool) (types.SQLColumnType, int, error) { evmSignature = strings.ToLower(evmSignature) re := regexp.MustCompile("[0-9]+") typeSize, _ := strconv.Atoi(re.FindString(evmSignature)) switch { // solidity address => sql varchar case evmSignature == types.EventFieldTypeAddress: return types.SQLColumnTypeVarchar, 40, nil // solidity bool => sql bool case evmSignature == types.EventFieldTypeBool: return types.SQLColumnTypeBool, 0, nil // solidity bytes => sql bytes // bytesToString == true means there is a string in there so => sql varchar case strings.HasPrefix(evmSignature, types.EventFieldTypeBytes): if bytesToString { return types.SQLColumnTypeVarchar, 40, nil } else { return types.SQLColumnTypeByteA, 0, nil } // solidity string => sql text case evmSignature == types.EventFieldTypeString: return types.SQLColumnTypeText, 0, nil // solidity int or int256 => sql bigint // solidity int <= 32 => sql int // solidity int > 32 => sql numeric case strings.HasPrefix(evmSignature, types.EventFieldTypeInt): if typeSize == 0 || typeSize == 256 { return types.SQLColumnTypeBigInt, 0, nil } if typeSize <= 32 { return types.SQLColumnTypeInt, 0, nil } else { return types.SQLColumnTypeNumeric, 0, nil } // solidity uint or uint256 => sql bigint // solidity uint <= 16 => sql int // solidity uint > 16 => sql numeric case strings.HasPrefix(evmSignature, types.EventFieldTypeUInt): if typeSize == 0 || typeSize == 256 { return types.SQLColumnTypeBigInt, 0, nil } if typeSize <= 16 { return types.SQLColumnTypeInt, 0, nil } else { return types.SQLColumnTypeNumeric, 0, nil } default: return -1, 0, fmt.Errorf("Don't know how to map evmSignature: %s ", evmSignature) } }
go
func getSQLType(evmSignature string, bytesToString bool) (types.SQLColumnType, int, error) { evmSignature = strings.ToLower(evmSignature) re := regexp.MustCompile("[0-9]+") typeSize, _ := strconv.Atoi(re.FindString(evmSignature)) switch { // solidity address => sql varchar case evmSignature == types.EventFieldTypeAddress: return types.SQLColumnTypeVarchar, 40, nil // solidity bool => sql bool case evmSignature == types.EventFieldTypeBool: return types.SQLColumnTypeBool, 0, nil // solidity bytes => sql bytes // bytesToString == true means there is a string in there so => sql varchar case strings.HasPrefix(evmSignature, types.EventFieldTypeBytes): if bytesToString { return types.SQLColumnTypeVarchar, 40, nil } else { return types.SQLColumnTypeByteA, 0, nil } // solidity string => sql text case evmSignature == types.EventFieldTypeString: return types.SQLColumnTypeText, 0, nil // solidity int or int256 => sql bigint // solidity int <= 32 => sql int // solidity int > 32 => sql numeric case strings.HasPrefix(evmSignature, types.EventFieldTypeInt): if typeSize == 0 || typeSize == 256 { return types.SQLColumnTypeBigInt, 0, nil } if typeSize <= 32 { return types.SQLColumnTypeInt, 0, nil } else { return types.SQLColumnTypeNumeric, 0, nil } // solidity uint or uint256 => sql bigint // solidity uint <= 16 => sql int // solidity uint > 16 => sql numeric case strings.HasPrefix(evmSignature, types.EventFieldTypeUInt): if typeSize == 0 || typeSize == 256 { return types.SQLColumnTypeBigInt, 0, nil } if typeSize <= 16 { return types.SQLColumnTypeInt, 0, nil } else { return types.SQLColumnTypeNumeric, 0, nil } default: return -1, 0, fmt.Errorf("Don't know how to map evmSignature: %s ", evmSignature) } }
[ "func", "getSQLType", "(", "evmSignature", "string", ",", "bytesToString", "bool", ")", "(", "types", ".", "SQLColumnType", ",", "int", ",", "error", ")", "{", "evmSignature", "=", "strings", ".", "ToLower", "(", "evmSignature", ")", "\n", "re", ":=", "regexp", ".", "MustCompile", "(", "\"[0-9]+\"", ")", "\n", "typeSize", ",", "_", ":=", "strconv", ".", "Atoi", "(", "re", ".", "FindString", "(", "evmSignature", ")", ")", "\n", "switch", "{", "case", "evmSignature", "==", "types", ".", "EventFieldTypeAddress", ":", "return", "types", ".", "SQLColumnTypeVarchar", ",", "40", ",", "nil", "\n", "case", "evmSignature", "==", "types", ".", "EventFieldTypeBool", ":", "return", "types", ".", "SQLColumnTypeBool", ",", "0", ",", "nil", "\n", "case", "strings", ".", "HasPrefix", "(", "evmSignature", ",", "types", ".", "EventFieldTypeBytes", ")", ":", "if", "bytesToString", "{", "return", "types", ".", "SQLColumnTypeVarchar", ",", "40", ",", "nil", "\n", "}", "else", "{", "return", "types", ".", "SQLColumnTypeByteA", ",", "0", ",", "nil", "\n", "}", "\n", "case", "evmSignature", "==", "types", ".", "EventFieldTypeString", ":", "return", "types", ".", "SQLColumnTypeText", ",", "0", ",", "nil", "\n", "case", "strings", ".", "HasPrefix", "(", "evmSignature", ",", "types", ".", "EventFieldTypeInt", ")", ":", "if", "typeSize", "==", "0", "||", "typeSize", "==", "256", "{", "return", "types", ".", "SQLColumnTypeBigInt", ",", "0", ",", "nil", "\n", "}", "\n", "if", "typeSize", "<=", "32", "{", "return", "types", ".", "SQLColumnTypeInt", ",", "0", ",", "nil", "\n", "}", "else", "{", "return", "types", ".", "SQLColumnTypeNumeric", ",", "0", ",", "nil", "\n", "}", "\n", "case", "strings", ".", "HasPrefix", "(", "evmSignature", ",", "types", ".", "EventFieldTypeUInt", ")", ":", "if", "typeSize", "==", "0", "||", "typeSize", "==", "256", "{", "return", "types", ".", "SQLColumnTypeBigInt", ",", "0", ",", "nil", "\n", "}", "\n", "if", "typeSize", "<=", "16", "{", "return", "types", ".", "SQLColumnTypeInt", ",", "0", ",", "nil", "\n", "}", "else", "{", "return", "types", ".", "SQLColumnTypeNumeric", ",", "0", ",", "nil", "\n", "}", "\n", "default", ":", "return", "-", "1", ",", "0", ",", "fmt", ".", "Errorf", "(", "\"Don't know how to map evmSignature: %s \"", ",", "evmSignature", ")", "\n", "}", "\n", "}" ]
// getSQLType maps event input types with corresponding SQL column types // takes into account related solidity types info and element indexed or hashed
[ "getSQLType", "maps", "event", "input", "types", "with", "corresponding", "SQL", "column", "types", "takes", "into", "account", "related", "solidity", "types", "info", "and", "element", "indexed", "or", "hashed" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/sqlsol/projection.go#L211-L261
train
hyperledger/burrow
vent/sqlsol/projection.go
getGlobalFieldMappings
func getGlobalFieldMappings() []*types.EventFieldMapping { return []*types.EventFieldMapping{ { ColumnName: types.SQLColumnLabelHeight, Field: types.BlockHeightLabel, Type: types.EventFieldTypeString, }, { ColumnName: types.SQLColumnLabelTxHash, Field: types.TxTxHashLabel, Type: types.EventFieldTypeString, }, { ColumnName: types.SQLColumnLabelEventType, Field: types.EventTypeLabel, Type: types.EventFieldTypeString, }, { ColumnName: types.SQLColumnLabelEventName, Field: types.EventNameLabel, Type: types.EventFieldTypeString, }, } }
go
func getGlobalFieldMappings() []*types.EventFieldMapping { return []*types.EventFieldMapping{ { ColumnName: types.SQLColumnLabelHeight, Field: types.BlockHeightLabel, Type: types.EventFieldTypeString, }, { ColumnName: types.SQLColumnLabelTxHash, Field: types.TxTxHashLabel, Type: types.EventFieldTypeString, }, { ColumnName: types.SQLColumnLabelEventType, Field: types.EventTypeLabel, Type: types.EventFieldTypeString, }, { ColumnName: types.SQLColumnLabelEventName, Field: types.EventNameLabel, Type: types.EventFieldTypeString, }, } }
[ "func", "getGlobalFieldMappings", "(", ")", "[", "]", "*", "types", ".", "EventFieldMapping", "{", "return", "[", "]", "*", "types", ".", "EventFieldMapping", "{", "{", "ColumnName", ":", "types", ".", "SQLColumnLabelHeight", ",", "Field", ":", "types", ".", "BlockHeightLabel", ",", "Type", ":", "types", ".", "EventFieldTypeString", ",", "}", ",", "{", "ColumnName", ":", "types", ".", "SQLColumnLabelTxHash", ",", "Field", ":", "types", ".", "TxTxHashLabel", ",", "Type", ":", "types", ".", "EventFieldTypeString", ",", "}", ",", "{", "ColumnName", ":", "types", ".", "SQLColumnLabelEventType", ",", "Field", ":", "types", ".", "EventTypeLabel", ",", "Type", ":", "types", ".", "EventFieldTypeString", ",", "}", ",", "{", "ColumnName", ":", "types", ".", "SQLColumnLabelEventName", ",", "Field", ":", "types", ".", "EventNameLabel", ",", "Type", ":", "types", ".", "EventFieldTypeString", ",", "}", ",", "}", "\n", "}" ]
// getGlobalColumns returns global columns for event table structures, // these columns will be part of every SQL event table to relate data with source events
[ "getGlobalColumns", "returns", "global", "columns", "for", "event", "table", "structures", "these", "columns", "will", "be", "part", "of", "every", "SQL", "event", "table", "to", "relate", "data", "with", "source", "events" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/sqlsol/projection.go#L265-L288
train
hyperledger/burrow
acm/account.go
Copy
func (acc *Account) Copy() *Account { if acc == nil { return nil } accCopy := *acc accCopy.Permissions.Roles = make([]string, len(acc.Permissions.Roles)) copy(accCopy.Permissions.Roles, acc.Permissions.Roles) return &accCopy }
go
func (acc *Account) Copy() *Account { if acc == nil { return nil } accCopy := *acc accCopy.Permissions.Roles = make([]string, len(acc.Permissions.Roles)) copy(accCopy.Permissions.Roles, acc.Permissions.Roles) return &accCopy }
[ "func", "(", "acc", "*", "Account", ")", "Copy", "(", ")", "*", "Account", "{", "if", "acc", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "accCopy", ":=", "*", "acc", "\n", "accCopy", ".", "Permissions", ".", "Roles", "=", "make", "(", "[", "]", "string", ",", "len", "(", "acc", ".", "Permissions", ".", "Roles", ")", ")", "\n", "copy", "(", "accCopy", ".", "Permissions", ".", "Roles", ",", "acc", ".", "Permissions", ".", "Roles", ")", "\n", "return", "&", "accCopy", "\n", "}" ]
// Copies all mutable parts of account
[ "Copies", "all", "mutable", "parts", "of", "account" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/account.go#L103-L111
train
hyperledger/burrow
genesis/spec/genesis_spec.go
GenesisDoc
func (gs *GenesisSpec) GenesisDoc(keyClient keys.KeyClient, generateNodeKeys bool) (*genesis.GenesisDoc, error) { genesisDoc := new(genesis.GenesisDoc) if gs.GenesisTime == nil { genesisDoc.GenesisTime = time.Now() } else { genesisDoc.GenesisTime = *gs.GenesisTime } if gs.ChainName == "" { genesisDoc.ChainName = fmt.Sprintf("BurrowChain_%X", gs.ShortHash()) } else { genesisDoc.ChainName = gs.ChainName } if gs.Params.ProposalThreshold != 0 { genesisDoc.Params.ProposalThreshold = DefaultProposalThreshold } if len(gs.GlobalPermissions) == 0 { genesisDoc.GlobalPermissions = permission.DefaultAccountPermissions.Clone() } else { basePerms, err := permission.BasePermissionsFromStringList(gs.GlobalPermissions) if err != nil { return nil, err } genesisDoc.GlobalPermissions = permission.AccountPermissions{ Base: basePerms, } } templateAccounts := gs.Accounts if len(gs.Accounts) == 0 { templateAccounts = append(templateAccounts, TemplateAccount{ Amounts: balance.New().Power(DefaultPower), }) } for i, templateAccount := range templateAccounts { account, err := templateAccount.GenesisAccount(keyClient, i) if err != nil { return nil, fmt.Errorf("could not create Account from template: %v", err) } genesisDoc.Accounts = append(genesisDoc.Accounts, *account) if templateAccount.Balances().HasPower() { // Note this does not modify the input template templateAccount.Address = &account.Address validator, err := templateAccount.Validator(keyClient, i, generateNodeKeys) if err != nil { return nil, fmt.Errorf("could not create Validator from template: %v", err) } genesisDoc.Validators = append(genesisDoc.Validators, *validator) } } return genesisDoc, nil }
go
func (gs *GenesisSpec) GenesisDoc(keyClient keys.KeyClient, generateNodeKeys bool) (*genesis.GenesisDoc, error) { genesisDoc := new(genesis.GenesisDoc) if gs.GenesisTime == nil { genesisDoc.GenesisTime = time.Now() } else { genesisDoc.GenesisTime = *gs.GenesisTime } if gs.ChainName == "" { genesisDoc.ChainName = fmt.Sprintf("BurrowChain_%X", gs.ShortHash()) } else { genesisDoc.ChainName = gs.ChainName } if gs.Params.ProposalThreshold != 0 { genesisDoc.Params.ProposalThreshold = DefaultProposalThreshold } if len(gs.GlobalPermissions) == 0 { genesisDoc.GlobalPermissions = permission.DefaultAccountPermissions.Clone() } else { basePerms, err := permission.BasePermissionsFromStringList(gs.GlobalPermissions) if err != nil { return nil, err } genesisDoc.GlobalPermissions = permission.AccountPermissions{ Base: basePerms, } } templateAccounts := gs.Accounts if len(gs.Accounts) == 0 { templateAccounts = append(templateAccounts, TemplateAccount{ Amounts: balance.New().Power(DefaultPower), }) } for i, templateAccount := range templateAccounts { account, err := templateAccount.GenesisAccount(keyClient, i) if err != nil { return nil, fmt.Errorf("could not create Account from template: %v", err) } genesisDoc.Accounts = append(genesisDoc.Accounts, *account) if templateAccount.Balances().HasPower() { // Note this does not modify the input template templateAccount.Address = &account.Address validator, err := templateAccount.Validator(keyClient, i, generateNodeKeys) if err != nil { return nil, fmt.Errorf("could not create Validator from template: %v", err) } genesisDoc.Validators = append(genesisDoc.Validators, *validator) } } return genesisDoc, nil }
[ "func", "(", "gs", "*", "GenesisSpec", ")", "GenesisDoc", "(", "keyClient", "keys", ".", "KeyClient", ",", "generateNodeKeys", "bool", ")", "(", "*", "genesis", ".", "GenesisDoc", ",", "error", ")", "{", "genesisDoc", ":=", "new", "(", "genesis", ".", "GenesisDoc", ")", "\n", "if", "gs", ".", "GenesisTime", "==", "nil", "{", "genesisDoc", ".", "GenesisTime", "=", "time", ".", "Now", "(", ")", "\n", "}", "else", "{", "genesisDoc", ".", "GenesisTime", "=", "*", "gs", ".", "GenesisTime", "\n", "}", "\n", "if", "gs", ".", "ChainName", "==", "\"\"", "{", "genesisDoc", ".", "ChainName", "=", "fmt", ".", "Sprintf", "(", "\"BurrowChain_%X\"", ",", "gs", ".", "ShortHash", "(", ")", ")", "\n", "}", "else", "{", "genesisDoc", ".", "ChainName", "=", "gs", ".", "ChainName", "\n", "}", "\n", "if", "gs", ".", "Params", ".", "ProposalThreshold", "!=", "0", "{", "genesisDoc", ".", "Params", ".", "ProposalThreshold", "=", "DefaultProposalThreshold", "\n", "}", "\n", "if", "len", "(", "gs", ".", "GlobalPermissions", ")", "==", "0", "{", "genesisDoc", ".", "GlobalPermissions", "=", "permission", ".", "DefaultAccountPermissions", ".", "Clone", "(", ")", "\n", "}", "else", "{", "basePerms", ",", "err", ":=", "permission", ".", "BasePermissionsFromStringList", "(", "gs", ".", "GlobalPermissions", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "genesisDoc", ".", "GlobalPermissions", "=", "permission", ".", "AccountPermissions", "{", "Base", ":", "basePerms", ",", "}", "\n", "}", "\n", "templateAccounts", ":=", "gs", ".", "Accounts", "\n", "if", "len", "(", "gs", ".", "Accounts", ")", "==", "0", "{", "templateAccounts", "=", "append", "(", "templateAccounts", ",", "TemplateAccount", "{", "Amounts", ":", "balance", ".", "New", "(", ")", ".", "Power", "(", "DefaultPower", ")", ",", "}", ")", "\n", "}", "\n", "for", "i", ",", "templateAccount", ":=", "range", "templateAccounts", "{", "account", ",", "err", ":=", "templateAccount", ".", "GenesisAccount", "(", "keyClient", ",", "i", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"could not create Account from template: %v\"", ",", "err", ")", "\n", "}", "\n", "genesisDoc", ".", "Accounts", "=", "append", "(", "genesisDoc", ".", "Accounts", ",", "*", "account", ")", "\n", "if", "templateAccount", ".", "Balances", "(", ")", ".", "HasPower", "(", ")", "{", "templateAccount", ".", "Address", "=", "&", "account", ".", "Address", "\n", "validator", ",", "err", ":=", "templateAccount", ".", "Validator", "(", "keyClient", ",", "i", ",", "generateNodeKeys", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"could not create Validator from template: %v\"", ",", "err", ")", "\n", "}", "\n", "genesisDoc", ".", "Validators", "=", "append", "(", "genesisDoc", ".", "Validators", ",", "*", "validator", ")", "\n", "}", "\n", "}", "\n", "return", "genesisDoc", ",", "nil", "\n", "}" ]
// Produce a fully realised GenesisDoc from a template GenesisDoc that may omit values
[ "Produce", "a", "fully", "realised", "GenesisDoc", "from", "a", "template", "GenesisDoc", "that", "may", "omit", "values" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/genesis/spec/genesis_spec.go#L50-L106
train
hyperledger/burrow
acm/validator/set.go
SetPower
func (vs *Set) SetPower(id crypto.PublicKey, power *big.Int) error { vs.ChangePower(id, power) return nil }
go
func (vs *Set) SetPower(id crypto.PublicKey, power *big.Int) error { vs.ChangePower(id, power) return nil }
[ "func", "(", "vs", "*", "Set", ")", "SetPower", "(", "id", "crypto", ".", "PublicKey", ",", "power", "*", "big", ".", "Int", ")", "error", "{", "vs", ".", "ChangePower", "(", "id", ",", "power", ")", "\n", "return", "nil", "\n", "}" ]
// Implements Writer, but will never error
[ "Implements", "Writer", "but", "will", "never", "error" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/validator/set.go#L44-L47
train
hyperledger/burrow
acm/validator/set.go
ChangePower
func (vs *Set) ChangePower(id crypto.PublicKey, power *big.Int) *big.Int { address := id.GetAddress() // Calculate flow into this validator (positive means in, negative means out) flow := vs.Flow(id, power) vs.totalPower.Add(vs.totalPower, flow) if vs.trim && power.Sign() == 0 { delete(vs.publicKeys, address) delete(vs.powers, address) } else { vs.publicKeys[address] = crypto.NewAddressable(id) vs.powers[address] = new(big.Int).Set(power) } return flow }
go
func (vs *Set) ChangePower(id crypto.PublicKey, power *big.Int) *big.Int { address := id.GetAddress() // Calculate flow into this validator (positive means in, negative means out) flow := vs.Flow(id, power) vs.totalPower.Add(vs.totalPower, flow) if vs.trim && power.Sign() == 0 { delete(vs.publicKeys, address) delete(vs.powers, address) } else { vs.publicKeys[address] = crypto.NewAddressable(id) vs.powers[address] = new(big.Int).Set(power) } return flow }
[ "func", "(", "vs", "*", "Set", ")", "ChangePower", "(", "id", "crypto", ".", "PublicKey", ",", "power", "*", "big", ".", "Int", ")", "*", "big", ".", "Int", "{", "address", ":=", "id", ".", "GetAddress", "(", ")", "\n", "flow", ":=", "vs", ".", "Flow", "(", "id", ",", "power", ")", "\n", "vs", ".", "totalPower", ".", "Add", "(", "vs", ".", "totalPower", ",", "flow", ")", "\n", "if", "vs", ".", "trim", "&&", "power", ".", "Sign", "(", ")", "==", "0", "{", "delete", "(", "vs", ".", "publicKeys", ",", "address", ")", "\n", "delete", "(", "vs", ".", "powers", ",", "address", ")", "\n", "}", "else", "{", "vs", ".", "publicKeys", "[", "address", "]", "=", "crypto", ".", "NewAddressable", "(", "id", ")", "\n", "vs", ".", "powers", "[", "address", "]", "=", "new", "(", "big", ".", "Int", ")", ".", "Set", "(", "power", ")", "\n", "}", "\n", "return", "flow", "\n", "}" ]
// Add the power of a validator and returns the flow into that validator
[ "Add", "the", "power", "of", "a", "validator", "and", "returns", "the", "flow", "into", "that", "validator" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/validator/set.go#L50-L64
train
hyperledger/burrow
acm/validator/set.go
Flow
func (vs *Set) Flow(id crypto.PublicKey, power *big.Int) *big.Int { return new(big.Int).Sub(power, vs.GetPower(id.GetAddress())) }
go
func (vs *Set) Flow(id crypto.PublicKey, power *big.Int) *big.Int { return new(big.Int).Sub(power, vs.GetPower(id.GetAddress())) }
[ "func", "(", "vs", "*", "Set", ")", "Flow", "(", "id", "crypto", ".", "PublicKey", ",", "power", "*", "big", ".", "Int", ")", "*", "big", ".", "Int", "{", "return", "new", "(", "big", ".", "Int", ")", ".", "Sub", "(", "power", ",", "vs", ".", "GetPower", "(", "id", ".", "GetAddress", "(", ")", ")", ")", "\n", "}" ]
// Returns the flow that would be induced by a validator power change
[ "Returns", "the", "flow", "that", "would", "be", "induced", "by", "a", "validator", "power", "change" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/validator/set.go#L79-L81
train
hyperledger/burrow
acm/validator/set.go
MaybePower
func (vs *Set) MaybePower(id crypto.Address) *big.Int { if vs.powers[id] == nil { return nil } return new(big.Int).Set(vs.powers[id]) }
go
func (vs *Set) MaybePower(id crypto.Address) *big.Int { if vs.powers[id] == nil { return nil } return new(big.Int).Set(vs.powers[id]) }
[ "func", "(", "vs", "*", "Set", ")", "MaybePower", "(", "id", "crypto", ".", "Address", ")", "*", "big", ".", "Int", "{", "if", "vs", ".", "powers", "[", "id", "]", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "new", "(", "big", ".", "Int", ")", ".", "Set", "(", "vs", ".", "powers", "[", "id", "]", ")", "\n", "}" ]
// Returns the power of id but only if it is set
[ "Returns", "the", "power", "of", "id", "but", "only", "if", "it", "is", "set" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/validator/set.go#L84-L89
train
hyperledger/burrow
acm/validator/set.go
Power
func (vs *Set) Power(id crypto.Address) (*big.Int, error) { return vs.GetPower(id), nil }
go
func (vs *Set) Power(id crypto.Address) (*big.Int, error) { return vs.GetPower(id), nil }
[ "func", "(", "vs", "*", "Set", ")", "Power", "(", "id", "crypto", ".", "Address", ")", "(", "*", "big", ".", "Int", ",", "error", ")", "{", "return", "vs", ".", "GetPower", "(", "id", ")", ",", "nil", "\n", "}" ]
// Version of Power to match interface
[ "Version", "of", "Power", "to", "match", "interface" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/validator/set.go#L92-L94
train
hyperledger/burrow
acm/validator/set.go
Equal
func (vs *Set) Equal(vsOther *Set) error { if vs.Size() != vsOther.Size() { return fmt.Errorf("set size %d != other set size %d", vs.Size(), vsOther.Size()) } // Stop iteration IFF we find a non-matching validator return vs.IterateValidators(func(id crypto.Addressable, power *big.Int) error { otherPower := vsOther.GetPower(id.GetAddress()) if otherPower.Cmp(power) != 0 { return fmt.Errorf("set power %d != other set power %d", power, otherPower) } return nil }) }
go
func (vs *Set) Equal(vsOther *Set) error { if vs.Size() != vsOther.Size() { return fmt.Errorf("set size %d != other set size %d", vs.Size(), vsOther.Size()) } // Stop iteration IFF we find a non-matching validator return vs.IterateValidators(func(id crypto.Addressable, power *big.Int) error { otherPower := vsOther.GetPower(id.GetAddress()) if otherPower.Cmp(power) != 0 { return fmt.Errorf("set power %d != other set power %d", power, otherPower) } return nil }) }
[ "func", "(", "vs", "*", "Set", ")", "Equal", "(", "vsOther", "*", "Set", ")", "error", "{", "if", "vs", ".", "Size", "(", ")", "!=", "vsOther", ".", "Size", "(", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"set size %d != other set size %d\"", ",", "vs", ".", "Size", "(", ")", ",", "vsOther", ".", "Size", "(", ")", ")", "\n", "}", "\n", "return", "vs", ".", "IterateValidators", "(", "func", "(", "id", "crypto", ".", "Addressable", ",", "power", "*", "big", ".", "Int", ")", "error", "{", "otherPower", ":=", "vsOther", ".", "GetPower", "(", "id", ".", "GetAddress", "(", ")", ")", "\n", "if", "otherPower", ".", "Cmp", "(", "power", ")", "!=", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"set power %d != other set power %d\"", ",", "power", ",", "otherPower", ")", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "}" ]
// Returns an error if the Sets are not equal describing which part of their structures differ
[ "Returns", "an", "error", "if", "the", "Sets", "are", "not", "equal", "describing", "which", "part", "of", "their", "structures", "differ" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/validator/set.go#L105-L117
train
hyperledger/burrow
acm/validator/set.go
IterateValidators
func (vs *Set) IterateValidators(iter func(id crypto.Addressable, power *big.Int) error) error { if vs == nil { return nil } addresses := make(crypto.Addresses, 0, len(vs.powers)) for address := range vs.powers { addresses = append(addresses, address) } sort.Sort(addresses) for _, address := range addresses { err := iter(vs.publicKeys[address], new(big.Int).Set(vs.powers[address])) if err != nil { return err } } return nil }
go
func (vs *Set) IterateValidators(iter func(id crypto.Addressable, power *big.Int) error) error { if vs == nil { return nil } addresses := make(crypto.Addresses, 0, len(vs.powers)) for address := range vs.powers { addresses = append(addresses, address) } sort.Sort(addresses) for _, address := range addresses { err := iter(vs.publicKeys[address], new(big.Int).Set(vs.powers[address])) if err != nil { return err } } return nil }
[ "func", "(", "vs", "*", "Set", ")", "IterateValidators", "(", "iter", "func", "(", "id", "crypto", ".", "Addressable", ",", "power", "*", "big", ".", "Int", ")", "error", ")", "error", "{", "if", "vs", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "addresses", ":=", "make", "(", "crypto", ".", "Addresses", ",", "0", ",", "len", "(", "vs", ".", "powers", ")", ")", "\n", "for", "address", ":=", "range", "vs", ".", "powers", "{", "addresses", "=", "append", "(", "addresses", ",", "address", ")", "\n", "}", "\n", "sort", ".", "Sort", "(", "addresses", ")", "\n", "for", "_", ",", "address", ":=", "range", "addresses", "{", "err", ":=", "iter", "(", "vs", ".", "publicKeys", "[", "address", "]", ",", "new", "(", "big", ".", "Int", ")", ".", "Set", "(", "vs", ".", "powers", "[", "address", "]", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Iterates over validators sorted by address
[ "Iterates", "over", "validators", "sorted", "by", "address" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/validator/set.go#L120-L136
train
hyperledger/burrow
rpc/rpcevents/blocks.go
Bounds
func (br *BlockRange) Bounds(latestBlockHeight uint64) (startHeight, endHeight uint64, streaming bool) { // End bound is exclusive in state.GetEvents so we increment the height return br.GetStart().Bound(latestBlockHeight), br.GetEnd().Bound(latestBlockHeight) + 1, br.GetEnd().GetType() == Bound_STREAM }
go
func (br *BlockRange) Bounds(latestBlockHeight uint64) (startHeight, endHeight uint64, streaming bool) { // End bound is exclusive in state.GetEvents so we increment the height return br.GetStart().Bound(latestBlockHeight), br.GetEnd().Bound(latestBlockHeight) + 1, br.GetEnd().GetType() == Bound_STREAM }
[ "func", "(", "br", "*", "BlockRange", ")", "Bounds", "(", "latestBlockHeight", "uint64", ")", "(", "startHeight", ",", "endHeight", "uint64", ",", "streaming", "bool", ")", "{", "return", "br", ".", "GetStart", "(", ")", ".", "Bound", "(", "latestBlockHeight", ")", ",", "br", ".", "GetEnd", "(", ")", ".", "Bound", "(", "latestBlockHeight", ")", "+", "1", ",", "br", ".", "GetEnd", "(", ")", ".", "GetType", "(", ")", "==", "Bound_STREAM", "\n", "}" ]
// Get bounds suitable for events.Provider
[ "Get", "bounds", "suitable", "for", "events", ".", "Provider" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/rpc/rpcevents/blocks.go#L8-L12
train
hyperledger/burrow
rpc/jsonrpc.go
NewRPCRequest
func NewRPCRequest(id string, method string, params json.RawMessage) *RPCRequest { return &RPCRequest{ JSONRPC: "2.0", Id: id, Method: method, Params: params, } }
go
func NewRPCRequest(id string, method string, params json.RawMessage) *RPCRequest { return &RPCRequest{ JSONRPC: "2.0", Id: id, Method: method, Params: params, } }
[ "func", "NewRPCRequest", "(", "id", "string", ",", "method", "string", ",", "params", "json", ".", "RawMessage", ")", "*", "RPCRequest", "{", "return", "&", "RPCRequest", "{", "JSONRPC", ":", "\"2.0\"", ",", "Id", ":", "id", ",", "Method", ":", "method", ",", "Params", ":", "params", ",", "}", "\n", "}" ]
// Create a new RPC request. This is the generic struct that is passed to RPC // methods
[ "Create", "a", "new", "RPC", "request", ".", "This", "is", "the", "generic", "struct", "that", "is", "passed", "to", "RPC", "methods" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/rpc/jsonrpc.go#L76-L83
train
hyperledger/burrow
rpc/jsonrpc.go
NewRPCResponse
func NewRPCResponse(id string, res interface{}) RPCResponse { return RPCResponse(&RPCResultResponse{ Result: res, Id: id, JSONRPC: "2.0", }) }
go
func NewRPCResponse(id string, res interface{}) RPCResponse { return RPCResponse(&RPCResultResponse{ Result: res, Id: id, JSONRPC: "2.0", }) }
[ "func", "NewRPCResponse", "(", "id", "string", ",", "res", "interface", "{", "}", ")", "RPCResponse", "{", "return", "RPCResponse", "(", "&", "RPCResultResponse", "{", "Result", ":", "res", ",", "Id", ":", "id", ",", "JSONRPC", ":", "\"2.0\"", ",", "}", ")", "\n", "}" ]
// NewRPCResponse creates a new response object from a result
[ "NewRPCResponse", "creates", "a", "new", "response", "object", "from", "a", "result" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/rpc/jsonrpc.go#L86-L92
train
hyperledger/burrow
rpc/jsonrpc.go
NewRPCErrorResponse
func NewRPCErrorResponse(id string, code int, message string) RPCResponse { return RPCResponse(&RPCErrorResponse{ Error: &RPCError{code, message}, Id: id, JSONRPC: "2.0", }) }
go
func NewRPCErrorResponse(id string, code int, message string) RPCResponse { return RPCResponse(&RPCErrorResponse{ Error: &RPCError{code, message}, Id: id, JSONRPC: "2.0", }) }
[ "func", "NewRPCErrorResponse", "(", "id", "string", ",", "code", "int", ",", "message", "string", ")", "RPCResponse", "{", "return", "RPCResponse", "(", "&", "RPCErrorResponse", "{", "Error", ":", "&", "RPCError", "{", "code", ",", "message", "}", ",", "Id", ":", "id", ",", "JSONRPC", ":", "\"2.0\"", ",", "}", ")", "\n", "}" ]
// NewRPCErrorResponse creates a new error-response object from the error code and message
[ "NewRPCErrorResponse", "creates", "a", "new", "error", "-", "response", "object", "from", "the", "error", "code", "and", "message" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/rpc/jsonrpc.go#L95-L101
train
hyperledger/burrow
storage/multi_iterator.go
NewMultiIterator
func NewMultiIterator(reverse bool, iterators ...KVIterator) *MultiIterator { // reuse backing array lessComp := -1 if reverse { lessComp = 1 } mi := &MultiIterator{ iterators: iterators, iteratorOrder: make(map[KVIterator]int), lessComp: lessComp, } mi.init() return mi }
go
func NewMultiIterator(reverse bool, iterators ...KVIterator) *MultiIterator { // reuse backing array lessComp := -1 if reverse { lessComp = 1 } mi := &MultiIterator{ iterators: iterators, iteratorOrder: make(map[KVIterator]int), lessComp: lessComp, } mi.init() return mi }
[ "func", "NewMultiIterator", "(", "reverse", "bool", ",", "iterators", "...", "KVIterator", ")", "*", "MultiIterator", "{", "lessComp", ":=", "-", "1", "\n", "if", "reverse", "{", "lessComp", "=", "1", "\n", "}", "\n", "mi", ":=", "&", "MultiIterator", "{", "iterators", ":", "iterators", ",", "iteratorOrder", ":", "make", "(", "map", "[", "KVIterator", "]", "int", ")", ",", "lessComp", ":", "lessComp", ",", "}", "\n", "mi", ".", "init", "(", ")", "\n", "return", "mi", "\n", "}" ]
// MultiIterator iterates in order over a series o
[ "MultiIterator", "iterates", "in", "order", "over", "a", "series", "o" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/storage/multi_iterator.go#L18-L31
train
hyperledger/burrow
deploy/keys/keys.go
InitKeyClient
func InitKeyClient(keysUrl string) (*LocalKeyClient, error) { aliveCh := make(chan struct{}) localKeyClient, err := keys.NewRemoteKeyClient(keysUrl, logging.NewNoopLogger()) if err != nil { return nil, err } err = localKeyClient.HealthCheck() go func() { for err != nil { err = localKeyClient.HealthCheck() } aliveCh <- struct{}{} }() select { case <-time.After(keysTimeout): return nil, fmt.Errorf("keys instance did not become responsive after %s: %v", keysTimeout, err) case <-aliveCh: return &LocalKeyClient{localKeyClient}, nil } }
go
func InitKeyClient(keysUrl string) (*LocalKeyClient, error) { aliveCh := make(chan struct{}) localKeyClient, err := keys.NewRemoteKeyClient(keysUrl, logging.NewNoopLogger()) if err != nil { return nil, err } err = localKeyClient.HealthCheck() go func() { for err != nil { err = localKeyClient.HealthCheck() } aliveCh <- struct{}{} }() select { case <-time.After(keysTimeout): return nil, fmt.Errorf("keys instance did not become responsive after %s: %v", keysTimeout, err) case <-aliveCh: return &LocalKeyClient{localKeyClient}, nil } }
[ "func", "InitKeyClient", "(", "keysUrl", "string", ")", "(", "*", "LocalKeyClient", ",", "error", ")", "{", "aliveCh", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "localKeyClient", ",", "err", ":=", "keys", ".", "NewRemoteKeyClient", "(", "keysUrl", ",", "logging", ".", "NewNoopLogger", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "err", "=", "localKeyClient", ".", "HealthCheck", "(", ")", "\n", "go", "func", "(", ")", "{", "for", "err", "!=", "nil", "{", "err", "=", "localKeyClient", ".", "HealthCheck", "(", ")", "\n", "}", "\n", "aliveCh", "<-", "struct", "{", "}", "{", "}", "\n", "}", "(", ")", "\n", "select", "{", "case", "<-", "time", ".", "After", "(", "keysTimeout", ")", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"keys instance did not become responsive after %s: %v\"", ",", "keysTimeout", ",", "err", ")", "\n", "case", "<-", "aliveCh", ":", "return", "&", "LocalKeyClient", "{", "localKeyClient", "}", ",", "nil", "\n", "}", "\n", "}" ]
// Returns an initialized key client to a docker container // running the keys server // Adding the Ip address is optional and should only be used // for passing data
[ "Returns", "an", "initialized", "key", "client", "to", "a", "docker", "container", "running", "the", "keys", "server", "Adding", "the", "Ip", "address", "is", "optional", "and", "should", "only", "be", "used", "for", "passing", "data" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/deploy/keys/keys.go#L22-L43
train
hyperledger/burrow
storage/kvstore.go
NormaliseDomain
func NormaliseDomain(low, high []byte) ([]byte, []byte) { if len(low) == 0 { low = []byte{} } return low, high }
go
func NormaliseDomain(low, high []byte) ([]byte, []byte) { if len(low) == 0 { low = []byte{} } return low, high }
[ "func", "NormaliseDomain", "(", "low", ",", "high", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "[", "]", "byte", ")", "{", "if", "len", "(", "low", ")", "==", "0", "{", "low", "=", "[", "]", "byte", "{", "}", "\n", "}", "\n", "return", "low", ",", "high", "\n", "}" ]
// NormaliseDomain encodes the assumption that when nil is used as a lower bound is interpreted as low rather than high
[ "NormaliseDomain", "encodes", "the", "assumption", "that", "when", "nil", "is", "used", "as", "a", "lower", "bound", "is", "interpreted", "as", "low", "rather", "than", "high" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/storage/kvstore.go#L83-L88
train
hyperledger/burrow
storage/kvstore.go
CompareKeys
func CompareKeys(k1, k2 []byte) int { ko1 := KeyOrder(k1) ko2 := KeyOrder(k2) if ko1 < ko2 { return -1 } if ko1 > ko2 { return 1 } return bytes.Compare(k1, k2) }
go
func CompareKeys(k1, k2 []byte) int { ko1 := KeyOrder(k1) ko2 := KeyOrder(k2) if ko1 < ko2 { return -1 } if ko1 > ko2 { return 1 } return bytes.Compare(k1, k2) }
[ "func", "CompareKeys", "(", "k1", ",", "k2", "[", "]", "byte", ")", "int", "{", "ko1", ":=", "KeyOrder", "(", "k1", ")", "\n", "ko2", ":=", "KeyOrder", "(", "k2", ")", "\n", "if", "ko1", "<", "ko2", "{", "return", "-", "1", "\n", "}", "\n", "if", "ko1", ">", "ko2", "{", "return", "1", "\n", "}", "\n", "return", "bytes", ".", "Compare", "(", "k1", ",", "k2", ")", "\n", "}" ]
// Sorts the keys as if they were compared lexicographically with their KeyOrder prepended
[ "Sorts", "the", "keys", "as", "if", "they", "were", "compared", "lexicographically", "with", "their", "KeyOrder", "prepended" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/storage/kvstore.go#L106-L116
train
hyperledger/burrow
execution/evm/vm.go
delegateCall
func (vm *VM) delegateCall(callState Interface, eventSink EventSink, caller, callee crypto.Address, code, input []byte, value uint64, gas *uint64, callType exec.CallType) (output []byte, err errors.CodedError) { // fire the post call event (including exception if applicable) and make sure we return the accumulated call error defer func() { vm.fireCallEvent(eventSink, callType, callState, &output, caller, callee, input, value, gas, callState) err = callState.Error() }() // DelegateCall does not transfer the value to the callee. callState.PushError(vm.ensureStackDepth()) // Early exit if callState.Error() != nil { return } if len(code) > 0 { vm.stackDepth += 1 output = vm.execute(callState, eventSink, caller, callee, code, input, value, gas) vm.stackDepth -= 1 } return }
go
func (vm *VM) delegateCall(callState Interface, eventSink EventSink, caller, callee crypto.Address, code, input []byte, value uint64, gas *uint64, callType exec.CallType) (output []byte, err errors.CodedError) { // fire the post call event (including exception if applicable) and make sure we return the accumulated call error defer func() { vm.fireCallEvent(eventSink, callType, callState, &output, caller, callee, input, value, gas, callState) err = callState.Error() }() // DelegateCall does not transfer the value to the callee. callState.PushError(vm.ensureStackDepth()) // Early exit if callState.Error() != nil { return } if len(code) > 0 { vm.stackDepth += 1 output = vm.execute(callState, eventSink, caller, callee, code, input, value, gas) vm.stackDepth -= 1 } return }
[ "func", "(", "vm", "*", "VM", ")", "delegateCall", "(", "callState", "Interface", ",", "eventSink", "EventSink", ",", "caller", ",", "callee", "crypto", ".", "Address", ",", "code", ",", "input", "[", "]", "byte", ",", "value", "uint64", ",", "gas", "*", "uint64", ",", "callType", "exec", ".", "CallType", ")", "(", "output", "[", "]", "byte", ",", "err", "errors", ".", "CodedError", ")", "{", "defer", "func", "(", ")", "{", "vm", ".", "fireCallEvent", "(", "eventSink", ",", "callType", ",", "callState", ",", "&", "output", ",", "caller", ",", "callee", ",", "input", ",", "value", ",", "gas", ",", "callState", ")", "\n", "err", "=", "callState", ".", "Error", "(", ")", "\n", "}", "(", ")", "\n", "callState", ".", "PushError", "(", "vm", ".", "ensureStackDepth", "(", ")", ")", "\n", "if", "callState", ".", "Error", "(", ")", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "len", "(", "code", ")", ">", "0", "{", "vm", ".", "stackDepth", "+=", "1", "\n", "output", "=", "vm", ".", "execute", "(", "callState", ",", "eventSink", ",", "caller", ",", "callee", ",", "code", ",", "input", ",", "value", ",", "gas", ")", "\n", "vm", ".", "stackDepth", "-=", "1", "\n", "}", "\n", "return", "\n", "}" ]
// DelegateCall is executed by the DELEGATECALL opcode, introduced as off Ethereum Homestead. // The intent of delegate call is to run the code of the callee in the storage context of the caller; // while preserving the original caller to the previous callee. // Different to the normal CALL or CALLCODE, the value does not need to be transferred to the callee.
[ "DelegateCall", "is", "executed", "by", "the", "DELEGATECALL", "opcode", "introduced", "as", "off", "Ethereum", "Homestead", ".", "The", "intent", "of", "delegate", "call", "is", "to", "run", "the", "code", "of", "the", "callee", "in", "the", "storage", "context", "of", "the", "caller", ";", "while", "preserving", "the", "original", "caller", "to", "the", "previous", "callee", ".", "Different", "to", "the", "normal", "CALL", "or", "CALLCODE", "the", "value", "does", "not", "need", "to", "be", "transferred", "to", "the", "callee", "." ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/execution/evm/vm.go#L188-L213
train
hyperledger/burrow
execution/evm/vm.go
useGasNegative
func useGasNegative(gasLeft *uint64, gasToUse uint64, err errors.Sink) { if *gasLeft >= gasToUse { *gasLeft -= gasToUse } else { err.PushError(errors.ErrorCodeInsufficientGas) } }
go
func useGasNegative(gasLeft *uint64, gasToUse uint64, err errors.Sink) { if *gasLeft >= gasToUse { *gasLeft -= gasToUse } else { err.PushError(errors.ErrorCodeInsufficientGas) } }
[ "func", "useGasNegative", "(", "gasLeft", "*", "uint64", ",", "gasToUse", "uint64", ",", "err", "errors", ".", "Sink", ")", "{", "if", "*", "gasLeft", ">=", "gasToUse", "{", "*", "gasLeft", "-=", "gasToUse", "\n", "}", "else", "{", "err", ".", "PushError", "(", "errors", ".", "ErrorCodeInsufficientGas", ")", "\n", "}", "\n", "}" ]
// Try to deduct gasToUse from gasLeft. If ok return false, otherwise // set err and return true.
[ "Try", "to", "deduct", "gasToUse", "from", "gasLeft", ".", "If", "ok", "return", "false", "otherwise", "set", "err", "and", "return", "true", "." ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/execution/evm/vm.go#L217-L223
train
hyperledger/burrow
execution/evm/vm.go
dumpTokens
func dumpTokens(nonce []byte, caller, callee crypto.Address, code []byte) { var tokensString string tokens, err := acm.Bytecode(code).Tokens() if err != nil { tokensString = fmt.Sprintf("error generating tokens from bytecode: %v", err) } else { tokensString = strings.Join(tokens, "\n") } txHashString := "nil-nonce" if len(nonce) >= 4 { txHashString = fmt.Sprintf("nonce-%X", nonce[:4]) } callerString := "caller-none" if caller != crypto.ZeroAddress { callerString = fmt.Sprintf("caller-%v", caller) } calleeString := "callee-none" if callee != crypto.ZeroAddress { calleeString = fmt.Sprintf("callee-%v", caller) } ioutil.WriteFile(fmt.Sprintf("tokens_%s_%s_%s.asm", txHashString, callerString, calleeString), []byte(tokensString), 0777) }
go
func dumpTokens(nonce []byte, caller, callee crypto.Address, code []byte) { var tokensString string tokens, err := acm.Bytecode(code).Tokens() if err != nil { tokensString = fmt.Sprintf("error generating tokens from bytecode: %v", err) } else { tokensString = strings.Join(tokens, "\n") } txHashString := "nil-nonce" if len(nonce) >= 4 { txHashString = fmt.Sprintf("nonce-%X", nonce[:4]) } callerString := "caller-none" if caller != crypto.ZeroAddress { callerString = fmt.Sprintf("caller-%v", caller) } calleeString := "callee-none" if callee != crypto.ZeroAddress { calleeString = fmt.Sprintf("callee-%v", caller) } ioutil.WriteFile(fmt.Sprintf("tokens_%s_%s_%s.asm", txHashString, callerString, calleeString), []byte(tokensString), 0777) }
[ "func", "dumpTokens", "(", "nonce", "[", "]", "byte", ",", "caller", ",", "callee", "crypto", ".", "Address", ",", "code", "[", "]", "byte", ")", "{", "var", "tokensString", "string", "\n", "tokens", ",", "err", ":=", "acm", ".", "Bytecode", "(", "code", ")", ".", "Tokens", "(", ")", "\n", "if", "err", "!=", "nil", "{", "tokensString", "=", "fmt", ".", "Sprintf", "(", "\"error generating tokens from bytecode: %v\"", ",", "err", ")", "\n", "}", "else", "{", "tokensString", "=", "strings", ".", "Join", "(", "tokens", ",", "\"\\n\"", ")", "\n", "}", "\n", "\\n", "\n", "txHashString", ":=", "\"nil-nonce\"", "\n", "if", "len", "(", "nonce", ")", ">=", "4", "{", "txHashString", "=", "fmt", ".", "Sprintf", "(", "\"nonce-%X\"", ",", "nonce", "[", ":", "4", "]", ")", "\n", "}", "\n", "callerString", ":=", "\"caller-none\"", "\n", "if", "caller", "!=", "crypto", ".", "ZeroAddress", "{", "callerString", "=", "fmt", ".", "Sprintf", "(", "\"caller-%v\"", ",", "caller", ")", "\n", "}", "\n", "calleeString", ":=", "\"callee-none\"", "\n", "if", "callee", "!=", "crypto", ".", "ZeroAddress", "{", "calleeString", "=", "fmt", ".", "Sprintf", "(", "\"callee-%v\"", ",", "caller", ")", "\n", "}", "\n", "}" ]
// Dump the bytecode being sent to the EVM in the current working directory
[ "Dump", "the", "bytecode", "being", "sent", "to", "the", "EVM", "in", "the", "current", "working", "directory" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/execution/evm/vm.go#L1064-L1086
train
hyperledger/burrow
integration/integration.go
MakePrivateAccounts
func MakePrivateAccounts(n int) []*acm.PrivateAccount { accounts := make([]*acm.PrivateAccount, n) for i := 0; i < n; i++ { accounts[i] = acm.GeneratePrivateAccountFromSecret("mysecret" + strconv.Itoa(i)) } return accounts }
go
func MakePrivateAccounts(n int) []*acm.PrivateAccount { accounts := make([]*acm.PrivateAccount, n) for i := 0; i < n; i++ { accounts[i] = acm.GeneratePrivateAccountFromSecret("mysecret" + strconv.Itoa(i)) } return accounts }
[ "func", "MakePrivateAccounts", "(", "n", "int", ")", "[", "]", "*", "acm", ".", "PrivateAccount", "{", "accounts", ":=", "make", "(", "[", "]", "*", "acm", ".", "PrivateAccount", ",", "n", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "n", ";", "i", "++", "{", "accounts", "[", "i", "]", "=", "acm", ".", "GeneratePrivateAccountFromSecret", "(", "\"mysecret\"", "+", "strconv", ".", "Itoa", "(", "i", ")", ")", "\n", "}", "\n", "return", "accounts", "\n", "}" ]
// Deterministic account generation helper. Pass number of accounts to make
[ "Deterministic", "account", "generation", "helper", ".", "Pass", "number", "of", "accounts", "to", "make" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/integration/integration.go#L190-L196
train
hyperledger/burrow
vent/sqldb/adapters/postgres_adapter.go
NewPostgresAdapter
func NewPostgresAdapter(schema string, log *logger.Logger) *PostgresAdapter { return &PostgresAdapter{ Log: log, Schema: schema, } }
go
func NewPostgresAdapter(schema string, log *logger.Logger) *PostgresAdapter { return &PostgresAdapter{ Log: log, Schema: schema, } }
[ "func", "NewPostgresAdapter", "(", "schema", "string", ",", "log", "*", "logger", ".", "Logger", ")", "*", "PostgresAdapter", "{", "return", "&", "PostgresAdapter", "{", "Log", ":", "log", ",", "Schema", ":", "schema", ",", "}", "\n", "}" ]
// NewPostgresAdapter constructs a new db adapter
[ "NewPostgresAdapter", "constructs", "a", "new", "db", "adapter" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/sqldb/adapters/postgres_adapter.go#L33-L38
train
hyperledger/burrow
vent/sqldb/adapters/postgres_adapter.go
Open
func (adapter *PostgresAdapter) Open(dbURL string) (*sql.DB, error) { db, err := sql.Open("postgres", dbURL) if err != nil { adapter.Log.Info("msg", "Error creating database connection", "err", err) return nil, err } // if there is a supplied Schema if adapter.Schema != "" { if err = db.Ping(); err != nil { adapter.Log.Info("msg", "Error opening database connection", "err", err) return nil, err } var found bool query := Cleanf(`SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace n WHERE n.nspname = '%s');`, adapter.Schema) adapter.Log.Info("msg", "FIND SCHEMA", "query", query) if err := db.QueryRow(query).Scan(&found); err == nil { if !found { adapter.Log.Warn("msg", "Schema not found") } adapter.Log.Info("msg", "Creating schema") query = Cleanf("CREATE SCHEMA %s;", adapter.Schema) adapter.Log.Info("msg", "CREATE SCHEMA", "query", query) if _, err = db.Exec(query); err != nil { if adapter.ErrorEquals(err, types.SQLErrorTypeDuplicatedSchema) { adapter.Log.Warn("msg", "Duplicated schema") return db, nil } } } else { adapter.Log.Info("msg", "Error searching schema", "err", err) return nil, err } } else { return nil, fmt.Errorf("no schema supplied") } return db, err }
go
func (adapter *PostgresAdapter) Open(dbURL string) (*sql.DB, error) { db, err := sql.Open("postgres", dbURL) if err != nil { adapter.Log.Info("msg", "Error creating database connection", "err", err) return nil, err } // if there is a supplied Schema if adapter.Schema != "" { if err = db.Ping(); err != nil { adapter.Log.Info("msg", "Error opening database connection", "err", err) return nil, err } var found bool query := Cleanf(`SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace n WHERE n.nspname = '%s');`, adapter.Schema) adapter.Log.Info("msg", "FIND SCHEMA", "query", query) if err := db.QueryRow(query).Scan(&found); err == nil { if !found { adapter.Log.Warn("msg", "Schema not found") } adapter.Log.Info("msg", "Creating schema") query = Cleanf("CREATE SCHEMA %s;", adapter.Schema) adapter.Log.Info("msg", "CREATE SCHEMA", "query", query) if _, err = db.Exec(query); err != nil { if adapter.ErrorEquals(err, types.SQLErrorTypeDuplicatedSchema) { adapter.Log.Warn("msg", "Duplicated schema") return db, nil } } } else { adapter.Log.Info("msg", "Error searching schema", "err", err) return nil, err } } else { return nil, fmt.Errorf("no schema supplied") } return db, err }
[ "func", "(", "adapter", "*", "PostgresAdapter", ")", "Open", "(", "dbURL", "string", ")", "(", "*", "sql", ".", "DB", ",", "error", ")", "{", "db", ",", "err", ":=", "sql", ".", "Open", "(", "\"postgres\"", ",", "dbURL", ")", "\n", "if", "err", "!=", "nil", "{", "adapter", ".", "Log", ".", "Info", "(", "\"msg\"", ",", "\"Error creating database connection\"", ",", "\"err\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "if", "adapter", ".", "Schema", "!=", "\"\"", "{", "if", "err", "=", "db", ".", "Ping", "(", ")", ";", "err", "!=", "nil", "{", "adapter", ".", "Log", ".", "Info", "(", "\"msg\"", ",", "\"Error opening database connection\"", ",", "\"err\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "var", "found", "bool", "\n", "query", ":=", "Cleanf", "(", "`SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace n WHERE n.nspname = '%s');`", ",", "adapter", ".", "Schema", ")", "\n", "adapter", ".", "Log", ".", "Info", "(", "\"msg\"", ",", "\"FIND SCHEMA\"", ",", "\"query\"", ",", "query", ")", "\n", "if", "err", ":=", "db", ".", "QueryRow", "(", "query", ")", ".", "Scan", "(", "&", "found", ")", ";", "err", "==", "nil", "{", "if", "!", "found", "{", "adapter", ".", "Log", ".", "Warn", "(", "\"msg\"", ",", "\"Schema not found\"", ")", "\n", "}", "\n", "adapter", ".", "Log", ".", "Info", "(", "\"msg\"", ",", "\"Creating schema\"", ")", "\n", "query", "=", "Cleanf", "(", "\"CREATE SCHEMA %s;\"", ",", "adapter", ".", "Schema", ")", "\n", "adapter", ".", "Log", ".", "Info", "(", "\"msg\"", ",", "\"CREATE SCHEMA\"", ",", "\"query\"", ",", "query", ")", "\n", "if", "_", ",", "err", "=", "db", ".", "Exec", "(", "query", ")", ";", "err", "!=", "nil", "{", "if", "adapter", ".", "ErrorEquals", "(", "err", ",", "types", ".", "SQLErrorTypeDuplicatedSchema", ")", "{", "adapter", ".", "Log", ".", "Warn", "(", "\"msg\"", ",", "\"Duplicated schema\"", ")", "\n", "return", "db", ",", "nil", "\n", "}", "\n", "}", "\n", "}", "else", "{", "adapter", ".", "Log", ".", "Info", "(", "\"msg\"", ",", "\"Error searching schema\"", ",", "\"err\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "}", "else", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"no schema supplied\"", ")", "\n", "}", "\n", "return", "db", ",", "err", "\n", "}" ]
// Open connects to a PostgreSQL database, opens it & create default schema if provided
[ "Open", "connects", "to", "a", "PostgreSQL", "database", "opens", "it", "&", "create", "default", "schema", "if", "provided" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/sqldb/adapters/postgres_adapter.go#L41-L84
train
hyperledger/burrow
vent/sqldb/adapters/postgres_adapter.go
CreateTableQuery
func (adapter *PostgresAdapter) CreateTableQuery(tableName string, columns []*types.SQLTableColumn) (string, string) { // build query columnsDef := "" primaryKey := "" dictionaryValues := "" for i, column := range columns { secureColumn := adapter.SecureName(column.Name) sqlType, _ := adapter.TypeMapping(column.Type) pKey := 0 if columnsDef != "" { columnsDef += ", " dictionaryValues += ", " } columnsDef += Cleanf("%s %s", secureColumn, sqlType) if column.Length > 0 { columnsDef += Cleanf("(%v)", column.Length) } if column.Primary { pKey = 1 columnsDef += " NOT NULL" if primaryKey != "" { primaryKey += ", " } primaryKey += secureColumn } dictionaryValues += Cleanf("('%s','%s',%d,%d,%d,%d)", tableName, column.Name, column.Type, column.Length, pKey, i) } query := Cleanf("CREATE TABLE %s.%s (%s", adapter.Schema, adapter.SecureName(tableName), columnsDef) if primaryKey != "" { query += "," + Cleanf("CONSTRAINT %s_pkey PRIMARY KEY (%s)", tableName, primaryKey) } query += ");" dictionaryQuery := Cleanf("INSERT INTO %s.%s (%s,%s,%s,%s,%s,%s) VALUES %s;", adapter.Schema, types.SQLDictionaryTableName, types.SQLColumnLabelTableName, types.SQLColumnLabelColumnName, types.SQLColumnLabelColumnType, types.SQLColumnLabelColumnLength, types.SQLColumnLabelPrimaryKey, types.SQLColumnLabelColumnOrder, dictionaryValues) return query, dictionaryQuery }
go
func (adapter *PostgresAdapter) CreateTableQuery(tableName string, columns []*types.SQLTableColumn) (string, string) { // build query columnsDef := "" primaryKey := "" dictionaryValues := "" for i, column := range columns { secureColumn := adapter.SecureName(column.Name) sqlType, _ := adapter.TypeMapping(column.Type) pKey := 0 if columnsDef != "" { columnsDef += ", " dictionaryValues += ", " } columnsDef += Cleanf("%s %s", secureColumn, sqlType) if column.Length > 0 { columnsDef += Cleanf("(%v)", column.Length) } if column.Primary { pKey = 1 columnsDef += " NOT NULL" if primaryKey != "" { primaryKey += ", " } primaryKey += secureColumn } dictionaryValues += Cleanf("('%s','%s',%d,%d,%d,%d)", tableName, column.Name, column.Type, column.Length, pKey, i) } query := Cleanf("CREATE TABLE %s.%s (%s", adapter.Schema, adapter.SecureName(tableName), columnsDef) if primaryKey != "" { query += "," + Cleanf("CONSTRAINT %s_pkey PRIMARY KEY (%s)", tableName, primaryKey) } query += ");" dictionaryQuery := Cleanf("INSERT INTO %s.%s (%s,%s,%s,%s,%s,%s) VALUES %s;", adapter.Schema, types.SQLDictionaryTableName, types.SQLColumnLabelTableName, types.SQLColumnLabelColumnName, types.SQLColumnLabelColumnType, types.SQLColumnLabelColumnLength, types.SQLColumnLabelPrimaryKey, types.SQLColumnLabelColumnOrder, dictionaryValues) return query, dictionaryQuery }
[ "func", "(", "adapter", "*", "PostgresAdapter", ")", "CreateTableQuery", "(", "tableName", "string", ",", "columns", "[", "]", "*", "types", ".", "SQLTableColumn", ")", "(", "string", ",", "string", ")", "{", "columnsDef", ":=", "\"\"", "\n", "primaryKey", ":=", "\"\"", "\n", "dictionaryValues", ":=", "\"\"", "\n", "for", "i", ",", "column", ":=", "range", "columns", "{", "secureColumn", ":=", "adapter", ".", "SecureName", "(", "column", ".", "Name", ")", "\n", "sqlType", ",", "_", ":=", "adapter", ".", "TypeMapping", "(", "column", ".", "Type", ")", "\n", "pKey", ":=", "0", "\n", "if", "columnsDef", "!=", "\"\"", "{", "columnsDef", "+=", "\", \"", "\n", "dictionaryValues", "+=", "\", \"", "\n", "}", "\n", "columnsDef", "+=", "Cleanf", "(", "\"%s %s\"", ",", "secureColumn", ",", "sqlType", ")", "\n", "if", "column", ".", "Length", ">", "0", "{", "columnsDef", "+=", "Cleanf", "(", "\"(%v)\"", ",", "column", ".", "Length", ")", "\n", "}", "\n", "if", "column", ".", "Primary", "{", "pKey", "=", "1", "\n", "columnsDef", "+=", "\" NOT NULL\"", "\n", "if", "primaryKey", "!=", "\"\"", "{", "primaryKey", "+=", "\", \"", "\n", "}", "\n", "primaryKey", "+=", "secureColumn", "\n", "}", "\n", "dictionaryValues", "+=", "Cleanf", "(", "\"('%s','%s',%d,%d,%d,%d)\"", ",", "tableName", ",", "column", ".", "Name", ",", "column", ".", "Type", ",", "column", ".", "Length", ",", "pKey", ",", "i", ")", "\n", "}", "\n", "query", ":=", "Cleanf", "(", "\"CREATE TABLE %s.%s (%s\"", ",", "adapter", ".", "Schema", ",", "adapter", ".", "SecureName", "(", "tableName", ")", ",", "columnsDef", ")", "\n", "if", "primaryKey", "!=", "\"\"", "{", "query", "+=", "\",\"", "+", "Cleanf", "(", "\"CONSTRAINT %s_pkey PRIMARY KEY (%s)\"", ",", "tableName", ",", "primaryKey", ")", "\n", "}", "\n", "query", "+=", "\");\"", "\n", "dictionaryQuery", ":=", "Cleanf", "(", "\"INSERT INTO %s.%s (%s,%s,%s,%s,%s,%s) VALUES %s;\"", ",", "adapter", ".", "Schema", ",", "types", ".", "SQLDictionaryTableName", ",", "types", ".", "SQLColumnLabelTableName", ",", "types", ".", "SQLColumnLabelColumnName", ",", "types", ".", "SQLColumnLabelColumnType", ",", "types", ".", "SQLColumnLabelColumnLength", ",", "types", ".", "SQLColumnLabelPrimaryKey", ",", "types", ".", "SQLColumnLabelColumnOrder", ",", "dictionaryValues", ")", "\n", "return", "query", ",", "dictionaryQuery", "\n", "}" ]
// CreateTableQuery builds query for creating a new table
[ "CreateTableQuery", "builds", "query", "for", "creating", "a", "new", "table" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/sqldb/adapters/postgres_adapter.go#L101-L155
train
hyperledger/burrow
vent/sqldb/adapters/postgres_adapter.go
TableDefinitionQuery
func (adapter *PostgresAdapter) TableDefinitionQuery() string { query := ` SELECT %s,%s,%s,%s FROM %s.%s WHERE %s = $1 ORDER BY %s;` return Cleanf(query, types.SQLColumnLabelColumnName, types.SQLColumnLabelColumnType, // select types.SQLColumnLabelColumnLength, types.SQLColumnLabelPrimaryKey, // select adapter.Schema, types.SQLDictionaryTableName, // from types.SQLColumnLabelTableName, // where types.SQLColumnLabelColumnOrder) // order by }
go
func (adapter *PostgresAdapter) TableDefinitionQuery() string { query := ` SELECT %s,%s,%s,%s FROM %s.%s WHERE %s = $1 ORDER BY %s;` return Cleanf(query, types.SQLColumnLabelColumnName, types.SQLColumnLabelColumnType, // select types.SQLColumnLabelColumnLength, types.SQLColumnLabelPrimaryKey, // select adapter.Schema, types.SQLDictionaryTableName, // from types.SQLColumnLabelTableName, // where types.SQLColumnLabelColumnOrder) // order by }
[ "func", "(", "adapter", "*", "PostgresAdapter", ")", "TableDefinitionQuery", "(", ")", "string", "{", "query", ":=", "`\t\tSELECT\t\t\t%s,%s,%s,%s\t\tFROM\t\t\t%s.%s\t\tWHERE\t\t\t%s = $1\t\tORDER BY\t\t\t%s;`", "\n", "return", "Cleanf", "(", "query", ",", "types", ".", "SQLColumnLabelColumnName", ",", "types", ".", "SQLColumnLabelColumnType", ",", "types", ".", "SQLColumnLabelColumnLength", ",", "types", ".", "SQLColumnLabelPrimaryKey", ",", "adapter", ".", "Schema", ",", "types", ".", "SQLDictionaryTableName", ",", "types", ".", "SQLColumnLabelTableName", ",", "types", ".", "SQLColumnLabelColumnOrder", ")", "\n", "}" ]
// TableDefinitionQuery returns a query with table structure
[ "TableDefinitionQuery", "returns", "a", "query", "with", "table", "structure" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/sqldb/adapters/postgres_adapter.go#L187-L205
train
hyperledger/burrow
vent/sqldb/adapters/postgres_adapter.go
InsertLogQuery
func (adapter *PostgresAdapter) InsertLogQuery() string { query := ` INSERT INTO %s.%s (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) VALUES (CURRENT_TIMESTAMP, $1, $2, $3, $4, $5, $6 ,$7, $8, $9);` return Cleanf(query, adapter.Schema, types.SQLLogTableName, // insert //fields types.SQLColumnLabelTimeStamp, types.SQLColumnLabelTableName, types.SQLColumnLabelEventName, types.SQLColumnLabelEventFilter, types.SQLColumnLabelHeight, types.SQLColumnLabelTxHash, types.SQLColumnLabelAction, types.SQLColumnLabelDataRow, types.SQLColumnLabelSqlStmt, types.SQLColumnLabelSqlValues) }
go
func (adapter *PostgresAdapter) InsertLogQuery() string { query := ` INSERT INTO %s.%s (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) VALUES (CURRENT_TIMESTAMP, $1, $2, $3, $4, $5, $6 ,$7, $8, $9);` return Cleanf(query, adapter.Schema, types.SQLLogTableName, // insert //fields types.SQLColumnLabelTimeStamp, types.SQLColumnLabelTableName, types.SQLColumnLabelEventName, types.SQLColumnLabelEventFilter, types.SQLColumnLabelHeight, types.SQLColumnLabelTxHash, types.SQLColumnLabelAction, types.SQLColumnLabelDataRow, types.SQLColumnLabelSqlStmt, types.SQLColumnLabelSqlValues) }
[ "func", "(", "adapter", "*", "PostgresAdapter", ")", "InsertLogQuery", "(", ")", "string", "{", "query", ":=", "`\t\tINSERT INTO %s.%s (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)\t\tVALUES (CURRENT_TIMESTAMP, $1, $2, $3, $4, $5, $6 ,$7, $8, $9);`", "\n", "return", "Cleanf", "(", "query", ",", "adapter", ".", "Schema", ",", "types", ".", "SQLLogTableName", ",", "types", ".", "SQLColumnLabelTimeStamp", ",", "types", ".", "SQLColumnLabelTableName", ",", "types", ".", "SQLColumnLabelEventName", ",", "types", ".", "SQLColumnLabelEventFilter", ",", "types", ".", "SQLColumnLabelHeight", ",", "types", ".", "SQLColumnLabelTxHash", ",", "types", ".", "SQLColumnLabelAction", ",", "types", ".", "SQLColumnLabelDataRow", ",", "types", ".", "SQLColumnLabelSqlStmt", ",", "types", ".", "SQLColumnLabelSqlValues", ")", "\n", "}" ]
// InsertLogQuery returns a query to insert a row in log table
[ "InsertLogQuery", "returns", "a", "query", "to", "insert", "a", "row", "in", "log", "table" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/vent/sqldb/adapters/postgres_adapter.go#L256-L267
train
hyperledger/burrow
consensus/abci/process.go
NewProcess
func NewProcess(committer execution.BatchCommitter, blockchain *bcm.Blockchain, txDecoder txs.Decoder, commitInterval time.Duration, panicFunc func(error)) *Process { p := &Process{ committer: committer, blockchain: blockchain, done: make(chan struct{}), txDecoder: txDecoder, panic: panicFunc, } if commitInterval != 0 { p.ticker = time.NewTicker(commitInterval) go p.triggerCommits() } return p }
go
func NewProcess(committer execution.BatchCommitter, blockchain *bcm.Blockchain, txDecoder txs.Decoder, commitInterval time.Duration, panicFunc func(error)) *Process { p := &Process{ committer: committer, blockchain: blockchain, done: make(chan struct{}), txDecoder: txDecoder, panic: panicFunc, } if commitInterval != 0 { p.ticker = time.NewTicker(commitInterval) go p.triggerCommits() } return p }
[ "func", "NewProcess", "(", "committer", "execution", ".", "BatchCommitter", ",", "blockchain", "*", "bcm", ".", "Blockchain", ",", "txDecoder", "txs", ".", "Decoder", ",", "commitInterval", "time", ".", "Duration", ",", "panicFunc", "func", "(", "error", ")", ")", "*", "Process", "{", "p", ":=", "&", "Process", "{", "committer", ":", "committer", ",", "blockchain", ":", "blockchain", ",", "done", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "txDecoder", ":", "txDecoder", ",", "panic", ":", "panicFunc", ",", "}", "\n", "if", "commitInterval", "!=", "0", "{", "p", ".", "ticker", "=", "time", ".", "NewTicker", "(", "commitInterval", ")", "\n", "go", "p", ".", "triggerCommits", "(", ")", "\n", "}", "\n", "return", "p", "\n", "}" ]
// NewProcess returns a no-consensus ABCI process suitable for running a single node without Tendermint. // The CheckTx function can be used to submit transactions which are processed according
[ "NewProcess", "returns", "a", "no", "-", "consensus", "ABCI", "process", "suitable", "for", "running", "a", "single", "node", "without", "Tendermint", ".", "The", "CheckTx", "function", "can", "be", "used", "to", "submit", "transactions", "which", "are", "processed", "according" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/consensus/abci/process.go#L31-L48
train
hyperledger/burrow
txs/tx.go
Sign
func (tx *Tx) Sign(signingAccounts ...acm.AddressableSigner) (*Envelope, error) { env := tx.Enclose() err := env.Sign(signingAccounts...) if err != nil { return nil, err } tx.Rehash() return env, nil }
go
func (tx *Tx) Sign(signingAccounts ...acm.AddressableSigner) (*Envelope, error) { env := tx.Enclose() err := env.Sign(signingAccounts...) if err != nil { return nil, err } tx.Rehash() return env, nil }
[ "func", "(", "tx", "*", "Tx", ")", "Sign", "(", "signingAccounts", "...", "acm", ".", "AddressableSigner", ")", "(", "*", "Envelope", ",", "error", ")", "{", "env", ":=", "tx", ".", "Enclose", "(", ")", "\n", "err", ":=", "env", ".", "Sign", "(", "signingAccounts", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "tx", ".", "Rehash", "(", ")", "\n", "return", "env", ",", "nil", "\n", "}" ]
// Encloses in Envelope and signs envelope
[ "Encloses", "in", "Envelope", "and", "signs", "envelope" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/txs/tx.go#L56-L64
train
hyperledger/burrow
txs/tx.go
MustSignBytes
func (tx *Tx) MustSignBytes() []byte { bs, err := tx.SignBytes() if err != nil { panic(err) } return bs }
go
func (tx *Tx) MustSignBytes() []byte { bs, err := tx.SignBytes() if err != nil { panic(err) } return bs }
[ "func", "(", "tx", "*", "Tx", ")", "MustSignBytes", "(", ")", "[", "]", "byte", "{", "bs", ",", "err", ":=", "tx", ".", "SignBytes", "(", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "bs", "\n", "}" ]
// Generate SignBytes, panicking on any failure
[ "Generate", "SignBytes", "panicking", "on", "any", "failure" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/txs/tx.go#L67-L73
train
hyperledger/burrow
txs/tx.go
GenerateReceipt
func (tx *Tx) GenerateReceipt() *Receipt { receipt := &Receipt{ TxType: tx.Type(), TxHash: tx.Hash(), } if callTx, ok := tx.Payload.(*payload.CallTx); ok { receipt.CreatesContract = callTx.Address == nil if receipt.CreatesContract { receipt.ContractAddress = crypto.NewContractAddress(callTx.Input.Address, tx.Hash()) } else { receipt.ContractAddress = *callTx.Address } } return receipt }
go
func (tx *Tx) GenerateReceipt() *Receipt { receipt := &Receipt{ TxType: tx.Type(), TxHash: tx.Hash(), } if callTx, ok := tx.Payload.(*payload.CallTx); ok { receipt.CreatesContract = callTx.Address == nil if receipt.CreatesContract { receipt.ContractAddress = crypto.NewContractAddress(callTx.Input.Address, tx.Hash()) } else { receipt.ContractAddress = *callTx.Address } } return receipt }
[ "func", "(", "tx", "*", "Tx", ")", "GenerateReceipt", "(", ")", "*", "Receipt", "{", "receipt", ":=", "&", "Receipt", "{", "TxType", ":", "tx", ".", "Type", "(", ")", ",", "TxHash", ":", "tx", ".", "Hash", "(", ")", ",", "}", "\n", "if", "callTx", ",", "ok", ":=", "tx", ".", "Payload", ".", "(", "*", "payload", ".", "CallTx", ")", ";", "ok", "{", "receipt", ".", "CreatesContract", "=", "callTx", ".", "Address", "==", "nil", "\n", "if", "receipt", ".", "CreatesContract", "{", "receipt", ".", "ContractAddress", "=", "crypto", ".", "NewContractAddress", "(", "callTx", ".", "Input", ".", "Address", ",", "tx", ".", "Hash", "(", ")", ")", "\n", "}", "else", "{", "receipt", ".", "ContractAddress", "=", "*", "callTx", ".", "Address", "\n", "}", "\n", "}", "\n", "return", "receipt", "\n", "}" ]
// Generate a transaction Receipt containing the Tx hash and other information if the Tx is call. // Returned by ABCI methods.
[ "Generate", "a", "transaction", "Receipt", "containing", "the", "Tx", "hash", "and", "other", "information", "if", "the", "Tx", "is", "call", ".", "Returned", "by", "ABCI", "methods", "." ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/txs/tx.go#L184-L198
train
hyperledger/burrow
logging/loggers/filter_logger.go
FilterLogger
func FilterLogger(outputLogger log.Logger, predicate func(keyvals []interface{}) bool) log.Logger { return log.LoggerFunc(func(keyvals ...interface{}) error { // Always forward signals if structure.Signal(keyvals) != "" || !predicate(keyvals) { return outputLogger.Log(keyvals...) } return nil }) }
go
func FilterLogger(outputLogger log.Logger, predicate func(keyvals []interface{}) bool) log.Logger { return log.LoggerFunc(func(keyvals ...interface{}) error { // Always forward signals if structure.Signal(keyvals) != "" || !predicate(keyvals) { return outputLogger.Log(keyvals...) } return nil }) }
[ "func", "FilterLogger", "(", "outputLogger", "log", ".", "Logger", ",", "predicate", "func", "(", "keyvals", "[", "]", "interface", "{", "}", ")", "bool", ")", "log", ".", "Logger", "{", "return", "log", ".", "LoggerFunc", "(", "func", "(", "keyvals", "...", "interface", "{", "}", ")", "error", "{", "if", "structure", ".", "Signal", "(", "keyvals", ")", "!=", "\"\"", "||", "!", "predicate", "(", "keyvals", ")", "{", "return", "outputLogger", ".", "Log", "(", "keyvals", "...", ")", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "}" ]
// Filter logger allows us to filter lines logged to it before passing on to underlying // output logger // Creates a logger that removes lines from output when the predicate evaluates true
[ "Filter", "logger", "allows", "us", "to", "filter", "lines", "logged", "to", "it", "before", "passing", "on", "to", "underlying", "output", "logger", "Creates", "a", "logger", "that", "removes", "lines", "from", "output", "when", "the", "predicate", "evaluates", "true" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/logging/loggers/filter_logger.go#L11-L19
train
hyperledger/burrow
deploy/def/client.go
dial
func (c *Client) dial(logger *logging.Logger) error { if c.transactClient == nil { conn, err := grpc.Dial(c.ChainAddress, grpc.WithInsecure()) if err != nil { return err } c.transactClient = rpctransact.NewTransactClient(conn) c.queryClient = rpcquery.NewQueryClient(conn) c.executionEventsClient = rpcevents.NewExecutionEventsClient(conn) if c.KeysClientAddress == "" { logger.InfoMsg("Using mempool signing since no keyClient set, pass --keys to sign locally or elsewhere") c.MempoolSigning = true c.keyClient, err = keys.NewRemoteKeyClient(c.ChainAddress, logger) } else { logger.InfoMsg("Using keys server", "server", c.KeysClientAddress) c.keyClient, err = keys.NewRemoteKeyClient(c.KeysClientAddress, logger) } if err != nil { return err } ctx, cancel := context.WithTimeout(context.Background(), c.timeout) defer cancel() stat, err := c.queryClient.Status(ctx, &rpcquery.StatusParam{}) if err != nil { return err } c.chainID = stat.ChainID } return nil }
go
func (c *Client) dial(logger *logging.Logger) error { if c.transactClient == nil { conn, err := grpc.Dial(c.ChainAddress, grpc.WithInsecure()) if err != nil { return err } c.transactClient = rpctransact.NewTransactClient(conn) c.queryClient = rpcquery.NewQueryClient(conn) c.executionEventsClient = rpcevents.NewExecutionEventsClient(conn) if c.KeysClientAddress == "" { logger.InfoMsg("Using mempool signing since no keyClient set, pass --keys to sign locally or elsewhere") c.MempoolSigning = true c.keyClient, err = keys.NewRemoteKeyClient(c.ChainAddress, logger) } else { logger.InfoMsg("Using keys server", "server", c.KeysClientAddress) c.keyClient, err = keys.NewRemoteKeyClient(c.KeysClientAddress, logger) } if err != nil { return err } ctx, cancel := context.WithTimeout(context.Background(), c.timeout) defer cancel() stat, err := c.queryClient.Status(ctx, &rpcquery.StatusParam{}) if err != nil { return err } c.chainID = stat.ChainID } return nil }
[ "func", "(", "c", "*", "Client", ")", "dial", "(", "logger", "*", "logging", ".", "Logger", ")", "error", "{", "if", "c", ".", "transactClient", "==", "nil", "{", "conn", ",", "err", ":=", "grpc", ".", "Dial", "(", "c", ".", "ChainAddress", ",", "grpc", ".", "WithInsecure", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "c", ".", "transactClient", "=", "rpctransact", ".", "NewTransactClient", "(", "conn", ")", "\n", "c", ".", "queryClient", "=", "rpcquery", ".", "NewQueryClient", "(", "conn", ")", "\n", "c", ".", "executionEventsClient", "=", "rpcevents", ".", "NewExecutionEventsClient", "(", "conn", ")", "\n", "if", "c", ".", "KeysClientAddress", "==", "\"\"", "{", "logger", ".", "InfoMsg", "(", "\"Using mempool signing since no keyClient set, pass --keys to sign locally or elsewhere\"", ")", "\n", "c", ".", "MempoolSigning", "=", "true", "\n", "c", ".", "keyClient", ",", "err", "=", "keys", ".", "NewRemoteKeyClient", "(", "c", ".", "ChainAddress", ",", "logger", ")", "\n", "}", "else", "{", "logger", ".", "InfoMsg", "(", "\"Using keys server\"", ",", "\"server\"", ",", "c", ".", "KeysClientAddress", ")", "\n", "c", ".", "keyClient", ",", "err", "=", "keys", ".", "NewRemoteKeyClient", "(", "c", ".", "KeysClientAddress", ",", "logger", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "context", ".", "Background", "(", ")", ",", "c", ".", "timeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "stat", ",", "err", ":=", "c", ".", "queryClient", ".", "Status", "(", "ctx", ",", "&", "rpcquery", ".", "StatusParam", "{", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "c", ".", "chainID", "=", "stat", ".", "ChainID", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Connect GRPC clients using ChainURL
[ "Connect", "GRPC", "clients", "using", "ChainURL" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/deploy/def/client.go#L58-L89
train
hyperledger/burrow
deploy/def/client.go
CreateKey
func (c *Client) CreateKey(keyName, curveTypeString string, logger *logging.Logger) (crypto.PublicKey, error) { err := c.dial(logger) if err != nil { return crypto.PublicKey{}, err } if c.keyClient == nil { return crypto.PublicKey{}, fmt.Errorf("could not create key pair since no keys service is attached, " + "pass --keys flag") } curveType := crypto.CurveTypeEd25519 if curveTypeString != "" { curveType, err = crypto.CurveTypeFromString(curveTypeString) if err != nil { return crypto.PublicKey{}, err } } address, err := c.keyClient.Generate(keyName, curveType) if err != nil { return crypto.PublicKey{}, err } return c.keyClient.PublicKey(address) }
go
func (c *Client) CreateKey(keyName, curveTypeString string, logger *logging.Logger) (crypto.PublicKey, error) { err := c.dial(logger) if err != nil { return crypto.PublicKey{}, err } if c.keyClient == nil { return crypto.PublicKey{}, fmt.Errorf("could not create key pair since no keys service is attached, " + "pass --keys flag") } curveType := crypto.CurveTypeEd25519 if curveTypeString != "" { curveType, err = crypto.CurveTypeFromString(curveTypeString) if err != nil { return crypto.PublicKey{}, err } } address, err := c.keyClient.Generate(keyName, curveType) if err != nil { return crypto.PublicKey{}, err } return c.keyClient.PublicKey(address) }
[ "func", "(", "c", "*", "Client", ")", "CreateKey", "(", "keyName", ",", "curveTypeString", "string", ",", "logger", "*", "logging", ".", "Logger", ")", "(", "crypto", ".", "PublicKey", ",", "error", ")", "{", "err", ":=", "c", ".", "dial", "(", "logger", ")", "\n", "if", "err", "!=", "nil", "{", "return", "crypto", ".", "PublicKey", "{", "}", ",", "err", "\n", "}", "\n", "if", "c", ".", "keyClient", "==", "nil", "{", "return", "crypto", ".", "PublicKey", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"could not create key pair since no keys service is attached, \"", "+", "\"pass --keys flag\"", ")", "\n", "}", "\n", "curveType", ":=", "crypto", ".", "CurveTypeEd25519", "\n", "if", "curveTypeString", "!=", "\"\"", "{", "curveType", ",", "err", "=", "crypto", ".", "CurveTypeFromString", "(", "curveTypeString", ")", "\n", "if", "err", "!=", "nil", "{", "return", "crypto", ".", "PublicKey", "{", "}", ",", "err", "\n", "}", "\n", "}", "\n", "address", ",", "err", ":=", "c", ".", "keyClient", ".", "Generate", "(", "keyName", ",", "curveType", ")", "\n", "if", "err", "!=", "nil", "{", "return", "crypto", ".", "PublicKey", "{", "}", ",", "err", "\n", "}", "\n", "return", "c", ".", "keyClient", ".", "PublicKey", "(", "address", ")", "\n", "}" ]
// Creates a keypair using attached keys service
[ "Creates", "a", "keypair", "using", "attached", "keys", "service" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/deploy/def/client.go#L238-L259
train
hyperledger/burrow
deploy/def/client.go
Broadcast
func (c *Client) Broadcast(tx payload.Payload, logger *logging.Logger) (*exec.TxExecution, error) { err := c.dial(logger) if err != nil { return nil, err } ctx, cancel := context.WithTimeout(context.Background(), c.timeout) defer cancel() return c.transactClient.BroadcastTxSync(ctx, &rpctransact.TxEnvelopeParam{Payload: tx.Any()}) }
go
func (c *Client) Broadcast(tx payload.Payload, logger *logging.Logger) (*exec.TxExecution, error) { err := c.dial(logger) if err != nil { return nil, err } ctx, cancel := context.WithTimeout(context.Background(), c.timeout) defer cancel() return c.transactClient.BroadcastTxSync(ctx, &rpctransact.TxEnvelopeParam{Payload: tx.Any()}) }
[ "func", "(", "c", "*", "Client", ")", "Broadcast", "(", "tx", "payload", ".", "Payload", ",", "logger", "*", "logging", ".", "Logger", ")", "(", "*", "exec", ".", "TxExecution", ",", "error", ")", "{", "err", ":=", "c", ".", "dial", "(", "logger", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "context", ".", "Background", "(", ")", ",", "c", ".", "timeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "return", "c", ".", "transactClient", ".", "BroadcastTxSync", "(", "ctx", ",", "&", "rpctransact", ".", "TxEnvelopeParam", "{", "Payload", ":", "tx", ".", "Any", "(", ")", "}", ")", "\n", "}" ]
// Broadcast payload for remote signing
[ "Broadcast", "payload", "for", "remote", "signing" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/deploy/def/client.go#L262-L270
train
hyperledger/burrow
deploy/def/client.go
BroadcastEnvelope
func (c *Client) BroadcastEnvelope(txEnv *txs.Envelope, logger *logging.Logger) (*exec.TxExecution, error) { err := c.dial(logger) if err != nil { return nil, err } ctx, cancel := context.WithTimeout(context.Background(), c.timeout) defer cancel() return c.transactClient.BroadcastTxSync(ctx, &rpctransact.TxEnvelopeParam{Envelope: txEnv}) }
go
func (c *Client) BroadcastEnvelope(txEnv *txs.Envelope, logger *logging.Logger) (*exec.TxExecution, error) { err := c.dial(logger) if err != nil { return nil, err } ctx, cancel := context.WithTimeout(context.Background(), c.timeout) defer cancel() return c.transactClient.BroadcastTxSync(ctx, &rpctransact.TxEnvelopeParam{Envelope: txEnv}) }
[ "func", "(", "c", "*", "Client", ")", "BroadcastEnvelope", "(", "txEnv", "*", "txs", ".", "Envelope", ",", "logger", "*", "logging", ".", "Logger", ")", "(", "*", "exec", ".", "TxExecution", ",", "error", ")", "{", "err", ":=", "c", ".", "dial", "(", "logger", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "context", ".", "Background", "(", ")", ",", "c", ".", "timeout", ")", "\n", "defer", "cancel", "(", ")", "\n", "return", "c", ".", "transactClient", ".", "BroadcastTxSync", "(", "ctx", ",", "&", "rpctransact", ".", "TxEnvelopeParam", "{", "Envelope", ":", "txEnv", "}", ")", "\n", "}" ]
// Broadcast envelope - can be locally signed or remote signing will be attempted
[ "Broadcast", "envelope", "-", "can", "be", "locally", "signed", "or", "remote", "signing", "will", "be", "attempted" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/deploy/def/client.go#L273-L282
train
hyperledger/burrow
core/processes.go
NoConsensusLauncher
func NoConsensusLauncher(kern *Kernel) process.Launcher { return process.Launcher{ Name: NoConsensusProcessName, Enabled: kern.Node == nil, Launch: func() (process.Process, error) { accountState := kern.State nameRegState := kern.State kern.Service = rpc.NewService(accountState, nameRegState, kern.Blockchain, kern.State, nil, kern.Logger) // TimeoutFactor scales in units of seconds blockDuration := time.Duration(kern.timeoutFactor * float64(time.Second)) //proc := abci.NewProcess(kern.checker, kern.committer, kern.Blockchain, kern.txCodec, blockDuration, kern.Panic) proc := abci.NewProcess(kern.committer, kern.Blockchain, kern.txCodec, blockDuration, kern.Panic) // Provide execution accounts against backend state since we will commit immediately accounts := execution.NewAccounts(kern.committer, kern.keyClient, AccountsRingMutexCount) // Elide consensus and use a CheckTx function that immediately commits any valid transaction kern.Transactor = execution.NewTransactor(kern.Blockchain, kern.Emitter, accounts, proc.CheckTx, kern.txCodec, kern.Logger) return proc, nil }, } }
go
func NoConsensusLauncher(kern *Kernel) process.Launcher { return process.Launcher{ Name: NoConsensusProcessName, Enabled: kern.Node == nil, Launch: func() (process.Process, error) { accountState := kern.State nameRegState := kern.State kern.Service = rpc.NewService(accountState, nameRegState, kern.Blockchain, kern.State, nil, kern.Logger) // TimeoutFactor scales in units of seconds blockDuration := time.Duration(kern.timeoutFactor * float64(time.Second)) //proc := abci.NewProcess(kern.checker, kern.committer, kern.Blockchain, kern.txCodec, blockDuration, kern.Panic) proc := abci.NewProcess(kern.committer, kern.Blockchain, kern.txCodec, blockDuration, kern.Panic) // Provide execution accounts against backend state since we will commit immediately accounts := execution.NewAccounts(kern.committer, kern.keyClient, AccountsRingMutexCount) // Elide consensus and use a CheckTx function that immediately commits any valid transaction kern.Transactor = execution.NewTransactor(kern.Blockchain, kern.Emitter, accounts, proc.CheckTx, kern.txCodec, kern.Logger) return proc, nil }, } }
[ "func", "NoConsensusLauncher", "(", "kern", "*", "Kernel", ")", "process", ".", "Launcher", "{", "return", "process", ".", "Launcher", "{", "Name", ":", "NoConsensusProcessName", ",", "Enabled", ":", "kern", ".", "Node", "==", "nil", ",", "Launch", ":", "func", "(", ")", "(", "process", ".", "Process", ",", "error", ")", "{", "accountState", ":=", "kern", ".", "State", "\n", "nameRegState", ":=", "kern", ".", "State", "\n", "kern", ".", "Service", "=", "rpc", ".", "NewService", "(", "accountState", ",", "nameRegState", ",", "kern", ".", "Blockchain", ",", "kern", ".", "State", ",", "nil", ",", "kern", ".", "Logger", ")", "\n", "blockDuration", ":=", "time", ".", "Duration", "(", "kern", ".", "timeoutFactor", "*", "float64", "(", "time", ".", "Second", ")", ")", "\n", "proc", ":=", "abci", ".", "NewProcess", "(", "kern", ".", "committer", ",", "kern", ".", "Blockchain", ",", "kern", ".", "txCodec", ",", "blockDuration", ",", "kern", ".", "Panic", ")", "\n", "accounts", ":=", "execution", ".", "NewAccounts", "(", "kern", ".", "committer", ",", "kern", ".", "keyClient", ",", "AccountsRingMutexCount", ")", "\n", "kern", ".", "Transactor", "=", "execution", ".", "NewTransactor", "(", "kern", ".", "Blockchain", ",", "kern", ".", "Emitter", ",", "accounts", ",", "proc", ".", "CheckTx", ",", "kern", ".", "txCodec", ",", "kern", ".", "Logger", ")", "\n", "return", "proc", ",", "nil", "\n", "}", ",", "}", "\n", "}" ]
// Run a single uncoordinated local state
[ "Run", "a", "single", "uncoordinated", "local", "state" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/core/processes.go#L87-L107
train
hyperledger/burrow
acm/private_account.go
SigningAccounts
func SigningAccounts(concretePrivateAccounts []*PrivateAccount) []AddressableSigner { signingAccounts := make([]AddressableSigner, len(concretePrivateAccounts)) for i, cpa := range concretePrivateAccounts { signingAccounts[i] = cpa } return signingAccounts }
go
func SigningAccounts(concretePrivateAccounts []*PrivateAccount) []AddressableSigner { signingAccounts := make([]AddressableSigner, len(concretePrivateAccounts)) for i, cpa := range concretePrivateAccounts { signingAccounts[i] = cpa } return signingAccounts }
[ "func", "SigningAccounts", "(", "concretePrivateAccounts", "[", "]", "*", "PrivateAccount", ")", "[", "]", "AddressableSigner", "{", "signingAccounts", ":=", "make", "(", "[", "]", "AddressableSigner", ",", "len", "(", "concretePrivateAccounts", ")", ")", "\n", "for", "i", ",", "cpa", ":=", "range", "concretePrivateAccounts", "{", "signingAccounts", "[", "i", "]", "=", "cpa", "\n", "}", "\n", "return", "signingAccounts", "\n", "}" ]
// Convert slice of ConcretePrivateAccounts to slice of SigningAccounts
[ "Convert", "slice", "of", "ConcretePrivateAccounts", "to", "slice", "of", "SigningAccounts" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/private_account.go#L99-L105
train
hyperledger/burrow
acm/private_account.go
GeneratePrivateAccount
func GeneratePrivateAccount() (*PrivateAccount, error) { privateKey, err := crypto.GeneratePrivateKey(nil, crypto.CurveTypeEd25519) if err != nil { return nil, err } publicKey := privateKey.GetPublicKey() return ConcretePrivateAccount{ Address: publicKey.GetAddress(), PublicKey: publicKey, PrivateKey: privateKey, }.PrivateAccount(), nil }
go
func GeneratePrivateAccount() (*PrivateAccount, error) { privateKey, err := crypto.GeneratePrivateKey(nil, crypto.CurveTypeEd25519) if err != nil { return nil, err } publicKey := privateKey.GetPublicKey() return ConcretePrivateAccount{ Address: publicKey.GetAddress(), PublicKey: publicKey, PrivateKey: privateKey, }.PrivateAccount(), nil }
[ "func", "GeneratePrivateAccount", "(", ")", "(", "*", "PrivateAccount", ",", "error", ")", "{", "privateKey", ",", "err", ":=", "crypto", ".", "GeneratePrivateKey", "(", "nil", ",", "crypto", ".", "CurveTypeEd25519", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "publicKey", ":=", "privateKey", ".", "GetPublicKey", "(", ")", "\n", "return", "ConcretePrivateAccount", "{", "Address", ":", "publicKey", ".", "GetAddress", "(", ")", ",", "PublicKey", ":", "publicKey", ",", "PrivateKey", ":", "privateKey", ",", "}", ".", "PrivateAccount", "(", ")", ",", "nil", "\n", "}" ]
// Generates a new account with private key.
[ "Generates", "a", "new", "account", "with", "private", "key", "." ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/private_account.go#L108-L119
train
hyperledger/burrow
acm/private_account.go
GeneratePrivateAccountFromSecret
func GeneratePrivateAccountFromSecret(secret string) *PrivateAccount { privateKey := crypto.PrivateKeyFromSecret(secret, crypto.CurveTypeEd25519) publicKey := privateKey.GetPublicKey() return ConcretePrivateAccount{ Address: publicKey.GetAddress(), PublicKey: publicKey, PrivateKey: privateKey, }.PrivateAccount() }
go
func GeneratePrivateAccountFromSecret(secret string) *PrivateAccount { privateKey := crypto.PrivateKeyFromSecret(secret, crypto.CurveTypeEd25519) publicKey := privateKey.GetPublicKey() return ConcretePrivateAccount{ Address: publicKey.GetAddress(), PublicKey: publicKey, PrivateKey: privateKey, }.PrivateAccount() }
[ "func", "GeneratePrivateAccountFromSecret", "(", "secret", "string", ")", "*", "PrivateAccount", "{", "privateKey", ":=", "crypto", ".", "PrivateKeyFromSecret", "(", "secret", ",", "crypto", ".", "CurveTypeEd25519", ")", "\n", "publicKey", ":=", "privateKey", ".", "GetPublicKey", "(", ")", "\n", "return", "ConcretePrivateAccount", "{", "Address", ":", "publicKey", ".", "GetAddress", "(", ")", ",", "PublicKey", ":", "publicKey", ",", "PrivateKey", ":", "privateKey", ",", "}", ".", "PrivateAccount", "(", ")", "\n", "}" ]
// Generates a new account with private key from SHA256 hash of a secret
[ "Generates", "a", "new", "account", "with", "private", "key", "from", "SHA256", "hash", "of", "a", "secret" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/private_account.go#L122-L130
train
hyperledger/burrow
cmd/burrow/commands/snatives.go
Snatives
func Snatives(output Output) func(cmd *cli.Cmd) { return func(cmd *cli.Cmd) { contractsOpt := cmd.StringsOpt("c contracts", nil, "Contracts to generate") cmd.Action = func() { contracts := evm.SNativeContracts() // Index of next contract i := 1 for _, contract := range contracts { if len(*contractsOpt) > 0 { found := false for _, c := range *contractsOpt { if c == contract.Name { found = true break } } if !found { continue } } solidity, err := templates.NewSolidityContract(contract).Solidity() if err != nil { fmt.Printf("Error generating solidity for contract %s: %s\n", contract.Name, err) } fmt.Println(solidity) if i < len(contracts) { // Two new lines between contracts as per Solidity style guide // (the template gives us 1 trailing new line) fmt.Println() } i++ } } } }
go
func Snatives(output Output) func(cmd *cli.Cmd) { return func(cmd *cli.Cmd) { contractsOpt := cmd.StringsOpt("c contracts", nil, "Contracts to generate") cmd.Action = func() { contracts := evm.SNativeContracts() // Index of next contract i := 1 for _, contract := range contracts { if len(*contractsOpt) > 0 { found := false for _, c := range *contractsOpt { if c == contract.Name { found = true break } } if !found { continue } } solidity, err := templates.NewSolidityContract(contract).Solidity() if err != nil { fmt.Printf("Error generating solidity for contract %s: %s\n", contract.Name, err) } fmt.Println(solidity) if i < len(contracts) { // Two new lines between contracts as per Solidity style guide // (the template gives us 1 trailing new line) fmt.Println() } i++ } } } }
[ "func", "Snatives", "(", "output", "Output", ")", "func", "(", "cmd", "*", "cli", ".", "Cmd", ")", "{", "return", "func", "(", "cmd", "*", "cli", ".", "Cmd", ")", "{", "contractsOpt", ":=", "cmd", ".", "StringsOpt", "(", "\"c contracts\"", ",", "nil", ",", "\"Contracts to generate\"", ")", "\n", "cmd", ".", "Action", "=", "func", "(", ")", "{", "contracts", ":=", "evm", ".", "SNativeContracts", "(", ")", "\n", "i", ":=", "1", "\n", "for", "_", ",", "contract", ":=", "range", "contracts", "{", "if", "len", "(", "*", "contractsOpt", ")", ">", "0", "{", "found", ":=", "false", "\n", "for", "_", ",", "c", ":=", "range", "*", "contractsOpt", "{", "if", "c", "==", "contract", ".", "Name", "{", "found", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "!", "found", "{", "continue", "\n", "}", "\n", "}", "\n", "solidity", ",", "err", ":=", "templates", ".", "NewSolidityContract", "(", "contract", ")", ".", "Solidity", "(", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"Error generating solidity for contract %s: %s\\n\"", ",", "\\n", ",", "contract", ".", "Name", ")", "\n", "}", "\n", "err", "\n", "fmt", ".", "Println", "(", "solidity", ")", "\n", "if", "i", "<", "len", "(", "contracts", ")", "{", "fmt", ".", "Println", "(", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// Dump SNative contracts
[ "Dump", "SNative", "contracts" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/cmd/burrow/commands/snatives.go#L27-L62
train
hyperledger/burrow
storage/rwtree.go
Save
func (rwt *RWTree) Save() ([]byte, int64, error) { // save state at a new version may still be orphaned before we save the version against the hash hash, version, err := rwt.tree.SaveVersion() if err != nil { return nil, 0, fmt.Errorf("could not save RWTree: %v", err) } // Take an immutable reference to the tree we just saved for querying rwt.ImmutableTree, err = rwt.tree.GetImmutable(version) if err != nil { return nil, 0, fmt.Errorf("RWTree.Save() could not obtain ImmutableTree read tree: %v", err) } rwt.updated = false return hash, version, nil }
go
func (rwt *RWTree) Save() ([]byte, int64, error) { // save state at a new version may still be orphaned before we save the version against the hash hash, version, err := rwt.tree.SaveVersion() if err != nil { return nil, 0, fmt.Errorf("could not save RWTree: %v", err) } // Take an immutable reference to the tree we just saved for querying rwt.ImmutableTree, err = rwt.tree.GetImmutable(version) if err != nil { return nil, 0, fmt.Errorf("RWTree.Save() could not obtain ImmutableTree read tree: %v", err) } rwt.updated = false return hash, version, nil }
[ "func", "(", "rwt", "*", "RWTree", ")", "Save", "(", ")", "(", "[", "]", "byte", ",", "int64", ",", "error", ")", "{", "hash", ",", "version", ",", "err", ":=", "rwt", ".", "tree", ".", "SaveVersion", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "fmt", ".", "Errorf", "(", "\"could not save RWTree: %v\"", ",", "err", ")", "\n", "}", "\n", "rwt", ".", "ImmutableTree", ",", "err", "=", "rwt", ".", "tree", ".", "GetImmutable", "(", "version", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "fmt", ".", "Errorf", "(", "\"RWTree.Save() could not obtain ImmutableTree read tree: %v\"", ",", "err", ")", "\n", "}", "\n", "rwt", ".", "updated", "=", "false", "\n", "return", "hash", ",", "version", ",", "nil", "\n", "}" ]
// Save the current write tree making writes accessible from read tree.
[ "Save", "the", "current", "write", "tree", "making", "writes", "accessible", "from", "read", "tree", "." ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/storage/rwtree.go#L50-L63
train
hyperledger/burrow
execution/evm/stack.go
PushBytes
func (st *Stack) PushBytes(bz []byte) { if len(bz) != 32 { panic("Invalid bytes size: expected 32") } st.Push(LeftPadWord256(bz)) }
go
func (st *Stack) PushBytes(bz []byte) { if len(bz) != 32 { panic("Invalid bytes size: expected 32") } st.Push(LeftPadWord256(bz)) }
[ "func", "(", "st", "*", "Stack", ")", "PushBytes", "(", "bz", "[", "]", "byte", ")", "{", "if", "len", "(", "bz", ")", "!=", "32", "{", "panic", "(", "\"Invalid bytes size: expected 32\"", ")", "\n", "}", "\n", "st", ".", "Push", "(", "LeftPadWord256", "(", "bz", ")", ")", "\n", "}" ]
// currently only called after sha3.Sha3
[ "currently", "only", "called", "after", "sha3", ".", "Sha3" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/execution/evm/stack.go#L74-L79
train
hyperledger/burrow
execution/evm/stack.go
PushBigInt
func (st *Stack) PushBigInt(bigInt *big.Int) Word256 { word := LeftPadWord256(U256(bigInt).Bytes()) st.Push(word) return word }
go
func (st *Stack) PushBigInt(bigInt *big.Int) Word256 { word := LeftPadWord256(U256(bigInt).Bytes()) st.Push(word) return word }
[ "func", "(", "st", "*", "Stack", ")", "PushBigInt", "(", "bigInt", "*", "big", ".", "Int", ")", "Word256", "{", "word", ":=", "LeftPadWord256", "(", "U256", "(", "bigInt", ")", ".", "Bytes", "(", ")", ")", "\n", "st", ".", "Push", "(", "word", ")", "\n", "return", "word", "\n", "}" ]
// Pushes the bigInt as a Word256 encoding negative values in 32-byte twos complement and returns the encoded result
[ "Pushes", "the", "bigInt", "as", "a", "Word256", "encoding", "negative", "values", "in", "32", "-", "byte", "twos", "complement", "and", "returns", "the", "encoded", "result" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/execution/evm/stack.go#L94-L98
train
hyperledger/burrow
execution/evm/stack.go
Peek
func (st *Stack) Peek() Word256 { if st.ptr == 0 { st.pushErr(errors.ErrorCodeDataStackUnderflow) return Zero256 } return st.slice[st.ptr-1] }
go
func (st *Stack) Peek() Word256 { if st.ptr == 0 { st.pushErr(errors.ErrorCodeDataStackUnderflow) return Zero256 } return st.slice[st.ptr-1] }
[ "func", "(", "st", "*", "Stack", ")", "Peek", "(", ")", "Word256", "{", "if", "st", ".", "ptr", "==", "0", "{", "st", ".", "pushErr", "(", "errors", ".", "ErrorCodeDataStackUnderflow", ")", "\n", "return", "Zero256", "\n", "}", "\n", "return", "st", ".", "slice", "[", "st", ".", "ptr", "-", "1", "]", "\n", "}" ]
// Not an opcode, costs no gas.
[ "Not", "an", "opcode", "costs", "no", "gas", "." ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/execution/evm/stack.go#L170-L176
train
hyperledger/burrow
acm/acmstate/state_cache.go
NewCache
func NewCache(backend Reader, options ...CacheOption) *Cache { cache := &Cache{ backend: backend, accounts: make(map[crypto.Address]*accountInfo), } for _, option := range options { option(cache) } return cache }
go
func NewCache(backend Reader, options ...CacheOption) *Cache { cache := &Cache{ backend: backend, accounts: make(map[crypto.Address]*accountInfo), } for _, option := range options { option(cache) } return cache }
[ "func", "NewCache", "(", "backend", "Reader", ",", "options", "...", "CacheOption", ")", "*", "Cache", "{", "cache", ":=", "&", "Cache", "{", "backend", ":", "backend", ",", "accounts", ":", "make", "(", "map", "[", "crypto", ".", "Address", "]", "*", "accountInfo", ")", ",", "}", "\n", "for", "_", ",", "option", ":=", "range", "options", "{", "option", "(", "cache", ")", "\n", "}", "\n", "return", "cache", "\n", "}" ]
// Returns a Cache that wraps an underlying Reader to use on a cache miss, can write to an output Writer // via Sync. Goroutine safe for concurrent access.
[ "Returns", "a", "Cache", "that", "wraps", "an", "underlying", "Reader", "to", "use", "on", "a", "cache", "miss", "can", "write", "to", "an", "output", "Writer", "via", "Sync", ".", "Goroutine", "safe", "for", "concurrent", "access", "." ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/acmstate/state_cache.go#L49-L58
train
hyperledger/burrow
acm/acmstate/state_cache.go
IterateCachedAccount
func (cache *Cache) IterateCachedAccount(consumer func(*acm.Account) (stop bool)) (stopped bool, err error) { // Try cache first for early exit cache.RLock() for _, info := range cache.accounts { if consumer(info.account) { cache.RUnlock() return true, nil } } cache.RUnlock() return false, nil }
go
func (cache *Cache) IterateCachedAccount(consumer func(*acm.Account) (stop bool)) (stopped bool, err error) { // Try cache first for early exit cache.RLock() for _, info := range cache.accounts { if consumer(info.account) { cache.RUnlock() return true, nil } } cache.RUnlock() return false, nil }
[ "func", "(", "cache", "*", "Cache", ")", "IterateCachedAccount", "(", "consumer", "func", "(", "*", "acm", ".", "Account", ")", "(", "stop", "bool", ")", ")", "(", "stopped", "bool", ",", "err", "error", ")", "{", "cache", ".", "RLock", "(", ")", "\n", "for", "_", ",", "info", ":=", "range", "cache", ".", "accounts", "{", "if", "consumer", "(", "info", ".", "account", ")", "{", "cache", ".", "RUnlock", "(", ")", "\n", "return", "true", ",", "nil", "\n", "}", "\n", "}", "\n", "cache", ".", "RUnlock", "(", ")", "\n", "return", "false", ",", "nil", "\n", "}" ]
// Iterates over all cached accounts first in cache and then in backend until consumer returns true for 'stop'
[ "Iterates", "over", "all", "cached", "accounts", "first", "in", "cache", "and", "then", "in", "backend", "until", "consumer", "returns", "true", "for", "stop" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/acmstate/state_cache.go#L125-L136
train
hyperledger/burrow
acm/acmstate/state_cache.go
IterateCachedStorage
func (cache *Cache) IterateCachedStorage(address crypto.Address, consumer func(key, value binary.Word256) error) error { accInfo, err := cache.get(address) if err != nil { return err } accInfo.RLock() // Try cache first for early exit for key, value := range accInfo.storage { if err := consumer(key, value); err != nil { accInfo.RUnlock() return err } } accInfo.RUnlock() return err }
go
func (cache *Cache) IterateCachedStorage(address crypto.Address, consumer func(key, value binary.Word256) error) error { accInfo, err := cache.get(address) if err != nil { return err } accInfo.RLock() // Try cache first for early exit for key, value := range accInfo.storage { if err := consumer(key, value); err != nil { accInfo.RUnlock() return err } } accInfo.RUnlock() return err }
[ "func", "(", "cache", "*", "Cache", ")", "IterateCachedStorage", "(", "address", "crypto", ".", "Address", ",", "consumer", "func", "(", "key", ",", "value", "binary", ".", "Word256", ")", "error", ")", "error", "{", "accInfo", ",", "err", ":=", "cache", ".", "get", "(", "address", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "accInfo", ".", "RLock", "(", ")", "\n", "for", "key", ",", "value", ":=", "range", "accInfo", ".", "storage", "{", "if", "err", ":=", "consumer", "(", "key", ",", "value", ")", ";", "err", "!=", "nil", "{", "accInfo", ".", "RUnlock", "(", ")", "\n", "return", "err", "\n", "}", "\n", "}", "\n", "accInfo", ".", "RUnlock", "(", ")", "\n", "return", "err", "\n", "}" ]
// Iterates over all cached storage items first in cache and then in backend until consumer returns true for 'stop'
[ "Iterates", "over", "all", "cached", "storage", "items", "first", "in", "cache", "and", "then", "in", "backend", "until", "consumer", "returns", "true", "for", "stop" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/acmstate/state_cache.go#L188-L204
train
hyperledger/burrow
acm/acmstate/state_cache.go
Sync
func (cache *Cache) Sync(st Writer) error { if cache.readonly { // Sync is (should be) a no-op for read-only - any modifications should have been caught in respective methods return nil } cache.Lock() defer cache.Unlock() var addresses crypto.Addresses for address := range cache.accounts { addresses = append(addresses, address) } sort.Sort(addresses) for _, address := range addresses { accInfo := cache.accounts[address] accInfo.RLock() if accInfo.removed { err := st.RemoveAccount(address) if err != nil { return err } } else if accInfo.updated { // First update account in case it needs to be created err := st.UpdateAccount(accInfo.account) if err != nil { return err } // Sort keys var keys binary.Words256 for key := range accInfo.storage { keys = append(keys, key) } sort.Sort(keys) // Update account's storage for _, key := range keys { value := accInfo.storage[key] err := st.SetStorage(address, key, value) if err != nil { return err } } } accInfo.RUnlock() } return nil }
go
func (cache *Cache) Sync(st Writer) error { if cache.readonly { // Sync is (should be) a no-op for read-only - any modifications should have been caught in respective methods return nil } cache.Lock() defer cache.Unlock() var addresses crypto.Addresses for address := range cache.accounts { addresses = append(addresses, address) } sort.Sort(addresses) for _, address := range addresses { accInfo := cache.accounts[address] accInfo.RLock() if accInfo.removed { err := st.RemoveAccount(address) if err != nil { return err } } else if accInfo.updated { // First update account in case it needs to be created err := st.UpdateAccount(accInfo.account) if err != nil { return err } // Sort keys var keys binary.Words256 for key := range accInfo.storage { keys = append(keys, key) } sort.Sort(keys) // Update account's storage for _, key := range keys { value := accInfo.storage[key] err := st.SetStorage(address, key, value) if err != nil { return err } } } accInfo.RUnlock() } return nil }
[ "func", "(", "cache", "*", "Cache", ")", "Sync", "(", "st", "Writer", ")", "error", "{", "if", "cache", ".", "readonly", "{", "return", "nil", "\n", "}", "\n", "cache", ".", "Lock", "(", ")", "\n", "defer", "cache", ".", "Unlock", "(", ")", "\n", "var", "addresses", "crypto", ".", "Addresses", "\n", "for", "address", ":=", "range", "cache", ".", "accounts", "{", "addresses", "=", "append", "(", "addresses", ",", "address", ")", "\n", "}", "\n", "sort", ".", "Sort", "(", "addresses", ")", "\n", "for", "_", ",", "address", ":=", "range", "addresses", "{", "accInfo", ":=", "cache", ".", "accounts", "[", "address", "]", "\n", "accInfo", ".", "RLock", "(", ")", "\n", "if", "accInfo", ".", "removed", "{", "err", ":=", "st", ".", "RemoveAccount", "(", "address", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "else", "if", "accInfo", ".", "updated", "{", "err", ":=", "st", ".", "UpdateAccount", "(", "accInfo", ".", "account", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "var", "keys", "binary", ".", "Words256", "\n", "for", "key", ":=", "range", "accInfo", ".", "storage", "{", "keys", "=", "append", "(", "keys", ",", "key", ")", "\n", "}", "\n", "sort", ".", "Sort", "(", "keys", ")", "\n", "for", "_", ",", "key", ":=", "range", "keys", "{", "value", ":=", "accInfo", ".", "storage", "[", "key", "]", "\n", "err", ":=", "st", ".", "SetStorage", "(", "address", ",", "key", ",", "value", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "accInfo", ".", "RUnlock", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Syncs changes to the backend in deterministic order. Sends storage updates before updating // the account they belong so that storage values can be taken account of in the update.
[ "Syncs", "changes", "to", "the", "backend", "in", "deterministic", "order", ".", "Sends", "storage", "updates", "before", "updating", "the", "account", "they", "belong", "so", "that", "storage", "values", "can", "be", "taken", "account", "of", "in", "the", "update", "." ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/acmstate/state_cache.go#L208-L254
train
hyperledger/burrow
logging/logconfig/filter.go
matchLogLine
func matchLogLine(keyvals []interface{}, keyRegexes, valueRegexes []*regexp.Regexp, matchAll bool) bool { all := matchAll // We should be passed an aligned list of keyRegexes and valueRegexes, but since we can't error here we'll guard // against a failure of the caller to pass valid arguments length := len(keyRegexes) if len(valueRegexes) < length { length = len(valueRegexes) } for i := 0; i < length; i++ { matched := findMatchInLogLine(keyvals, keyRegexes[i], valueRegexes[i]) if matchAll { all = all && matched } else if matched { return true } } return all }
go
func matchLogLine(keyvals []interface{}, keyRegexes, valueRegexes []*regexp.Regexp, matchAll bool) bool { all := matchAll // We should be passed an aligned list of keyRegexes and valueRegexes, but since we can't error here we'll guard // against a failure of the caller to pass valid arguments length := len(keyRegexes) if len(valueRegexes) < length { length = len(valueRegexes) } for i := 0; i < length; i++ { matched := findMatchInLogLine(keyvals, keyRegexes[i], valueRegexes[i]) if matchAll { all = all && matched } else if matched { return true } } return all }
[ "func", "matchLogLine", "(", "keyvals", "[", "]", "interface", "{", "}", ",", "keyRegexes", ",", "valueRegexes", "[", "]", "*", "regexp", ".", "Regexp", ",", "matchAll", "bool", ")", "bool", "{", "all", ":=", "matchAll", "\n", "length", ":=", "len", "(", "keyRegexes", ")", "\n", "if", "len", "(", "valueRegexes", ")", "<", "length", "{", "length", "=", "len", "(", "valueRegexes", ")", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "length", ";", "i", "++", "{", "matched", ":=", "findMatchInLogLine", "(", "keyvals", ",", "keyRegexes", "[", "i", "]", ",", "valueRegexes", "[", "i", "]", ")", "\n", "if", "matchAll", "{", "all", "=", "all", "&&", "matched", "\n", "}", "else", "if", "matched", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "all", "\n", "}" ]
// matchLogLine tries to match a log line by trying to match each key value pair with each pair of key value regexes // if matchAll is true then matchLogLine returns true iff every key value regexes finds a match or the line or regexes // are empty
[ "matchLogLine", "tries", "to", "match", "a", "log", "line", "by", "trying", "to", "match", "each", "key", "value", "pair", "with", "each", "pair", "of", "key", "value", "regexes", "if", "matchAll", "is", "true", "then", "matchLogLine", "returns", "true", "iff", "every", "key", "value", "regexes", "finds", "a", "match", "or", "the", "line", "or", "regexes", "are", "empty" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/logging/logconfig/filter.go#L54-L71
train
hyperledger/burrow
genesis/genesis.go
JSONBytes
func (genesisDoc *GenesisDoc) JSONBytes() ([]byte, error) { // Just in case genesisDoc.GenesisTime = genesisDoc.GenesisTime.UTC() return json.MarshalIndent(genesisDoc, "", "\t") }
go
func (genesisDoc *GenesisDoc) JSONBytes() ([]byte, error) { // Just in case genesisDoc.GenesisTime = genesisDoc.GenesisTime.UTC() return json.MarshalIndent(genesisDoc, "", "\t") }
[ "func", "(", "genesisDoc", "*", "GenesisDoc", ")", "JSONBytes", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "genesisDoc", ".", "GenesisTime", "=", "genesisDoc", ".", "GenesisTime", ".", "UTC", "(", ")", "\n", "return", "json", ".", "MarshalIndent", "(", "genesisDoc", ",", "\"\"", ",", "\"\\t\"", ")", "\n", "}" ]
// JSONBytes returns the JSON canonical bytes for a given GenesisDoc or an error.
[ "JSONBytes", "returns", "the", "JSON", "canonical", "bytes", "for", "a", "given", "GenesisDoc", "or", "an", "error", "." ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/genesis/genesis.go#L91-L95
train
hyperledger/burrow
genesis/genesis.go
Clone
func (genesisAccount *Account) Clone() Account { // clone the account permissions return Account{ BasicAccount: BasicAccount{ Address: genesisAccount.Address, Amount: genesisAccount.Amount, }, Name: genesisAccount.Name, Permissions: genesisAccount.Permissions.Clone(), } }
go
func (genesisAccount *Account) Clone() Account { // clone the account permissions return Account{ BasicAccount: BasicAccount{ Address: genesisAccount.Address, Amount: genesisAccount.Amount, }, Name: genesisAccount.Name, Permissions: genesisAccount.Permissions.Clone(), } }
[ "func", "(", "genesisAccount", "*", "Account", ")", "Clone", "(", ")", "Account", "{", "return", "Account", "{", "BasicAccount", ":", "BasicAccount", "{", "Address", ":", "genesisAccount", ".", "Address", ",", "Amount", ":", "genesisAccount", ".", "Amount", ",", "}", ",", "Name", ":", "genesisAccount", ".", "Name", ",", "Permissions", ":", "genesisAccount", ".", "Permissions", ".", "Clone", "(", ")", ",", "}", "\n", "}" ]
// Clone clones the genesis account
[ "Clone", "clones", "the", "genesis", "account" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/genesis/genesis.go#L151-L161
train
hyperledger/burrow
genesis/genesis.go
Clone
func (gv *Validator) Clone() Validator { // clone the addresses to unbond to unbondToClone := make([]BasicAccount, len(gv.UnbondTo)) for i, basicAccount := range gv.UnbondTo { unbondToClone[i] = basicAccount.Clone() } return Validator{ BasicAccount: BasicAccount{ PublicKey: gv.PublicKey, Amount: gv.Amount, }, Name: gv.Name, UnbondTo: unbondToClone, NodeAddress: gv.NodeAddress, } }
go
func (gv *Validator) Clone() Validator { // clone the addresses to unbond to unbondToClone := make([]BasicAccount, len(gv.UnbondTo)) for i, basicAccount := range gv.UnbondTo { unbondToClone[i] = basicAccount.Clone() } return Validator{ BasicAccount: BasicAccount{ PublicKey: gv.PublicKey, Amount: gv.Amount, }, Name: gv.Name, UnbondTo: unbondToClone, NodeAddress: gv.NodeAddress, } }
[ "func", "(", "gv", "*", "Validator", ")", "Clone", "(", ")", "Validator", "{", "unbondToClone", ":=", "make", "(", "[", "]", "BasicAccount", ",", "len", "(", "gv", ".", "UnbondTo", ")", ")", "\n", "for", "i", ",", "basicAccount", ":=", "range", "gv", ".", "UnbondTo", "{", "unbondToClone", "[", "i", "]", "=", "basicAccount", ".", "Clone", "(", ")", "\n", "}", "\n", "return", "Validator", "{", "BasicAccount", ":", "BasicAccount", "{", "PublicKey", ":", "gv", ".", "PublicKey", ",", "Amount", ":", "gv", ".", "Amount", ",", "}", ",", "Name", ":", "gv", ".", "Name", ",", "UnbondTo", ":", "unbondToClone", ",", "NodeAddress", ":", "gv", ".", "NodeAddress", ",", "}", "\n", "}" ]
// Clone clones the genesis validator
[ "Clone", "clones", "the", "genesis", "validator" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/genesis/genesis.go#L185-L200
train
hyperledger/burrow
genesis/genesis.go
MakeGenesisDocFromAccounts
func MakeGenesisDocFromAccounts(chainName string, salt []byte, genesisTime time.Time, accounts map[string]*acm.Account, validators map[string]*validator.Validator) *GenesisDoc { // Establish deterministic order of accounts by name so we obtain identical GenesisDoc // from identical input names := make([]string, 0, len(accounts)) for name := range accounts { names = append(names, name) } sort.Strings(names) // copy slice of pointers to accounts into slice of accounts genesisAccounts := make([]Account, 0, len(accounts)) for _, name := range names { genesisAccounts = append(genesisAccounts, GenesisAccountFromAccount(name, accounts[name])) } // Sigh... names = names[:0] for name := range validators { names = append(names, name) } sort.Strings(names) // copy slice of pointers to validators into slice of validators genesisValidators := make([]Validator, 0, len(validators)) for _, name := range names { val := validators[name] genesisValidators = append(genesisValidators, Validator{ Name: name, BasicAccount: BasicAccount{ Address: *val.Address, PublicKey: val.PublicKey, Amount: val.Power, }, // Simpler to just do this by convention UnbondTo: []BasicAccount{ { Amount: val.Power, Address: *val.Address, }, }, }) } return &GenesisDoc{ ChainName: chainName, Salt: salt, GenesisTime: genesisTime, GlobalPermissions: permission.DefaultAccountPermissions.Clone(), Accounts: genesisAccounts, Validators: genesisValidators, } }
go
func MakeGenesisDocFromAccounts(chainName string, salt []byte, genesisTime time.Time, accounts map[string]*acm.Account, validators map[string]*validator.Validator) *GenesisDoc { // Establish deterministic order of accounts by name so we obtain identical GenesisDoc // from identical input names := make([]string, 0, len(accounts)) for name := range accounts { names = append(names, name) } sort.Strings(names) // copy slice of pointers to accounts into slice of accounts genesisAccounts := make([]Account, 0, len(accounts)) for _, name := range names { genesisAccounts = append(genesisAccounts, GenesisAccountFromAccount(name, accounts[name])) } // Sigh... names = names[:0] for name := range validators { names = append(names, name) } sort.Strings(names) // copy slice of pointers to validators into slice of validators genesisValidators := make([]Validator, 0, len(validators)) for _, name := range names { val := validators[name] genesisValidators = append(genesisValidators, Validator{ Name: name, BasicAccount: BasicAccount{ Address: *val.Address, PublicKey: val.PublicKey, Amount: val.Power, }, // Simpler to just do this by convention UnbondTo: []BasicAccount{ { Amount: val.Power, Address: *val.Address, }, }, }) } return &GenesisDoc{ ChainName: chainName, Salt: salt, GenesisTime: genesisTime, GlobalPermissions: permission.DefaultAccountPermissions.Clone(), Accounts: genesisAccounts, Validators: genesisValidators, } }
[ "func", "MakeGenesisDocFromAccounts", "(", "chainName", "string", ",", "salt", "[", "]", "byte", ",", "genesisTime", "time", ".", "Time", ",", "accounts", "map", "[", "string", "]", "*", "acm", ".", "Account", ",", "validators", "map", "[", "string", "]", "*", "validator", ".", "Validator", ")", "*", "GenesisDoc", "{", "names", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "accounts", ")", ")", "\n", "for", "name", ":=", "range", "accounts", "{", "names", "=", "append", "(", "names", ",", "name", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "names", ")", "\n", "genesisAccounts", ":=", "make", "(", "[", "]", "Account", ",", "0", ",", "len", "(", "accounts", ")", ")", "\n", "for", "_", ",", "name", ":=", "range", "names", "{", "genesisAccounts", "=", "append", "(", "genesisAccounts", ",", "GenesisAccountFromAccount", "(", "name", ",", "accounts", "[", "name", "]", ")", ")", "\n", "}", "\n", "names", "=", "names", "[", ":", "0", "]", "\n", "for", "name", ":=", "range", "validators", "{", "names", "=", "append", "(", "names", ",", "name", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "names", ")", "\n", "genesisValidators", ":=", "make", "(", "[", "]", "Validator", ",", "0", ",", "len", "(", "validators", ")", ")", "\n", "for", "_", ",", "name", ":=", "range", "names", "{", "val", ":=", "validators", "[", "name", "]", "\n", "genesisValidators", "=", "append", "(", "genesisValidators", ",", "Validator", "{", "Name", ":", "name", ",", "BasicAccount", ":", "BasicAccount", "{", "Address", ":", "*", "val", ".", "Address", ",", "PublicKey", ":", "val", ".", "PublicKey", ",", "Amount", ":", "val", ".", "Power", ",", "}", ",", "UnbondTo", ":", "[", "]", "BasicAccount", "{", "{", "Amount", ":", "val", ".", "Power", ",", "Address", ":", "*", "val", ".", "Address", ",", "}", ",", "}", ",", "}", ")", "\n", "}", "\n", "return", "&", "GenesisDoc", "{", "ChainName", ":", "chainName", ",", "Salt", ":", "salt", ",", "GenesisTime", ":", "genesisTime", ",", "GlobalPermissions", ":", "permission", ".", "DefaultAccountPermissions", ".", "Clone", "(", ")", ",", "Accounts", ":", "genesisAccounts", ",", "Validators", ":", "genesisValidators", ",", "}", "\n", "}" ]
// MakeGenesisDocFromAccounts takes a chainName and a slice of pointers to Account, // and a slice of pointers to Validator to construct a GenesisDoc, or returns an error on // failure. In particular MakeGenesisDocFromAccount uses the local time as a // timestamp for the GenesisDoc.
[ "MakeGenesisDocFromAccounts", "takes", "a", "chainName", "and", "a", "slice", "of", "pointers", "to", "Account", "and", "a", "slice", "of", "pointers", "to", "Validator", "to", "construct", "a", "GenesisDoc", "or", "returns", "an", "error", "on", "failure", ".", "In", "particular", "MakeGenesisDocFromAccount", "uses", "the", "local", "time", "as", "a", "timestamp", "for", "the", "GenesisDoc", "." ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/genesis/genesis.go#L217-L266
train
hyperledger/burrow
acm/bytecode.go
Tokens
func (bc Bytecode) Tokens() ([]string, error) { // Overestimate of capacity in the presence of pushes tokens := make([]string, 0, len(bc)) for i := 0; i < len(bc); i++ { op, ok := asm.GetOpCode(bc[i]) if !ok { return tokens, fmt.Errorf("did not recognise byte %#x at position %v as an OpCode:\n %s", bc[i], i, lexingPositionString(bc, i, tokens)) } pushes := op.Pushes() tokens = append(tokens, op.Name()) if pushes > 0 { // This is a PUSH<N> OpCode so consume N bytes from the input, render them as hex, and skip to next OpCode if i+pushes >= len(bc) { return tokens, fmt.Errorf("token %v of input is %s but not enough input remains to push %v: %s", i, op.Name(), pushes, lexingPositionString(bc, i, tokens)) } pushedBytes := bc[i+1 : i+pushes+1] tokens = append(tokens, fmt.Sprintf("0x%s", pushedBytes)) i += pushes } } return tokens, nil }
go
func (bc Bytecode) Tokens() ([]string, error) { // Overestimate of capacity in the presence of pushes tokens := make([]string, 0, len(bc)) for i := 0; i < len(bc); i++ { op, ok := asm.GetOpCode(bc[i]) if !ok { return tokens, fmt.Errorf("did not recognise byte %#x at position %v as an OpCode:\n %s", bc[i], i, lexingPositionString(bc, i, tokens)) } pushes := op.Pushes() tokens = append(tokens, op.Name()) if pushes > 0 { // This is a PUSH<N> OpCode so consume N bytes from the input, render them as hex, and skip to next OpCode if i+pushes >= len(bc) { return tokens, fmt.Errorf("token %v of input is %s but not enough input remains to push %v: %s", i, op.Name(), pushes, lexingPositionString(bc, i, tokens)) } pushedBytes := bc[i+1 : i+pushes+1] tokens = append(tokens, fmt.Sprintf("0x%s", pushedBytes)) i += pushes } } return tokens, nil }
[ "func", "(", "bc", "Bytecode", ")", "Tokens", "(", ")", "(", "[", "]", "string", ",", "error", ")", "{", "tokens", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "bc", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "bc", ")", ";", "i", "++", "{", "op", ",", "ok", ":=", "asm", ".", "GetOpCode", "(", "bc", "[", "i", "]", ")", "\n", "if", "!", "ok", "{", "return", "tokens", ",", "fmt", ".", "Errorf", "(", "\"did not recognise byte %#x at position %v as an OpCode:\\n %s\"", ",", "\\n", ",", "bc", "[", "i", "]", ",", "i", ")", "\n", "}", "\n", "lexingPositionString", "(", "bc", ",", "i", ",", "tokens", ")", "\n", "pushes", ":=", "op", ".", "Pushes", "(", ")", "\n", "tokens", "=", "append", "(", "tokens", ",", "op", ".", "Name", "(", ")", ")", "\n", "}", "\n", "if", "pushes", ">", "0", "{", "if", "i", "+", "pushes", ">=", "len", "(", "bc", ")", "{", "return", "tokens", ",", "fmt", ".", "Errorf", "(", "\"token %v of input is %s but not enough input remains to push %v: %s\"", ",", "i", ",", "op", ".", "Name", "(", ")", ",", "pushes", ",", "lexingPositionString", "(", "bc", ",", "i", ",", "tokens", ")", ")", "\n", "}", "\n", "pushedBytes", ":=", "bc", "[", "i", "+", "1", ":", "i", "+", "pushes", "+", "1", "]", "\n", "tokens", "=", "append", "(", "tokens", ",", "fmt", ".", "Sprintf", "(", "\"0x%s\"", ",", "pushedBytes", ")", ")", "\n", "i", "+=", "pushes", "\n", "}", "\n", "}" ]
// Tokenises the bytecode into opcodes and values
[ "Tokenises", "the", "bytecode", "into", "opcodes", "and", "values" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/acm/bytecode.go#L94-L118
train
hyperledger/burrow
event/query/builder.go
NewBuilder
func NewBuilder(queries ...string) *Builder { qb := new(Builder) qb.queryString = qb.and(stringIterator(queries...)) return qb }
go
func NewBuilder(queries ...string) *Builder { qb := new(Builder) qb.queryString = qb.and(stringIterator(queries...)) return qb }
[ "func", "NewBuilder", "(", "queries", "...", "string", ")", "*", "Builder", "{", "qb", ":=", "new", "(", "Builder", ")", "\n", "qb", ".", "queryString", "=", "qb", ".", "and", "(", "stringIterator", "(", "queries", "...", ")", ")", "\n", "return", "qb", "\n", "}" ]
// Creates a new query builder with a base query that is the conjunction of all queries passed
[ "Creates", "a", "new", "query", "builder", "with", "a", "base", "query", "that", "is", "the", "conjunction", "of", "all", "queries", "passed" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/event/query/builder.go#L95-L99
train
hyperledger/burrow
event/query/builder.go
And
func (qb *Builder) And(queryBuilders ...*Builder) *Builder { return NewBuilder(qb.and(queryBuilderIterator(queryBuilders...))) }
go
func (qb *Builder) And(queryBuilders ...*Builder) *Builder { return NewBuilder(qb.and(queryBuilderIterator(queryBuilders...))) }
[ "func", "(", "qb", "*", "Builder", ")", "And", "(", "queryBuilders", "...", "*", "Builder", ")", "*", "Builder", "{", "return", "NewBuilder", "(", "qb", ".", "and", "(", "queryBuilderIterator", "(", "queryBuilders", "...", ")", ")", ")", "\n", "}" ]
// Creates the conjunction of Builder and rightQuery
[ "Creates", "the", "conjunction", "of", "Builder", "and", "rightQuery" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/event/query/builder.go#L120-L122
train
hyperledger/burrow
event/query/builder.go
AndEquals
func (qb *Builder) AndEquals(tag string, operand interface{}) *Builder { qb.condition.Tag = tag qb.condition.Op = equalString qb.condition.Operand = operandString(operand) return NewBuilder(qb.and(stringIterator(qb.conditionString()))) }
go
func (qb *Builder) AndEquals(tag string, operand interface{}) *Builder { qb.condition.Tag = tag qb.condition.Op = equalString qb.condition.Operand = operandString(operand) return NewBuilder(qb.and(stringIterator(qb.conditionString()))) }
[ "func", "(", "qb", "*", "Builder", ")", "AndEquals", "(", "tag", "string", ",", "operand", "interface", "{", "}", ")", "*", "Builder", "{", "qb", ".", "condition", ".", "Tag", "=", "tag", "\n", "qb", ".", "condition", ".", "Op", "=", "equalString", "\n", "qb", ".", "condition", ".", "Operand", "=", "operandString", "(", "operand", ")", "\n", "return", "NewBuilder", "(", "qb", ".", "and", "(", "stringIterator", "(", "qb", ".", "conditionString", "(", ")", ")", ")", ")", "\n", "}" ]
// Creates the conjunction of Builder and tag = operand
[ "Creates", "the", "conjunction", "of", "Builder", "and", "tag", "=", "operand" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/event/query/builder.go#L125-L130
train
hyperledger/burrow
event/query/builder.go
stringIterator
func stringIterator(strs ...string) func(func(string)) { return func(callback func(string)) { for _, s := range strs { callback(s) } } }
go
func stringIterator(strs ...string) func(func(string)) { return func(callback func(string)) { for _, s := range strs { callback(s) } } }
[ "func", "stringIterator", "(", "strs", "...", "string", ")", "func", "(", "func", "(", "string", ")", ")", "{", "return", "func", "(", "callback", "func", "(", "string", ")", ")", "{", "for", "_", ",", "s", ":=", "range", "strs", "{", "callback", "(", "s", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Iterators over some strings
[ "Iterators", "over", "some", "strings" ]
59993f5aad71a8e16ab6ed4e57e138e2398eae4e
https://github.com/hyperledger/burrow/blob/59993f5aad71a8e16ab6ed4e57e138e2398eae4e/event/query/builder.go#L260-L266
train
mvdan/sh
syntax/parser.go
NewParser
func NewParser(options ...func(*Parser)) *Parser { p := &Parser{helperBuf: new(bytes.Buffer)} for _, opt := range options { opt(p) } return p }
go
func NewParser(options ...func(*Parser)) *Parser { p := &Parser{helperBuf: new(bytes.Buffer)} for _, opt := range options { opt(p) } return p }
[ "func", "NewParser", "(", "options", "...", "func", "(", "*", "Parser", ")", ")", "*", "Parser", "{", "p", ":=", "&", "Parser", "{", "helperBuf", ":", "new", "(", "bytes", ".", "Buffer", ")", "}", "\n", "for", "_", ",", "opt", ":=", "range", "options", "{", "opt", "(", "p", ")", "\n", "}", "\n", "return", "p", "\n", "}" ]
// NewParser allocates a new Parser and applies any number of options.
[ "NewParser", "allocates", "a", "new", "Parser", "and", "applies", "any", "number", "of", "options", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/syntax/parser.go#L69-L75
train
mvdan/sh
syntax/parser.go
Parse
func (p *Parser) Parse(r io.Reader, name string) (*File, error) { p.reset() p.f = &File{Name: name} p.src = r p.rune() p.next() p.f.Stmts, p.f.Last = p.stmtList() if p.err == nil { // EOF immediately after heredoc word so no newline to // trigger it p.doHeredocs() } return p.f, p.err }
go
func (p *Parser) Parse(r io.Reader, name string) (*File, error) { p.reset() p.f = &File{Name: name} p.src = r p.rune() p.next() p.f.Stmts, p.f.Last = p.stmtList() if p.err == nil { // EOF immediately after heredoc word so no newline to // trigger it p.doHeredocs() } return p.f, p.err }
[ "func", "(", "p", "*", "Parser", ")", "Parse", "(", "r", "io", ".", "Reader", ",", "name", "string", ")", "(", "*", "File", ",", "error", ")", "{", "p", ".", "reset", "(", ")", "\n", "p", ".", "f", "=", "&", "File", "{", "Name", ":", "name", "}", "\n", "p", ".", "src", "=", "r", "\n", "p", ".", "rune", "(", ")", "\n", "p", ".", "next", "(", ")", "\n", "p", ".", "f", ".", "Stmts", ",", "p", ".", "f", ".", "Last", "=", "p", ".", "stmtList", "(", ")", "\n", "if", "p", ".", "err", "==", "nil", "{", "p", ".", "doHeredocs", "(", ")", "\n", "}", "\n", "return", "p", ".", "f", ",", "p", ".", "err", "\n", "}" ]
// Parse reads and parses a shell program with an optional name. It // returns the parsed program if no issues were encountered. Otherwise, // an error is returned. Reads from r are buffered. // // Parse can be called more than once, but not concurrently. That is, a // Parser can be reused once it is done working.
[ "Parse", "reads", "and", "parses", "a", "shell", "program", "with", "an", "optional", "name", ".", "It", "returns", "the", "parsed", "program", "if", "no", "issues", "were", "encountered", ".", "Otherwise", "an", "error", "is", "returned", ".", "Reads", "from", "r", "are", "buffered", ".", "Parse", "can", "be", "called", "more", "than", "once", "but", "not", "concurrently", ".", "That", "is", "a", "Parser", "can", "be", "reused", "once", "it", "is", "done", "working", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/syntax/parser.go#L83-L96
train
mvdan/sh
syntax/parser.go
Stmts
func (p *Parser) Stmts(r io.Reader, fn func(*Stmt) bool) error { p.reset() p.f = &File{} p.src = r p.rune() p.next() p.stmts(fn) if p.err == nil { // EOF immediately after heredoc word so no newline to // trigger it p.doHeredocs() } return p.err }
go
func (p *Parser) Stmts(r io.Reader, fn func(*Stmt) bool) error { p.reset() p.f = &File{} p.src = r p.rune() p.next() p.stmts(fn) if p.err == nil { // EOF immediately after heredoc word so no newline to // trigger it p.doHeredocs() } return p.err }
[ "func", "(", "p", "*", "Parser", ")", "Stmts", "(", "r", "io", ".", "Reader", ",", "fn", "func", "(", "*", "Stmt", ")", "bool", ")", "error", "{", "p", ".", "reset", "(", ")", "\n", "p", ".", "f", "=", "&", "File", "{", "}", "\n", "p", ".", "src", "=", "r", "\n", "p", ".", "rune", "(", ")", "\n", "p", ".", "next", "(", ")", "\n", "p", ".", "stmts", "(", "fn", ")", "\n", "if", "p", ".", "err", "==", "nil", "{", "p", ".", "doHeredocs", "(", ")", "\n", "}", "\n", "return", "p", ".", "err", "\n", "}" ]
// Stmts reads and parses statements one at a time, calling a function // each time one is parsed. If the function returns false, parsing is // stopped and the function is not called again.
[ "Stmts", "reads", "and", "parses", "statements", "one", "at", "a", "time", "calling", "a", "function", "each", "time", "one", "is", "parsed", ".", "If", "the", "function", "returns", "false", "parsing", "is", "stopped", "and", "the", "function", "is", "not", "called", "again", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/syntax/parser.go#L101-L114
train
mvdan/sh
syntax/parser.go
Words
func (p *Parser) Words(r io.Reader, fn func(*Word) bool) error { p.reset() p.f = &File{} p.src = r p.rune() p.next() for { p.got(_Newl) w := p.getWord() if w == nil { if p.tok != _EOF { p.curErr("%s is not a valid word", p.tok) } return p.err } if !fn(w) { return nil } } }
go
func (p *Parser) Words(r io.Reader, fn func(*Word) bool) error { p.reset() p.f = &File{} p.src = r p.rune() p.next() for { p.got(_Newl) w := p.getWord() if w == nil { if p.tok != _EOF { p.curErr("%s is not a valid word", p.tok) } return p.err } if !fn(w) { return nil } } }
[ "func", "(", "p", "*", "Parser", ")", "Words", "(", "r", "io", ".", "Reader", ",", "fn", "func", "(", "*", "Word", ")", "bool", ")", "error", "{", "p", ".", "reset", "(", ")", "\n", "p", ".", "f", "=", "&", "File", "{", "}", "\n", "p", ".", "src", "=", "r", "\n", "p", ".", "rune", "(", ")", "\n", "p", ".", "next", "(", ")", "\n", "for", "{", "p", ".", "got", "(", "_Newl", ")", "\n", "w", ":=", "p", ".", "getWord", "(", ")", "\n", "if", "w", "==", "nil", "{", "if", "p", ".", "tok", "!=", "_EOF", "{", "p", ".", "curErr", "(", "\"%s is not a valid word\"", ",", "p", ".", "tok", ")", "\n", "}", "\n", "return", "p", ".", "err", "\n", "}", "\n", "if", "!", "fn", "(", "w", ")", "{", "return", "nil", "\n", "}", "\n", "}", "\n", "}" ]
// Words reads and parses words one at a time, calling a function each time one // is parsed. If the function returns false, parsing is stopped and the function // is not called again. // // Newlines are skipped, meaning that multi-line input will work fine. If the // parser encounters a token that isn't a word, such as a semicolon, an error // will be returned. // // Note that the lexer doesn't currently tokenize spaces, so it may need to read // a non-space byte such as a newline or a letter before finishing the parsing // of a word. This will be fixed in the future.
[ "Words", "reads", "and", "parses", "words", "one", "at", "a", "time", "calling", "a", "function", "each", "time", "one", "is", "parsed", ".", "If", "the", "function", "returns", "false", "parsing", "is", "stopped", "and", "the", "function", "is", "not", "called", "again", ".", "Newlines", "are", "skipped", "meaning", "that", "multi", "-", "line", "input", "will", "work", "fine", ".", "If", "the", "parser", "encounters", "a", "token", "that", "isn", "t", "a", "word", "such", "as", "a", "semicolon", "an", "error", "will", "be", "returned", ".", "Note", "that", "the", "lexer", "doesn", "t", "currently", "tokenize", "spaces", "so", "it", "may", "need", "to", "read", "a", "non", "-", "space", "byte", "such", "as", "a", "newline", "or", "a", "letter", "before", "finishing", "the", "parsing", "of", "a", "word", ".", "This", "will", "be", "fixed", "in", "the", "future", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/syntax/parser.go#L204-L223
train
mvdan/sh
syntax/parser.go
Document
func (p *Parser) Document(r io.Reader) (*Word, error) { p.reset() p.f = &File{} p.src = r p.rune() p.quote = hdocBody p.hdocStop = []byte("MVDAN_CC_SH_SYNTAX_EOF") p.parsingDoc = true p.next() w := p.getWord() return w, p.err }
go
func (p *Parser) Document(r io.Reader) (*Word, error) { p.reset() p.f = &File{} p.src = r p.rune() p.quote = hdocBody p.hdocStop = []byte("MVDAN_CC_SH_SYNTAX_EOF") p.parsingDoc = true p.next() w := p.getWord() return w, p.err }
[ "func", "(", "p", "*", "Parser", ")", "Document", "(", "r", "io", ".", "Reader", ")", "(", "*", "Word", ",", "error", ")", "{", "p", ".", "reset", "(", ")", "\n", "p", ".", "f", "=", "&", "File", "{", "}", "\n", "p", ".", "src", "=", "r", "\n", "p", ".", "rune", "(", ")", "\n", "p", ".", "quote", "=", "hdocBody", "\n", "p", ".", "hdocStop", "=", "[", "]", "byte", "(", "\"MVDAN_CC_SH_SYNTAX_EOF\"", ")", "\n", "p", ".", "parsingDoc", "=", "true", "\n", "p", ".", "next", "(", ")", "\n", "w", ":=", "p", ".", "getWord", "(", ")", "\n", "return", "w", ",", "p", ".", "err", "\n", "}" ]
// Document parses a single here-document word. That is, it parses the input as // if they were lines following a <<EOF redirection. // // In practice, this is the same as parsing the input as if it were within // double quotes, but without having to escape all double quote characters. // Similarly, the here-document word parsed here cannot be ended by any // delimiter other than reaching the end of the input.
[ "Document", "parses", "a", "single", "here", "-", "document", "word", ".", "That", "is", "it", "parses", "the", "input", "as", "if", "they", "were", "lines", "following", "a", "<<EOF", "redirection", ".", "In", "practice", "this", "is", "the", "same", "as", "parsing", "the", "input", "as", "if", "it", "were", "within", "double", "quotes", "but", "without", "having", "to", "escape", "all", "double", "quote", "characters", ".", "Similarly", "the", "here", "-", "document", "word", "parsed", "here", "cannot", "be", "ended", "by", "any", "delimiter", "other", "than", "reaching", "the", "end", "of", "the", "input", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/syntax/parser.go#L232-L243
train
mvdan/sh
syntax/parser.go
Incomplete
func (p *Parser) Incomplete() bool { // If we're in a quote state other than noState, we're parsing a node // such as a double-quoted string. // If there are any open statements, we need to finish them. // If we're constructing a literal, we need to finish it. return p.quote != noState || p.openStmts > 0 || p.litBs != nil }
go
func (p *Parser) Incomplete() bool { // If we're in a quote state other than noState, we're parsing a node // such as a double-quoted string. // If there are any open statements, we need to finish them. // If we're constructing a literal, we need to finish it. return p.quote != noState || p.openStmts > 0 || p.litBs != nil }
[ "func", "(", "p", "*", "Parser", ")", "Incomplete", "(", ")", "bool", "{", "return", "p", ".", "quote", "!=", "noState", "||", "p", ".", "openStmts", ">", "0", "||", "p", ".", "litBs", "!=", "nil", "\n", "}" ]
// Incomplete reports whether the parser is waiting to read more bytes because // it needs to finish properly parsing a statement. // // It is only safe to call while the parser is blocked on a read. For an example // use case, see the documentation for Parser.Interactive.
[ "Incomplete", "reports", "whether", "the", "parser", "is", "waiting", "to", "read", "more", "bytes", "because", "it", "needs", "to", "finish", "properly", "parsing", "a", "statement", ".", "It", "is", "only", "safe", "to", "call", "while", "the", "parser", "is", "blocked", "on", "a", "read", ".", "For", "an", "example", "use", "case", "see", "the", "documentation", "for", "Parser", ".", "Interactive", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/syntax/parser.go#L322-L328
train
mvdan/sh
syntax/parser.go
IsIncomplete
func IsIncomplete(err error) bool { perr, ok := err.(ParseError) return ok && perr.Incomplete }
go
func IsIncomplete(err error) bool { perr, ok := err.(ParseError) return ok && perr.Incomplete }
[ "func", "IsIncomplete", "(", "err", "error", ")", "bool", "{", "perr", ",", "ok", ":=", "err", ".", "(", "ParseError", ")", "\n", "return", "ok", "&&", "perr", ".", "Incomplete", "\n", "}" ]
// IsIncomplete reports whether a Parser error could have been avoided with // extra input bytes. For example, if an io.EOF was encountered while there was // an unclosed quote or parenthesis.
[ "IsIncomplete", "reports", "whether", "a", "Parser", "error", "could", "have", "been", "avoided", "with", "extra", "input", "bytes", ".", "For", "example", "if", "an", "io", ".", "EOF", "was", "encountered", "while", "there", "was", "an", "unclosed", "quote", "or", "parenthesis", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/syntax/parser.go#L653-L656
train
mvdan/sh
syntax/parser.go
ValidName
func ValidName(val string) bool { if val == "" { return false } for i, r := range val { switch { case 'a' <= r && r <= 'z': case 'A' <= r && r <= 'Z': case r == '_': case i > 0 && '0' <= r && r <= '9': default: return false } } return true }
go
func ValidName(val string) bool { if val == "" { return false } for i, r := range val { switch { case 'a' <= r && r <= 'z': case 'A' <= r && r <= 'Z': case r == '_': case i > 0 && '0' <= r && r <= '9': default: return false } } return true }
[ "func", "ValidName", "(", "val", "string", ")", "bool", "{", "if", "val", "==", "\"\"", "{", "return", "false", "\n", "}", "\n", "for", "i", ",", "r", ":=", "range", "val", "{", "switch", "{", "case", "'a'", "<=", "r", "&&", "r", "<=", "'z'", ":", "case", "'A'", "<=", "r", "&&", "r", "<=", "'Z'", ":", "case", "r", "==", "'_'", ":", "case", "i", ">", "0", "&&", "'0'", "<=", "r", "&&", "r", "<=", "'9'", ":", "default", ":", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// ValidName returns whether val is a valid name as per the POSIX spec.
[ "ValidName", "returns", "whether", "val", "is", "a", "valid", "name", "as", "per", "the", "POSIX", "spec", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/syntax/parser.go#L1499-L1514
train
mvdan/sh
expand/environ.go
String
func (v Variable) String() string { switch v.Kind { case String: return v.Str case Indexed: if len(v.List) > 0 { return v.List[0] } case Associative: // nothing to do } return "" }
go
func (v Variable) String() string { switch v.Kind { case String: return v.Str case Indexed: if len(v.List) > 0 { return v.List[0] } case Associative: // nothing to do } return "" }
[ "func", "(", "v", "Variable", ")", "String", "(", ")", "string", "{", "switch", "v", ".", "Kind", "{", "case", "String", ":", "return", "v", ".", "Str", "\n", "case", "Indexed", ":", "if", "len", "(", "v", ".", "List", ")", ">", "0", "{", "return", "v", ".", "List", "[", "0", "]", "\n", "}", "\n", "case", "Associative", ":", "}", "\n", "return", "\"\"", "\n", "}" ]
// String returns the variable's value as a string. In general, this only makes // sense if the variable has a string value or no value at all.
[ "String", "returns", "the", "variable", "s", "value", "as", "a", "string", ".", "In", "general", "this", "only", "makes", "sense", "if", "the", "variable", "has", "a", "string", "value", "or", "no", "value", "at", "all", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/expand/environ.go#L88-L100
train
mvdan/sh
expand/environ.go
Resolve
func (v Variable) Resolve(env Environ) (string, Variable) { name := "" for i := 0; i < maxNameRefDepth; i++ { if v.Kind != NameRef { return name, v } name = v.Str // keep name for the next iteration v = env.Get(name) } return name, Variable{} }
go
func (v Variable) Resolve(env Environ) (string, Variable) { name := "" for i := 0; i < maxNameRefDepth; i++ { if v.Kind != NameRef { return name, v } name = v.Str // keep name for the next iteration v = env.Get(name) } return name, Variable{} }
[ "func", "(", "v", "Variable", ")", "Resolve", "(", "env", "Environ", ")", "(", "string", ",", "Variable", ")", "{", "name", ":=", "\"\"", "\n", "for", "i", ":=", "0", ";", "i", "<", "maxNameRefDepth", ";", "i", "++", "{", "if", "v", ".", "Kind", "!=", "NameRef", "{", "return", "name", ",", "v", "\n", "}", "\n", "name", "=", "v", ".", "Str", "\n", "v", "=", "env", ".", "Get", "(", "name", ")", "\n", "}", "\n", "return", "name", ",", "Variable", "{", "}", "\n", "}" ]
// Resolve follows a number of nameref variables, returning the last reference // name that was followed and the variable that it points to.
[ "Resolve", "follows", "a", "number", "of", "nameref", "variables", "returning", "the", "last", "reference", "name", "that", "was", "followed", "and", "the", "variable", "that", "it", "points", "to", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/expand/environ.go#L109-L119
train
mvdan/sh
expand/environ.go
listEnvironWithUpper
func listEnvironWithUpper(upper bool, pairs ...string) Environ { list := append([]string{}, pairs...) if upper { // Uppercase before sorting, so that we can remove duplicates // without the need for linear search nor a map. for i, s := range list { if sep := strings.IndexByte(s, '='); sep > 0 { list[i] = strings.ToUpper(s[:sep]) + s[sep:] } } } sort.Strings(list) last := "" for i := 0; i < len(list); { s := list[i] sep := strings.IndexByte(s, '=') if sep <= 0 { // invalid element; remove it list = append(list[:i], list[i+1:]...) continue } name := s[:sep] if last == name { // duplicate; the last one wins list = append(list[:i-1], list[i:]...) continue } last = name i++ } return listEnviron(list) }
go
func listEnvironWithUpper(upper bool, pairs ...string) Environ { list := append([]string{}, pairs...) if upper { // Uppercase before sorting, so that we can remove duplicates // without the need for linear search nor a map. for i, s := range list { if sep := strings.IndexByte(s, '='); sep > 0 { list[i] = strings.ToUpper(s[:sep]) + s[sep:] } } } sort.Strings(list) last := "" for i := 0; i < len(list); { s := list[i] sep := strings.IndexByte(s, '=') if sep <= 0 { // invalid element; remove it list = append(list[:i], list[i+1:]...) continue } name := s[:sep] if last == name { // duplicate; the last one wins list = append(list[:i-1], list[i:]...) continue } last = name i++ } return listEnviron(list) }
[ "func", "listEnvironWithUpper", "(", "upper", "bool", ",", "pairs", "...", "string", ")", "Environ", "{", "list", ":=", "append", "(", "[", "]", "string", "{", "}", ",", "pairs", "...", ")", "\n", "if", "upper", "{", "for", "i", ",", "s", ":=", "range", "list", "{", "if", "sep", ":=", "strings", ".", "IndexByte", "(", "s", ",", "'='", ")", ";", "sep", ">", "0", "{", "list", "[", "i", "]", "=", "strings", ".", "ToUpper", "(", "s", "[", ":", "sep", "]", ")", "+", "s", "[", "sep", ":", "]", "\n", "}", "\n", "}", "\n", "}", "\n", "sort", ".", "Strings", "(", "list", ")", "\n", "last", ":=", "\"\"", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "list", ")", ";", "{", "s", ":=", "list", "[", "i", "]", "\n", "sep", ":=", "strings", ".", "IndexByte", "(", "s", ",", "'='", ")", "\n", "if", "sep", "<=", "0", "{", "list", "=", "append", "(", "list", "[", ":", "i", "]", ",", "list", "[", "i", "+", "1", ":", "]", "...", ")", "\n", "continue", "\n", "}", "\n", "name", ":=", "s", "[", ":", "sep", "]", "\n", "if", "last", "==", "name", "{", "list", "=", "append", "(", "list", "[", ":", "i", "-", "1", "]", ",", "list", "[", "i", ":", "]", "...", ")", "\n", "continue", "\n", "}", "\n", "last", "=", "name", "\n", "i", "++", "\n", "}", "\n", "return", "listEnviron", "(", "list", ")", "\n", "}" ]
// listEnvironWithUpper implements ListEnviron, but letting the tests specify // whether to uppercase all names or not.
[ "listEnvironWithUpper", "implements", "ListEnviron", "but", "letting", "the", "tests", "specify", "whether", "to", "uppercase", "all", "names", "or", "not", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/expand/environ.go#L153-L184
train
mvdan/sh
interp/perm_unix.go
hasPermissionToDir
func hasPermissionToDir(info os.FileInfo) bool { user, err := user.Current() if err != nil { return true } uid, _ := strconv.Atoi(user.Uid) // super-user if uid == 0 { return true } st, _ := info.Sys().(*syscall.Stat_t) if st == nil { return true } perm := info.Mode().Perm() // user (u) if perm&0100 != 0 && st.Uid == uint32(uid) { return true } gid, _ := strconv.Atoi(user.Gid) // other users in group (g) if perm&0010 != 0 && st.Uid != uint32(uid) && st.Gid == uint32(gid) { return true } // remaining users (o) if perm&0001 != 0 && st.Uid != uint32(uid) && st.Gid != uint32(gid) { return true } return false }
go
func hasPermissionToDir(info os.FileInfo) bool { user, err := user.Current() if err != nil { return true } uid, _ := strconv.Atoi(user.Uid) // super-user if uid == 0 { return true } st, _ := info.Sys().(*syscall.Stat_t) if st == nil { return true } perm := info.Mode().Perm() // user (u) if perm&0100 != 0 && st.Uid == uint32(uid) { return true } gid, _ := strconv.Atoi(user.Gid) // other users in group (g) if perm&0010 != 0 && st.Uid != uint32(uid) && st.Gid == uint32(gid) { return true } // remaining users (o) if perm&0001 != 0 && st.Uid != uint32(uid) && st.Gid != uint32(gid) { return true } return false }
[ "func", "hasPermissionToDir", "(", "info", "os", ".", "FileInfo", ")", "bool", "{", "user", ",", "err", ":=", "user", ".", "Current", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "true", "\n", "}", "\n", "uid", ",", "_", ":=", "strconv", ".", "Atoi", "(", "user", ".", "Uid", ")", "\n", "if", "uid", "==", "0", "{", "return", "true", "\n", "}", "\n", "st", ",", "_", ":=", "info", ".", "Sys", "(", ")", ".", "(", "*", "syscall", ".", "Stat_t", ")", "\n", "if", "st", "==", "nil", "{", "return", "true", "\n", "}", "\n", "perm", ":=", "info", ".", "Mode", "(", ")", ".", "Perm", "(", ")", "\n", "if", "perm", "&", "0100", "!=", "0", "&&", "st", ".", "Uid", "==", "uint32", "(", "uid", ")", "{", "return", "true", "\n", "}", "\n", "gid", ",", "_", ":=", "strconv", ".", "Atoi", "(", "user", ".", "Gid", ")", "\n", "if", "perm", "&", "0010", "!=", "0", "&&", "st", ".", "Uid", "!=", "uint32", "(", "uid", ")", "&&", "st", ".", "Gid", "==", "uint32", "(", "gid", ")", "{", "return", "true", "\n", "}", "\n", "if", "perm", "&", "0001", "!=", "0", "&&", "st", ".", "Uid", "!=", "uint32", "(", "uid", ")", "&&", "st", ".", "Gid", "!=", "uint32", "(", "gid", ")", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// hasPermissionToDir returns if the OS current user has execute permission // to the given directory
[ "hasPermissionToDir", "returns", "if", "the", "OS", "current", "user", "has", "execute", "permission", "to", "the", "given", "directory" ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/interp/perm_unix.go#L17-L49
train
mvdan/sh
shell/source.go
SourceFile
func SourceFile(ctx context.Context, path string) (map[string]expand.Variable, error) { f, err := os.Open(path) if err != nil { return nil, fmt.Errorf("could not open: %v", err) } defer f.Close() file, err := syntax.NewParser().Parse(f, path) if err != nil { return nil, fmt.Errorf("could not parse: %v", err) } return SourceNode(ctx, file) }
go
func SourceFile(ctx context.Context, path string) (map[string]expand.Variable, error) { f, err := os.Open(path) if err != nil { return nil, fmt.Errorf("could not open: %v", err) } defer f.Close() file, err := syntax.NewParser().Parse(f, path) if err != nil { return nil, fmt.Errorf("could not parse: %v", err) } return SourceNode(ctx, file) }
[ "func", "SourceFile", "(", "ctx", "context", ".", "Context", ",", "path", "string", ")", "(", "map", "[", "string", "]", "expand", ".", "Variable", ",", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"could not open: %v\"", ",", "err", ")", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "file", ",", "err", ":=", "syntax", ".", "NewParser", "(", ")", ".", "Parse", "(", "f", ",", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"could not parse: %v\"", ",", "err", ")", "\n", "}", "\n", "return", "SourceNode", "(", "ctx", ",", "file", ")", "\n", "}" ]
// SourceFile sources a shell file from disk and returns the variables // declared in it. It is a convenience function that uses a default shell // parser, parses a file from disk, and calls SourceNode. // // This function should be used with caution, as it can interpret arbitrary // code. Untrusted shell programs shoudn't be sourced outside of a sandbox // environment.
[ "SourceFile", "sources", "a", "shell", "file", "from", "disk", "and", "returns", "the", "variables", "declared", "in", "it", ".", "It", "is", "a", "convenience", "function", "that", "uses", "a", "default", "shell", "parser", "parses", "a", "file", "from", "disk", "and", "calls", "SourceNode", ".", "This", "function", "should", "be", "used", "with", "caution", "as", "it", "can", "interpret", "arbitrary", "code", ".", "Untrusted", "shell", "programs", "shoudn", "t", "be", "sourced", "outside", "of", "a", "sandbox", "environment", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/shell/source.go#L23-L34
train
mvdan/sh
interp/interp.go
New
func New(opts ...func(*Runner) error) (*Runner, error) { r := &Runner{usedNew: true} r.dirStack = r.dirBootstrap[:0] for _, opt := range opts { if err := opt(r); err != nil { return nil, err } } // Set the default fallbacks, if necessary. if r.Env == nil { Env(nil)(r) } if r.Dir == "" { if err := Dir("")(r); err != nil { return nil, err } } if r.Exec == nil { Module(ModuleExec(nil))(r) } if r.Open == nil { Module(ModuleOpen(nil))(r) } if r.Stdout == nil || r.Stderr == nil { StdIO(r.Stdin, r.Stdout, r.Stderr)(r) } return r, nil }
go
func New(opts ...func(*Runner) error) (*Runner, error) { r := &Runner{usedNew: true} r.dirStack = r.dirBootstrap[:0] for _, opt := range opts { if err := opt(r); err != nil { return nil, err } } // Set the default fallbacks, if necessary. if r.Env == nil { Env(nil)(r) } if r.Dir == "" { if err := Dir("")(r); err != nil { return nil, err } } if r.Exec == nil { Module(ModuleExec(nil))(r) } if r.Open == nil { Module(ModuleOpen(nil))(r) } if r.Stdout == nil || r.Stderr == nil { StdIO(r.Stdin, r.Stdout, r.Stderr)(r) } return r, nil }
[ "func", "New", "(", "opts", "...", "func", "(", "*", "Runner", ")", "error", ")", "(", "*", "Runner", ",", "error", ")", "{", "r", ":=", "&", "Runner", "{", "usedNew", ":", "true", "}", "\n", "r", ".", "dirStack", "=", "r", ".", "dirBootstrap", "[", ":", "0", "]", "\n", "for", "_", ",", "opt", ":=", "range", "opts", "{", "if", "err", ":=", "opt", "(", "r", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "if", "r", ".", "Env", "==", "nil", "{", "Env", "(", "nil", ")", "(", "r", ")", "\n", "}", "\n", "if", "r", ".", "Dir", "==", "\"\"", "{", "if", "err", ":=", "Dir", "(", "\"\"", ")", "(", "r", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "if", "r", ".", "Exec", "==", "nil", "{", "Module", "(", "ModuleExec", "(", "nil", ")", ")", "(", "r", ")", "\n", "}", "\n", "if", "r", ".", "Open", "==", "nil", "{", "Module", "(", "ModuleOpen", "(", "nil", ")", ")", "(", "r", ")", "\n", "}", "\n", "if", "r", ".", "Stdout", "==", "nil", "||", "r", ".", "Stderr", "==", "nil", "{", "StdIO", "(", "r", ".", "Stdin", ",", "r", ".", "Stdout", ",", "r", ".", "Stderr", ")", "(", "r", ")", "\n", "}", "\n", "return", "r", ",", "nil", "\n", "}" ]
// New creates a new Runner, applying a number of options. If applying any of // the options results in an error, it is returned. // // Any unset options fall back to their defaults. For example, not supplying the // environment falls back to the process's environment, and not supplying the // standard output writer means that the output will be discarded.
[ "New", "creates", "a", "new", "Runner", "applying", "a", "number", "of", "options", ".", "If", "applying", "any", "of", "the", "options", "results", "in", "an", "error", "it", "is", "returned", ".", "Any", "unset", "options", "fall", "back", "to", "their", "defaults", ".", "For", "example", "not", "supplying", "the", "environment", "falls", "back", "to", "the", "process", "s", "environment", "and", "not", "supplying", "the", "standard", "output", "writer", "means", "that", "the", "output", "will", "be", "discarded", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/interp/interp.go#L34-L61
train
mvdan/sh
interp/interp.go
Env
func Env(env expand.Environ) func(*Runner) error { return func(r *Runner) error { if env == nil { env = expand.ListEnviron(os.Environ()...) } r.Env = env return nil } }
go
func Env(env expand.Environ) func(*Runner) error { return func(r *Runner) error { if env == nil { env = expand.ListEnviron(os.Environ()...) } r.Env = env return nil } }
[ "func", "Env", "(", "env", "expand", ".", "Environ", ")", "func", "(", "*", "Runner", ")", "error", "{", "return", "func", "(", "r", "*", "Runner", ")", "error", "{", "if", "env", "==", "nil", "{", "env", "=", "expand", ".", "ListEnviron", "(", "os", ".", "Environ", "(", ")", "...", ")", "\n", "}", "\n", "r", ".", "Env", "=", "env", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Env sets the interpreter's environment. If nil, a copy of the current // process's environment is used.
[ "Env", "sets", "the", "interpreter", "s", "environment", ".", "If", "nil", "a", "copy", "of", "the", "current", "process", "s", "environment", "is", "used", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/interp/interp.go#L181-L189
train
mvdan/sh
interp/interp.go
Dir
func Dir(path string) func(*Runner) error { return func(r *Runner) error { if path == "" { path, err := os.Getwd() if err != nil { return fmt.Errorf("could not get current dir: %v", err) } r.Dir = path return nil } path, err := filepath.Abs(path) if err != nil { return fmt.Errorf("could not get absolute dir: %v", err) } info, err := os.Stat(path) if err != nil { return fmt.Errorf("could not stat: %v", err) } if !info.IsDir() { return fmt.Errorf("%s is not a directory", path) } r.Dir = path return nil } }
go
func Dir(path string) func(*Runner) error { return func(r *Runner) error { if path == "" { path, err := os.Getwd() if err != nil { return fmt.Errorf("could not get current dir: %v", err) } r.Dir = path return nil } path, err := filepath.Abs(path) if err != nil { return fmt.Errorf("could not get absolute dir: %v", err) } info, err := os.Stat(path) if err != nil { return fmt.Errorf("could not stat: %v", err) } if !info.IsDir() { return fmt.Errorf("%s is not a directory", path) } r.Dir = path return nil } }
[ "func", "Dir", "(", "path", "string", ")", "func", "(", "*", "Runner", ")", "error", "{", "return", "func", "(", "r", "*", "Runner", ")", "error", "{", "if", "path", "==", "\"\"", "{", "path", ",", "err", ":=", "os", ".", "Getwd", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"could not get current dir: %v\"", ",", "err", ")", "\n", "}", "\n", "r", ".", "Dir", "=", "path", "\n", "return", "nil", "\n", "}", "\n", "path", ",", "err", ":=", "filepath", ".", "Abs", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"could not get absolute dir: %v\"", ",", "err", ")", "\n", "}", "\n", "info", ",", "err", ":=", "os", ".", "Stat", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"could not stat: %v\"", ",", "err", ")", "\n", "}", "\n", "if", "!", "info", ".", "IsDir", "(", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"%s is not a directory\"", ",", "path", ")", "\n", "}", "\n", "r", ".", "Dir", "=", "path", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Dir sets the interpreter's working directory. If empty, the process's current // directory is used.
[ "Dir", "sets", "the", "interpreter", "s", "working", "directory", ".", "If", "empty", "the", "process", "s", "current", "directory", "is", "used", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/interp/interp.go#L193-L217
train
mvdan/sh
interp/interp.go
Module
func Module(mod ModuleFunc) func(*Runner) error { return func(r *Runner) error { switch mod := mod.(type) { case ModuleExec: if mod == nil { mod = DefaultExec } r.Exec = mod case ModuleOpen: if mod == nil { mod = DefaultOpen } r.Open = mod default: return fmt.Errorf("unknown module type: %T", mod) } return nil } }
go
func Module(mod ModuleFunc) func(*Runner) error { return func(r *Runner) error { switch mod := mod.(type) { case ModuleExec: if mod == nil { mod = DefaultExec } r.Exec = mod case ModuleOpen: if mod == nil { mod = DefaultOpen } r.Open = mod default: return fmt.Errorf("unknown module type: %T", mod) } return nil } }
[ "func", "Module", "(", "mod", "ModuleFunc", ")", "func", "(", "*", "Runner", ")", "error", "{", "return", "func", "(", "r", "*", "Runner", ")", "error", "{", "switch", "mod", ":=", "mod", ".", "(", "type", ")", "{", "case", "ModuleExec", ":", "if", "mod", "==", "nil", "{", "mod", "=", "DefaultExec", "\n", "}", "\n", "r", ".", "Exec", "=", "mod", "\n", "case", "ModuleOpen", ":", "if", "mod", "==", "nil", "{", "mod", "=", "DefaultOpen", "\n", "}", "\n", "r", ".", "Open", "=", "mod", "\n", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"unknown module type: %T\"", ",", "mod", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Module sets an interpreter module, which can be ModuleExec or ModuleOpen. If // the value is nil, the default module implementation is used.
[ "Module", "sets", "an", "interpreter", "module", "which", "can", "be", "ModuleExec", "or", "ModuleOpen", ".", "If", "the", "value", "is", "nil", "the", "default", "module", "implementation", "is", "used", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/interp/interp.go#L283-L301
train
mvdan/sh
interp/interp.go
StdIO
func StdIO(in io.Reader, out, err io.Writer) func(*Runner) error { return func(r *Runner) error { r.Stdin = in if out == nil { out = ioutil.Discard } r.Stdout = out if err == nil { err = ioutil.Discard } r.Stderr = err return nil } }
go
func StdIO(in io.Reader, out, err io.Writer) func(*Runner) error { return func(r *Runner) error { r.Stdin = in if out == nil { out = ioutil.Discard } r.Stdout = out if err == nil { err = ioutil.Discard } r.Stderr = err return nil } }
[ "func", "StdIO", "(", "in", "io", ".", "Reader", ",", "out", ",", "err", "io", ".", "Writer", ")", "func", "(", "*", "Runner", ")", "error", "{", "return", "func", "(", "r", "*", "Runner", ")", "error", "{", "r", ".", "Stdin", "=", "in", "\n", "if", "out", "==", "nil", "{", "out", "=", "ioutil", ".", "Discard", "\n", "}", "\n", "r", ".", "Stdout", "=", "out", "\n", "if", "err", "==", "nil", "{", "err", "=", "ioutil", ".", "Discard", "\n", "}", "\n", "r", ".", "Stderr", "=", "err", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// StdIO configures an interpreter's standard input, standard output, and // standard error. If out or err are nil, they default to a writer that discards // the output.
[ "StdIO", "configures", "an", "interpreter", "s", "standard", "input", "standard", "output", "and", "standard", "error", ".", "If", "out", "or", "err", "are", "nil", "they", "default", "to", "a", "writer", "that", "discards", "the", "output", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/interp/interp.go#L306-L319
train
mvdan/sh
expand/expand.go
Literal
func Literal(cfg *Config, word *syntax.Word) (string, error) { if word == nil { return "", nil } cfg = prepareConfig(cfg) field, err := cfg.wordField(word.Parts, quoteNone) if err != nil { return "", err } return cfg.fieldJoin(field), nil }
go
func Literal(cfg *Config, word *syntax.Word) (string, error) { if word == nil { return "", nil } cfg = prepareConfig(cfg) field, err := cfg.wordField(word.Parts, quoteNone) if err != nil { return "", err } return cfg.fieldJoin(field), nil }
[ "func", "Literal", "(", "cfg", "*", "Config", ",", "word", "*", "syntax", ".", "Word", ")", "(", "string", ",", "error", ")", "{", "if", "word", "==", "nil", "{", "return", "\"\"", ",", "nil", "\n", "}", "\n", "cfg", "=", "prepareConfig", "(", "cfg", ")", "\n", "field", ",", "err", ":=", "cfg", ".", "wordField", "(", "word", ".", "Parts", ",", "quoteNone", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "return", "cfg", ".", "fieldJoin", "(", "field", ")", ",", "nil", "\n", "}" ]
// Literal expands a single shell word. It is similar to Fields, but the result // is a single string. This is the behavior when a word is used as the value in // a shell variable assignment, for example. // // The config specifies shell expansion options; nil behaves the same as an // empty config.
[ "Literal", "expands", "a", "single", "shell", "word", ".", "It", "is", "similar", "to", "Fields", "but", "the", "result", "is", "a", "single", "string", ".", "This", "is", "the", "behavior", "when", "a", "word", "is", "used", "as", "the", "value", "in", "a", "shell", "variable", "assignment", "for", "example", ".", "The", "config", "specifies", "shell", "expansion", "options", ";", "nil", "behaves", "the", "same", "as", "an", "empty", "config", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/expand/expand.go#L130-L140
train
mvdan/sh
expand/expand.go
Document
func Document(cfg *Config, word *syntax.Word) (string, error) { if word == nil { return "", nil } cfg = prepareConfig(cfg) field, err := cfg.wordField(word.Parts, quoteDouble) if err != nil { return "", err } return cfg.fieldJoin(field), nil }
go
func Document(cfg *Config, word *syntax.Word) (string, error) { if word == nil { return "", nil } cfg = prepareConfig(cfg) field, err := cfg.wordField(word.Parts, quoteDouble) if err != nil { return "", err } return cfg.fieldJoin(field), nil }
[ "func", "Document", "(", "cfg", "*", "Config", ",", "word", "*", "syntax", ".", "Word", ")", "(", "string", ",", "error", ")", "{", "if", "word", "==", "nil", "{", "return", "\"\"", ",", "nil", "\n", "}", "\n", "cfg", "=", "prepareConfig", "(", "cfg", ")", "\n", "field", ",", "err", ":=", "cfg", ".", "wordField", "(", "word", ".", "Parts", ",", "quoteDouble", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "return", "cfg", ".", "fieldJoin", "(", "field", ")", ",", "nil", "\n", "}" ]
// Document expands a single shell word as if it were within double quotes. It // is simlar to Literal, but without brace expansion, tilde expansion, and // globbing. // // The config specifies shell expansion options; nil behaves the same as an // empty config.
[ "Document", "expands", "a", "single", "shell", "word", "as", "if", "it", "were", "within", "double", "quotes", ".", "It", "is", "simlar", "to", "Literal", "but", "without", "brace", "expansion", "tilde", "expansion", "and", "globbing", ".", "The", "config", "specifies", "shell", "expansion", "options", ";", "nil", "behaves", "the", "same", "as", "an", "empty", "config", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/expand/expand.go#L148-L158
train
mvdan/sh
expand/expand.go
Pattern
func Pattern(cfg *Config, word *syntax.Word) (string, error) { cfg = prepareConfig(cfg) field, err := cfg.wordField(word.Parts, quoteNone) if err != nil { return "", err } buf := cfg.strBuilder() for _, part := range field { if part.quote > quoteNone { buf.WriteString(syntax.QuotePattern(part.val)) } else { buf.WriteString(part.val) } } return buf.String(), nil }
go
func Pattern(cfg *Config, word *syntax.Word) (string, error) { cfg = prepareConfig(cfg) field, err := cfg.wordField(word.Parts, quoteNone) if err != nil { return "", err } buf := cfg.strBuilder() for _, part := range field { if part.quote > quoteNone { buf.WriteString(syntax.QuotePattern(part.val)) } else { buf.WriteString(part.val) } } return buf.String(), nil }
[ "func", "Pattern", "(", "cfg", "*", "Config", ",", "word", "*", "syntax", ".", "Word", ")", "(", "string", ",", "error", ")", "{", "cfg", "=", "prepareConfig", "(", "cfg", ")", "\n", "field", ",", "err", ":=", "cfg", ".", "wordField", "(", "word", ".", "Parts", ",", "quoteNone", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "buf", ":=", "cfg", ".", "strBuilder", "(", ")", "\n", "for", "_", ",", "part", ":=", "range", "field", "{", "if", "part", ".", "quote", ">", "quoteNone", "{", "buf", ".", "WriteString", "(", "syntax", ".", "QuotePattern", "(", "part", ".", "val", ")", ")", "\n", "}", "else", "{", "buf", ".", "WriteString", "(", "part", ".", "val", ")", "\n", "}", "\n", "}", "\n", "return", "buf", ".", "String", "(", ")", ",", "nil", "\n", "}" ]
// Pattern expands a single shell word as a pattern, using syntax.QuotePattern // on any non-quoted parts of the input word. The result can be used on // syntax.TranslatePattern directly. // // The config specifies shell expansion options; nil behaves the same as an // empty config.
[ "Pattern", "expands", "a", "single", "shell", "word", "as", "a", "pattern", "using", "syntax", ".", "QuotePattern", "on", "any", "non", "-", "quoted", "parts", "of", "the", "input", "word", ".", "The", "result", "can", "be", "used", "on", "syntax", ".", "TranslatePattern", "directly", ".", "The", "config", "specifies", "shell", "expansion", "options", ";", "nil", "behaves", "the", "same", "as", "an", "empty", "config", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/expand/expand.go#L166-L181
train
mvdan/sh
expand/expand.go
Fields
func Fields(cfg *Config, words ...*syntax.Word) ([]string, error) { cfg = prepareConfig(cfg) fields := make([]string, 0, len(words)) dir := cfg.envGet("PWD") for _, word := range words { afterBraces := []*syntax.Word{word} if w2 := syntax.SplitBraces(word); w2 != word { afterBraces = Braces(w2) } for _, word2 := range afterBraces { wfields, err := cfg.wordFields(word2.Parts) if err != nil { return nil, err } for _, field := range wfields { path, doGlob := cfg.escapedGlobField(field) var matches []string if doGlob && cfg.ReadDir != nil { matches, err = cfg.glob(dir, path) if err != nil { return nil, err } if len(matches) > 0 { fields = append(fields, matches...) continue } } fields = append(fields, cfg.fieldJoin(field)) } } } return fields, nil }
go
func Fields(cfg *Config, words ...*syntax.Word) ([]string, error) { cfg = prepareConfig(cfg) fields := make([]string, 0, len(words)) dir := cfg.envGet("PWD") for _, word := range words { afterBraces := []*syntax.Word{word} if w2 := syntax.SplitBraces(word); w2 != word { afterBraces = Braces(w2) } for _, word2 := range afterBraces { wfields, err := cfg.wordFields(word2.Parts) if err != nil { return nil, err } for _, field := range wfields { path, doGlob := cfg.escapedGlobField(field) var matches []string if doGlob && cfg.ReadDir != nil { matches, err = cfg.glob(dir, path) if err != nil { return nil, err } if len(matches) > 0 { fields = append(fields, matches...) continue } } fields = append(fields, cfg.fieldJoin(field)) } } } return fields, nil }
[ "func", "Fields", "(", "cfg", "*", "Config", ",", "words", "...", "*", "syntax", ".", "Word", ")", "(", "[", "]", "string", ",", "error", ")", "{", "cfg", "=", "prepareConfig", "(", "cfg", ")", "\n", "fields", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "words", ")", ")", "\n", "dir", ":=", "cfg", ".", "envGet", "(", "\"PWD\"", ")", "\n", "for", "_", ",", "word", ":=", "range", "words", "{", "afterBraces", ":=", "[", "]", "*", "syntax", ".", "Word", "{", "word", "}", "\n", "if", "w2", ":=", "syntax", ".", "SplitBraces", "(", "word", ")", ";", "w2", "!=", "word", "{", "afterBraces", "=", "Braces", "(", "w2", ")", "\n", "}", "\n", "for", "_", ",", "word2", ":=", "range", "afterBraces", "{", "wfields", ",", "err", ":=", "cfg", ".", "wordFields", "(", "word2", ".", "Parts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "for", "_", ",", "field", ":=", "range", "wfields", "{", "path", ",", "doGlob", ":=", "cfg", ".", "escapedGlobField", "(", "field", ")", "\n", "var", "matches", "[", "]", "string", "\n", "if", "doGlob", "&&", "cfg", ".", "ReadDir", "!=", "nil", "{", "matches", ",", "err", "=", "cfg", ".", "glob", "(", "dir", ",", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "matches", ")", ">", "0", "{", "fields", "=", "append", "(", "fields", ",", "matches", "...", ")", "\n", "continue", "\n", "}", "\n", "}", "\n", "fields", "=", "append", "(", "fields", ",", "cfg", ".", "fieldJoin", "(", "field", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "fields", ",", "nil", "\n", "}" ]
// Fields expands a number of words as if they were arguments in a shell // command. This includes brace expansion, tilde expansion, parameter expansion, // command substitution, arithmetic expansion, and quote removal.
[ "Fields", "expands", "a", "number", "of", "words", "as", "if", "they", "were", "arguments", "in", "a", "shell", "command", ".", "This", "includes", "brace", "expansion", "tilde", "expansion", "parameter", "expansion", "command", "substitution", "arithmetic", "expansion", "and", "quote", "removal", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/expand/expand.go#L363-L395
train
mvdan/sh
expand/expand.go
pathJoin2
func pathJoin2(elem1, elem2 string) string { if elem1 == "" { return elem2 } if strings.HasSuffix(elem1, string(filepath.Separator)) { return elem1 + elem2 } return elem1 + string(filepath.Separator) + elem2 }
go
func pathJoin2(elem1, elem2 string) string { if elem1 == "" { return elem2 } if strings.HasSuffix(elem1, string(filepath.Separator)) { return elem1 + elem2 } return elem1 + string(filepath.Separator) + elem2 }
[ "func", "pathJoin2", "(", "elem1", ",", "elem2", "string", ")", "string", "{", "if", "elem1", "==", "\"\"", "{", "return", "elem2", "\n", "}", "\n", "if", "strings", ".", "HasSuffix", "(", "elem1", ",", "string", "(", "filepath", ".", "Separator", ")", ")", "{", "return", "elem1", "+", "elem2", "\n", "}", "\n", "return", "elem1", "+", "string", "(", "filepath", ".", "Separator", ")", "+", "elem2", "\n", "}" ]
// pathJoin2 is a simpler version of filepath.Join without cleaning the result, // since that's needed for globbing.
[ "pathJoin2", "is", "a", "simpler", "version", "of", "filepath", ".", "Join", "without", "cleaning", "the", "result", "since", "that", "s", "needed", "for", "globbing", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/expand/expand.go#L651-L659
train
mvdan/sh
expand/expand.go
pathSplit
func pathSplit(path string) []string { path = filepath.FromSlash(path) return strings.Split(path, string(filepath.Separator)) }
go
func pathSplit(path string) []string { path = filepath.FromSlash(path) return strings.Split(path, string(filepath.Separator)) }
[ "func", "pathSplit", "(", "path", "string", ")", "[", "]", "string", "{", "path", "=", "filepath", ".", "FromSlash", "(", "path", ")", "\n", "return", "strings", ".", "Split", "(", "path", ",", "string", "(", "filepath", ".", "Separator", ")", ")", "\n", "}" ]
// pathSplit splits a file path into its elements, retaining empty ones. Before // splitting, slashes are replaced with filepath.Separator, so that splitting // Unix paths on Windows works as well.
[ "pathSplit", "splits", "a", "file", "path", "into", "its", "elements", "retaining", "empty", "ones", ".", "Before", "splitting", "slashes", "are", "replaced", "with", "filepath", ".", "Separator", "so", "that", "splitting", "Unix", "paths", "on", "Windows", "works", "as", "well", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/expand/expand.go#L664-L667
train
mvdan/sh
fileutil/file.go
CouldBeScript
func CouldBeScript(info os.FileInfo) ScriptConfidence { name := info.Name() switch { case info.IsDir(), name[0] == '.': return ConfNotScript case info.Mode()&os.ModeSymlink != 0: return ConfNotScript case extRe.MatchString(name): return ConfIsScript case strings.IndexByte(name, '.') > 0: return ConfNotScript // different extension case info.Size() < int64(len("#/bin/sh\n")): return ConfNotScript // cannot possibly hold valid shebang default: return ConfIfShebang } }
go
func CouldBeScript(info os.FileInfo) ScriptConfidence { name := info.Name() switch { case info.IsDir(), name[0] == '.': return ConfNotScript case info.Mode()&os.ModeSymlink != 0: return ConfNotScript case extRe.MatchString(name): return ConfIsScript case strings.IndexByte(name, '.') > 0: return ConfNotScript // different extension case info.Size() < int64(len("#/bin/sh\n")): return ConfNotScript // cannot possibly hold valid shebang default: return ConfIfShebang } }
[ "func", "CouldBeScript", "(", "info", "os", ".", "FileInfo", ")", "ScriptConfidence", "{", "name", ":=", "info", ".", "Name", "(", ")", "\n", "switch", "{", "case", "info", ".", "IsDir", "(", ")", ",", "name", "[", "0", "]", "==", "'.'", ":", "return", "ConfNotScript", "\n", "case", "info", ".", "Mode", "(", ")", "&", "os", ".", "ModeSymlink", "!=", "0", ":", "return", "ConfNotScript", "\n", "case", "extRe", ".", "MatchString", "(", "name", ")", ":", "return", "ConfIsScript", "\n", "case", "strings", ".", "IndexByte", "(", "name", ",", "'.'", ")", ">", "0", ":", "return", "ConfNotScript", "\n", "case", "info", ".", "Size", "(", ")", "<", "int64", "(", "len", "(", "\"#/bin/sh\\n\"", ")", ")", ":", "\\n", "\n", "return", "ConfNotScript", "}", "\n", "}" ]
// CouldBeScript reports how likely a file is to be a shell script. It // discards directories, symlinks, hidden files and files with non-shell // extensions.
[ "CouldBeScript", "reports", "how", "likely", "a", "file", "is", "to", "be", "a", "shell", "script", ".", "It", "discards", "directories", "symlinks", "hidden", "files", "and", "files", "with", "non", "-", "shell", "extensions", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/fileutil/file.go#L39-L55
train
mvdan/sh
expand/arith.go
atoi
func atoi(s string) int { n, _ := strconv.Atoi(s) return n }
go
func atoi(s string) int { n, _ := strconv.Atoi(s) return n }
[ "func", "atoi", "(", "s", "string", ")", "int", "{", "n", ",", "_", ":=", "strconv", ".", "Atoi", "(", "s", ")", "\n", "return", "n", "\n", "}" ]
// atoi is just a shorthand for strconv.Atoi that ignores the error, // just like shells do.
[ "atoi", "is", "just", "a", "shorthand", "for", "strconv", ".", "Atoi", "that", "ignores", "the", "error", "just", "like", "shells", "do", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/expand/arith.go#L110-L113
train
mvdan/sh
shell/expand.go
Fields
func Fields(s string, env func(string) string) ([]string, error) { p := syntax.NewParser() var words []*syntax.Word err := p.Words(strings.NewReader(s), func(w *syntax.Word) bool { words = append(words, w) return true }) if err != nil { return nil, err } if env == nil { env = os.Getenv } cfg := &expand.Config{Env: expand.FuncEnviron(env)} return expand.Fields(cfg, words...) }
go
func Fields(s string, env func(string) string) ([]string, error) { p := syntax.NewParser() var words []*syntax.Word err := p.Words(strings.NewReader(s), func(w *syntax.Word) bool { words = append(words, w) return true }) if err != nil { return nil, err } if env == nil { env = os.Getenv } cfg := &expand.Config{Env: expand.FuncEnviron(env)} return expand.Fields(cfg, words...) }
[ "func", "Fields", "(", "s", "string", ",", "env", "func", "(", "string", ")", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "p", ":=", "syntax", ".", "NewParser", "(", ")", "\n", "var", "words", "[", "]", "*", "syntax", ".", "Word", "\n", "err", ":=", "p", ".", "Words", "(", "strings", ".", "NewReader", "(", "s", ")", ",", "func", "(", "w", "*", "syntax", ".", "Word", ")", "bool", "{", "words", "=", "append", "(", "words", ",", "w", ")", "\n", "return", "true", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "env", "==", "nil", "{", "env", "=", "os", ".", "Getenv", "\n", "}", "\n", "cfg", ":=", "&", "expand", ".", "Config", "{", "Env", ":", "expand", ".", "FuncEnviron", "(", "env", ")", "}", "\n", "return", "expand", ".", "Fields", "(", "cfg", ",", "words", "...", ")", "\n", "}" ]
// Fields performs shell expansion on s as if it were a command's arguments, // using env to resolve variables. It is similar to Expand, but includes brace // expansion, tilde expansion, and globbing. // // If env is nil, the current environment variables are used. Empty variables // are treated as unset; to support variables which are set but empty, use the // expand package directly. // // An error will be reported if the input string had invalid syntax.
[ "Fields", "performs", "shell", "expansion", "on", "s", "as", "if", "it", "were", "a", "command", "s", "arguments", "using", "env", "to", "resolve", "variables", ".", "It", "is", "similar", "to", "Expand", "but", "includes", "brace", "expansion", "tilde", "expansion", "and", "globbing", ".", "If", "env", "is", "nil", "the", "current", "environment", "variables", "are", "used", ".", "Empty", "variables", "are", "treated", "as", "unset", ";", "to", "support", "variables", "which", "are", "set", "but", "empty", "use", "the", "expand", "package", "directly", ".", "An", "error", "will", "be", "reported", "if", "the", "input", "string", "had", "invalid", "syntax", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/shell/expand.go#L48-L63
train
mvdan/sh
syntax/printer.go
KeepPadding
func KeepPadding(p *Printer) { p.keepPadding = true p.cols.Writer = p.bufWriter.(*bufio.Writer) p.bufWriter = &p.cols }
go
func KeepPadding(p *Printer) { p.keepPadding = true p.cols.Writer = p.bufWriter.(*bufio.Writer) p.bufWriter = &p.cols }
[ "func", "KeepPadding", "(", "p", "*", "Printer", ")", "{", "p", ".", "keepPadding", "=", "true", "\n", "p", ".", "cols", ".", "Writer", "=", "p", ".", "bufWriter", ".", "(", "*", "bufio", ".", "Writer", ")", "\n", "p", ".", "bufWriter", "=", "&", "p", ".", "cols", "\n", "}" ]
// KeepPadding will keep most nodes and tokens in the same column that // they were in the original source. This allows the user to decide how // to align and pad their code with spaces. // // Note that this feature is best-effort and will only keep the // alignment stable, so it may need some human help the first time it is // run.
[ "KeepPadding", "will", "keep", "most", "nodes", "and", "tokens", "in", "the", "same", "column", "that", "they", "were", "in", "the", "original", "source", ".", "This", "allows", "the", "user", "to", "decide", "how", "to", "align", "and", "pad", "their", "code", "with", "spaces", ".", "Note", "that", "this", "feature", "is", "best", "-", "effort", "and", "will", "only", "keep", "the", "alignment", "stable", "so", "it", "may", "need", "some", "human", "help", "the", "first", "time", "it", "is", "run", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/syntax/printer.go#L42-L46
train
mvdan/sh
syntax/printer.go
NewPrinter
func NewPrinter(options ...func(*Printer)) *Printer { p := &Printer{ bufWriter: bufio.NewWriter(nil), tabsPrinter: new(Printer), tabWriter: new(tabwriter.Writer), } for _, opt := range options { opt(p) } return p }
go
func NewPrinter(options ...func(*Printer)) *Printer { p := &Printer{ bufWriter: bufio.NewWriter(nil), tabsPrinter: new(Printer), tabWriter: new(tabwriter.Writer), } for _, opt := range options { opt(p) } return p }
[ "func", "NewPrinter", "(", "options", "...", "func", "(", "*", "Printer", ")", ")", "*", "Printer", "{", "p", ":=", "&", "Printer", "{", "bufWriter", ":", "bufio", ".", "NewWriter", "(", "nil", ")", ",", "tabsPrinter", ":", "new", "(", "Printer", ")", ",", "tabWriter", ":", "new", "(", "tabwriter", ".", "Writer", ")", ",", "}", "\n", "for", "_", ",", "opt", ":=", "range", "options", "{", "opt", "(", "p", ")", "\n", "}", "\n", "return", "p", "\n", "}" ]
// NewPrinter allocates a new Printer and applies any number of options.
[ "NewPrinter", "allocates", "a", "new", "Printer", "and", "applies", "any", "number", "of", "options", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/syntax/printer.go#L54-L64
train
mvdan/sh
interp/module.go
FromModuleContext
func FromModuleContext(ctx context.Context) (ModuleCtx, bool) { mc, ok := ctx.Value(moduleCtxKey{}).(ModuleCtx) return mc, ok }
go
func FromModuleContext(ctx context.Context) (ModuleCtx, bool) { mc, ok := ctx.Value(moduleCtxKey{}).(ModuleCtx) return mc, ok }
[ "func", "FromModuleContext", "(", "ctx", "context", ".", "Context", ")", "(", "ModuleCtx", ",", "bool", ")", "{", "mc", ",", "ok", ":=", "ctx", ".", "Value", "(", "moduleCtxKey", "{", "}", ")", ".", "(", "ModuleCtx", ")", "\n", "return", "mc", ",", "ok", "\n", "}" ]
// FromModuleContext returns the ModuleCtx value stored in ctx, if any.
[ "FromModuleContext", "returns", "the", "ModuleCtx", "value", "stored", "in", "ctx", "if", "any", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/interp/module.go#L21-L24
train
mvdan/sh
syntax/walk.go
DebugPrint
func DebugPrint(w io.Writer, node Node) error { p := debugPrinter{out: w} p.print(reflect.ValueOf(node)) return p.err }
go
func DebugPrint(w io.Writer, node Node) error { p := debugPrinter{out: w} p.print(reflect.ValueOf(node)) return p.err }
[ "func", "DebugPrint", "(", "w", "io", ".", "Writer", ",", "node", "Node", ")", "error", "{", "p", ":=", "debugPrinter", "{", "out", ":", "w", "}", "\n", "p", ".", "print", "(", "reflect", ".", "ValueOf", "(", "node", ")", ")", "\n", "return", "p", ".", "err", "\n", "}" ]
// DebugPrint prints the provided syntax tree, spanning multiple lines and with // indentation. Can be useful to investigate the content of a syntax tree.
[ "DebugPrint", "prints", "the", "provided", "syntax", "tree", "spanning", "multiple", "lines", "and", "with", "indentation", ".", "Can", "be", "useful", "to", "investigate", "the", "content", "of", "a", "syntax", "tree", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/syntax/walk.go#L233-L237
train
mvdan/sh
syntax/lexer.go
fill
func (p *Parser) fill() { p.offs += p.bsp left := len(p.bs) - p.bsp copy(p.readBuf[:left], p.readBuf[p.bsp:]) readAgain: n, err := 0, p.readErr if err == nil { n, err = p.src.Read(p.readBuf[left:]) p.readErr = err } if n == 0 { if err == nil { goto readAgain } // don't use p.errPass as we don't want to overwrite p.tok if err != io.EOF { p.err = err } if left > 0 { p.bs = p.readBuf[:left] } else { p.bs = nil } } else { p.bs = p.readBuf[:left+n] } p.bsp = 0 }
go
func (p *Parser) fill() { p.offs += p.bsp left := len(p.bs) - p.bsp copy(p.readBuf[:left], p.readBuf[p.bsp:]) readAgain: n, err := 0, p.readErr if err == nil { n, err = p.src.Read(p.readBuf[left:]) p.readErr = err } if n == 0 { if err == nil { goto readAgain } // don't use p.errPass as we don't want to overwrite p.tok if err != io.EOF { p.err = err } if left > 0 { p.bs = p.readBuf[:left] } else { p.bs = nil } } else { p.bs = p.readBuf[:left+n] } p.bsp = 0 }
[ "func", "(", "p", "*", "Parser", ")", "fill", "(", ")", "{", "p", ".", "offs", "+=", "p", ".", "bsp", "\n", "left", ":=", "len", "(", "p", ".", "bs", ")", "-", "p", ".", "bsp", "\n", "copy", "(", "p", ".", "readBuf", "[", ":", "left", "]", ",", "p", ".", "readBuf", "[", "p", ".", "bsp", ":", "]", ")", "\n", "readAgain", ":", "n", ",", "err", ":=", "0", ",", "p", ".", "readErr", "\n", "if", "err", "==", "nil", "{", "n", ",", "err", "=", "p", ".", "src", ".", "Read", "(", "p", ".", "readBuf", "[", "left", ":", "]", ")", "\n", "p", ".", "readErr", "=", "err", "\n", "}", "\n", "if", "n", "==", "0", "{", "if", "err", "==", "nil", "{", "goto", "readAgain", "\n", "}", "\n", "if", "err", "!=", "io", ".", "EOF", "{", "p", ".", "err", "=", "err", "\n", "}", "\n", "if", "left", ">", "0", "{", "p", ".", "bs", "=", "p", ".", "readBuf", "[", ":", "left", "]", "\n", "}", "else", "{", "p", ".", "bs", "=", "nil", "\n", "}", "\n", "}", "else", "{", "p", ".", "bs", "=", "p", ".", "readBuf", "[", ":", "left", "+", "n", "]", "\n", "}", "\n", "p", ".", "bsp", "=", "0", "\n", "}" ]
// fill reads more bytes from the input src into readBuf. Any bytes that // had not yet been used at the end of the buffer are slid into the // beginning of the buffer.
[ "fill", "reads", "more", "bytes", "from", "the", "input", "src", "into", "readBuf", ".", "Any", "bytes", "that", "had", "not", "yet", "been", "used", "at", "the", "end", "of", "the", "buffer", "are", "slid", "into", "the", "beginning", "of", "the", "buffer", "." ]
5700c68a35dc3882e646a5e41776e31bb2c078e3
https://github.com/mvdan/sh/blob/5700c68a35dc3882e646a5e41776e31bb2c078e3/syntax/lexer.go#L119-L146
train
robertkrimen/otto
file/file.go
AddFile
func (self *FileSet) AddFile(filename, src string) int { base := self.nextBase() file := &File{ name: filename, src: src, base: base, } self.files = append(self.files, file) self.last = file return base }
go
func (self *FileSet) AddFile(filename, src string) int { base := self.nextBase() file := &File{ name: filename, src: src, base: base, } self.files = append(self.files, file) self.last = file return base }
[ "func", "(", "self", "*", "FileSet", ")", "AddFile", "(", "filename", ",", "src", "string", ")", "int", "{", "base", ":=", "self", ".", "nextBase", "(", ")", "\n", "file", ":=", "&", "File", "{", "name", ":", "filename", ",", "src", ":", "src", ",", "base", ":", "base", ",", "}", "\n", "self", ".", "files", "=", "append", "(", "self", ".", "files", ",", "file", ")", "\n", "self", ".", "last", "=", "file", "\n", "return", "base", "\n", "}" ]
// AddFile adds a new file with the given filename and src. // // This an internal method, but exported for cross-package use.
[ "AddFile", "adds", "a", "new", "file", "with", "the", "given", "filename", "and", "src", ".", "This", "an", "internal", "method", "but", "exported", "for", "cross", "-", "package", "use", "." ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/file/file.go#L65-L75
train
robertkrimen/otto
global.go
newBoundFunction
func (runtime *_runtime) newBoundFunction(target *_object, this Value, argumentList []Value) *_object { self := runtime.newBoundFunctionObject(target, this, argumentList) self.prototype = runtime.global.FunctionPrototype prototype := runtime.newObject() self.defineProperty("prototype", toValue_object(prototype), 0100, false) prototype.defineProperty("constructor", toValue_object(self), 0100, false) return self }
go
func (runtime *_runtime) newBoundFunction(target *_object, this Value, argumentList []Value) *_object { self := runtime.newBoundFunctionObject(target, this, argumentList) self.prototype = runtime.global.FunctionPrototype prototype := runtime.newObject() self.defineProperty("prototype", toValue_object(prototype), 0100, false) prototype.defineProperty("constructor", toValue_object(self), 0100, false) return self }
[ "func", "(", "runtime", "*", "_runtime", ")", "newBoundFunction", "(", "target", "*", "_object", ",", "this", "Value", ",", "argumentList", "[", "]", "Value", ")", "*", "_object", "{", "self", ":=", "runtime", ".", "newBoundFunctionObject", "(", "target", ",", "this", ",", "argumentList", ")", "\n", "self", ".", "prototype", "=", "runtime", ".", "global", ".", "FunctionPrototype", "\n", "prototype", ":=", "runtime", ".", "newObject", "(", ")", "\n", "self", ".", "defineProperty", "(", "\"prototype\"", ",", "toValue_object", "(", "prototype", ")", ",", "0100", ",", "false", ")", "\n", "prototype", ".", "defineProperty", "(", "\"constructor\"", ",", "toValue_object", "(", "self", ")", ",", "0100", ",", "false", ")", "\n", "return", "self", "\n", "}" ]
// FIXME Only in one place...
[ "FIXME", "Only", "in", "one", "place", "..." ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/global.go#L214-L221
train
robertkrimen/otto
script.go
CompileWithSourceMap
func (self *Otto) CompileWithSourceMap(filename string, src, sm interface{}) (*Script, error) { program, err := self.runtime.parse(filename, src, sm) if err != nil { return nil, err } cmpl_program := cmpl_parse(program) script := &Script{ version: scriptVersion, program: cmpl_program, filename: filename, src: program.File.Source(), } return script, nil }
go
func (self *Otto) CompileWithSourceMap(filename string, src, sm interface{}) (*Script, error) { program, err := self.runtime.parse(filename, src, sm) if err != nil { return nil, err } cmpl_program := cmpl_parse(program) script := &Script{ version: scriptVersion, program: cmpl_program, filename: filename, src: program.File.Source(), } return script, nil }
[ "func", "(", "self", "*", "Otto", ")", "CompileWithSourceMap", "(", "filename", "string", ",", "src", ",", "sm", "interface", "{", "}", ")", "(", "*", "Script", ",", "error", ")", "{", "program", ",", "err", ":=", "self", ".", "runtime", ".", "parse", "(", "filename", ",", "src", ",", "sm", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "cmpl_program", ":=", "cmpl_parse", "(", "program", ")", "\n", "script", ":=", "&", "Script", "{", "version", ":", "scriptVersion", ",", "program", ":", "cmpl_program", ",", "filename", ":", "filename", ",", "src", ":", "program", ".", "File", ".", "Source", "(", ")", ",", "}", "\n", "return", "script", ",", "nil", "\n", "}" ]
// CompileWithSourceMap does the same thing as Compile, but with the obvious // difference of applying a source map.
[ "CompileWithSourceMap", "does", "the", "same", "thing", "as", "Compile", "but", "with", "the", "obvious", "difference", "of", "applying", "a", "source", "map", "." ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/script.go#L35-L51
train
robertkrimen/otto
script.go
marshalBinary
func (self *Script) marshalBinary() ([]byte, error) { var bfr bytes.Buffer encoder := gob.NewEncoder(&bfr) err := encoder.Encode(self.version) if err != nil { return nil, err } err = encoder.Encode(self.program) if err != nil { return nil, err } err = encoder.Encode(self.filename) if err != nil { return nil, err } err = encoder.Encode(self.src) if err != nil { return nil, err } return bfr.Bytes(), nil }
go
func (self *Script) marshalBinary() ([]byte, error) { var bfr bytes.Buffer encoder := gob.NewEncoder(&bfr) err := encoder.Encode(self.version) if err != nil { return nil, err } err = encoder.Encode(self.program) if err != nil { return nil, err } err = encoder.Encode(self.filename) if err != nil { return nil, err } err = encoder.Encode(self.src) if err != nil { return nil, err } return bfr.Bytes(), nil }
[ "func", "(", "self", "*", "Script", ")", "marshalBinary", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "bfr", "bytes", ".", "Buffer", "\n", "encoder", ":=", "gob", ".", "NewEncoder", "(", "&", "bfr", ")", "\n", "err", ":=", "encoder", ".", "Encode", "(", "self", ".", "version", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "err", "=", "encoder", ".", "Encode", "(", "self", ".", "program", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "err", "=", "encoder", ".", "Encode", "(", "self", ".", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "err", "=", "encoder", ".", "Encode", "(", "self", ".", "src", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "bfr", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// MarshalBinary will marshal a script into a binary form. A marshalled script // that is later unmarshalled can be executed on the same version of the otto runtime. // // The binary format can change at any time and should be considered unspecified and opaque. //
[ "MarshalBinary", "will", "marshal", "a", "script", "into", "a", "binary", "form", ".", "A", "marshalled", "script", "that", "is", "later", "unmarshalled", "can", "be", "executed", "on", "the", "same", "version", "of", "the", "otto", "runtime", ".", "The", "binary", "format", "can", "change", "at", "any", "time", "and", "should", "be", "considered", "unspecified", "and", "opaque", "." ]
15f95af6e78dcd2030d8195a138bd88d4f403546
https://github.com/robertkrimen/otto/blob/15f95af6e78dcd2030d8195a138bd88d4f403546/script.go#L62-L82
train