id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
2,300
russross/meddler
scan.go
scanRow
func (d *Database) scanRow(data *structData, rows *sql.Rows, dst interface{}, columns []string) error { // check if there is data waiting if !rows.Next() { if err := rows.Err(); err != nil { return err } return sql.ErrNoRows } // get a list of targets targets, err := d.Targets(dst, columns) if err != nil { return err } // perform the scan if err := rows.Scan(targets...); err != nil { return err } // post-process and copy the target values into the struct if err := d.WriteTargets(dst, columns, targets); err != nil { return err } return rows.Err() }
go
func (d *Database) scanRow(data *structData, rows *sql.Rows, dst interface{}, columns []string) error { // check if there is data waiting if !rows.Next() { if err := rows.Err(); err != nil { return err } return sql.ErrNoRows } // get a list of targets targets, err := d.Targets(dst, columns) if err != nil { return err } // perform the scan if err := rows.Scan(targets...); err != nil { return err } // post-process and copy the target values into the struct if err := d.WriteTargets(dst, columns, targets); err != nil { return err } return rows.Err() }
[ "func", "(", "d", "*", "Database", ")", "scanRow", "(", "data", "*", "structData", ",", "rows", "*", "sql", ".", "Rows", ",", "dst", "interface", "{", "}", ",", "columns", "[", "]", "string", ")", "error", "{", "// check if there is data waiting", "if", "!", "rows", ".", "Next", "(", ")", "{", "if", "err", ":=", "rows", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "sql", ".", "ErrNoRows", "\n", "}", "\n\n", "// get a list of targets", "targets", ",", "err", ":=", "d", ".", "Targets", "(", "dst", ",", "columns", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// perform the scan", "if", "err", ":=", "rows", ".", "Scan", "(", "targets", "...", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// post-process and copy the target values into the struct", "if", "err", ":=", "d", ".", "WriteTargets", "(", "dst", ",", "columns", ",", "targets", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "rows", ".", "Err", "(", ")", "\n", "}" ]
// scan a single row of data into a struct.
[ "scan", "a", "single", "row", "of", "data", "into", "a", "struct", "." ]
87a225081a7cb35c4f5f8d0977a79105e5287115
https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/scan.go#L372-L398
2,301
russross/meddler
scan.go
Targets
func (d *Database) Targets(dst interface{}, columns []string) ([]interface{}, error) { data, err := getFields(reflect.TypeOf(dst)) if err != nil { return nil, err } structVal := reflect.ValueOf(dst).Elem() var targets []interface{} for _, name := range columns { if field, present := data.fields[name]; present { fieldAddr := structVal.Field(field.index).Addr().Interface() scanTarget, err := field.meddler.PreRead(fieldAddr) if err != nil { return nil, fmt.Errorf("meddler.Targets: PreRead error on column %s: %v", name, err) } targets = append(targets, scanTarget) } else { // no destination, so throw this away targets = append(targets, new(interface{})) if Debug { log.Printf("meddler.Targets: column [%s] not found in struct", name) } } } return targets, nil }
go
func (d *Database) Targets(dst interface{}, columns []string) ([]interface{}, error) { data, err := getFields(reflect.TypeOf(dst)) if err != nil { return nil, err } structVal := reflect.ValueOf(dst).Elem() var targets []interface{} for _, name := range columns { if field, present := data.fields[name]; present { fieldAddr := structVal.Field(field.index).Addr().Interface() scanTarget, err := field.meddler.PreRead(fieldAddr) if err != nil { return nil, fmt.Errorf("meddler.Targets: PreRead error on column %s: %v", name, err) } targets = append(targets, scanTarget) } else { // no destination, so throw this away targets = append(targets, new(interface{})) if Debug { log.Printf("meddler.Targets: column [%s] not found in struct", name) } } } return targets, nil }
[ "func", "(", "d", "*", "Database", ")", "Targets", "(", "dst", "interface", "{", "}", ",", "columns", "[", "]", "string", ")", "(", "[", "]", "interface", "{", "}", ",", "error", ")", "{", "data", ",", "err", ":=", "getFields", "(", "reflect", ".", "TypeOf", "(", "dst", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "structVal", ":=", "reflect", ".", "ValueOf", "(", "dst", ")", ".", "Elem", "(", ")", "\n\n", "var", "targets", "[", "]", "interface", "{", "}", "\n", "for", "_", ",", "name", ":=", "range", "columns", "{", "if", "field", ",", "present", ":=", "data", ".", "fields", "[", "name", "]", ";", "present", "{", "fieldAddr", ":=", "structVal", ".", "Field", "(", "field", ".", "index", ")", ".", "Addr", "(", ")", ".", "Interface", "(", ")", "\n", "scanTarget", ",", "err", ":=", "field", ".", "meddler", ".", "PreRead", "(", "fieldAddr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "err", ")", "\n", "}", "\n", "targets", "=", "append", "(", "targets", ",", "scanTarget", ")", "\n", "}", "else", "{", "// no destination, so throw this away", "targets", "=", "append", "(", "targets", ",", "new", "(", "interface", "{", "}", ")", ")", "\n\n", "if", "Debug", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "targets", ",", "nil", "\n", "}" ]
// Targets returns a list of values suitable for handing to a // Scan function in the sql package, complete with meddling. After // the Scan is performed, the same values should be handed to // WriteTargets to finalize the values and record them in the struct.
[ "Targets", "returns", "a", "list", "of", "values", "suitable", "for", "handing", "to", "a", "Scan", "function", "in", "the", "sql", "package", "complete", "with", "meddling", ".", "After", "the", "Scan", "is", "performed", "the", "same", "values", "should", "be", "handed", "to", "WriteTargets", "to", "finalize", "the", "values", "and", "record", "them", "in", "the", "struct", "." ]
87a225081a7cb35c4f5f8d0977a79105e5287115
https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/scan.go#L404-L432
2,302
russross/meddler
scan.go
WriteTargets
func (d *Database) WriteTargets(dst interface{}, columns []string, targets []interface{}) error { if len(columns) != len(targets) { return fmt.Errorf("meddler.WriteTargets: mismatch in number of columns (%d) and targets (%d)", len(columns), len(targets)) } data, err := getFields(reflect.TypeOf(dst)) if err != nil { return err } structVal := reflect.ValueOf(dst).Elem() for i, name := range columns { if field, present := data.fields[name]; present { fieldAddr := structVal.Field(field.index).Addr().Interface() err := field.meddler.PostRead(fieldAddr, targets[i]) if err != nil { return fmt.Errorf("meddler.WriteTargets: PostRead error on column [%s]: %v", name, err) } } else { // not destination, so throw this away if Debug { log.Printf("meddler.WriteTargets: column [%s] not found in struct", name) } } } return nil }
go
func (d *Database) WriteTargets(dst interface{}, columns []string, targets []interface{}) error { if len(columns) != len(targets) { return fmt.Errorf("meddler.WriteTargets: mismatch in number of columns (%d) and targets (%d)", len(columns), len(targets)) } data, err := getFields(reflect.TypeOf(dst)) if err != nil { return err } structVal := reflect.ValueOf(dst).Elem() for i, name := range columns { if field, present := data.fields[name]; present { fieldAddr := structVal.Field(field.index).Addr().Interface() err := field.meddler.PostRead(fieldAddr, targets[i]) if err != nil { return fmt.Errorf("meddler.WriteTargets: PostRead error on column [%s]: %v", name, err) } } else { // not destination, so throw this away if Debug { log.Printf("meddler.WriteTargets: column [%s] not found in struct", name) } } } return nil }
[ "func", "(", "d", "*", "Database", ")", "WriteTargets", "(", "dst", "interface", "{", "}", ",", "columns", "[", "]", "string", ",", "targets", "[", "]", "interface", "{", "}", ")", "error", "{", "if", "len", "(", "columns", ")", "!=", "len", "(", "targets", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "columns", ")", ",", "len", "(", "targets", ")", ")", "\n", "}", "\n\n", "data", ",", "err", ":=", "getFields", "(", "reflect", ".", "TypeOf", "(", "dst", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "structVal", ":=", "reflect", ".", "ValueOf", "(", "dst", ")", ".", "Elem", "(", ")", "\n\n", "for", "i", ",", "name", ":=", "range", "columns", "{", "if", "field", ",", "present", ":=", "data", ".", "fields", "[", "name", "]", ";", "present", "{", "fieldAddr", ":=", "structVal", ".", "Field", "(", "field", ".", "index", ")", ".", "Addr", "(", ")", ".", "Interface", "(", ")", "\n", "err", ":=", "field", ".", "meddler", ".", "PostRead", "(", "fieldAddr", ",", "targets", "[", "i", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ",", "err", ")", "\n", "}", "\n", "}", "else", "{", "// not destination, so throw this away", "if", "Debug", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// WriteTargets post-processes values with meddlers after a Scan from the // sql package has been performed. The list of targets is normally produced // by Targets.
[ "WriteTargets", "post", "-", "processes", "values", "with", "meddlers", "after", "a", "Scan", "from", "the", "sql", "package", "has", "been", "performed", ".", "The", "list", "of", "targets", "is", "normally", "produced", "by", "Targets", "." ]
87a225081a7cb35c4f5f8d0977a79105e5287115
https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/scan.go#L442-L470
2,303
russross/meddler
scan.go
WriteTargets
func WriteTargets(dst interface{}, columns []string, targets []interface{}) error { return Default.WriteTargets(dst, columns, targets) }
go
func WriteTargets(dst interface{}, columns []string, targets []interface{}) error { return Default.WriteTargets(dst, columns, targets) }
[ "func", "WriteTargets", "(", "dst", "interface", "{", "}", ",", "columns", "[", "]", "string", ",", "targets", "[", "]", "interface", "{", "}", ")", "error", "{", "return", "Default", ".", "WriteTargets", "(", "dst", ",", "columns", ",", "targets", ")", "\n", "}" ]
// WriteTargets using the Default Database type
[ "WriteTargets", "using", "the", "Default", "Database", "type" ]
87a225081a7cb35c4f5f8d0977a79105e5287115
https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/scan.go#L473-L475
2,304
russross/meddler
scan.go
Scan
func (d *Database) Scan(rows *sql.Rows, dst interface{}) error { // get the list of struct fields data, err := getFields(reflect.TypeOf(dst)) if err != nil { return err } // get the sql columns columns, err := rows.Columns() if err != nil { return err } return d.scanRow(data, rows, dst, columns) }
go
func (d *Database) Scan(rows *sql.Rows, dst interface{}) error { // get the list of struct fields data, err := getFields(reflect.TypeOf(dst)) if err != nil { return err } // get the sql columns columns, err := rows.Columns() if err != nil { return err } return d.scanRow(data, rows, dst, columns) }
[ "func", "(", "d", "*", "Database", ")", "Scan", "(", "rows", "*", "sql", ".", "Rows", ",", "dst", "interface", "{", "}", ")", "error", "{", "// get the list of struct fields", "data", ",", "err", ":=", "getFields", "(", "reflect", ".", "TypeOf", "(", "dst", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// get the sql columns", "columns", ",", "err", ":=", "rows", ".", "Columns", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "d", ".", "scanRow", "(", "data", ",", "rows", ",", "dst", ",", "columns", ")", "\n", "}" ]
// Scan scans a single sql result row into a struct. // It leaves rows ready to be scanned again for the next row. // Returns sql.ErrNoRows if there is no data to read.
[ "Scan", "scans", "a", "single", "sql", "result", "row", "into", "a", "struct", ".", "It", "leaves", "rows", "ready", "to", "be", "scanned", "again", "for", "the", "next", "row", ".", "Returns", "sql", ".", "ErrNoRows", "if", "there", "is", "no", "data", "to", "read", "." ]
87a225081a7cb35c4f5f8d0977a79105e5287115
https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/scan.go#L480-L494
2,305
russross/meddler
scan.go
Scan
func Scan(rows *sql.Rows, dst interface{}) error { return Default.Scan(rows, dst) }
go
func Scan(rows *sql.Rows, dst interface{}) error { return Default.Scan(rows, dst) }
[ "func", "Scan", "(", "rows", "*", "sql", ".", "Rows", ",", "dst", "interface", "{", "}", ")", "error", "{", "return", "Default", ".", "Scan", "(", "rows", ",", "dst", ")", "\n", "}" ]
// Scan using the Default Database type
[ "Scan", "using", "the", "Default", "Database", "type" ]
87a225081a7cb35c4f5f8d0977a79105e5287115
https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/scan.go#L497-L499
2,306
russross/meddler
scan.go
ScanRow
func (d *Database) ScanRow(rows *sql.Rows, dst interface{}) error { // make sure we always close rows, even if there is a scan error defer rows.Close() if err := d.Scan(rows, dst); err != nil { return err } return rows.Close() }
go
func (d *Database) ScanRow(rows *sql.Rows, dst interface{}) error { // make sure we always close rows, even if there is a scan error defer rows.Close() if err := d.Scan(rows, dst); err != nil { return err } return rows.Close() }
[ "func", "(", "d", "*", "Database", ")", "ScanRow", "(", "rows", "*", "sql", ".", "Rows", ",", "dst", "interface", "{", "}", ")", "error", "{", "// make sure we always close rows, even if there is a scan error", "defer", "rows", ".", "Close", "(", ")", "\n\n", "if", "err", ":=", "d", ".", "Scan", "(", "rows", ",", "dst", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "rows", ".", "Close", "(", ")", "\n", "}" ]
// ScanRow scans a single sql result row into a struct. // It reads exactly one result row and closes rows when finished. // Returns sql.ErrNoRows if there is no result row.
[ "ScanRow", "scans", "a", "single", "sql", "result", "row", "into", "a", "struct", ".", "It", "reads", "exactly", "one", "result", "row", "and", "closes", "rows", "when", "finished", ".", "Returns", "sql", ".", "ErrNoRows", "if", "there", "is", "no", "result", "row", "." ]
87a225081a7cb35c4f5f8d0977a79105e5287115
https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/scan.go#L504-L513
2,307
russross/meddler
scan.go
ScanRow
func ScanRow(rows *sql.Rows, dst interface{}) error { return Default.ScanRow(rows, dst) }
go
func ScanRow(rows *sql.Rows, dst interface{}) error { return Default.ScanRow(rows, dst) }
[ "func", "ScanRow", "(", "rows", "*", "sql", ".", "Rows", ",", "dst", "interface", "{", "}", ")", "error", "{", "return", "Default", ".", "ScanRow", "(", "rows", ",", "dst", ")", "\n", "}" ]
// ScanRow using the Default Database type
[ "ScanRow", "using", "the", "Default", "Database", "type" ]
87a225081a7cb35c4f5f8d0977a79105e5287115
https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/scan.go#L516-L518
2,308
russross/meddler
scan.go
ScanAll
func (d *Database) ScanAll(rows *sql.Rows, dst interface{}) error { // make sure we always close rows defer rows.Close() // make sure dst is an appropriate type dstVal := reflect.ValueOf(dst) if dstVal.Kind() != reflect.Ptr || dstVal.IsNil() { return fmt.Errorf("ScanAll called with non-pointer destination: %T", dst) } sliceVal := dstVal.Elem() if sliceVal.Kind() != reflect.Slice { return fmt.Errorf("ScanAll called with pointer to non-slice: %T", dst) } ptrType := sliceVal.Type().Elem() if ptrType.Kind() != reflect.Ptr { return fmt.Errorf("ScanAll expects element to be pointers, found %T", dst) } eltType := ptrType.Elem() if eltType.Kind() != reflect.Struct { return fmt.Errorf("ScanAll expects element to be pointers to structs, found %T", dst) } // get the list of struct fields data, err := getFields(ptrType) if err != nil { return err } // get the sql columns columns, err := rows.Columns() if err != nil { return err } // gather the results for { // create a new element eltVal := reflect.New(eltType) elt := eltVal.Interface() // scan it if err := d.scanRow(data, rows, elt, columns); err != nil { if err == sql.ErrNoRows { return nil } return err } // add to the result slice sliceVal.Set(reflect.Append(sliceVal, eltVal)) } }
go
func (d *Database) ScanAll(rows *sql.Rows, dst interface{}) error { // make sure we always close rows defer rows.Close() // make sure dst is an appropriate type dstVal := reflect.ValueOf(dst) if dstVal.Kind() != reflect.Ptr || dstVal.IsNil() { return fmt.Errorf("ScanAll called with non-pointer destination: %T", dst) } sliceVal := dstVal.Elem() if sliceVal.Kind() != reflect.Slice { return fmt.Errorf("ScanAll called with pointer to non-slice: %T", dst) } ptrType := sliceVal.Type().Elem() if ptrType.Kind() != reflect.Ptr { return fmt.Errorf("ScanAll expects element to be pointers, found %T", dst) } eltType := ptrType.Elem() if eltType.Kind() != reflect.Struct { return fmt.Errorf("ScanAll expects element to be pointers to structs, found %T", dst) } // get the list of struct fields data, err := getFields(ptrType) if err != nil { return err } // get the sql columns columns, err := rows.Columns() if err != nil { return err } // gather the results for { // create a new element eltVal := reflect.New(eltType) elt := eltVal.Interface() // scan it if err := d.scanRow(data, rows, elt, columns); err != nil { if err == sql.ErrNoRows { return nil } return err } // add to the result slice sliceVal.Set(reflect.Append(sliceVal, eltVal)) } }
[ "func", "(", "d", "*", "Database", ")", "ScanAll", "(", "rows", "*", "sql", ".", "Rows", ",", "dst", "interface", "{", "}", ")", "error", "{", "// make sure we always close rows", "defer", "rows", ".", "Close", "(", ")", "\n\n", "// make sure dst is an appropriate type", "dstVal", ":=", "reflect", ".", "ValueOf", "(", "dst", ")", "\n", "if", "dstVal", ".", "Kind", "(", ")", "!=", "reflect", ".", "Ptr", "||", "dstVal", ".", "IsNil", "(", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "dst", ")", "\n", "}", "\n", "sliceVal", ":=", "dstVal", ".", "Elem", "(", ")", "\n", "if", "sliceVal", ".", "Kind", "(", ")", "!=", "reflect", ".", "Slice", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "dst", ")", "\n", "}", "\n", "ptrType", ":=", "sliceVal", ".", "Type", "(", ")", ".", "Elem", "(", ")", "\n", "if", "ptrType", ".", "Kind", "(", ")", "!=", "reflect", ".", "Ptr", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "dst", ")", "\n", "}", "\n", "eltType", ":=", "ptrType", ".", "Elem", "(", ")", "\n", "if", "eltType", ".", "Kind", "(", ")", "!=", "reflect", ".", "Struct", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "dst", ")", "\n", "}", "\n\n", "// get the list of struct fields", "data", ",", "err", ":=", "getFields", "(", "ptrType", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// get the sql columns", "columns", ",", "err", ":=", "rows", ".", "Columns", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// gather the results", "for", "{", "// create a new element", "eltVal", ":=", "reflect", ".", "New", "(", "eltType", ")", "\n", "elt", ":=", "eltVal", ".", "Interface", "(", ")", "\n\n", "// scan it", "if", "err", ":=", "d", ".", "scanRow", "(", "data", ",", "rows", ",", "elt", ",", "columns", ")", ";", "err", "!=", "nil", "{", "if", "err", "==", "sql", ".", "ErrNoRows", "{", "return", "nil", "\n", "}", "\n", "return", "err", "\n", "}", "\n\n", "// add to the result slice", "sliceVal", ".", "Set", "(", "reflect", ".", "Append", "(", "sliceVal", ",", "eltVal", ")", ")", "\n", "}", "\n", "}" ]
// ScanAll scans all sql result rows into a slice of structs. // It reads all rows and closes rows when finished. // dst should be a pointer to a slice of the appropriate type. // The new results will be appended to any existing data in dst.
[ "ScanAll", "scans", "all", "sql", "result", "rows", "into", "a", "slice", "of", "structs", ".", "It", "reads", "all", "rows", "and", "closes", "rows", "when", "finished", ".", "dst", "should", "be", "a", "pointer", "to", "a", "slice", "of", "the", "appropriate", "type", ".", "The", "new", "results", "will", "be", "appended", "to", "any", "existing", "data", "in", "dst", "." ]
87a225081a7cb35c4f5f8d0977a79105e5287115
https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/scan.go#L524-L575
2,309
russross/meddler
scan.go
ScanAll
func ScanAll(rows *sql.Rows, dst interface{}) error { return Default.ScanAll(rows, dst) }
go
func ScanAll(rows *sql.Rows, dst interface{}) error { return Default.ScanAll(rows, dst) }
[ "func", "ScanAll", "(", "rows", "*", "sql", ".", "Rows", ",", "dst", "interface", "{", "}", ")", "error", "{", "return", "Default", ".", "ScanAll", "(", "rows", ",", "dst", ")", "\n", "}" ]
// ScanAll using the Default Database type
[ "ScanAll", "using", "the", "Default", "Database", "type" ]
87a225081a7cb35c4f5f8d0977a79105e5287115
https://github.com/russross/meddler/blob/87a225081a7cb35c4f5f8d0977a79105e5287115/scan.go#L578-L580
2,310
cloudfoundry/bosh-utils
system/exec_cmd_runner_windows.go
mergeEnv
func mergeEnv(sysEnv []string, cmdEnv map[string]string) []string { // sort keys so that duplicates are filtered in deterministic order keys := make([]string, 0, len(cmdEnv)) for k := range cmdEnv { keys = append(keys, k) } sort.Strings(keys) var env []string seen := make(map[string]bool) // seen env keys // add vars from cmdEnv - skipping duplicates for _, k := range keys { v := cmdEnv[k] // value uk := strings.ToUpper(k) if !seen[uk] { env = append(env, k+"="+v) seen[uk] = true } } // add vars from sysEnv - skipping duplicates and keys present in cmdEnv for _, kv := range sysEnv { if n := strings.IndexByte(kv, '='); n != -1 { k := kv[:n] // key uk := strings.ToUpper(k) if !seen[uk] { env = append(env, kv) seen[uk] = true } } } return env }
go
func mergeEnv(sysEnv []string, cmdEnv map[string]string) []string { // sort keys so that duplicates are filtered in deterministic order keys := make([]string, 0, len(cmdEnv)) for k := range cmdEnv { keys = append(keys, k) } sort.Strings(keys) var env []string seen := make(map[string]bool) // seen env keys // add vars from cmdEnv - skipping duplicates for _, k := range keys { v := cmdEnv[k] // value uk := strings.ToUpper(k) if !seen[uk] { env = append(env, k+"="+v) seen[uk] = true } } // add vars from sysEnv - skipping duplicates and keys present in cmdEnv for _, kv := range sysEnv { if n := strings.IndexByte(kv, '='); n != -1 { k := kv[:n] // key uk := strings.ToUpper(k) if !seen[uk] { env = append(env, kv) seen[uk] = true } } } return env }
[ "func", "mergeEnv", "(", "sysEnv", "[", "]", "string", ",", "cmdEnv", "map", "[", "string", "]", "string", ")", "[", "]", "string", "{", "// sort keys so that duplicates are filtered in deterministic order", "keys", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "cmdEnv", ")", ")", "\n", "for", "k", ":=", "range", "cmdEnv", "{", "keys", "=", "append", "(", "keys", ",", "k", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "keys", ")", "\n\n", "var", "env", "[", "]", "string", "\n", "seen", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "// seen env keys", "\n\n", "// add vars from cmdEnv - skipping duplicates", "for", "_", ",", "k", ":=", "range", "keys", "{", "v", ":=", "cmdEnv", "[", "k", "]", "// value", "\n", "uk", ":=", "strings", ".", "ToUpper", "(", "k", ")", "\n", "if", "!", "seen", "[", "uk", "]", "{", "env", "=", "append", "(", "env", ",", "k", "+", "\"", "\"", "+", "v", ")", "\n", "seen", "[", "uk", "]", "=", "true", "\n", "}", "\n", "}", "\n", "// add vars from sysEnv - skipping duplicates and keys present in cmdEnv", "for", "_", ",", "kv", ":=", "range", "sysEnv", "{", "if", "n", ":=", "strings", ".", "IndexByte", "(", "kv", ",", "'='", ")", ";", "n", "!=", "-", "1", "{", "k", ":=", "kv", "[", ":", "n", "]", "// key", "\n", "uk", ":=", "strings", ".", "ToUpper", "(", "k", ")", "\n", "if", "!", "seen", "[", "uk", "]", "{", "env", "=", "append", "(", "env", ",", "kv", ")", "\n", "seen", "[", "uk", "]", "=", "true", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "env", "\n", "}" ]
// mergeEnv case-insensitive merge of system and command environments variables. // Command variables override any system variable with the same key.
[ "mergeEnv", "case", "-", "insensitive", "merge", "of", "system", "and", "command", "environments", "variables", ".", "Command", "variables", "override", "any", "system", "variable", "with", "the", "same", "key", "." ]
757f0ce2bf30bab7848e17679ca54f74e574facb
https://github.com/cloudfoundry/bosh-utils/blob/757f0ce2bf30bab7848e17679ca54f74e574facb/system/exec_cmd_runner_windows.go#L15-L48
2,311
cloudfoundry/bosh-utils
system/exec_process_unix.go
TerminateNicely
func (p *execProcess) TerminateNicely(killGracePeriod time.Duration) error { // Make sure process is being waited on for process state reaping to occur // as to avoid forcibly killing the process after killGracePeriod if p.waitCh == nil { panic("TerminateNicely() must be called after Wait()") } err := p.signalGroup(syscall.SIGTERM) if err != nil { return bosherr.WrapErrorf(err, "Sending SIGTERM to process group %d", p.pgid) } terminatedCh := make(chan struct{}) stopCheckingTerminatedCh := make(chan struct{}) go func() { for p.groupExists() { select { case <-time.After(500 * time.Millisecond): // nothing to do case <-stopCheckingTerminatedCh: return } } close(terminatedCh) }() select { case <-terminatedCh: // nothing to do case <-time.After(killGracePeriod): close(stopCheckingTerminatedCh) err = p.signalGroup(syscall.SIGKILL) if err != nil { return bosherr.WrapErrorf(err, "Sending SIGKILL to process group %d", p.pgid) } } // It takes some time for the process to disappear for i := 0; i < 20; i++ { if !p.groupExists() { return nil } time.Sleep(500 * time.Millisecond) } return bosherr.Errorf("Failed to kill process after grace timeout (PID %d)", p.pid) }
go
func (p *execProcess) TerminateNicely(killGracePeriod time.Duration) error { // Make sure process is being waited on for process state reaping to occur // as to avoid forcibly killing the process after killGracePeriod if p.waitCh == nil { panic("TerminateNicely() must be called after Wait()") } err := p.signalGroup(syscall.SIGTERM) if err != nil { return bosherr.WrapErrorf(err, "Sending SIGTERM to process group %d", p.pgid) } terminatedCh := make(chan struct{}) stopCheckingTerminatedCh := make(chan struct{}) go func() { for p.groupExists() { select { case <-time.After(500 * time.Millisecond): // nothing to do case <-stopCheckingTerminatedCh: return } } close(terminatedCh) }() select { case <-terminatedCh: // nothing to do case <-time.After(killGracePeriod): close(stopCheckingTerminatedCh) err = p.signalGroup(syscall.SIGKILL) if err != nil { return bosherr.WrapErrorf(err, "Sending SIGKILL to process group %d", p.pgid) } } // It takes some time for the process to disappear for i := 0; i < 20; i++ { if !p.groupExists() { return nil } time.Sleep(500 * time.Millisecond) } return bosherr.Errorf("Failed to kill process after grace timeout (PID %d)", p.pid) }
[ "func", "(", "p", "*", "execProcess", ")", "TerminateNicely", "(", "killGracePeriod", "time", ".", "Duration", ")", "error", "{", "// Make sure process is being waited on for process state reaping to occur", "// as to avoid forcibly killing the process after killGracePeriod", "if", "p", ".", "waitCh", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "err", ":=", "p", ".", "signalGroup", "(", "syscall", ".", "SIGTERM", ")", "\n", "if", "err", "!=", "nil", "{", "return", "bosherr", ".", "WrapErrorf", "(", "err", ",", "\"", "\"", ",", "p", ".", "pgid", ")", "\n", "}", "\n\n", "terminatedCh", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "stopCheckingTerminatedCh", ":=", "make", "(", "chan", "struct", "{", "}", ")", "\n\n", "go", "func", "(", ")", "{", "for", "p", ".", "groupExists", "(", ")", "{", "select", "{", "case", "<-", "time", ".", "After", "(", "500", "*", "time", ".", "Millisecond", ")", ":", "// nothing to do", "case", "<-", "stopCheckingTerminatedCh", ":", "return", "\n", "}", "\n", "}", "\n\n", "close", "(", "terminatedCh", ")", "\n", "}", "(", ")", "\n\n", "select", "{", "case", "<-", "terminatedCh", ":", "// nothing to do", "case", "<-", "time", ".", "After", "(", "killGracePeriod", ")", ":", "close", "(", "stopCheckingTerminatedCh", ")", "\n\n", "err", "=", "p", ".", "signalGroup", "(", "syscall", ".", "SIGKILL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "bosherr", ".", "WrapErrorf", "(", "err", ",", "\"", "\"", ",", "p", ".", "pgid", ")", "\n", "}", "\n", "}", "\n\n", "// It takes some time for the process to disappear", "for", "i", ":=", "0", ";", "i", "<", "20", ";", "i", "++", "{", "if", "!", "p", ".", "groupExists", "(", ")", "{", "return", "nil", "\n", "}", "\n", "time", ".", "Sleep", "(", "500", "*", "time", ".", "Millisecond", ")", "\n", "}", "\n\n", "return", "bosherr", ".", "Errorf", "(", "\"", "\"", ",", "p", ".", "pid", ")", "\n", "}" ]
// TerminateNicely can be called multiple times simultaneously from different goroutines
[ "TerminateNicely", "can", "be", "called", "multiple", "times", "simultaneously", "from", "different", "goroutines" ]
757f0ce2bf30bab7848e17679ca54f74e574facb
https://github.com/cloudfoundry/bosh-utils/blob/757f0ce2bf30bab7848e17679ca54f74e574facb/system/exec_process_unix.go#L48-L98
2,312
cloudfoundry/bosh-utils
system/exec_process_unix.go
signalGroup
func (p *execProcess) signalGroup(sig syscall.Signal) error { err := syscall.Kill(-p.pgid, sig) if p.isGroupDoesNotExistError(err) { return nil } return err }
go
func (p *execProcess) signalGroup(sig syscall.Signal) error { err := syscall.Kill(-p.pgid, sig) if p.isGroupDoesNotExistError(err) { return nil } return err }
[ "func", "(", "p", "*", "execProcess", ")", "signalGroup", "(", "sig", "syscall", ".", "Signal", ")", "error", "{", "err", ":=", "syscall", ".", "Kill", "(", "-", "p", ".", "pgid", ",", "sig", ")", "\n", "if", "p", ".", "isGroupDoesNotExistError", "(", "err", ")", "{", "return", "nil", "\n", "}", "\n", "return", "err", "\n", "}" ]
// signalGroup does not return an error if the process group does not exist
[ "signalGroup", "does", "not", "return", "an", "error", "if", "the", "process", "group", "does", "not", "exist" ]
757f0ce2bf30bab7848e17679ca54f74e574facb
https://github.com/cloudfoundry/bosh-utils/blob/757f0ce2bf30bab7848e17679ca54f74e574facb/system/exec_process_unix.go#L101-L107
2,313
cloudfoundry/bosh-utils
property/builders.go
Build
func Build(val interface{}) (Property, error) { if val == nil { return nil, nil } switch reflect.TypeOf(val).Kind() { case reflect.Map: valMap, ok := val.(map[interface{}]interface{}) if !ok { return nil, bosherr.Errorf("Converting map %#v", val) } return BuildMap(valMap) case reflect.Slice: valSlice, ok := val.([]interface{}) if !ok { return nil, bosherr.Errorf("Converting slice %#v", val) } return BuildList(valSlice) default: return val, nil } }
go
func Build(val interface{}) (Property, error) { if val == nil { return nil, nil } switch reflect.TypeOf(val).Kind() { case reflect.Map: valMap, ok := val.(map[interface{}]interface{}) if !ok { return nil, bosherr.Errorf("Converting map %#v", val) } return BuildMap(valMap) case reflect.Slice: valSlice, ok := val.([]interface{}) if !ok { return nil, bosherr.Errorf("Converting slice %#v", val) } return BuildList(valSlice) default: return val, nil } }
[ "func", "Build", "(", "val", "interface", "{", "}", ")", "(", "Property", ",", "error", ")", "{", "if", "val", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "switch", "reflect", ".", "TypeOf", "(", "val", ")", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Map", ":", "valMap", ",", "ok", ":=", "val", ".", "(", "map", "[", "interface", "{", "}", "]", "interface", "{", "}", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "bosherr", ".", "Errorf", "(", "\"", "\"", ",", "val", ")", "\n", "}", "\n\n", "return", "BuildMap", "(", "valMap", ")", "\n\n", "case", "reflect", ".", "Slice", ":", "valSlice", ",", "ok", ":=", "val", ".", "(", "[", "]", "interface", "{", "}", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "bosherr", ".", "Errorf", "(", "\"", "\"", ",", "val", ")", "\n", "}", "\n\n", "return", "BuildList", "(", "valSlice", ")", "\n\n", "default", ":", "return", "val", ",", "nil", "\n", "}", "\n", "}" ]
// Build creates a generic property that may be a Map, List or primitive. // If it is a Map or List it will be built using the appropriate builder and constraints.
[ "Build", "creates", "a", "generic", "property", "that", "may", "be", "a", "Map", "List", "or", "primitive", ".", "If", "it", "is", "a", "Map", "or", "List", "it", "will", "be", "built", "using", "the", "appropriate", "builder", "and", "constraints", "." ]
757f0ce2bf30bab7848e17679ca54f74e574facb
https://github.com/cloudfoundry/bosh-utils/blob/757f0ce2bf30bab7848e17679ca54f74e574facb/property/builders.go#L49-L74
2,314
cloudfoundry/bosh-utils
system/exec_cmd_runner_unix.go
mergeEnv
func mergeEnv(sysEnv []string, cmdEnv map[string]string) []string { var env []string // cmdEnv has precedence and overwrites any duplicate vars for k, v := range cmdEnv { env = append(env, k+"="+v) } for _, s := range sysEnv { if n := strings.IndexByte(s, '='); n != -1 { k := s[:n] // key if _, found := cmdEnv[k]; !found { env = append(env, s) } } } return env }
go
func mergeEnv(sysEnv []string, cmdEnv map[string]string) []string { var env []string // cmdEnv has precedence and overwrites any duplicate vars for k, v := range cmdEnv { env = append(env, k+"="+v) } for _, s := range sysEnv { if n := strings.IndexByte(s, '='); n != -1 { k := s[:n] // key if _, found := cmdEnv[k]; !found { env = append(env, s) } } } return env }
[ "func", "mergeEnv", "(", "sysEnv", "[", "]", "string", ",", "cmdEnv", "map", "[", "string", "]", "string", ")", "[", "]", "string", "{", "var", "env", "[", "]", "string", "\n", "// cmdEnv has precedence and overwrites any duplicate vars", "for", "k", ",", "v", ":=", "range", "cmdEnv", "{", "env", "=", "append", "(", "env", ",", "k", "+", "\"", "\"", "+", "v", ")", "\n", "}", "\n", "for", "_", ",", "s", ":=", "range", "sysEnv", "{", "if", "n", ":=", "strings", ".", "IndexByte", "(", "s", ",", "'='", ")", ";", "n", "!=", "-", "1", "{", "k", ":=", "s", "[", ":", "n", "]", "// key", "\n", "if", "_", ",", "found", ":=", "cmdEnv", "[", "k", "]", ";", "!", "found", "{", "env", "=", "append", "(", "env", ",", "s", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "env", "\n", "}" ]
// mergeEnv merges system and command environments variables. Command variables // override any system variable with the same key.
[ "mergeEnv", "merges", "system", "and", "command", "environments", "variables", ".", "Command", "variables", "override", "any", "system", "variable", "with", "the", "same", "key", "." ]
757f0ce2bf30bab7848e17679ca54f74e574facb
https://github.com/cloudfoundry/bosh-utils/blob/757f0ce2bf30bab7848e17679ca54f74e574facb/system/exec_cmd_runner_unix.go#L16-L31
2,315
cloudfoundry/bosh-utils
logger/logger.go
DebugWithDetails
func (l *logger) DebugWithDetails(tag, msg string, args ...interface{}) { msg = msg + "\n********************\n%s\n********************" l.Debug(tag, msg, args...) }
go
func (l *logger) DebugWithDetails(tag, msg string, args ...interface{}) { msg = msg + "\n********************\n%s\n********************" l.Debug(tag, msg, args...) }
[ "func", "(", "l", "*", "logger", ")", "DebugWithDetails", "(", "tag", ",", "msg", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "msg", "=", "msg", "+", "\"", "\\n", "\\n", "\\n", "\"", "\n", "l", ".", "Debug", "(", "tag", ",", "msg", ",", "args", "...", ")", "\n", "}" ]
// DebugWithDetails will automatically change the format of the message // to insert a block of text after the log
[ "DebugWithDetails", "will", "automatically", "change", "the", "format", "of", "the", "message", "to", "insert", "a", "block", "of", "text", "after", "the", "log" ]
757f0ce2bf30bab7848e17679ca54f74e574facb
https://github.com/cloudfoundry/bosh-utils/blob/757f0ce2bf30bab7848e17679ca54f74e574facb/logger/logger.go#L95-L98
2,316
cloudfoundry/bosh-utils
logger/logger.go
ErrorWithDetails
func (l *logger) ErrorWithDetails(tag, msg string, args ...interface{}) { msg = msg + "\n********************\n%s\n********************" l.Error(tag, msg, args...) }
go
func (l *logger) ErrorWithDetails(tag, msg string, args ...interface{}) { msg = msg + "\n********************\n%s\n********************" l.Error(tag, msg, args...) }
[ "func", "(", "l", "*", "logger", ")", "ErrorWithDetails", "(", "tag", ",", "msg", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "msg", "=", "msg", "+", "\"", "\\n", "\\n", "\\n", "\"", "\n", "l", ".", "Error", "(", "tag", ",", "msg", ",", "args", "...", ")", "\n", "}" ]
// ErrorWithDetails will automatically change the format of the message // to insert a block of text after the log
[ "ErrorWithDetails", "will", "automatically", "change", "the", "format", "of", "the", "message", "to", "insert", "a", "block", "of", "text", "after", "the", "log" ]
757f0ce2bf30bab7848e17679ca54f74e574facb
https://github.com/cloudfoundry/bosh-utils/blob/757f0ce2bf30bab7848e17679ca54f74e574facb/logger/logger.go#L129-L132
2,317
cloudfoundry/bosh-utils
work/pool.go
ParallelDo
func (p Pool) ParallelDo(tasks ...func() error) error { jobs := make(chan func() error, len(tasks)) errs := make(chan error, len(tasks)) wg := &sync.WaitGroup{} wg.Add(p.Count) for i := 0; i < p.Count; i++ { p.spawnWorker(jobs, errs, wg) } for _, task := range tasks { jobs <- task } close(jobs) wg.Wait() close(errs) var combinedErrors []error for e := range errs { combinedErrors = append(combinedErrors, e) } if len(combinedErrors) > 0 { return bosherr.NewMultiError(combinedErrors...) } return nil }
go
func (p Pool) ParallelDo(tasks ...func() error) error { jobs := make(chan func() error, len(tasks)) errs := make(chan error, len(tasks)) wg := &sync.WaitGroup{} wg.Add(p.Count) for i := 0; i < p.Count; i++ { p.spawnWorker(jobs, errs, wg) } for _, task := range tasks { jobs <- task } close(jobs) wg.Wait() close(errs) var combinedErrors []error for e := range errs { combinedErrors = append(combinedErrors, e) } if len(combinedErrors) > 0 { return bosherr.NewMultiError(combinedErrors...) } return nil }
[ "func", "(", "p", "Pool", ")", "ParallelDo", "(", "tasks", "...", "func", "(", ")", "error", ")", "error", "{", "jobs", ":=", "make", "(", "chan", "func", "(", ")", "error", ",", "len", "(", "tasks", ")", ")", "\n", "errs", ":=", "make", "(", "chan", "error", ",", "len", "(", "tasks", ")", ")", "\n", "wg", ":=", "&", "sync", ".", "WaitGroup", "{", "}", "\n\n", "wg", ".", "Add", "(", "p", ".", "Count", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "p", ".", "Count", ";", "i", "++", "{", "p", ".", "spawnWorker", "(", "jobs", ",", "errs", ",", "wg", ")", "\n", "}", "\n\n", "for", "_", ",", "task", ":=", "range", "tasks", "{", "jobs", "<-", "task", "\n", "}", "\n\n", "close", "(", "jobs", ")", "\n\n", "wg", ".", "Wait", "(", ")", "\n\n", "close", "(", "errs", ")", "\n\n", "var", "combinedErrors", "[", "]", "error", "\n", "for", "e", ":=", "range", "errs", "{", "combinedErrors", "=", "append", "(", "combinedErrors", ",", "e", ")", "\n", "}", "\n\n", "if", "len", "(", "combinedErrors", ")", ">", "0", "{", "return", "bosherr", ".", "NewMultiError", "(", "combinedErrors", "...", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// ParallelDo Runs the given set of tasks in parallel using the configured number of worker go routines // Will stop adding new tasks if a task throws an error, but will wait for in-flight tasks to finish
[ "ParallelDo", "Runs", "the", "given", "set", "of", "tasks", "in", "parallel", "using", "the", "configured", "number", "of", "worker", "go", "routines", "Will", "stop", "adding", "new", "tasks", "if", "a", "task", "throws", "an", "error", "but", "will", "wait", "for", "in", "-", "flight", "tasks", "to", "finish" ]
757f0ce2bf30bab7848e17679ca54f74e574facb
https://github.com/cloudfoundry/bosh-utils/blob/757f0ce2bf30bab7848e17679ca54f74e574facb/work/pool.go#L15-L45
2,318
alexmullins/zip
writer.go
CreateHeader
func (w *Writer) CreateHeader(fh *FileHeader) (io.Writer, error) { if w.last != nil && !w.last.closed { if err := w.last.close(); err != nil { return nil, err } } if len(w.dir) > 0 && w.dir[len(w.dir)-1].FileHeader == fh { // See https://golang.org/issue/11144 confusion. return nil, errors.New("archive/zip: invalid duplicate FileHeader") } fh.Flags |= 0x8 // we will write a data descriptor // TODO(alex): Look at spec and see if these need to be changed // when using encryption. fh.CreatorVersion = fh.CreatorVersion&0xff00 | zipVersion20 // preserve compatibility byte fh.ReaderVersion = zipVersion20 fw := &fileWriter{ zipw: w.cw, compCount: &countWriter{w: w.cw}, crc32: crc32.NewIEEE(), } // Get the compressor before possibly changing Method to 99 due to password comp := compressor(fh.Method) if comp == nil { return nil, ErrAlgorithm } // check for password var sw io.Writer = fw.compCount if fh.password != nil { // we have a password and need to encrypt. fh.writeWinZipExtra() fh.Method = 99 // ok to change, we've gotten the comp and wrote extra ew, err := newEncryptionWriter(sw, fh.password, fw) if err != nil { return nil, err } sw = ew } var err error fw.comp, err = comp(sw) if err != nil { return nil, err } fw.rawCount = &countWriter{w: fw.comp} h := &header{ FileHeader: fh, offset: uint64(w.cw.count), } w.dir = append(w.dir, h) fw.header = h if err := writeHeader(w.cw, fh); err != nil { return nil, err } w.last = fw return fw, nil }
go
func (w *Writer) CreateHeader(fh *FileHeader) (io.Writer, error) { if w.last != nil && !w.last.closed { if err := w.last.close(); err != nil { return nil, err } } if len(w.dir) > 0 && w.dir[len(w.dir)-1].FileHeader == fh { // See https://golang.org/issue/11144 confusion. return nil, errors.New("archive/zip: invalid duplicate FileHeader") } fh.Flags |= 0x8 // we will write a data descriptor // TODO(alex): Look at spec and see if these need to be changed // when using encryption. fh.CreatorVersion = fh.CreatorVersion&0xff00 | zipVersion20 // preserve compatibility byte fh.ReaderVersion = zipVersion20 fw := &fileWriter{ zipw: w.cw, compCount: &countWriter{w: w.cw}, crc32: crc32.NewIEEE(), } // Get the compressor before possibly changing Method to 99 due to password comp := compressor(fh.Method) if comp == nil { return nil, ErrAlgorithm } // check for password var sw io.Writer = fw.compCount if fh.password != nil { // we have a password and need to encrypt. fh.writeWinZipExtra() fh.Method = 99 // ok to change, we've gotten the comp and wrote extra ew, err := newEncryptionWriter(sw, fh.password, fw) if err != nil { return nil, err } sw = ew } var err error fw.comp, err = comp(sw) if err != nil { return nil, err } fw.rawCount = &countWriter{w: fw.comp} h := &header{ FileHeader: fh, offset: uint64(w.cw.count), } w.dir = append(w.dir, h) fw.header = h if err := writeHeader(w.cw, fh); err != nil { return nil, err } w.last = fw return fw, nil }
[ "func", "(", "w", "*", "Writer", ")", "CreateHeader", "(", "fh", "*", "FileHeader", ")", "(", "io", ".", "Writer", ",", "error", ")", "{", "if", "w", ".", "last", "!=", "nil", "&&", "!", "w", ".", "last", ".", "closed", "{", "if", "err", ":=", "w", ".", "last", ".", "close", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "if", "len", "(", "w", ".", "dir", ")", ">", "0", "&&", "w", ".", "dir", "[", "len", "(", "w", ".", "dir", ")", "-", "1", "]", ".", "FileHeader", "==", "fh", "{", "// See https://golang.org/issue/11144 confusion.", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "fh", ".", "Flags", "|=", "0x8", "// we will write a data descriptor", "\n", "// TODO(alex): Look at spec and see if these need to be changed", "// when using encryption.", "fh", ".", "CreatorVersion", "=", "fh", ".", "CreatorVersion", "&", "0xff00", "|", "zipVersion20", "// preserve compatibility byte", "\n", "fh", ".", "ReaderVersion", "=", "zipVersion20", "\n\n", "fw", ":=", "&", "fileWriter", "{", "zipw", ":", "w", ".", "cw", ",", "compCount", ":", "&", "countWriter", "{", "w", ":", "w", ".", "cw", "}", ",", "crc32", ":", "crc32", ".", "NewIEEE", "(", ")", ",", "}", "\n", "// Get the compressor before possibly changing Method to 99 due to password", "comp", ":=", "compressor", "(", "fh", ".", "Method", ")", "\n", "if", "comp", "==", "nil", "{", "return", "nil", ",", "ErrAlgorithm", "\n", "}", "\n", "// check for password", "var", "sw", "io", ".", "Writer", "=", "fw", ".", "compCount", "\n", "if", "fh", ".", "password", "!=", "nil", "{", "// we have a password and need to encrypt.", "fh", ".", "writeWinZipExtra", "(", ")", "\n", "fh", ".", "Method", "=", "99", "// ok to change, we've gotten the comp and wrote extra", "\n", "ew", ",", "err", ":=", "newEncryptionWriter", "(", "sw", ",", "fh", ".", "password", ",", "fw", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "sw", "=", "ew", "\n", "}", "\n", "var", "err", "error", "\n", "fw", ".", "comp", ",", "err", "=", "comp", "(", "sw", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "fw", ".", "rawCount", "=", "&", "countWriter", "{", "w", ":", "fw", ".", "comp", "}", "\n\n", "h", ":=", "&", "header", "{", "FileHeader", ":", "fh", ",", "offset", ":", "uint64", "(", "w", ".", "cw", ".", "count", ")", ",", "}", "\n", "w", ".", "dir", "=", "append", "(", "w", ".", "dir", ",", "h", ")", "\n", "fw", ".", "header", "=", "h", "\n\n", "if", "err", ":=", "writeHeader", "(", "w", ".", "cw", ",", "fh", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "w", ".", "last", "=", "fw", "\n", "return", "fw", ",", "nil", "\n", "}" ]
// CreateHeader adds a file to the zip file using the provided FileHeader // for the file metadata. // It returns a Writer to which the file contents should be written. // // The file's contents must be written to the io.Writer before the next // call to Create, CreateHeader, or Close. The provided FileHeader fh // must not be modified after a call to CreateHeader.
[ "CreateHeader", "adds", "a", "file", "to", "the", "zip", "file", "using", "the", "provided", "FileHeader", "for", "the", "file", "metadata", ".", "It", "returns", "a", "Writer", "to", "which", "the", "file", "contents", "should", "be", "written", ".", "The", "file", "s", "contents", "must", "be", "written", "to", "the", "io", ".", "Writer", "before", "the", "next", "call", "to", "Create", "CreateHeader", "or", "Close", ".", "The", "provided", "FileHeader", "fh", "must", "not", "be", "modified", "after", "a", "call", "to", "CreateHeader", "." ]
4affb64b04d017a32f9443975e26e841da367e0f
https://github.com/alexmullins/zip/blob/4affb64b04d017a32f9443975e26e841da367e0f/writer.go#L202-L261
2,319
alexmullins/zip
crypto.go
newDecryptionReader
func newDecryptionReader(r *io.SectionReader, f *File) (io.Reader, error) { keyLen := aesKeyLen(f.aesStrength) saltLen := keyLen / 2 // salt is half of key len if saltLen == 0 { return nil, ErrDecryption } // grab the salt and pwvv saltpwvv := make([]byte, saltLen+2) if _, err := r.Read(saltpwvv); err != nil { return nil, err } salt := saltpwvv[:saltLen] pwvv := saltpwvv[saltLen : saltLen+2] // generate keys only if we have a password if f.password == nil { return nil, ErrPassword } decKey, authKey, pwv := generateKeys(f.password(), salt, keyLen) if !checkPasswordVerification(pwv, pwvv) { return nil, ErrPassword } dataOff := int64(saltLen + 2) dataLen := int64(f.CompressedSize64 - uint64(saltLen) - 2 - 10) // // TODO(alex): Should the compressed sizes be fixed? // // Not the ideal place to do this. // f.CompressedSize64 = uint64(dataLen) // f.CompressedSize = uint32(dataLen) data := io.NewSectionReader(r, dataOff, dataLen) authOff := dataOff + dataLen authcode := io.NewSectionReader(r, authOff, 10) ar := newAuthReader(authKey, data, authcode, f.DeferAuth) dr := decryptStream(decKey, ar) if dr == nil { return nil, ErrDecryption } return dr, nil }
go
func newDecryptionReader(r *io.SectionReader, f *File) (io.Reader, error) { keyLen := aesKeyLen(f.aesStrength) saltLen := keyLen / 2 // salt is half of key len if saltLen == 0 { return nil, ErrDecryption } // grab the salt and pwvv saltpwvv := make([]byte, saltLen+2) if _, err := r.Read(saltpwvv); err != nil { return nil, err } salt := saltpwvv[:saltLen] pwvv := saltpwvv[saltLen : saltLen+2] // generate keys only if we have a password if f.password == nil { return nil, ErrPassword } decKey, authKey, pwv := generateKeys(f.password(), salt, keyLen) if !checkPasswordVerification(pwv, pwvv) { return nil, ErrPassword } dataOff := int64(saltLen + 2) dataLen := int64(f.CompressedSize64 - uint64(saltLen) - 2 - 10) // // TODO(alex): Should the compressed sizes be fixed? // // Not the ideal place to do this. // f.CompressedSize64 = uint64(dataLen) // f.CompressedSize = uint32(dataLen) data := io.NewSectionReader(r, dataOff, dataLen) authOff := dataOff + dataLen authcode := io.NewSectionReader(r, authOff, 10) ar := newAuthReader(authKey, data, authcode, f.DeferAuth) dr := decryptStream(decKey, ar) if dr == nil { return nil, ErrDecryption } return dr, nil }
[ "func", "newDecryptionReader", "(", "r", "*", "io", ".", "SectionReader", ",", "f", "*", "File", ")", "(", "io", ".", "Reader", ",", "error", ")", "{", "keyLen", ":=", "aesKeyLen", "(", "f", ".", "aesStrength", ")", "\n", "saltLen", ":=", "keyLen", "/", "2", "// salt is half of key len", "\n", "if", "saltLen", "==", "0", "{", "return", "nil", ",", "ErrDecryption", "\n", "}", "\n", "// grab the salt and pwvv", "saltpwvv", ":=", "make", "(", "[", "]", "byte", ",", "saltLen", "+", "2", ")", "\n", "if", "_", ",", "err", ":=", "r", ".", "Read", "(", "saltpwvv", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "salt", ":=", "saltpwvv", "[", ":", "saltLen", "]", "\n", "pwvv", ":=", "saltpwvv", "[", "saltLen", ":", "saltLen", "+", "2", "]", "\n", "// generate keys only if we have a password", "if", "f", ".", "password", "==", "nil", "{", "return", "nil", ",", "ErrPassword", "\n", "}", "\n", "decKey", ",", "authKey", ",", "pwv", ":=", "generateKeys", "(", "f", ".", "password", "(", ")", ",", "salt", ",", "keyLen", ")", "\n", "if", "!", "checkPasswordVerification", "(", "pwv", ",", "pwvv", ")", "{", "return", "nil", ",", "ErrPassword", "\n", "}", "\n", "dataOff", ":=", "int64", "(", "saltLen", "+", "2", ")", "\n", "dataLen", ":=", "int64", "(", "f", ".", "CompressedSize64", "-", "uint64", "(", "saltLen", ")", "-", "2", "-", "10", ")", "\n", "// // TODO(alex): Should the compressed sizes be fixed?", "// // Not the ideal place to do this.", "// f.CompressedSize64 = uint64(dataLen)", "// f.CompressedSize = uint32(dataLen)", "data", ":=", "io", ".", "NewSectionReader", "(", "r", ",", "dataOff", ",", "dataLen", ")", "\n", "authOff", ":=", "dataOff", "+", "dataLen", "\n", "authcode", ":=", "io", ".", "NewSectionReader", "(", "r", ",", "authOff", ",", "10", ")", "\n", "ar", ":=", "newAuthReader", "(", "authKey", ",", "data", ",", "authcode", ",", "f", ".", "DeferAuth", ")", "\n", "dr", ":=", "decryptStream", "(", "decKey", ",", "ar", ")", "\n", "if", "dr", "==", "nil", "{", "return", "nil", ",", "ErrDecryption", "\n", "}", "\n", "return", "dr", ",", "nil", "\n", "}" ]
// newDecryptionReader returns an authenticated, decryption reader
[ "newDecryptionReader", "returns", "an", "authenticated", "decryption", "reader" ]
4affb64b04d017a32f9443975e26e841da367e0f
https://github.com/alexmullins/zip/blob/4affb64b04d017a32f9443975e26e841da367e0f/crypto.go#L278-L314
2,320
alexmullins/zip
crypto.go
Encrypt
func (w *Writer) Encrypt(name string, password string) (io.Writer, error) { fh := &FileHeader{ Name: name, Method: Deflate, } fh.SetPassword(password) return w.CreateHeader(fh) }
go
func (w *Writer) Encrypt(name string, password string) (io.Writer, error) { fh := &FileHeader{ Name: name, Method: Deflate, } fh.SetPassword(password) return w.CreateHeader(fh) }
[ "func", "(", "w", "*", "Writer", ")", "Encrypt", "(", "name", "string", ",", "password", "string", ")", "(", "io", ".", "Writer", ",", "error", ")", "{", "fh", ":=", "&", "FileHeader", "{", "Name", ":", "name", ",", "Method", ":", "Deflate", ",", "}", "\n", "fh", ".", "SetPassword", "(", "password", ")", "\n", "return", "w", ".", "CreateHeader", "(", "fh", ")", "\n", "}" ]
// Encrypt adds a file to the zip file using the provided name. // It returns a Writer to which the file contents should be written. File // contents will be encrypted with AES-256 using the given password. The // file's contents must be written to the io.Writer before the next call // to Create, CreateHeader, or Close.
[ "Encrypt", "adds", "a", "file", "to", "the", "zip", "file", "using", "the", "provided", "name", ".", "It", "returns", "a", "Writer", "to", "which", "the", "file", "contents", "should", "be", "written", ".", "File", "contents", "will", "be", "encrypted", "with", "AES", "-", "256", "using", "the", "given", "password", ".", "The", "file", "s", "contents", "must", "be", "written", "to", "the", "io", ".", "Writer", "before", "the", "next", "call", "to", "Create", "CreateHeader", "or", "Close", "." ]
4affb64b04d017a32f9443975e26e841da367e0f
https://github.com/alexmullins/zip/blob/4affb64b04d017a32f9443975e26e841da367e0f/crypto.go#L455-L462
2,321
alexmullins/zip
reader.go
findDirectory64End
func findDirectory64End(r io.ReaderAt, directoryEndOffset int64) (int64, error) { locOffset := directoryEndOffset - directory64LocLen if locOffset < 0 { return -1, nil // no need to look for a header outside the file } buf := make([]byte, directory64LocLen) if _, err := r.ReadAt(buf, locOffset); err != nil { return -1, err } b := readBuf(buf) if sig := b.uint32(); sig != directory64LocSignature { return -1, nil } b = b[4:] // skip number of the disk with the start of the zip64 end of central directory p := b.uint64() // relative offset of the zip64 end of central directory record return int64(p), nil }
go
func findDirectory64End(r io.ReaderAt, directoryEndOffset int64) (int64, error) { locOffset := directoryEndOffset - directory64LocLen if locOffset < 0 { return -1, nil // no need to look for a header outside the file } buf := make([]byte, directory64LocLen) if _, err := r.ReadAt(buf, locOffset); err != nil { return -1, err } b := readBuf(buf) if sig := b.uint32(); sig != directory64LocSignature { return -1, nil } b = b[4:] // skip number of the disk with the start of the zip64 end of central directory p := b.uint64() // relative offset of the zip64 end of central directory record return int64(p), nil }
[ "func", "findDirectory64End", "(", "r", "io", ".", "ReaderAt", ",", "directoryEndOffset", "int64", ")", "(", "int64", ",", "error", ")", "{", "locOffset", ":=", "directoryEndOffset", "-", "directory64LocLen", "\n", "if", "locOffset", "<", "0", "{", "return", "-", "1", ",", "nil", "// no need to look for a header outside the file", "\n", "}", "\n", "buf", ":=", "make", "(", "[", "]", "byte", ",", "directory64LocLen", ")", "\n", "if", "_", ",", "err", ":=", "r", ".", "ReadAt", "(", "buf", ",", "locOffset", ")", ";", "err", "!=", "nil", "{", "return", "-", "1", ",", "err", "\n", "}", "\n", "b", ":=", "readBuf", "(", "buf", ")", "\n", "if", "sig", ":=", "b", ".", "uint32", "(", ")", ";", "sig", "!=", "directory64LocSignature", "{", "return", "-", "1", ",", "nil", "\n", "}", "\n", "b", "=", "b", "[", "4", ":", "]", "// skip number of the disk with the start of the zip64 end of central directory", "\n", "p", ":=", "b", ".", "uint64", "(", ")", "// relative offset of the zip64 end of central directory record", "\n", "return", "int64", "(", "p", ")", ",", "nil", "\n", "}" ]
// findDirectory64End tries to read the zip64 locator just before the // directory end and returns the offset of the zip64 directory end if // found.
[ "findDirectory64End", "tries", "to", "read", "the", "zip64", "locator", "just", "before", "the", "directory", "end", "and", "returns", "the", "offset", "of", "the", "zip64", "directory", "end", "if", "found", "." ]
4affb64b04d017a32f9443975e26e841da367e0f
https://github.com/alexmullins/zip/blob/4affb64b04d017a32f9443975e26e841da367e0f/reader.go#L422-L438
2,322
layeh/gopher-luar
metatable.go
MT
func MT(L *lua.LState, value interface{}) *Metatable { if value == nil { return nil } switch typ := reflect.TypeOf(value); typ.Kind() { case reflect.Array, reflect.Chan, reflect.Map, reflect.Ptr, reflect.Slice, reflect.Struct: return &Metatable{ LTable: getMetatable(L, typ), } } return nil }
go
func MT(L *lua.LState, value interface{}) *Metatable { if value == nil { return nil } switch typ := reflect.TypeOf(value); typ.Kind() { case reflect.Array, reflect.Chan, reflect.Map, reflect.Ptr, reflect.Slice, reflect.Struct: return &Metatable{ LTable: getMetatable(L, typ), } } return nil }
[ "func", "MT", "(", "L", "*", "lua", ".", "LState", ",", "value", "interface", "{", "}", ")", "*", "Metatable", "{", "if", "value", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "switch", "typ", ":=", "reflect", ".", "TypeOf", "(", "value", ")", ";", "typ", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Array", ",", "reflect", ".", "Chan", ",", "reflect", ".", "Map", ",", "reflect", ".", "Ptr", ",", "reflect", ".", "Slice", ",", "reflect", ".", "Struct", ":", "return", "&", "Metatable", "{", "LTable", ":", "getMetatable", "(", "L", ",", "typ", ")", ",", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// MT returns the metatable for value's type. nil is returned if value's type // does not use a custom metatable.
[ "MT", "returns", "the", "metatable", "for", "value", "s", "type", ".", "nil", "is", "returned", "if", "value", "s", "type", "does", "not", "use", "a", "custom", "metatable", "." ]
bb67d5653b402f2d2b49134e21e09bd11a706308
https://github.com/layeh/gopher-luar/blob/bb67d5653b402f2d2b49134e21e09bd11a706308/metatable.go#L16-L28
2,323
mikkeloscar/sshconfig
parser.go
MustParseSSHConfig
func MustParseSSHConfig(path string) []*SSHHost { config, err := ParseSSHConfig(path) if err != nil { panic(err) } return config }
go
func MustParseSSHConfig(path string) []*SSHHost { config, err := ParseSSHConfig(path) if err != nil { panic(err) } return config }
[ "func", "MustParseSSHConfig", "(", "path", "string", ")", "[", "]", "*", "SSHHost", "{", "config", ",", "err", ":=", "ParseSSHConfig", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "config", "\n", "}" ]
// MustParseSSHConfig must parse the SSH config given by path or it will panic
[ "MustParseSSHConfig", "must", "parse", "the", "SSH", "config", "given", "by", "path", "or", "it", "will", "panic" ]
ec0822bcc4f4baae05da47b53dbea6cfd599150c
https://github.com/mikkeloscar/sshconfig/blob/ec0822bcc4f4baae05da47b53dbea6cfd599150c/parser.go#L22-L28
2,324
mikkeloscar/sshconfig
parser.go
ParseSSHConfig
func ParseSSHConfig(path string) ([]*SSHHost, error) { // read config file content, err := ioutil.ReadFile(path) if err != nil { return nil, err } return parse(string(content)) }
go
func ParseSSHConfig(path string) ([]*SSHHost, error) { // read config file content, err := ioutil.ReadFile(path) if err != nil { return nil, err } return parse(string(content)) }
[ "func", "ParseSSHConfig", "(", "path", "string", ")", "(", "[", "]", "*", "SSHHost", ",", "error", ")", "{", "// read config file", "content", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "parse", "(", "string", "(", "content", ")", ")", "\n", "}" ]
// ParseSSHConfig parses a SSH config given by path.
[ "ParseSSHConfig", "parses", "a", "SSH", "config", "given", "by", "path", "." ]
ec0822bcc4f4baae05da47b53dbea6cfd599150c
https://github.com/mikkeloscar/sshconfig/blob/ec0822bcc4f4baae05da47b53dbea6cfd599150c/parser.go#L31-L39
2,325
mikkeloscar/sshconfig
parser.go
parse
func parse(input string) ([]*SSHHost, error) { sshConfigs := []*SSHHost{} var next item var sshHost *SSHHost lexer := lex(input) Loop: for { token := lexer.nextItem() if sshHost == nil && token.typ != itemHost { return nil, fmt.Errorf("config variable before Host variable") } switch token.typ { case itemHost: if sshHost != nil { sshConfigs = append(sshConfigs, sshHost) } sshHost = &SSHHost{Host: []string{}, Port: 22} case itemHostValue: sshHost.Host = strings.Split(token.val, " ") case itemHostName: next = lexer.nextItem() if next.typ != itemValue { return nil, fmt.Errorf(next.val) } sshHost.HostName = next.val case itemUser: next = lexer.nextItem() if next.typ != itemValue { return nil, fmt.Errorf(next.val) } sshHost.User = next.val case itemPort: next = lexer.nextItem() if next.typ != itemValue { return nil, fmt.Errorf(next.val) } port, err := strconv.Atoi(next.val) if err != nil { return nil, err } sshHost.Port = port case itemProxyCommand: next = lexer.nextItem() if next.typ != itemValue { return nil, fmt.Errorf(next.val) } sshHost.ProxyCommand = next.val case itemHostKeyAlgorithms: next = lexer.nextItem() if next.typ != itemValue { return nil, fmt.Errorf(next.val) } sshHost.HostKeyAlgorithms = next.val case itemIdentityFile: next = lexer.nextItem() if next.typ != itemValue { return nil, fmt.Errorf(next.val) } sshHost.IdentityFile = next.val case itemError: return nil, fmt.Errorf("%s at pos %d", token.val, token.pos) case itemEOF: if sshHost != nil { sshConfigs = append(sshConfigs, sshHost) } break Loop default: // continue onwards } } return sshConfigs, nil }
go
func parse(input string) ([]*SSHHost, error) { sshConfigs := []*SSHHost{} var next item var sshHost *SSHHost lexer := lex(input) Loop: for { token := lexer.nextItem() if sshHost == nil && token.typ != itemHost { return nil, fmt.Errorf("config variable before Host variable") } switch token.typ { case itemHost: if sshHost != nil { sshConfigs = append(sshConfigs, sshHost) } sshHost = &SSHHost{Host: []string{}, Port: 22} case itemHostValue: sshHost.Host = strings.Split(token.val, " ") case itemHostName: next = lexer.nextItem() if next.typ != itemValue { return nil, fmt.Errorf(next.val) } sshHost.HostName = next.val case itemUser: next = lexer.nextItem() if next.typ != itemValue { return nil, fmt.Errorf(next.val) } sshHost.User = next.val case itemPort: next = lexer.nextItem() if next.typ != itemValue { return nil, fmt.Errorf(next.val) } port, err := strconv.Atoi(next.val) if err != nil { return nil, err } sshHost.Port = port case itemProxyCommand: next = lexer.nextItem() if next.typ != itemValue { return nil, fmt.Errorf(next.val) } sshHost.ProxyCommand = next.val case itemHostKeyAlgorithms: next = lexer.nextItem() if next.typ != itemValue { return nil, fmt.Errorf(next.val) } sshHost.HostKeyAlgorithms = next.val case itemIdentityFile: next = lexer.nextItem() if next.typ != itemValue { return nil, fmt.Errorf(next.val) } sshHost.IdentityFile = next.val case itemError: return nil, fmt.Errorf("%s at pos %d", token.val, token.pos) case itemEOF: if sshHost != nil { sshConfigs = append(sshConfigs, sshHost) } break Loop default: // continue onwards } } return sshConfigs, nil }
[ "func", "parse", "(", "input", "string", ")", "(", "[", "]", "*", "SSHHost", ",", "error", ")", "{", "sshConfigs", ":=", "[", "]", "*", "SSHHost", "{", "}", "\n", "var", "next", "item", "\n", "var", "sshHost", "*", "SSHHost", "\n\n", "lexer", ":=", "lex", "(", "input", ")", "\n", "Loop", ":", "for", "{", "token", ":=", "lexer", ".", "nextItem", "(", ")", "\n\n", "if", "sshHost", "==", "nil", "&&", "token", ".", "typ", "!=", "itemHost", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "switch", "token", ".", "typ", "{", "case", "itemHost", ":", "if", "sshHost", "!=", "nil", "{", "sshConfigs", "=", "append", "(", "sshConfigs", ",", "sshHost", ")", "\n", "}", "\n\n", "sshHost", "=", "&", "SSHHost", "{", "Host", ":", "[", "]", "string", "{", "}", ",", "Port", ":", "22", "}", "\n", "case", "itemHostValue", ":", "sshHost", ".", "Host", "=", "strings", ".", "Split", "(", "token", ".", "val", ",", "\"", "\"", ")", "\n", "case", "itemHostName", ":", "next", "=", "lexer", ".", "nextItem", "(", ")", "\n", "if", "next", ".", "typ", "!=", "itemValue", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "next", ".", "val", ")", "\n", "}", "\n", "sshHost", ".", "HostName", "=", "next", ".", "val", "\n", "case", "itemUser", ":", "next", "=", "lexer", ".", "nextItem", "(", ")", "\n", "if", "next", ".", "typ", "!=", "itemValue", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "next", ".", "val", ")", "\n", "}", "\n", "sshHost", ".", "User", "=", "next", ".", "val", "\n", "case", "itemPort", ":", "next", "=", "lexer", ".", "nextItem", "(", ")", "\n", "if", "next", ".", "typ", "!=", "itemValue", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "next", ".", "val", ")", "\n", "}", "\n", "port", ",", "err", ":=", "strconv", ".", "Atoi", "(", "next", ".", "val", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "sshHost", ".", "Port", "=", "port", "\n", "case", "itemProxyCommand", ":", "next", "=", "lexer", ".", "nextItem", "(", ")", "\n", "if", "next", ".", "typ", "!=", "itemValue", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "next", ".", "val", ")", "\n", "}", "\n", "sshHost", ".", "ProxyCommand", "=", "next", ".", "val", "\n", "case", "itemHostKeyAlgorithms", ":", "next", "=", "lexer", ".", "nextItem", "(", ")", "\n", "if", "next", ".", "typ", "!=", "itemValue", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "next", ".", "val", ")", "\n", "}", "\n", "sshHost", ".", "HostKeyAlgorithms", "=", "next", ".", "val", "\n", "case", "itemIdentityFile", ":", "next", "=", "lexer", ".", "nextItem", "(", ")", "\n", "if", "next", ".", "typ", "!=", "itemValue", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "next", ".", "val", ")", "\n", "}", "\n", "sshHost", ".", "IdentityFile", "=", "next", ".", "val", "\n", "case", "itemError", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "token", ".", "val", ",", "token", ".", "pos", ")", "\n", "case", "itemEOF", ":", "if", "sshHost", "!=", "nil", "{", "sshConfigs", "=", "append", "(", "sshConfigs", ",", "sshHost", ")", "\n", "}", "\n", "break", "Loop", "\n", "default", ":", "// continue onwards", "}", "\n", "}", "\n", "return", "sshConfigs", ",", "nil", "\n", "}" ]
// parses an openssh config file
[ "parses", "an", "openssh", "config", "file" ]
ec0822bcc4f4baae05da47b53dbea6cfd599150c
https://github.com/mikkeloscar/sshconfig/blob/ec0822bcc4f4baae05da47b53dbea6cfd599150c/parser.go#L42-L117
2,326
michaelsauter/crane
crane/config.go
readFile
func readFile(filename string) *config { verboseMsg("Reading configuration " + filename) data, err := ioutil.ReadFile(filename) if err != nil { panic(StatusError{err, 74}) } ext := filepath.Ext(filename) return unmarshal(data, ext) }
go
func readFile(filename string) *config { verboseMsg("Reading configuration " + filename) data, err := ioutil.ReadFile(filename) if err != nil { panic(StatusError{err, 74}) } ext := filepath.Ext(filename) return unmarshal(data, ext) }
[ "func", "readFile", "(", "filename", "string", ")", "*", "config", "{", "verboseMsg", "(", "\"", "\"", "+", "filename", ")", "\n", "data", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "StatusError", "{", "err", ",", "74", "}", ")", "\n", "}", "\n\n", "ext", ":=", "filepath", ".", "Ext", "(", "filename", ")", "\n", "return", "unmarshal", "(", "data", ",", "ext", ")", "\n", "}" ]
// readFile will read the config file // and return the created config.
[ "readFile", "will", "read", "the", "config", "file", "and", "return", "the", "created", "config", "." ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/config.go#L74-L83
2,327
michaelsauter/crane
crane/config.go
unmarshal
func unmarshal(data []byte, ext string) *config { var config *config var err error if ext == ".json" { err = json.Unmarshal(data, &config) } else if ext == ".yml" || ext == ".yaml" { err = yaml.Unmarshal(data, &config) } else { panic(StatusError{errors.New("Unrecognized file extension"), 65}) } if err != nil { err = displaySyntaxError(data, err) panic(StatusError{err, 65}) } return config }
go
func unmarshal(data []byte, ext string) *config { var config *config var err error if ext == ".json" { err = json.Unmarshal(data, &config) } else if ext == ".yml" || ext == ".yaml" { err = yaml.Unmarshal(data, &config) } else { panic(StatusError{errors.New("Unrecognized file extension"), 65}) } if err != nil { err = displaySyntaxError(data, err) panic(StatusError{err, 65}) } return config }
[ "func", "unmarshal", "(", "data", "[", "]", "byte", ",", "ext", "string", ")", "*", "config", "{", "var", "config", "*", "config", "\n", "var", "err", "error", "\n", "if", "ext", "==", "\"", "\"", "{", "err", "=", "json", ".", "Unmarshal", "(", "data", ",", "&", "config", ")", "\n", "}", "else", "if", "ext", "==", "\"", "\"", "||", "ext", "==", "\"", "\"", "{", "err", "=", "yaml", ".", "Unmarshal", "(", "data", ",", "&", "config", ")", "\n", "}", "else", "{", "panic", "(", "StatusError", "{", "errors", ".", "New", "(", "\"", "\"", ")", ",", "65", "}", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "err", "=", "displaySyntaxError", "(", "data", ",", "err", ")", "\n", "panic", "(", "StatusError", "{", "err", ",", "65", "}", ")", "\n", "}", "\n", "return", "config", "\n", "}" ]
// unmarshal converts either JSON // or YAML into a config object.
[ "unmarshal", "converts", "either", "JSON", "or", "YAML", "into", "a", "config", "object", "." ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/config.go#L111-L126
2,328
michaelsauter/crane
crane/config.go
NewConfig
func NewConfig(files []string, prefix string, tag string) Config { var config *config // Files can be given colon-separated expandedFiles := []string{} for _, f := range files { expandedFiles = append(expandedFiles, strings.Split(f, ":")...) } configPath := findConfigPath(expandedFiles) config = readConfig(configPath, expandedFiles) config.path = configPath config.initialize(prefix) config.validate() config.tag = tag milliseconds := time.Now().UnixNano() / 1000000 config.uniqueID = strconv.FormatInt(milliseconds, 10) return config }
go
func NewConfig(files []string, prefix string, tag string) Config { var config *config // Files can be given colon-separated expandedFiles := []string{} for _, f := range files { expandedFiles = append(expandedFiles, strings.Split(f, ":")...) } configPath := findConfigPath(expandedFiles) config = readConfig(configPath, expandedFiles) config.path = configPath config.initialize(prefix) config.validate() config.tag = tag milliseconds := time.Now().UnixNano() / 1000000 config.uniqueID = strconv.FormatInt(milliseconds, 10) return config }
[ "func", "NewConfig", "(", "files", "[", "]", "string", ",", "prefix", "string", ",", "tag", "string", ")", "Config", "{", "var", "config", "*", "config", "\n", "// Files can be given colon-separated", "expandedFiles", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "f", ":=", "range", "files", "{", "expandedFiles", "=", "append", "(", "expandedFiles", ",", "strings", ".", "Split", "(", "f", ",", "\"", "\"", ")", "...", ")", "\n", "}", "\n", "configPath", ":=", "findConfigPath", "(", "expandedFiles", ")", "\n", "config", "=", "readConfig", "(", "configPath", ",", "expandedFiles", ")", "\n", "config", ".", "path", "=", "configPath", "\n", "config", ".", "initialize", "(", "prefix", ")", "\n", "config", ".", "validate", "(", ")", "\n", "config", ".", "tag", "=", "tag", "\n", "milliseconds", ":=", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", "/", "1000000", "\n", "config", ".", "uniqueID", "=", "strconv", ".", "FormatInt", "(", "milliseconds", ",", "10", ")", "\n", "return", "config", "\n", "}" ]
// NewConfig retus a new config based on given // location. // Containers will be ordered so that they can be // brought up and down with Docker.
[ "NewConfig", "retus", "a", "new", "config", "based", "on", "given", "location", ".", "Containers", "will", "be", "ordered", "so", "that", "they", "can", "be", "brought", "up", "and", "down", "with", "Docker", "." ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/config.go#L132-L148
2,329
michaelsauter/crane
crane/config.go
initialize
func (c *config) initialize(prefixFlag string) { // Local container map to query by expanded name containerMap := make(map[string]*container) for rawName, container := range c.RawContainers { container.RawName = rawName containerMap[container.Name()] = container } // Local hooks map to query by expanded name hooksMap := make(map[string]hooks) for hooksRawName, hooks := range c.RawHooks { hooksMap[expandEnv(hooksRawName)] = hooks } // Groups c.groups = make(map[string][]string) for groupRawName, rawNames := range c.RawGroups { groupName := expandEnv(groupRawName) for _, rawName := range rawNames { c.groups[groupName] = append(c.groups[groupName], expandEnv(rawName)) } if hooks, ok := hooksMap[groupName]; ok { // attach group-defined hooks to the group containers for _, name := range c.groups[groupName] { if overriden := containerMap[name].hooks.CopyFrom(hooks); overriden { panic(StatusError{fmt.Errorf("Multiple conflicting hooks inherited from groups for container `%s`", name), 64}) } } } } // Cmds c.cmds = make(map[string][]string) for cmdRawName, rawCmd := range c.RawCmds { cmdName := expandEnv(cmdRawName) c.cmds[cmdName] = stringSlice(rawCmd) } // Container map c.containerMap = make(map[string]Container) for name, container := range containerMap { if hooks, ok := hooksMap[name]; ok { // attach container-defined hooks, overriding potential group-inherited hooks container.hooks.CopyFrom(hooks) } c.containerMap[name] = container } c.determinePrefix(prefixFlag) c.setNetworkMap() c.setVolumeMap() c.setAcceleratedMountMap() }
go
func (c *config) initialize(prefixFlag string) { // Local container map to query by expanded name containerMap := make(map[string]*container) for rawName, container := range c.RawContainers { container.RawName = rawName containerMap[container.Name()] = container } // Local hooks map to query by expanded name hooksMap := make(map[string]hooks) for hooksRawName, hooks := range c.RawHooks { hooksMap[expandEnv(hooksRawName)] = hooks } // Groups c.groups = make(map[string][]string) for groupRawName, rawNames := range c.RawGroups { groupName := expandEnv(groupRawName) for _, rawName := range rawNames { c.groups[groupName] = append(c.groups[groupName], expandEnv(rawName)) } if hooks, ok := hooksMap[groupName]; ok { // attach group-defined hooks to the group containers for _, name := range c.groups[groupName] { if overriden := containerMap[name].hooks.CopyFrom(hooks); overriden { panic(StatusError{fmt.Errorf("Multiple conflicting hooks inherited from groups for container `%s`", name), 64}) } } } } // Cmds c.cmds = make(map[string][]string) for cmdRawName, rawCmd := range c.RawCmds { cmdName := expandEnv(cmdRawName) c.cmds[cmdName] = stringSlice(rawCmd) } // Container map c.containerMap = make(map[string]Container) for name, container := range containerMap { if hooks, ok := hooksMap[name]; ok { // attach container-defined hooks, overriding potential group-inherited hooks container.hooks.CopyFrom(hooks) } c.containerMap[name] = container } c.determinePrefix(prefixFlag) c.setNetworkMap() c.setVolumeMap() c.setAcceleratedMountMap() }
[ "func", "(", "c", "*", "config", ")", "initialize", "(", "prefixFlag", "string", ")", "{", "// Local container map to query by expanded name", "containerMap", ":=", "make", "(", "map", "[", "string", "]", "*", "container", ")", "\n", "for", "rawName", ",", "container", ":=", "range", "c", ".", "RawContainers", "{", "container", ".", "RawName", "=", "rawName", "\n", "containerMap", "[", "container", ".", "Name", "(", ")", "]", "=", "container", "\n", "}", "\n", "// Local hooks map to query by expanded name", "hooksMap", ":=", "make", "(", "map", "[", "string", "]", "hooks", ")", "\n", "for", "hooksRawName", ",", "hooks", ":=", "range", "c", ".", "RawHooks", "{", "hooksMap", "[", "expandEnv", "(", "hooksRawName", ")", "]", "=", "hooks", "\n", "}", "\n", "// Groups", "c", ".", "groups", "=", "make", "(", "map", "[", "string", "]", "[", "]", "string", ")", "\n", "for", "groupRawName", ",", "rawNames", ":=", "range", "c", ".", "RawGroups", "{", "groupName", ":=", "expandEnv", "(", "groupRawName", ")", "\n", "for", "_", ",", "rawName", ":=", "range", "rawNames", "{", "c", ".", "groups", "[", "groupName", "]", "=", "append", "(", "c", ".", "groups", "[", "groupName", "]", ",", "expandEnv", "(", "rawName", ")", ")", "\n", "}", "\n", "if", "hooks", ",", "ok", ":=", "hooksMap", "[", "groupName", "]", ";", "ok", "{", "// attach group-defined hooks to the group containers", "for", "_", ",", "name", ":=", "range", "c", ".", "groups", "[", "groupName", "]", "{", "if", "overriden", ":=", "containerMap", "[", "name", "]", ".", "hooks", ".", "CopyFrom", "(", "hooks", ")", ";", "overriden", "{", "panic", "(", "StatusError", "{", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", ",", "64", "}", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "// Cmds", "c", ".", "cmds", "=", "make", "(", "map", "[", "string", "]", "[", "]", "string", ")", "\n", "for", "cmdRawName", ",", "rawCmd", ":=", "range", "c", ".", "RawCmds", "{", "cmdName", ":=", "expandEnv", "(", "cmdRawName", ")", "\n", "c", ".", "cmds", "[", "cmdName", "]", "=", "stringSlice", "(", "rawCmd", ")", "\n", "}", "\n", "// Container map", "c", ".", "containerMap", "=", "make", "(", "map", "[", "string", "]", "Container", ")", "\n", "for", "name", ",", "container", ":=", "range", "containerMap", "{", "if", "hooks", ",", "ok", ":=", "hooksMap", "[", "name", "]", ";", "ok", "{", "// attach container-defined hooks, overriding potential group-inherited hooks", "container", ".", "hooks", ".", "CopyFrom", "(", "hooks", ")", "\n", "}", "\n", "c", ".", "containerMap", "[", "name", "]", "=", "container", "\n", "}", "\n\n", "c", ".", "determinePrefix", "(", "prefixFlag", ")", "\n", "c", ".", "setNetworkMap", "(", ")", "\n", "c", ".", "setVolumeMap", "(", ")", "\n", "c", ".", "setAcceleratedMountMap", "(", ")", "\n", "}" ]
// Load configuration into the internal structs from the raw, parsed ones
[ "Load", "configuration", "into", "the", "internal", "structs", "from", "the", "raw", "parsed", "ones" ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/config.go#L277-L325
2,330
michaelsauter/crane
crane/config.go
determinePrefix
func (c *config) determinePrefix(prefixFlag string) { // CLI takes precedence over config if len(prefixFlag) > 0 { c.prefix = prefixFlag return } // If prefix is not configured, it is equal to prefix: true if c.RawPrefix == nil { c.RawPrefix = true } // Use configured prefix: // true -> folder name // false -> no prefix // string -> use as-is switch concretePrefix := c.RawPrefix.(type) { case bool: if concretePrefix { c.prefix = filepath.Base(c.path) + "_" } else { c.prefix = "" } case string: c.prefix = expandEnv(concretePrefix) default: panic(StatusError{fmt.Errorf("prefix must be either string or boolean, got %s", c.RawPrefix), 65}) } }
go
func (c *config) determinePrefix(prefixFlag string) { // CLI takes precedence over config if len(prefixFlag) > 0 { c.prefix = prefixFlag return } // If prefix is not configured, it is equal to prefix: true if c.RawPrefix == nil { c.RawPrefix = true } // Use configured prefix: // true -> folder name // false -> no prefix // string -> use as-is switch concretePrefix := c.RawPrefix.(type) { case bool: if concretePrefix { c.prefix = filepath.Base(c.path) + "_" } else { c.prefix = "" } case string: c.prefix = expandEnv(concretePrefix) default: panic(StatusError{fmt.Errorf("prefix must be either string or boolean, got %s", c.RawPrefix), 65}) } }
[ "func", "(", "c", "*", "config", ")", "determinePrefix", "(", "prefixFlag", "string", ")", "{", "// CLI takes precedence over config", "if", "len", "(", "prefixFlag", ")", ">", "0", "{", "c", ".", "prefix", "=", "prefixFlag", "\n", "return", "\n", "}", "\n", "// If prefix is not configured, it is equal to prefix: true", "if", "c", ".", "RawPrefix", "==", "nil", "{", "c", ".", "RawPrefix", "=", "true", "\n", "}", "\n", "// Use configured prefix:", "// true -> folder name", "// false -> no prefix", "// string -> use as-is", "switch", "concretePrefix", ":=", "c", ".", "RawPrefix", ".", "(", "type", ")", "{", "case", "bool", ":", "if", "concretePrefix", "{", "c", ".", "prefix", "=", "filepath", ".", "Base", "(", "c", ".", "path", ")", "+", "\"", "\"", "\n", "}", "else", "{", "c", ".", "prefix", "=", "\"", "\"", "\n", "}", "\n", "case", "string", ":", "c", ".", "prefix", "=", "expandEnv", "(", "concretePrefix", ")", "\n", "default", ":", "panic", "(", "StatusError", "{", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "c", ".", "RawPrefix", ")", ",", "65", "}", ")", "\n", "}", "\n", "}" ]
// CLI > Config > Default
[ "CLI", ">", "Config", ">", "Default" ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/config.go#L398-L424
2,331
michaelsauter/crane
crane/config.go
DependencyMap
func (c *config) DependencyMap() map[string]*Dependencies { dependencyMap := make(map[string]*Dependencies) for _, container := range c.containerMap { if includes(allowed, container.Name()) { dependencyMap[container.Name()] = container.Dependencies() } } return dependencyMap }
go
func (c *config) DependencyMap() map[string]*Dependencies { dependencyMap := make(map[string]*Dependencies) for _, container := range c.containerMap { if includes(allowed, container.Name()) { dependencyMap[container.Name()] = container.Dependencies() } } return dependencyMap }
[ "func", "(", "c", "*", "config", ")", "DependencyMap", "(", ")", "map", "[", "string", "]", "*", "Dependencies", "{", "dependencyMap", ":=", "make", "(", "map", "[", "string", "]", "*", "Dependencies", ")", "\n", "for", "_", ",", "container", ":=", "range", "c", ".", "containerMap", "{", "if", "includes", "(", "allowed", ",", "container", ".", "Name", "(", ")", ")", "{", "dependencyMap", "[", "container", ".", "Name", "(", ")", "]", "=", "container", ".", "Dependencies", "(", ")", "\n", "}", "\n", "}", "\n", "return", "dependencyMap", "\n", "}" ]
// DependencyMap returns a map of containers to their dependencies.
[ "DependencyMap", "returns", "a", "map", "of", "containers", "to", "their", "dependencies", "." ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/config.go#L435-L443
2,332
michaelsauter/crane
crane/config.go
ContainersForReference
func (c *config) ContainersForReference(reference string) (result []string) { containers := []string{} if len(reference) == 0 { // reference not given var defaultGroup []string for group, containers := range c.groups { if group == "default" { defaultGroup = containers break } } if defaultGroup != nil { // If default group exists, return its containers containers = defaultGroup } else { // Otherwise, return all containers for name := range c.containerMap { containers = append(containers, name) } } } else { // reference given reference = expandEnv(reference) // Select reference from listed groups for group, groupContainers := range c.groups { if group == reference { containers = append(containers, groupContainers...) break } } if len(containers) == 0 { // The reference might just be one container for name := range c.containerMap { if name == reference { containers = append(containers, reference) break } } } if len(containers) == 0 { // reference was not found anywhere panic(StatusError{fmt.Errorf("No group or container matching `%s`", reference), 64}) } } // ensure all container references exist for _, container := range containers { containerDeclared := false for name := range c.containerMap { if container == name { containerDeclared = true break } } if !containerDeclared { panic(StatusError{fmt.Errorf("Invalid container reference `%s`", container), 64}) } if !includes(result, container) { result = append(result, container) } } return }
go
func (c *config) ContainersForReference(reference string) (result []string) { containers := []string{} if len(reference) == 0 { // reference not given var defaultGroup []string for group, containers := range c.groups { if group == "default" { defaultGroup = containers break } } if defaultGroup != nil { // If default group exists, return its containers containers = defaultGroup } else { // Otherwise, return all containers for name := range c.containerMap { containers = append(containers, name) } } } else { // reference given reference = expandEnv(reference) // Select reference from listed groups for group, groupContainers := range c.groups { if group == reference { containers = append(containers, groupContainers...) break } } if len(containers) == 0 { // The reference might just be one container for name := range c.containerMap { if name == reference { containers = append(containers, reference) break } } } if len(containers) == 0 { // reference was not found anywhere panic(StatusError{fmt.Errorf("No group or container matching `%s`", reference), 64}) } } // ensure all container references exist for _, container := range containers { containerDeclared := false for name := range c.containerMap { if container == name { containerDeclared = true break } } if !containerDeclared { panic(StatusError{fmt.Errorf("Invalid container reference `%s`", container), 64}) } if !includes(result, container) { result = append(result, container) } } return }
[ "func", "(", "c", "*", "config", ")", "ContainersForReference", "(", "reference", "string", ")", "(", "result", "[", "]", "string", ")", "{", "containers", ":=", "[", "]", "string", "{", "}", "\n", "if", "len", "(", "reference", ")", "==", "0", "{", "// reference not given", "var", "defaultGroup", "[", "]", "string", "\n", "for", "group", ",", "containers", ":=", "range", "c", ".", "groups", "{", "if", "group", "==", "\"", "\"", "{", "defaultGroup", "=", "containers", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "defaultGroup", "!=", "nil", "{", "// If default group exists, return its containers", "containers", "=", "defaultGroup", "\n", "}", "else", "{", "// Otherwise, return all containers", "for", "name", ":=", "range", "c", ".", "containerMap", "{", "containers", "=", "append", "(", "containers", ",", "name", ")", "\n", "}", "\n", "}", "\n", "}", "else", "{", "// reference given", "reference", "=", "expandEnv", "(", "reference", ")", "\n", "// Select reference from listed groups", "for", "group", ",", "groupContainers", ":=", "range", "c", ".", "groups", "{", "if", "group", "==", "reference", "{", "containers", "=", "append", "(", "containers", ",", "groupContainers", "...", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "len", "(", "containers", ")", "==", "0", "{", "// The reference might just be one container", "for", "name", ":=", "range", "c", ".", "containerMap", "{", "if", "name", "==", "reference", "{", "containers", "=", "append", "(", "containers", ",", "reference", ")", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "len", "(", "containers", ")", "==", "0", "{", "// reference was not found anywhere", "panic", "(", "StatusError", "{", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "reference", ")", ",", "64", "}", ")", "\n", "}", "\n", "}", "\n", "// ensure all container references exist", "for", "_", ",", "container", ":=", "range", "containers", "{", "containerDeclared", ":=", "false", "\n", "for", "name", ":=", "range", "c", ".", "containerMap", "{", "if", "container", "==", "name", "{", "containerDeclared", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "!", "containerDeclared", "{", "panic", "(", "StatusError", "{", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "container", ")", ",", "64", "}", ")", "\n", "}", "\n", "if", "!", "includes", "(", "result", ",", "container", ")", "{", "result", "=", "append", "(", "result", ",", "container", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// ContainersForReference receives a reference and determines which // containers of the map that resolves to.
[ "ContainersForReference", "receives", "a", "reference", "and", "determines", "which", "containers", "of", "the", "map", "that", "resolves", "to", "." ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/config.go#L447-L508
2,333
michaelsauter/crane
crane/crane.go
checkDockerClient
func checkDockerClient() { output, err := commandOutput("docker", []string{"--version"}) if err != nil { panic(StatusError{errors.New("Error when probing Docker's client version. Is docker installed and within the $PATH?"), 69}) } re := regexp.MustCompile("([0-9]+)\\.([0-9]+)\\.?([0-9]+)?") rawVersions := re.FindStringSubmatch(output) var versions []int for _, rawVersion := range rawVersions[1:] { version, err := strconv.Atoi(rawVersion) if err != nil { printErrorf("Error when parsing Docker's version %v: %v", rawVersion, err) break } versions = append(versions, version) } for i, expectedVersion := range requiredDockerVersion { if versions[i] > expectedVersion { break } if versions[i] < expectedVersion { printErrorf("Unsupported client version! Please upgrade to Docker %v or later.\n", intJoin(requiredDockerVersion, ".")) } } }
go
func checkDockerClient() { output, err := commandOutput("docker", []string{"--version"}) if err != nil { panic(StatusError{errors.New("Error when probing Docker's client version. Is docker installed and within the $PATH?"), 69}) } re := regexp.MustCompile("([0-9]+)\\.([0-9]+)\\.?([0-9]+)?") rawVersions := re.FindStringSubmatch(output) var versions []int for _, rawVersion := range rawVersions[1:] { version, err := strconv.Atoi(rawVersion) if err != nil { printErrorf("Error when parsing Docker's version %v: %v", rawVersion, err) break } versions = append(versions, version) } for i, expectedVersion := range requiredDockerVersion { if versions[i] > expectedVersion { break } if versions[i] < expectedVersion { printErrorf("Unsupported client version! Please upgrade to Docker %v or later.\n", intJoin(requiredDockerVersion, ".")) } } }
[ "func", "checkDockerClient", "(", ")", "{", "output", ",", "err", ":=", "commandOutput", "(", "\"", "\"", ",", "[", "]", "string", "{", "\"", "\"", "}", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "StatusError", "{", "errors", ".", "New", "(", "\"", "\"", ")", ",", "69", "}", ")", "\n", "}", "\n", "re", ":=", "regexp", ".", "MustCompile", "(", "\"", "\\\\", "\\\\", "\"", ")", "\n", "rawVersions", ":=", "re", ".", "FindStringSubmatch", "(", "output", ")", "\n", "var", "versions", "[", "]", "int", "\n", "for", "_", ",", "rawVersion", ":=", "range", "rawVersions", "[", "1", ":", "]", "{", "version", ",", "err", ":=", "strconv", ".", "Atoi", "(", "rawVersion", ")", "\n", "if", "err", "!=", "nil", "{", "printErrorf", "(", "\"", "\"", ",", "rawVersion", ",", "err", ")", "\n", "break", "\n", "}", "\n", "versions", "=", "append", "(", "versions", ",", "version", ")", "\n", "}", "\n\n", "for", "i", ",", "expectedVersion", ":=", "range", "requiredDockerVersion", "{", "if", "versions", "[", "i", "]", ">", "expectedVersion", "{", "break", "\n", "}", "\n", "if", "versions", "[", "i", "]", "<", "expectedVersion", "{", "printErrorf", "(", "\"", "\\n", "\"", ",", "intJoin", "(", "requiredDockerVersion", ",", "\"", "\"", ")", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Ensure there is a docker binary in the path, // and printing an error if its version is below the minimal requirement.
[ "Ensure", "there", "is", "a", "docker", "binary", "in", "the", "path", "and", "printing", "an", "error", "if", "its", "version", "is", "below", "the", "minimal", "requirement", "." ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/crane.go#L73-L98
2,334
michaelsauter/crane
crane/crane.go
stringSlice
func stringSlice(sliceLike interface{}) []string { var strSlice []string switch sl := sliceLike.(type) { case string: if len(sl) > 0 { parts, err := shlex.Split(expandEnv(sl)) if err != nil { printErrorf("Error when parsing cmd `%v`: %v. Proceeding with %q.", sl, err, parts) } strSlice = append(strSlice, parts...) } case []interface{}: parts := make([]string, len(sl)) for i, v := range sl { parts[i] = expandEnv(fmt.Sprintf("%v", v)) } strSlice = append(strSlice, parts...) default: panic(StatusError{fmt.Errorf("unknown type: %v", sl), 65}) } return strSlice }
go
func stringSlice(sliceLike interface{}) []string { var strSlice []string switch sl := sliceLike.(type) { case string: if len(sl) > 0 { parts, err := shlex.Split(expandEnv(sl)) if err != nil { printErrorf("Error when parsing cmd `%v`: %v. Proceeding with %q.", sl, err, parts) } strSlice = append(strSlice, parts...) } case []interface{}: parts := make([]string, len(sl)) for i, v := range sl { parts[i] = expandEnv(fmt.Sprintf("%v", v)) } strSlice = append(strSlice, parts...) default: panic(StatusError{fmt.Errorf("unknown type: %v", sl), 65}) } return strSlice }
[ "func", "stringSlice", "(", "sliceLike", "interface", "{", "}", ")", "[", "]", "string", "{", "var", "strSlice", "[", "]", "string", "\n", "switch", "sl", ":=", "sliceLike", ".", "(", "type", ")", "{", "case", "string", ":", "if", "len", "(", "sl", ")", ">", "0", "{", "parts", ",", "err", ":=", "shlex", ".", "Split", "(", "expandEnv", "(", "sl", ")", ")", "\n", "if", "err", "!=", "nil", "{", "printErrorf", "(", "\"", "\"", ",", "sl", ",", "err", ",", "parts", ")", "\n", "}", "\n", "strSlice", "=", "append", "(", "strSlice", ",", "parts", "...", ")", "\n", "}", "\n", "case", "[", "]", "interface", "{", "}", ":", "parts", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "sl", ")", ")", "\n", "for", "i", ",", "v", ":=", "range", "sl", "{", "parts", "[", "i", "]", "=", "expandEnv", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "v", ")", ")", "\n", "}", "\n", "strSlice", "=", "append", "(", "strSlice", ",", "parts", "...", ")", "\n", "default", ":", "panic", "(", "StatusError", "{", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "sl", ")", ",", "65", "}", ")", "\n", "}", "\n", "return", "strSlice", "\n", "}" ]
// Assemble slice of strings from slice or string with spaces
[ "Assemble", "slice", "of", "strings", "from", "slice", "or", "string", "with", "spaces" ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/crane.go#L101-L122
2,335
michaelsauter/crane
crane/settings.go
CorrectVersion
func (s *Settings) CorrectVersion() error { if Version != s.Version { s.Version = Version return s.Update(Version) } return nil }
go
func (s *Settings) CorrectVersion() error { if Version != s.Version { s.Version = Version return s.Update(Version) } return nil }
[ "func", "(", "s", "*", "Settings", ")", "CorrectVersion", "(", ")", "error", "{", "if", "Version", "!=", "s", ".", "Version", "{", "s", ".", "Version", "=", "Version", "\n", "return", "s", ".", "Update", "(", "Version", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// If version in settings does not match version of binary, // we assume that the binary was updated and update the // settings file with the new information.
[ "If", "version", "in", "settings", "does", "not", "match", "version", "of", "binary", "we", "assume", "that", "the", "binary", "was", "updated", "and", "update", "the", "settings", "file", "with", "the", "new", "information", "." ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/settings.go#L111-L117
2,336
michaelsauter/crane
crane/containers.go
Logs
func (containers Containers) Logs(follow bool, timestamps bool, tail string, colorize bool, since string) { var ( sources = make([]multiplexio.Source, 0, 2*len(containers)) maxPrefixLength = strconv.Itoa(containers.maxNameLength()) ) appendSources := func(reader io.Reader, color *ansi.Color, name string, separator string) { if reader != nil { prefix := fmt.Sprintf("%"+maxPrefixLength+"s "+separator+" ", name) sources = append(sources, multiplexio.Source{ Reader: reader, Write: write(prefix, color, timestamps), }) } } counter := 0 for _, container := range containers { var ( logs = container.Logs(follow, since, tail) stdoutColor *ansi.Color stderrColor *ansi.Color ) for _, log := range logs { if colorize { // red has a negative/error connotation, so skip it ansiAttribute := ansi.Attribute(int(ansi.FgGreen) + counter%int(ansi.FgWhite-ansi.FgGreen)) stdoutColor = ansi.New(ansiAttribute) // To synchronize their output, we need to multiplex stdout & stderr // onto the same stream. Unfortunately, that means that the user won't // be able to pipe them separately, so we use bold as a distinguishing // characteristic. stderrColor = ansi.New(ansiAttribute).Add(ansi.Bold) } appendSources(log.Stdout, stdoutColor, log.Name, "|") appendSources(log.Stderr, stderrColor, log.Name, "*") counter += 1 } } if len(sources) > 0 { aggregatedReader := multiplexio.NewReader(multiplexio.Options{}, sources...) io.Copy(os.Stdout, aggregatedReader) } }
go
func (containers Containers) Logs(follow bool, timestamps bool, tail string, colorize bool, since string) { var ( sources = make([]multiplexio.Source, 0, 2*len(containers)) maxPrefixLength = strconv.Itoa(containers.maxNameLength()) ) appendSources := func(reader io.Reader, color *ansi.Color, name string, separator string) { if reader != nil { prefix := fmt.Sprintf("%"+maxPrefixLength+"s "+separator+" ", name) sources = append(sources, multiplexio.Source{ Reader: reader, Write: write(prefix, color, timestamps), }) } } counter := 0 for _, container := range containers { var ( logs = container.Logs(follow, since, tail) stdoutColor *ansi.Color stderrColor *ansi.Color ) for _, log := range logs { if colorize { // red has a negative/error connotation, so skip it ansiAttribute := ansi.Attribute(int(ansi.FgGreen) + counter%int(ansi.FgWhite-ansi.FgGreen)) stdoutColor = ansi.New(ansiAttribute) // To synchronize their output, we need to multiplex stdout & stderr // onto the same stream. Unfortunately, that means that the user won't // be able to pipe them separately, so we use bold as a distinguishing // characteristic. stderrColor = ansi.New(ansiAttribute).Add(ansi.Bold) } appendSources(log.Stdout, stdoutColor, log.Name, "|") appendSources(log.Stderr, stderrColor, log.Name, "*") counter += 1 } } if len(sources) > 0 { aggregatedReader := multiplexio.NewReader(multiplexio.Options{}, sources...) io.Copy(os.Stdout, aggregatedReader) } }
[ "func", "(", "containers", "Containers", ")", "Logs", "(", "follow", "bool", ",", "timestamps", "bool", ",", "tail", "string", ",", "colorize", "bool", ",", "since", "string", ")", "{", "var", "(", "sources", "=", "make", "(", "[", "]", "multiplexio", ".", "Source", ",", "0", ",", "2", "*", "len", "(", "containers", ")", ")", "\n", "maxPrefixLength", "=", "strconv", ".", "Itoa", "(", "containers", ".", "maxNameLength", "(", ")", ")", "\n", ")", "\n", "appendSources", ":=", "func", "(", "reader", "io", ".", "Reader", ",", "color", "*", "ansi", ".", "Color", ",", "name", "string", ",", "separator", "string", ")", "{", "if", "reader", "!=", "nil", "{", "prefix", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", "+", "maxPrefixLength", "+", "\"", "\"", "+", "separator", "+", "\"", "\"", ",", "name", ")", "\n", "sources", "=", "append", "(", "sources", ",", "multiplexio", ".", "Source", "{", "Reader", ":", "reader", ",", "Write", ":", "write", "(", "prefix", ",", "color", ",", "timestamps", ")", ",", "}", ")", "\n", "}", "\n", "}", "\n", "counter", ":=", "0", "\n", "for", "_", ",", "container", ":=", "range", "containers", "{", "var", "(", "logs", "=", "container", ".", "Logs", "(", "follow", ",", "since", ",", "tail", ")", "\n", "stdoutColor", "*", "ansi", ".", "Color", "\n", "stderrColor", "*", "ansi", ".", "Color", "\n", ")", "\n", "for", "_", ",", "log", ":=", "range", "logs", "{", "if", "colorize", "{", "// red has a negative/error connotation, so skip it", "ansiAttribute", ":=", "ansi", ".", "Attribute", "(", "int", "(", "ansi", ".", "FgGreen", ")", "+", "counter", "%", "int", "(", "ansi", ".", "FgWhite", "-", "ansi", ".", "FgGreen", ")", ")", "\n", "stdoutColor", "=", "ansi", ".", "New", "(", "ansiAttribute", ")", "\n", "// To synchronize their output, we need to multiplex stdout & stderr", "// onto the same stream. Unfortunately, that means that the user won't", "// be able to pipe them separately, so we use bold as a distinguishing", "// characteristic.", "stderrColor", "=", "ansi", ".", "New", "(", "ansiAttribute", ")", ".", "Add", "(", "ansi", ".", "Bold", ")", "\n", "}", "\n", "appendSources", "(", "log", ".", "Stdout", ",", "stdoutColor", ",", "log", ".", "Name", ",", "\"", "\"", ")", "\n", "appendSources", "(", "log", ".", "Stderr", ",", "stderrColor", ",", "log", ".", "Name", ",", "\"", "\"", ")", "\n", "counter", "+=", "1", "\n", "}", "\n", "}", "\n", "if", "len", "(", "sources", ")", ">", "0", "{", "aggregatedReader", ":=", "multiplexio", ".", "NewReader", "(", "multiplexio", ".", "Options", "{", "}", ",", "sources", "...", ")", "\n", "io", ".", "Copy", "(", "os", ".", "Stdout", ",", "aggregatedReader", ")", "\n", "}", "\n", "}" ]
// Dump container logs.
[ "Dump", "container", "logs", "." ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/containers.go#L68-L109
2,337
michaelsauter/crane
crane/containers.go
Status
func (containers Containers) Status(notrunc bool) { w := new(tabwriter.Writer) w.Init(os.Stdout, 0, 8, 1, '\t', 0) fmt.Fprintln(w, "NAME\tIMAGE\tID\tUP TO DATE\tIP\tPORTS\tRUNNING") for _, container := range containers { rows := container.Status() for _, fields := range rows { if !notrunc { fields[2] = truncateID(fields[2]) } fmt.Fprintf(w, "%s\n", strings.Join(fields, "\t")) } } w.Flush() }
go
func (containers Containers) Status(notrunc bool) { w := new(tabwriter.Writer) w.Init(os.Stdout, 0, 8, 1, '\t', 0) fmt.Fprintln(w, "NAME\tIMAGE\tID\tUP TO DATE\tIP\tPORTS\tRUNNING") for _, container := range containers { rows := container.Status() for _, fields := range rows { if !notrunc { fields[2] = truncateID(fields[2]) } fmt.Fprintf(w, "%s\n", strings.Join(fields, "\t")) } } w.Flush() }
[ "func", "(", "containers", "Containers", ")", "Status", "(", "notrunc", "bool", ")", "{", "w", ":=", "new", "(", "tabwriter", ".", "Writer", ")", "\n", "w", ".", "Init", "(", "os", ".", "Stdout", ",", "0", ",", "8", ",", "1", ",", "'\\t'", ",", "0", ")", "\n", "fmt", ".", "Fprintln", "(", "w", ",", "\"", "\\t", "\\t", "\\t", "\\t", "\\t", "\\t", "\"", ")", "\n", "for", "_", ",", "container", ":=", "range", "containers", "{", "rows", ":=", "container", ".", "Status", "(", ")", "\n", "for", "_", ",", "fields", ":=", "range", "rows", "{", "if", "!", "notrunc", "{", "fields", "[", "2", "]", "=", "truncateID", "(", "fields", "[", "2", "]", ")", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "strings", ".", "Join", "(", "fields", ",", "\"", "\\t", "\"", ")", ")", "\n", "}", "\n", "}", "\n", "w", ".", "Flush", "(", ")", "\n", "}" ]
// Status of containers.
[ "Status", "of", "containers", "." ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/containers.go#L112-L126
2,338
michaelsauter/crane
crane/containers.go
maxNameLength
func (containers Containers) maxNameLength() (maxPrefixLength int) { for _, container := range containers { prefixLength := len(container.ActualName(false)) if prefixLength > maxPrefixLength { maxPrefixLength = prefixLength } } return }
go
func (containers Containers) maxNameLength() (maxPrefixLength int) { for _, container := range containers { prefixLength := len(container.ActualName(false)) if prefixLength > maxPrefixLength { maxPrefixLength = prefixLength } } return }
[ "func", "(", "containers", "Containers", ")", "maxNameLength", "(", ")", "(", "maxPrefixLength", "int", ")", "{", "for", "_", ",", "container", ":=", "range", "containers", "{", "prefixLength", ":=", "len", "(", "container", ".", "ActualName", "(", "false", ")", ")", "\n", "if", "prefixLength", ">", "maxPrefixLength", "{", "maxPrefixLength", "=", "prefixLength", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// Return the length of the longest container name.
[ "Return", "the", "length", "of", "the", "longest", "container", "name", "." ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/containers.go#L129-L137
2,339
michaelsauter/crane
crane/containers.go
stripProvisioningDuplicates
func (containers Containers) stripProvisioningDuplicates() (deduplicated Containers) { seenProvisioningKeys := make(map[string]bool) for _, container := range containers { // for 2 containers that would the same provisioning // commands, the key should be equal key := container.BuildParams().Context() + "#" + container.Image() if _, ok := seenProvisioningKeys[key]; !ok { deduplicated = append(deduplicated, container) seenProvisioningKeys[key] = true } } return }
go
func (containers Containers) stripProvisioningDuplicates() (deduplicated Containers) { seenProvisioningKeys := make(map[string]bool) for _, container := range containers { // for 2 containers that would the same provisioning // commands, the key should be equal key := container.BuildParams().Context() + "#" + container.Image() if _, ok := seenProvisioningKeys[key]; !ok { deduplicated = append(deduplicated, container) seenProvisioningKeys[key] = true } } return }
[ "func", "(", "containers", "Containers", ")", "stripProvisioningDuplicates", "(", ")", "(", "deduplicated", "Containers", ")", "{", "seenProvisioningKeys", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "for", "_", ",", "container", ":=", "range", "containers", "{", "// for 2 containers that would the same provisioning", "// commands, the key should be equal", "key", ":=", "container", ".", "BuildParams", "(", ")", ".", "Context", "(", ")", "+", "\"", "\"", "+", "container", ".", "Image", "(", ")", "\n", "if", "_", ",", "ok", ":=", "seenProvisioningKeys", "[", "key", "]", ";", "!", "ok", "{", "deduplicated", "=", "append", "(", "deduplicated", ",", "container", ")", "\n", "seenProvisioningKeys", "[", "key", "]", "=", "true", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// returns another list of containers, stripping out containers which // would trigger some commands more than once for provisioning.
[ "returns", "another", "list", "of", "containers", "stripping", "out", "containers", "which", "would", "trigger", "some", "commands", "more", "than", "once", "for", "provisioning", "." ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/containers.go#L141-L153
2,340
michaelsauter/crane
crane/containers.go
write
func write(prefix string, color *ansi.Color, timestamps bool) func(dest io.Writer, token []byte) (n int, err error) { return func(dest io.Writer, token []byte) (n int, err error) { countingWriter := countingWriter{Writer: dest} if color != nil { ansi.Output = &countingWriter color.Set() } _, err = countingWriter.Write([]byte(prefix)) if err == nil { if !timestamps { // timestamps are always present in the incoming stream for // sorting purposes, so we strip them if the user didn't ask // for them const timestampPrefixLength = 31 strip := timestampPrefixLength if string(token[0]) == "[" { // it seems that timestamps are wrapped in [] for events // streamed in real time during a `docker logs -f` strip += 2 } token = token[strip:] } _, err = countingWriter.Write(token) } if err == nil { if color != nil { ansi.Unset() } _, err = dest.Write([]byte("\n")) } return countingWriter.written, err } }
go
func write(prefix string, color *ansi.Color, timestamps bool) func(dest io.Writer, token []byte) (n int, err error) { return func(dest io.Writer, token []byte) (n int, err error) { countingWriter := countingWriter{Writer: dest} if color != nil { ansi.Output = &countingWriter color.Set() } _, err = countingWriter.Write([]byte(prefix)) if err == nil { if !timestamps { // timestamps are always present in the incoming stream for // sorting purposes, so we strip them if the user didn't ask // for them const timestampPrefixLength = 31 strip := timestampPrefixLength if string(token[0]) == "[" { // it seems that timestamps are wrapped in [] for events // streamed in real time during a `docker logs -f` strip += 2 } token = token[strip:] } _, err = countingWriter.Write(token) } if err == nil { if color != nil { ansi.Unset() } _, err = dest.Write([]byte("\n")) } return countingWriter.written, err } }
[ "func", "write", "(", "prefix", "string", ",", "color", "*", "ansi", ".", "Color", ",", "timestamps", "bool", ")", "func", "(", "dest", "io", ".", "Writer", ",", "token", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "return", "func", "(", "dest", "io", ".", "Writer", ",", "token", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "countingWriter", ":=", "countingWriter", "{", "Writer", ":", "dest", "}", "\n", "if", "color", "!=", "nil", "{", "ansi", ".", "Output", "=", "&", "countingWriter", "\n", "color", ".", "Set", "(", ")", "\n", "}", "\n", "_", ",", "err", "=", "countingWriter", ".", "Write", "(", "[", "]", "byte", "(", "prefix", ")", ")", "\n", "if", "err", "==", "nil", "{", "if", "!", "timestamps", "{", "// timestamps are always present in the incoming stream for", "// sorting purposes, so we strip them if the user didn't ask", "// for them", "const", "timestampPrefixLength", "=", "31", "\n", "strip", ":=", "timestampPrefixLength", "\n", "if", "string", "(", "token", "[", "0", "]", ")", "==", "\"", "\"", "{", "// it seems that timestamps are wrapped in [] for events", "// streamed in real time during a `docker logs -f`", "strip", "+=", "2", "\n", "}", "\n", "token", "=", "token", "[", "strip", ":", "]", "\n", "}", "\n", "_", ",", "err", "=", "countingWriter", ".", "Write", "(", "token", ")", "\n", "}", "\n", "if", "err", "==", "nil", "{", "if", "color", "!=", "nil", "{", "ansi", ".", "Unset", "(", ")", "\n", "}", "\n", "_", ",", "err", "=", "dest", ".", "Write", "(", "[", "]", "byte", "(", "\"", "\\n", "\"", ")", ")", "\n", "}", "\n", "return", "countingWriter", ".", "written", ",", "err", "\n\n", "}", "\n", "}" ]
// returns a function that will format and writes the line extracted from the logs of a given container
[ "returns", "a", "function", "that", "will", "format", "and", "writes", "the", "line", "extracted", "from", "the", "logs", "of", "a", "given", "container" ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/containers.go#L176-L209
2,341
michaelsauter/crane
crane/target.go
all
func (t Target) all() []string { all := t.initial for _, name := range t.dependencies { all = append(all, name) } sort.Strings(all) return all }
go
func (t Target) all() []string { all := t.initial for _, name := range t.dependencies { all = append(all, name) } sort.Strings(all) return all }
[ "func", "(", "t", "Target", ")", "all", "(", ")", "[", "]", "string", "{", "all", ":=", "t", ".", "initial", "\n", "for", "_", ",", "name", ":=", "range", "t", ".", "dependencies", "{", "all", "=", "append", "(", "all", ",", "name", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "all", ")", "\n", "return", "all", "\n", "}" ]
// Return all targeted containers, sorted alphabetically
[ "Return", "all", "targeted", "containers", "sorted", "alphabetically" ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/target.go#L72-L79
2,342
michaelsauter/crane
crane/hooks.go
CopyFrom
func (h *hooks) CopyFrom(source hooks) (overridden bool) { overrideIfFromNotEmpty := func(from string, to *string) { if from != "" { overridden = overridden || *to != "" *to = from } } overrideIfFromNotEmpty(source.RawPreBuild, &h.RawPreBuild) overrideIfFromNotEmpty(source.RawPostBuild, &h.RawPostBuild) overrideIfFromNotEmpty(source.RawPreStart, &h.RawPreStart) overrideIfFromNotEmpty(source.RawPostStart, &h.RawPostStart) overrideIfFromNotEmpty(source.RawPreStop, &h.RawPreStop) overrideIfFromNotEmpty(source.RawPostStop, &h.RawPostStop) return }
go
func (h *hooks) CopyFrom(source hooks) (overridden bool) { overrideIfFromNotEmpty := func(from string, to *string) { if from != "" { overridden = overridden || *to != "" *to = from } } overrideIfFromNotEmpty(source.RawPreBuild, &h.RawPreBuild) overrideIfFromNotEmpty(source.RawPostBuild, &h.RawPostBuild) overrideIfFromNotEmpty(source.RawPreStart, &h.RawPreStart) overrideIfFromNotEmpty(source.RawPostStart, &h.RawPostStart) overrideIfFromNotEmpty(source.RawPreStop, &h.RawPreStop) overrideIfFromNotEmpty(source.RawPostStop, &h.RawPostStop) return }
[ "func", "(", "h", "*", "hooks", ")", "CopyFrom", "(", "source", "hooks", ")", "(", "overridden", "bool", ")", "{", "overrideIfFromNotEmpty", ":=", "func", "(", "from", "string", ",", "to", "*", "string", ")", "{", "if", "from", "!=", "\"", "\"", "{", "overridden", "=", "overridden", "||", "*", "to", "!=", "\"", "\"", "\n", "*", "to", "=", "from", "\n", "}", "\n", "}", "\n", "overrideIfFromNotEmpty", "(", "source", ".", "RawPreBuild", ",", "&", "h", ".", "RawPreBuild", ")", "\n", "overrideIfFromNotEmpty", "(", "source", ".", "RawPostBuild", ",", "&", "h", ".", "RawPostBuild", ")", "\n", "overrideIfFromNotEmpty", "(", "source", ".", "RawPreStart", ",", "&", "h", ".", "RawPreStart", ")", "\n", "overrideIfFromNotEmpty", "(", "source", ".", "RawPostStart", ",", "&", "h", ".", "RawPostStart", ")", "\n", "overrideIfFromNotEmpty", "(", "source", ".", "RawPreStop", ",", "&", "h", ".", "RawPreStop", ")", "\n", "overrideIfFromNotEmpty", "(", "source", ".", "RawPostStop", ",", "&", "h", ".", "RawPostStop", ")", "\n", "return", "\n", "}" ]
// Merge another set of hooks into the existing object. Existing // hooks will be overridden if the corresponding hooks from the // source struct are defined. Returns true if some content was // overiden in the process.
[ "Merge", "another", "set", "of", "hooks", "into", "the", "existing", "object", ".", "Existing", "hooks", "will", "be", "overridden", "if", "the", "corresponding", "hooks", "from", "the", "source", "struct", "are", "defined", ".", "Returns", "true", "if", "some", "content", "was", "overiden", "in", "the", "process", "." ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/hooks.go#L52-L66
2,343
michaelsauter/crane
crane/network_parameters.go
Alias
func (n NetworkParameters) Alias(containerName string) []string { var aliases []string rawAliases := n.RawAliases if n.RawAlias != nil { rawAliases = n.RawAlias } if rawAliases == nil { aliases = append(aliases, containerName) } else { switch concreteValue := rawAliases.(type) { case []interface{}: for _, v := range concreteValue { aliases = append(aliases, expandEnv(v.(string))) } } } return aliases }
go
func (n NetworkParameters) Alias(containerName string) []string { var aliases []string rawAliases := n.RawAliases if n.RawAlias != nil { rawAliases = n.RawAlias } if rawAliases == nil { aliases = append(aliases, containerName) } else { switch concreteValue := rawAliases.(type) { case []interface{}: for _, v := range concreteValue { aliases = append(aliases, expandEnv(v.(string))) } } } return aliases }
[ "func", "(", "n", "NetworkParameters", ")", "Alias", "(", "containerName", "string", ")", "[", "]", "string", "{", "var", "aliases", "[", "]", "string", "\n\n", "rawAliases", ":=", "n", ".", "RawAliases", "\n", "if", "n", ".", "RawAlias", "!=", "nil", "{", "rawAliases", "=", "n", ".", "RawAlias", "\n", "}", "\n\n", "if", "rawAliases", "==", "nil", "{", "aliases", "=", "append", "(", "aliases", ",", "containerName", ")", "\n", "}", "else", "{", "switch", "concreteValue", ":=", "rawAliases", ".", "(", "type", ")", "{", "case", "[", "]", "interface", "{", "}", ":", "for", "_", ",", "v", ":=", "range", "concreteValue", "{", "aliases", "=", "append", "(", "aliases", ",", "expandEnv", "(", "v", ".", "(", "string", ")", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "aliases", "\n", "}" ]
// If aliases are not defined in the config, // the container name is added as a default alias. // When an empty array is configured, no default alias is used.
[ "If", "aliases", "are", "not", "defined", "in", "the", "config", "the", "container", "name", "is", "added", "as", "a", "default", "alias", ".", "When", "an", "empty", "array", "is", "configured", "no", "default", "alias", "is", "used", "." ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/network_parameters.go#L17-L36
2,344
michaelsauter/crane
crane/unit_of_work.go
Pause
func (uow *UnitOfWork) Pause() { for _, container := range uow.Targeted().Reversed() { container.Pause() } }
go
func (uow *UnitOfWork) Pause() { for _, container := range uow.Targeted().Reversed() { container.Pause() } }
[ "func", "(", "uow", "*", "UnitOfWork", ")", "Pause", "(", ")", "{", "for", "_", ",", "container", ":=", "range", "uow", ".", "Targeted", "(", ")", ".", "Reversed", "(", ")", "{", "container", ".", "Pause", "(", ")", "\n", "}", "\n", "}" ]
// Pause containers.
[ "Pause", "containers", "." ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/unit_of_work.go#L137-L141
2,345
michaelsauter/crane
crane/unit_of_work.go
Start
func (uow *UnitOfWork) Start() { uow.prepareRequirements() for _, container := range uow.Containers() { if includes(uow.targeted, container.Name()) { container.Start(true) } else if includes(uow.requireStarted, container.Name()) || !container.Exists() { container.Start(false) } } }
go
func (uow *UnitOfWork) Start() { uow.prepareRequirements() for _, container := range uow.Containers() { if includes(uow.targeted, container.Name()) { container.Start(true) } else if includes(uow.requireStarted, container.Name()) || !container.Exists() { container.Start(false) } } }
[ "func", "(", "uow", "*", "UnitOfWork", ")", "Start", "(", ")", "{", "uow", ".", "prepareRequirements", "(", ")", "\n", "for", "_", ",", "container", ":=", "range", "uow", ".", "Containers", "(", ")", "{", "if", "includes", "(", "uow", ".", "targeted", ",", "container", ".", "Name", "(", ")", ")", "{", "container", ".", "Start", "(", "true", ")", "\n", "}", "else", "if", "includes", "(", "uow", ".", "requireStarted", ",", "container", ".", "Name", "(", ")", ")", "||", "!", "container", ".", "Exists", "(", ")", "{", "container", ".", "Start", "(", "false", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Start containers.
[ "Start", "containers", "." ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/unit_of_work.go#L144-L153
2,346
michaelsauter/crane
crane/unit_of_work.go
Stop
func (uow *UnitOfWork) Stop() { for _, container := range uow.Targeted().Reversed() { container.Stop() } }
go
func (uow *UnitOfWork) Stop() { for _, container := range uow.Targeted().Reversed() { container.Stop() } }
[ "func", "(", "uow", "*", "UnitOfWork", ")", "Stop", "(", ")", "{", "for", "_", ",", "container", ":=", "range", "uow", ".", "Targeted", "(", ")", ".", "Reversed", "(", ")", "{", "container", ".", "Stop", "(", ")", "\n", "}", "\n", "}" ]
// Stop containers.
[ "Stop", "containers", "." ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/unit_of_work.go#L156-L160
2,347
michaelsauter/crane
crane/unit_of_work.go
Kill
func (uow *UnitOfWork) Kill() { for _, container := range uow.Targeted().Reversed() { container.Kill() } }
go
func (uow *UnitOfWork) Kill() { for _, container := range uow.Targeted().Reversed() { container.Kill() } }
[ "func", "(", "uow", "*", "UnitOfWork", ")", "Kill", "(", ")", "{", "for", "_", ",", "container", ":=", "range", "uow", ".", "Targeted", "(", ")", ".", "Reversed", "(", ")", "{", "container", ".", "Kill", "(", ")", "\n", "}", "\n", "}" ]
// Kill containers.
[ "Kill", "containers", "." ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/unit_of_work.go#L163-L167
2,348
michaelsauter/crane
crane/unit_of_work.go
Rm
func (uow *UnitOfWork) Rm(force bool, volumes bool) { for _, container := range uow.Targeted().Reversed() { container.Rm(force, volumes) } }
go
func (uow *UnitOfWork) Rm(force bool, volumes bool) { for _, container := range uow.Targeted().Reversed() { container.Rm(force, volumes) } }
[ "func", "(", "uow", "*", "UnitOfWork", ")", "Rm", "(", "force", "bool", ",", "volumes", "bool", ")", "{", "for", "_", ",", "container", ":=", "range", "uow", ".", "Targeted", "(", ")", ".", "Reversed", "(", ")", "{", "container", ".", "Rm", "(", "force", ",", "volumes", ")", "\n", "}", "\n", "}" ]
// Rm containers.
[ "Rm", "containers", "." ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/unit_of_work.go#L180-L184
2,349
michaelsauter/crane
crane/unit_of_work.go
Create
func (uow *UnitOfWork) Create(cmds []string) { uow.prepareRequirements() for _, container := range uow.Containers() { if includes(uow.targeted, container.Name()) { container.Create(cmds) } else if includes(uow.requireStarted, container.Name()) || !container.Exists() { container.Start(false) } } }
go
func (uow *UnitOfWork) Create(cmds []string) { uow.prepareRequirements() for _, container := range uow.Containers() { if includes(uow.targeted, container.Name()) { container.Create(cmds) } else if includes(uow.requireStarted, container.Name()) || !container.Exists() { container.Start(false) } } }
[ "func", "(", "uow", "*", "UnitOfWork", ")", "Create", "(", "cmds", "[", "]", "string", ")", "{", "uow", ".", "prepareRequirements", "(", ")", "\n", "for", "_", ",", "container", ":=", "range", "uow", ".", "Containers", "(", ")", "{", "if", "includes", "(", "uow", ".", "targeted", ",", "container", ".", "Name", "(", ")", ")", "{", "container", ".", "Create", "(", "cmds", ")", "\n", "}", "else", "if", "includes", "(", "uow", ".", "requireStarted", ",", "container", ".", "Name", "(", ")", ")", "||", "!", "container", ".", "Exists", "(", ")", "{", "container", ".", "Start", "(", "false", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Create containers.
[ "Create", "containers", "." ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/unit_of_work.go#L187-L196
2,350
michaelsauter/crane
crane/unit_of_work.go
PullImage
func (uow *UnitOfWork) PullImage() { for _, container := range uow.Targeted() { if len(container.BuildParams().Context()) == 0 { container.PullImage() } } }
go
func (uow *UnitOfWork) PullImage() { for _, container := range uow.Targeted() { if len(container.BuildParams().Context()) == 0 { container.PullImage() } } }
[ "func", "(", "uow", "*", "UnitOfWork", ")", "PullImage", "(", ")", "{", "for", "_", ",", "container", ":=", "range", "uow", ".", "Targeted", "(", ")", "{", "if", "len", "(", "container", ".", "BuildParams", "(", ")", ".", "Context", "(", ")", ")", "==", "0", "{", "container", ".", "PullImage", "(", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Pull containers.
[ "Pull", "containers", "." ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/unit_of_work.go#L204-L210
2,351
michaelsauter/crane
crane/unit_of_work.go
Logs
func (uow *UnitOfWork) Logs(follow bool, timestamps bool, tail string, colorize bool, since string) { uow.Targeted().Logs(follow, timestamps, tail, colorize, since) }
go
func (uow *UnitOfWork) Logs(follow bool, timestamps bool, tail string, colorize bool, since string) { uow.Targeted().Logs(follow, timestamps, tail, colorize, since) }
[ "func", "(", "uow", "*", "UnitOfWork", ")", "Logs", "(", "follow", "bool", ",", "timestamps", "bool", ",", "tail", "string", ",", "colorize", "bool", ",", "since", "string", ")", "{", "uow", ".", "Targeted", "(", ")", ".", "Logs", "(", "follow", ",", "timestamps", ",", "tail", ",", "colorize", ",", "since", ")", "\n", "}" ]
// Log containers.
[ "Log", "containers", "." ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/unit_of_work.go#L213-L215
2,352
michaelsauter/crane
crane/unit_of_work.go
Generate
func (uow *UnitOfWork) Generate(templateFile string, output string) { templateFileParts := strings.Split(templateFile, "/") templateName := templateFileParts[len(templateFileParts)-1] tmpl, err := template.New(templateName).ParseFiles(templateFile) if err != nil { printErrorf("ERROR: %s\n", err) return } executeTemplate := func(outputFile string, templateInfo interface{}) { writer := os.Stdout if len(outputFile) > 0 { writer, _ = os.Create(outputFile) } err = tmpl.Execute(writer, templateInfo) if err != nil { printErrorf("ERROR: %s\n", err) } } if strings.Contains(output, "%s") { for _, container := range uow.TargetedInfo() { executeTemplate(fmt.Sprintf(output, container.PrefixedName()), container) } } else { tmplInfo := struct { Containers []ContainerInfo }{ Containers: uow.TargetedInfo(), } executeTemplate(output, tmplInfo) } }
go
func (uow *UnitOfWork) Generate(templateFile string, output string) { templateFileParts := strings.Split(templateFile, "/") templateName := templateFileParts[len(templateFileParts)-1] tmpl, err := template.New(templateName).ParseFiles(templateFile) if err != nil { printErrorf("ERROR: %s\n", err) return } executeTemplate := func(outputFile string, templateInfo interface{}) { writer := os.Stdout if len(outputFile) > 0 { writer, _ = os.Create(outputFile) } err = tmpl.Execute(writer, templateInfo) if err != nil { printErrorf("ERROR: %s\n", err) } } if strings.Contains(output, "%s") { for _, container := range uow.TargetedInfo() { executeTemplate(fmt.Sprintf(output, container.PrefixedName()), container) } } else { tmplInfo := struct { Containers []ContainerInfo }{ Containers: uow.TargetedInfo(), } executeTemplate(output, tmplInfo) } }
[ "func", "(", "uow", "*", "UnitOfWork", ")", "Generate", "(", "templateFile", "string", ",", "output", "string", ")", "{", "templateFileParts", ":=", "strings", ".", "Split", "(", "templateFile", ",", "\"", "\"", ")", "\n", "templateName", ":=", "templateFileParts", "[", "len", "(", "templateFileParts", ")", "-", "1", "]", "\n\n", "tmpl", ",", "err", ":=", "template", ".", "New", "(", "templateName", ")", ".", "ParseFiles", "(", "templateFile", ")", "\n", "if", "err", "!=", "nil", "{", "printErrorf", "(", "\"", "\\n", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "executeTemplate", ":=", "func", "(", "outputFile", "string", ",", "templateInfo", "interface", "{", "}", ")", "{", "writer", ":=", "os", ".", "Stdout", "\n", "if", "len", "(", "outputFile", ")", ">", "0", "{", "writer", ",", "_", "=", "os", ".", "Create", "(", "outputFile", ")", "\n", "}", "\n", "err", "=", "tmpl", ".", "Execute", "(", "writer", ",", "templateInfo", ")", "\n", "if", "err", "!=", "nil", "{", "printErrorf", "(", "\"", "\\n", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "if", "strings", ".", "Contains", "(", "output", ",", "\"", "\"", ")", "{", "for", "_", ",", "container", ":=", "range", "uow", ".", "TargetedInfo", "(", ")", "{", "executeTemplate", "(", "fmt", ".", "Sprintf", "(", "output", ",", "container", ".", "PrefixedName", "(", ")", ")", ",", "container", ")", "\n", "}", "\n", "}", "else", "{", "tmplInfo", ":=", "struct", "{", "Containers", "[", "]", "ContainerInfo", "\n", "}", "{", "Containers", ":", "uow", ".", "TargetedInfo", "(", ")", ",", "}", "\n", "executeTemplate", "(", "output", ",", "tmplInfo", ")", "\n", "}", "\n", "}" ]
// Generate files.
[ "Generate", "files", "." ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/unit_of_work.go#L218-L251
2,353
michaelsauter/crane
crane/container.go
connectWithNetworks
func (c *container) connectWithNetworks(adHoc bool) { containerNetworks := c.Networks() for name, params := range containerNetworks { network := cfg.Network(name) if network == nil { panic(StatusError{fmt.Errorf("Error when parsing network `%v`: container network is not in main networks block.\n", name), 78}) } networkName := network.ActualName() args := []string{"network", "connect"} for _, alias := range params.Alias(c.Name()) { args = append(args, "--alias", alias) } if len(params.Ip()) > 0 { args = append(args, "--ip", params.Ip()) } if len(params.Ip6()) > 0 { args = append(args, "--ip6", params.Ip6()) } args = append(args, networkName, c.ActualName(adHoc)) executeCommand("docker", args, c.CommandsOut(), c.CommandsErr()) } }
go
func (c *container) connectWithNetworks(adHoc bool) { containerNetworks := c.Networks() for name, params := range containerNetworks { network := cfg.Network(name) if network == nil { panic(StatusError{fmt.Errorf("Error when parsing network `%v`: container network is not in main networks block.\n", name), 78}) } networkName := network.ActualName() args := []string{"network", "connect"} for _, alias := range params.Alias(c.Name()) { args = append(args, "--alias", alias) } if len(params.Ip()) > 0 { args = append(args, "--ip", params.Ip()) } if len(params.Ip6()) > 0 { args = append(args, "--ip6", params.Ip6()) } args = append(args, networkName, c.ActualName(adHoc)) executeCommand("docker", args, c.CommandsOut(), c.CommandsErr()) } }
[ "func", "(", "c", "*", "container", ")", "connectWithNetworks", "(", "adHoc", "bool", ")", "{", "containerNetworks", ":=", "c", ".", "Networks", "(", ")", "\n", "for", "name", ",", "params", ":=", "range", "containerNetworks", "{", "network", ":=", "cfg", ".", "Network", "(", "name", ")", "\n", "if", "network", "==", "nil", "{", "panic", "(", "StatusError", "{", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "name", ")", ",", "78", "}", ")", "\n", "}", "\n", "networkName", ":=", "network", ".", "ActualName", "(", ")", "\n", "args", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", "}", "\n", "for", "_", ",", "alias", ":=", "range", "params", ".", "Alias", "(", "c", ".", "Name", "(", ")", ")", "{", "args", "=", "append", "(", "args", ",", "\"", "\"", ",", "alias", ")", "\n", "}", "\n", "if", "len", "(", "params", ".", "Ip", "(", ")", ")", ">", "0", "{", "args", "=", "append", "(", "args", ",", "\"", "\"", ",", "params", ".", "Ip", "(", ")", ")", "\n", "}", "\n", "if", "len", "(", "params", ".", "Ip6", "(", ")", ")", ">", "0", "{", "args", "=", "append", "(", "args", ",", "\"", "\"", ",", "params", ".", "Ip6", "(", ")", ")", "\n", "}", "\n", "args", "=", "append", "(", "args", ",", "networkName", ",", "c", ".", "ActualName", "(", "adHoc", ")", ")", "\n", "executeCommand", "(", "\"", "\"", ",", "args", ",", "c", ".", "CommandsOut", "(", ")", ",", "c", ".", "CommandsErr", "(", ")", ")", "\n", "}", "\n", "}" ]
// Connects container with default network if required, // using the non-prefixed name as an alias
[ "Connects", "container", "with", "default", "network", "if", "required", "using", "the", "non", "-", "prefixed", "name", "as", "an", "alias" ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/container.go#L985-L1006
2,354
michaelsauter/crane
crane/container.go
startAcceleratedMounts
func (c *container) startAcceleratedMounts() { for _, volume := range c.Volume() { am := cfg.AcceleratedMount(volume) if accelerationEnabled() && am != nil { am.Run() } } }
go
func (c *container) startAcceleratedMounts() { for _, volume := range c.Volume() { am := cfg.AcceleratedMount(volume) if accelerationEnabled() && am != nil { am.Run() } } }
[ "func", "(", "c", "*", "container", ")", "startAcceleratedMounts", "(", ")", "{", "for", "_", ",", "volume", ":=", "range", "c", ".", "Volume", "(", ")", "{", "am", ":=", "cfg", ".", "AcceleratedMount", "(", "volume", ")", "\n", "if", "accelerationEnabled", "(", ")", "&&", "am", "!=", "nil", "{", "am", ".", "Run", "(", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Ensure all accelerated mounts used by this container are running.
[ "Ensure", "all", "accelerated", "mounts", "used", "by", "this", "container", "are", "running", "." ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/container.go#L1413-L1420
2,355
michaelsauter/crane
crane/container.go
Exec
func (c *container) Exec(cmds []string, privileged bool, user string) { name := c.ActualName(false) if !c.Running() { c.Start(false) } args := []string{"exec"} if privileged { args = append(args, "--privileged") } args = append(args, "--interactive") args = append(args, "--tty") if len(user) > 0 { args = append(args, "--user", user) } args = append(args, name) args = append(args, cmds...) executeCommand("docker", args, c.CommandsOut(), c.CommandsErr()) }
go
func (c *container) Exec(cmds []string, privileged bool, user string) { name := c.ActualName(false) if !c.Running() { c.Start(false) } args := []string{"exec"} if privileged { args = append(args, "--privileged") } args = append(args, "--interactive") args = append(args, "--tty") if len(user) > 0 { args = append(args, "--user", user) } args = append(args, name) args = append(args, cmds...) executeCommand("docker", args, c.CommandsOut(), c.CommandsErr()) }
[ "func", "(", "c", "*", "container", ")", "Exec", "(", "cmds", "[", "]", "string", ",", "privileged", "bool", ",", "user", "string", ")", "{", "name", ":=", "c", ".", "ActualName", "(", "false", ")", "\n", "if", "!", "c", ".", "Running", "(", ")", "{", "c", ".", "Start", "(", "false", ")", "\n", "}", "\n", "args", ":=", "[", "]", "string", "{", "\"", "\"", "}", "\n", "if", "privileged", "{", "args", "=", "append", "(", "args", ",", "\"", "\"", ")", "\n", "}", "\n", "args", "=", "append", "(", "args", ",", "\"", "\"", ")", "\n", "args", "=", "append", "(", "args", ",", "\"", "\"", ")", "\n", "if", "len", "(", "user", ")", ">", "0", "{", "args", "=", "append", "(", "args", ",", "\"", "\"", ",", "user", ")", "\n", "}", "\n", "args", "=", "append", "(", "args", ",", "name", ")", "\n", "args", "=", "append", "(", "args", ",", "cmds", "...", ")", "\n", "executeCommand", "(", "\"", "\"", ",", "args", ",", "c", ".", "CommandsOut", "(", ")", ",", "c", ".", "CommandsErr", "(", ")", ")", "\n", "}" ]
// Exec command in container
[ "Exec", "command", "in", "container" ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/container.go#L1505-L1522
2,356
michaelsauter/crane
crane/container.go
Logs
func (c *container) Logs(follow bool, since string, tail string) (sources []LogSource) { if c.Exists() { name := c.ActualName(false) args := []string{"logs"} if follow { args = append(args, "-f") } if len(since) > 0 { args = append(args, "--since", since) } if len(tail) > 0 && tail != "all" { args = append(args, "--tail", tail) } // always include timestamps for ordering, we'll just strip // them if the user doesn't want to see them args = append(args, "-t") args = append(args, name) cmd, stdout, stderr := executeCommandBackground("docker", args) if cmd != nil { sources = append(sources, LogSource{ Stdout: stdout, Stderr: stderr, Name: name, }) } } return }
go
func (c *container) Logs(follow bool, since string, tail string) (sources []LogSource) { if c.Exists() { name := c.ActualName(false) args := []string{"logs"} if follow { args = append(args, "-f") } if len(since) > 0 { args = append(args, "--since", since) } if len(tail) > 0 && tail != "all" { args = append(args, "--tail", tail) } // always include timestamps for ordering, we'll just strip // them if the user doesn't want to see them args = append(args, "-t") args = append(args, name) cmd, stdout, stderr := executeCommandBackground("docker", args) if cmd != nil { sources = append(sources, LogSource{ Stdout: stdout, Stderr: stderr, Name: name, }) } } return }
[ "func", "(", "c", "*", "container", ")", "Logs", "(", "follow", "bool", ",", "since", "string", ",", "tail", "string", ")", "(", "sources", "[", "]", "LogSource", ")", "{", "if", "c", ".", "Exists", "(", ")", "{", "name", ":=", "c", ".", "ActualName", "(", "false", ")", "\n", "args", ":=", "[", "]", "string", "{", "\"", "\"", "}", "\n", "if", "follow", "{", "args", "=", "append", "(", "args", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "since", ")", ">", "0", "{", "args", "=", "append", "(", "args", ",", "\"", "\"", ",", "since", ")", "\n", "}", "\n", "if", "len", "(", "tail", ")", ">", "0", "&&", "tail", "!=", "\"", "\"", "{", "args", "=", "append", "(", "args", ",", "\"", "\"", ",", "tail", ")", "\n", "}", "\n", "// always include timestamps for ordering, we'll just strip", "// them if the user doesn't want to see them", "args", "=", "append", "(", "args", ",", "\"", "\"", ")", "\n", "args", "=", "append", "(", "args", ",", "name", ")", "\n", "cmd", ",", "stdout", ",", "stderr", ":=", "executeCommandBackground", "(", "\"", "\"", ",", "args", ")", "\n", "if", "cmd", "!=", "nil", "{", "sources", "=", "append", "(", "sources", ",", "LogSource", "{", "Stdout", ":", "stdout", ",", "Stderr", ":", "stderr", ",", "Name", ":", "name", ",", "}", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// Dump container logs
[ "Dump", "container", "logs" ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/container.go#L1554-L1581
2,357
michaelsauter/crane
crane/container.go
BindMounts
func (c *container) BindMounts(volumeNames []string) []string { bindMounts := []string{} for _, volume := range c.Volume() { parts := strings.Split(volume, ":") if len(parts) > 1 && !includes(volumeNames, parts[0]) { bindMounts = append(bindMounts, volume) } } return bindMounts }
go
func (c *container) BindMounts(volumeNames []string) []string { bindMounts := []string{} for _, volume := range c.Volume() { parts := strings.Split(volume, ":") if len(parts) > 1 && !includes(volumeNames, parts[0]) { bindMounts = append(bindMounts, volume) } } return bindMounts }
[ "func", "(", "c", "*", "container", ")", "BindMounts", "(", "volumeNames", "[", "]", "string", ")", "[", "]", "string", "{", "bindMounts", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "volume", ":=", "range", "c", ".", "Volume", "(", ")", "{", "parts", ":=", "strings", ".", "Split", "(", "volume", ",", "\"", "\"", ")", "\n", "if", "len", "(", "parts", ")", ">", "1", "&&", "!", "includes", "(", "volumeNames", ",", "parts", "[", "0", "]", ")", "{", "bindMounts", "=", "append", "(", "bindMounts", ",", "volume", ")", "\n", "}", "\n", "}", "\n", "return", "bindMounts", "\n", "}" ]
// Volume values are bind-mounts if they contain a colon // and the part before the colon is not a configured volume.
[ "Volume", "values", "are", "bind", "-", "mounts", "if", "they", "contain", "a", "colon", "and", "the", "part", "before", "the", "colon", "is", "not", "a", "configured", "volume", "." ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/container.go#L1640-L1649
2,358
michaelsauter/crane
crane/container.go
buildImage
func (c *container) buildImage(nocache bool) { executeHook(c.Hooks().PreBuild(), c.ActualName(false)) fmt.Fprintf(c.CommandsOut(), "Building image %s ...\n", c.Image()) args := []string{"build"} if nocache { args = append(args, "--no-cache") } args = append(args, "--rm", "--tag="+c.Image()) if len(c.BuildParams().File()) > 0 { args = append(args, "--file="+filepath.FromSlash(c.BuildParams().Context()+"/"+c.BuildParams().File())) } for _, arg := range c.BuildParams().BuildArgs() { args = append(args, "--build-arg", arg) } args = append(args, c.BuildParams().Context()) executeCommand("docker", args, c.CommandsOut(), c.CommandsErr()) executeHook(c.Hooks().PostBuild(), c.ActualName(false)) }
go
func (c *container) buildImage(nocache bool) { executeHook(c.Hooks().PreBuild(), c.ActualName(false)) fmt.Fprintf(c.CommandsOut(), "Building image %s ...\n", c.Image()) args := []string{"build"} if nocache { args = append(args, "--no-cache") } args = append(args, "--rm", "--tag="+c.Image()) if len(c.BuildParams().File()) > 0 { args = append(args, "--file="+filepath.FromSlash(c.BuildParams().Context()+"/"+c.BuildParams().File())) } for _, arg := range c.BuildParams().BuildArgs() { args = append(args, "--build-arg", arg) } args = append(args, c.BuildParams().Context()) executeCommand("docker", args, c.CommandsOut(), c.CommandsErr()) executeHook(c.Hooks().PostBuild(), c.ActualName(false)) }
[ "func", "(", "c", "*", "container", ")", "buildImage", "(", "nocache", "bool", ")", "{", "executeHook", "(", "c", ".", "Hooks", "(", ")", ".", "PreBuild", "(", ")", ",", "c", ".", "ActualName", "(", "false", ")", ")", "\n", "fmt", ".", "Fprintf", "(", "c", ".", "CommandsOut", "(", ")", ",", "\"", "\\n", "\"", ",", "c", ".", "Image", "(", ")", ")", "\n", "args", ":=", "[", "]", "string", "{", "\"", "\"", "}", "\n", "if", "nocache", "{", "args", "=", "append", "(", "args", ",", "\"", "\"", ")", "\n", "}", "\n", "args", "=", "append", "(", "args", ",", "\"", "\"", ",", "\"", "\"", "+", "c", ".", "Image", "(", ")", ")", "\n", "if", "len", "(", "c", ".", "BuildParams", "(", ")", ".", "File", "(", ")", ")", ">", "0", "{", "args", "=", "append", "(", "args", ",", "\"", "\"", "+", "filepath", ".", "FromSlash", "(", "c", ".", "BuildParams", "(", ")", ".", "Context", "(", ")", "+", "\"", "\"", "+", "c", ".", "BuildParams", "(", ")", ".", "File", "(", ")", ")", ")", "\n", "}", "\n", "for", "_", ",", "arg", ":=", "range", "c", ".", "BuildParams", "(", ")", ".", "BuildArgs", "(", ")", "{", "args", "=", "append", "(", "args", ",", "\"", "\"", ",", "arg", ")", "\n", "}", "\n\n", "args", "=", "append", "(", "args", ",", "c", ".", "BuildParams", "(", ")", ".", "Context", "(", ")", ")", "\n", "executeCommand", "(", "\"", "\"", ",", "args", ",", "c", ".", "CommandsOut", "(", ")", ",", "c", ".", "CommandsErr", "(", ")", ")", "\n", "executeHook", "(", "c", ".", "Hooks", "(", ")", ".", "PostBuild", "(", ")", ",", "c", ".", "ActualName", "(", "false", ")", ")", "\n", "}" ]
// Build image for container
[ "Build", "image", "for", "container" ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/container.go#L1652-L1670
2,359
michaelsauter/crane
crane/container.go
imageIDFromTag
func imageIDFromTag(tag string) string { args := []string{"inspect", "--format={{.Id}}", tag} output, err := commandOutput("docker", args) if err != nil { return "" } return output }
go
func imageIDFromTag(tag string) string { args := []string{"inspect", "--format={{.Id}}", tag} output, err := commandOutput("docker", args) if err != nil { return "" } return output }
[ "func", "imageIDFromTag", "(", "tag", "string", ")", "string", "{", "args", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "tag", "}", "\n", "output", ",", "err", ":=", "commandOutput", "(", "\"", "\"", ",", "args", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "output", "\n", "}" ]
// Return the image id of a tag, or an empty string if it doesn't exist
[ "Return", "the", "image", "id", "of", "a", "tag", "or", "an", "empty", "string", "if", "it", "doesn", "t", "exist" ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/container.go#L1683-L1690
2,360
michaelsauter/crane
crane/container.go
inspectBool
func inspectBool(container string, format string) bool { output := inspectString(container, format) flag, _ := strconv.ParseBool(output) return flag }
go
func inspectBool(container string, format string) bool { output := inspectString(container, format) flag, _ := strconv.ParseBool(output) return flag }
[ "func", "inspectBool", "(", "container", "string", ",", "format", "string", ")", "bool", "{", "output", ":=", "inspectString", "(", "container", ",", "format", ")", "\n", "flag", ",", "_", ":=", "strconv", ".", "ParseBool", "(", "output", ")", "\n", "return", "flag", "\n", "}" ]
// Attempt to parse the value referenced by the go template // for the `docker inspect` as a boolean, falling back to // false on error
[ "Attempt", "to", "parse", "the", "value", "referenced", "by", "the", "go", "template", "for", "the", "docker", "inspect", "as", "a", "boolean", "falling", "back", "to", "false", "on", "error" ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/container.go#L1743-L1747
2,361
michaelsauter/crane
crane/container.go
inspectString
func inspectString(container string, format string) string { args := []string{"inspect", "--format=" + format, container} output, err := commandOutput("docker", args) if err != nil { return "" } return output }
go
func inspectString(container string, format string) string { args := []string{"inspect", "--format=" + format, container} output, err := commandOutput("docker", args) if err != nil { return "" } return output }
[ "func", "inspectString", "(", "container", "string", ",", "format", "string", ")", "string", "{", "args", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", "+", "format", ",", "container", "}", "\n", "output", ",", "err", ":=", "commandOutput", "(", "\"", "\"", ",", "args", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "output", "\n", "}" ]
// Returns the value referenced by the go template for // the `docker inspect` as a string, fallbacking to // an empty string on error
[ "Returns", "the", "value", "referenced", "by", "the", "go", "template", "for", "the", "docker", "inspect", "as", "a", "string", "fallbacking", "to", "an", "empty", "string", "on", "error" ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/container.go#L1752-L1759
2,362
michaelsauter/crane
crane/dependencies.go
includes
func (d *Dependencies) includes(needle string) bool { for _, name := range d.All { if name == needle { return true } } return false }
go
func (d *Dependencies) includes(needle string) bool { for _, name := range d.All { if name == needle { return true } } return false }
[ "func", "(", "d", "*", "Dependencies", ")", "includes", "(", "needle", "string", ")", "bool", "{", "for", "_", ",", "name", ":=", "range", "d", ".", "All", "{", "if", "name", "==", "needle", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// includes checks whether the given needle is // included in the dependency list
[ "includes", "checks", "whether", "the", "given", "needle", "is", "included", "in", "the", "dependency", "list" ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/dependencies.go#L20-L27
2,363
michaelsauter/crane
crane/dependencies.go
requireStarted
func (d *Dependencies) requireStarted(needle string) bool { if needle == d.Net || needle == d.IPC { return true } for _, name := range d.Requires { if name == needle { return true } } for _, name := range d.Link { if name == needle { return true } } return false }
go
func (d *Dependencies) requireStarted(needle string) bool { if needle == d.Net || needle == d.IPC { return true } for _, name := range d.Requires { if name == needle { return true } } for _, name := range d.Link { if name == needle { return true } } return false }
[ "func", "(", "d", "*", "Dependencies", ")", "requireStarted", "(", "needle", "string", ")", "bool", "{", "if", "needle", "==", "d", ".", "Net", "||", "needle", "==", "d", ".", "IPC", "{", "return", "true", "\n", "}", "\n", "for", "_", ",", "name", ":=", "range", "d", ".", "Requires", "{", "if", "name", "==", "needle", "{", "return", "true", "\n", "}", "\n", "}", "\n", "for", "_", ",", "name", ":=", "range", "d", ".", "Link", "{", "if", "name", "==", "needle", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// requireStarted checks whether the given needle needs // to be running in order to be satisfied.
[ "requireStarted", "checks", "whether", "the", "given", "needle", "needs", "to", "be", "running", "in", "order", "to", "be", "satisfied", "." ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/dependencies.go#L31-L46
2,364
michaelsauter/crane
crane/dependencies.go
remove
func (d *Dependencies) remove(resolved string) { for i, name := range d.All { if name == resolved { d.All = append(d.All[:i], d.All[i+1:]...) } } }
go
func (d *Dependencies) remove(resolved string) { for i, name := range d.All { if name == resolved { d.All = append(d.All[:i], d.All[i+1:]...) } } }
[ "func", "(", "d", "*", "Dependencies", ")", "remove", "(", "resolved", "string", ")", "{", "for", "i", ",", "name", ":=", "range", "d", ".", "All", "{", "if", "name", "==", "resolved", "{", "d", ".", "All", "=", "append", "(", "d", ".", "All", "[", ":", "i", "]", ",", "d", ".", "All", "[", "i", "+", "1", ":", "]", "...", ")", "\n", "}", "\n", "}", "\n", "}" ]
// remove removes the given name from All
[ "remove", "removes", "the", "given", "name", "from", "All" ]
9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76
https://github.com/michaelsauter/crane/blob/9485768dfd4f6ea5ca2aaf75b6f6947b4adf0a76/crane/dependencies.go#L55-L61
2,365
libp2p/go-libp2p-peer
peer.go
MatchesPrivateKey
func (id ID) MatchesPrivateKey(sk ic.PrivKey) bool { return id.MatchesPublicKey(sk.GetPublic()) }
go
func (id ID) MatchesPrivateKey(sk ic.PrivKey) bool { return id.MatchesPublicKey(sk.GetPublic()) }
[ "func", "(", "id", "ID", ")", "MatchesPrivateKey", "(", "sk", "ic", ".", "PrivKey", ")", "bool", "{", "return", "id", ".", "MatchesPublicKey", "(", "sk", ".", "GetPublic", "(", ")", ")", "\n", "}" ]
// MatchesPrivateKey tests whether this ID was derived from sk
[ "MatchesPrivateKey", "tests", "whether", "this", "ID", "was", "derived", "from", "sk" ]
9ccddf5f5d8318b00658dfbc06a4e32b16bae6a9
https://github.com/libp2p/go-libp2p-peer/blob/9ccddf5f5d8318b00658dfbc06a4e32b16bae6a9/peer.go#L70-L72
2,366
libp2p/go-libp2p-peer
peer.go
MatchesPublicKey
func (id ID) MatchesPublicKey(pk ic.PubKey) bool { oid, err := IDFromPublicKey(pk) if err != nil { return false } return oid == id }
go
func (id ID) MatchesPublicKey(pk ic.PubKey) bool { oid, err := IDFromPublicKey(pk) if err != nil { return false } return oid == id }
[ "func", "(", "id", "ID", ")", "MatchesPublicKey", "(", "pk", "ic", ".", "PubKey", ")", "bool", "{", "oid", ",", "err", ":=", "IDFromPublicKey", "(", "pk", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "return", "oid", "==", "id", "\n", "}" ]
// MatchesPublicKey tests whether this ID was derived from pk
[ "MatchesPublicKey", "tests", "whether", "this", "ID", "was", "derived", "from", "pk" ]
9ccddf5f5d8318b00658dfbc06a4e32b16bae6a9
https://github.com/libp2p/go-libp2p-peer/blob/9ccddf5f5d8318b00658dfbc06a4e32b16bae6a9/peer.go#L75-L81
2,367
libp2p/go-libp2p-peer
peer.go
ExtractPublicKey
func (id ID) ExtractPublicKey() (ic.PubKey, error) { decoded, err := mh.Decode([]byte(id)) if err != nil { return nil, err } if decoded.Code != mh.ID { return nil, ErrNoPublicKey } pk, err := ic.UnmarshalPublicKey(decoded.Digest) if err != nil { return nil, err } return pk, nil }
go
func (id ID) ExtractPublicKey() (ic.PubKey, error) { decoded, err := mh.Decode([]byte(id)) if err != nil { return nil, err } if decoded.Code != mh.ID { return nil, ErrNoPublicKey } pk, err := ic.UnmarshalPublicKey(decoded.Digest) if err != nil { return nil, err } return pk, nil }
[ "func", "(", "id", "ID", ")", "ExtractPublicKey", "(", ")", "(", "ic", ".", "PubKey", ",", "error", ")", "{", "decoded", ",", "err", ":=", "mh", ".", "Decode", "(", "[", "]", "byte", "(", "id", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "decoded", ".", "Code", "!=", "mh", ".", "ID", "{", "return", "nil", ",", "ErrNoPublicKey", "\n", "}", "\n", "pk", ",", "err", ":=", "ic", ".", "UnmarshalPublicKey", "(", "decoded", ".", "Digest", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "pk", ",", "nil", "\n", "}" ]
// ExtractPublicKey attempts to extract the public key from an ID // // This method returns ErrNoPublicKey if the peer ID looks valid but it can't extract // the public key.
[ "ExtractPublicKey", "attempts", "to", "extract", "the", "public", "key", "from", "an", "ID", "This", "method", "returns", "ErrNoPublicKey", "if", "the", "peer", "ID", "looks", "valid", "but", "it", "can", "t", "extract", "the", "public", "key", "." ]
9ccddf5f5d8318b00658dfbc06a4e32b16bae6a9
https://github.com/libp2p/go-libp2p-peer/blob/9ccddf5f5d8318b00658dfbc06a4e32b16bae6a9/peer.go#L87-L100
2,368
libp2p/go-libp2p-peer
peer.go
IDFromString
func IDFromString(s string) (ID, error) { if _, err := mh.Cast([]byte(s)); err != nil { return ID(""), err } return ID(s), nil }
go
func IDFromString(s string) (ID, error) { if _, err := mh.Cast([]byte(s)); err != nil { return ID(""), err } return ID(s), nil }
[ "func", "IDFromString", "(", "s", "string", ")", "(", "ID", ",", "error", ")", "{", "if", "_", ",", "err", ":=", "mh", ".", "Cast", "(", "[", "]", "byte", "(", "s", ")", ")", ";", "err", "!=", "nil", "{", "return", "ID", "(", "\"", "\"", ")", ",", "err", "\n", "}", "\n", "return", "ID", "(", "s", ")", ",", "nil", "\n", "}" ]
// IDFromString cast a string to ID type, and validate // the id to make sure it is a multihash.
[ "IDFromString", "cast", "a", "string", "to", "ID", "type", "and", "validate", "the", "id", "to", "make", "sure", "it", "is", "a", "multihash", "." ]
9ccddf5f5d8318b00658dfbc06a4e32b16bae6a9
https://github.com/libp2p/go-libp2p-peer/blob/9ccddf5f5d8318b00658dfbc06a4e32b16bae6a9/peer.go#L113-L118
2,369
libp2p/go-libp2p-peer
peer.go
IDFromBytes
func IDFromBytes(b []byte) (ID, error) { if _, err := mh.Cast(b); err != nil { return ID(""), err } return ID(b), nil }
go
func IDFromBytes(b []byte) (ID, error) { if _, err := mh.Cast(b); err != nil { return ID(""), err } return ID(b), nil }
[ "func", "IDFromBytes", "(", "b", "[", "]", "byte", ")", "(", "ID", ",", "error", ")", "{", "if", "_", ",", "err", ":=", "mh", ".", "Cast", "(", "b", ")", ";", "err", "!=", "nil", "{", "return", "ID", "(", "\"", "\"", ")", ",", "err", "\n", "}", "\n", "return", "ID", "(", "b", ")", ",", "nil", "\n", "}" ]
// IDFromBytes cast a string to ID type, and validate // the id to make sure it is a multihash.
[ "IDFromBytes", "cast", "a", "string", "to", "ID", "type", "and", "validate", "the", "id", "to", "make", "sure", "it", "is", "a", "multihash", "." ]
9ccddf5f5d8318b00658dfbc06a4e32b16bae6a9
https://github.com/libp2p/go-libp2p-peer/blob/9ccddf5f5d8318b00658dfbc06a4e32b16bae6a9/peer.go#L122-L127
2,370
libp2p/go-libp2p-peer
peer.go
IDB58Decode
func IDB58Decode(s string) (ID, error) { m, err := mh.FromB58String(s) if err != nil { return "", err } return ID(m), err }
go
func IDB58Decode(s string) (ID, error) { m, err := mh.FromB58String(s) if err != nil { return "", err } return ID(m), err }
[ "func", "IDB58Decode", "(", "s", "string", ")", "(", "ID", ",", "error", ")", "{", "m", ",", "err", ":=", "mh", ".", "FromB58String", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "ID", "(", "m", ")", ",", "err", "\n", "}" ]
// IDB58Decode returns a b58-decoded Peer
[ "IDB58Decode", "returns", "a", "b58", "-", "decoded", "Peer" ]
9ccddf5f5d8318b00658dfbc06a4e32b16bae6a9
https://github.com/libp2p/go-libp2p-peer/blob/9ccddf5f5d8318b00658dfbc06a4e32b16bae6a9/peer.go#L130-L136
2,371
libp2p/go-libp2p-peer
peer.go
IDHexDecode
func IDHexDecode(s string) (ID, error) { m, err := mh.FromHexString(s) if err != nil { return "", err } return ID(m), err }
go
func IDHexDecode(s string) (ID, error) { m, err := mh.FromHexString(s) if err != nil { return "", err } return ID(m), err }
[ "func", "IDHexDecode", "(", "s", "string", ")", "(", "ID", ",", "error", ")", "{", "m", ",", "err", ":=", "mh", ".", "FromHexString", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "ID", "(", "m", ")", ",", "err", "\n", "}" ]
// IDHexDecode returns a hex-decoded Peer
[ "IDHexDecode", "returns", "a", "hex", "-", "decoded", "Peer" ]
9ccddf5f5d8318b00658dfbc06a4e32b16bae6a9
https://github.com/libp2p/go-libp2p-peer/blob/9ccddf5f5d8318b00658dfbc06a4e32b16bae6a9/peer.go#L144-L150
2,372
libp2p/go-libp2p-peer
peer.go
IDFromPublicKey
func IDFromPublicKey(pk ic.PubKey) (ID, error) { b, err := pk.Bytes() if err != nil { return "", err } var alg uint64 = mh.SHA2_256 if AdvancedEnableInlining && len(b) <= maxInlineKeyLength { alg = mh.ID } hash, _ := mh.Sum(b, alg, -1) return ID(hash), nil }
go
func IDFromPublicKey(pk ic.PubKey) (ID, error) { b, err := pk.Bytes() if err != nil { return "", err } var alg uint64 = mh.SHA2_256 if AdvancedEnableInlining && len(b) <= maxInlineKeyLength { alg = mh.ID } hash, _ := mh.Sum(b, alg, -1) return ID(hash), nil }
[ "func", "IDFromPublicKey", "(", "pk", "ic", ".", "PubKey", ")", "(", "ID", ",", "error", ")", "{", "b", ",", "err", ":=", "pk", ".", "Bytes", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "var", "alg", "uint64", "=", "mh", ".", "SHA2_256", "\n", "if", "AdvancedEnableInlining", "&&", "len", "(", "b", ")", "<=", "maxInlineKeyLength", "{", "alg", "=", "mh", ".", "ID", "\n", "}", "\n", "hash", ",", "_", ":=", "mh", ".", "Sum", "(", "b", ",", "alg", ",", "-", "1", ")", "\n", "return", "ID", "(", "hash", ")", ",", "nil", "\n", "}" ]
// IDFromPublicKey returns the Peer ID corresponding to pk
[ "IDFromPublicKey", "returns", "the", "Peer", "ID", "corresponding", "to", "pk" ]
9ccddf5f5d8318b00658dfbc06a4e32b16bae6a9
https://github.com/libp2p/go-libp2p-peer/blob/9ccddf5f5d8318b00658dfbc06a4e32b16bae6a9/peer.go#L158-L169
2,373
libp2p/go-libp2p-peer
peer_serde.go
UnmarshalText
func (id *ID) UnmarshalText(data []byte) error { pid, err := IDB58Decode(string(data)) if err != nil { return err } *id = pid return nil }
go
func (id *ID) UnmarshalText(data []byte) error { pid, err := IDB58Decode(string(data)) if err != nil { return err } *id = pid return nil }
[ "func", "(", "id", "*", "ID", ")", "UnmarshalText", "(", "data", "[", "]", "byte", ")", "error", "{", "pid", ",", "err", ":=", "IDB58Decode", "(", "string", "(", "data", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "*", "id", "=", "pid", "\n", "return", "nil", "\n", "}" ]
// TextUnmarshal restores the ID from its text encoding.
[ "TextUnmarshal", "restores", "the", "ID", "from", "its", "text", "encoding", "." ]
9ccddf5f5d8318b00658dfbc06a4e32b16bae6a9
https://github.com/libp2p/go-libp2p-peer/blob/9ccddf5f5d8318b00658dfbc06a4e32b16bae6a9/peer_serde.go#L68-L75
2,374
bnkamalesh/webgo
responses.go
SendError
func SendError(w http.ResponseWriter, data interface{}, rCode int) { rw := responseWriter{ ResponseWriter: w, code: rCode, } err := json.NewEncoder(rw).Encode(errOutput{data, rCode}) if err != nil { /* In case of encoding error, send "internal server error" after logging the actual error. */ LOGHANDLER.Error(err) R500(w, ErrInternalServer) } }
go
func SendError(w http.ResponseWriter, data interface{}, rCode int) { rw := responseWriter{ ResponseWriter: w, code: rCode, } err := json.NewEncoder(rw).Encode(errOutput{data, rCode}) if err != nil { /* In case of encoding error, send "internal server error" after logging the actual error. */ LOGHANDLER.Error(err) R500(w, ErrInternalServer) } }
[ "func", "SendError", "(", "w", "http", ".", "ResponseWriter", ",", "data", "interface", "{", "}", ",", "rCode", "int", ")", "{", "rw", ":=", "responseWriter", "{", "ResponseWriter", ":", "w", ",", "code", ":", "rCode", ",", "}", "\n\n", "err", ":=", "json", ".", "NewEncoder", "(", "rw", ")", ".", "Encode", "(", "errOutput", "{", "data", ",", "rCode", "}", ")", "\n", "if", "err", "!=", "nil", "{", "/*\n\t\t\tIn case of encoding error, send \"internal server error\" after\n\t\t\tlogging the actual error.\n\t\t*/", "LOGHANDLER", ".", "Error", "(", "err", ")", "\n", "R500", "(", "w", ",", "ErrInternalServer", ")", "\n", "}", "\n", "}" ]
// SendError is used to respond to any request with an error
[ "SendError", "is", "used", "to", "respond", "to", "any", "request", "with", "an", "error" ]
e239f16b08195410eee3adc9136b297e2726005b
https://github.com/bnkamalesh/webgo/blob/e239f16b08195410eee3adc9136b297e2726005b/responses.go#L91-L106
2,375
bnkamalesh/webgo
responses.go
Render404
func Render404(w http.ResponseWriter, tpl *template.Template) { Render(w, ErrorData{ http.StatusNotFound, "Sorry, the URL you requested was not found on this server... Or you're lost :-/", }, http.StatusNotFound, tpl, ) }
go
func Render404(w http.ResponseWriter, tpl *template.Template) { Render(w, ErrorData{ http.StatusNotFound, "Sorry, the URL you requested was not found on this server... Or you're lost :-/", }, http.StatusNotFound, tpl, ) }
[ "func", "Render404", "(", "w", "http", ".", "ResponseWriter", ",", "tpl", "*", "template", ".", "Template", ")", "{", "Render", "(", "w", ",", "ErrorData", "{", "http", ".", "StatusNotFound", ",", "\"", "\"", ",", "}", ",", "http", ".", "StatusNotFound", ",", "tpl", ",", ")", "\n", "}" ]
// Render404 - used to render a 404 page
[ "Render404", "-", "used", "to", "render", "a", "404", "page" ]
e239f16b08195410eee3adc9136b297e2726005b
https://github.com/bnkamalesh/webgo/blob/e239f16b08195410eee3adc9136b297e2726005b/responses.go#L122-L130
2,376
bnkamalesh/webgo
responses.go
R201
func R201(w http.ResponseWriter, data interface{}) { SendResponse(w, data, http.StatusCreated) }
go
func R201(w http.ResponseWriter, data interface{}) { SendResponse(w, data, http.StatusCreated) }
[ "func", "R201", "(", "w", "http", ".", "ResponseWriter", ",", "data", "interface", "{", "}", ")", "{", "SendResponse", "(", "w", ",", "data", ",", "http", ".", "StatusCreated", ")", "\n", "}" ]
// R201 - New item created
[ "R201", "-", "New", "item", "created" ]
e239f16b08195410eee3adc9136b297e2726005b
https://github.com/bnkamalesh/webgo/blob/e239f16b08195410eee3adc9136b297e2726005b/responses.go#L138-L140
2,377
bnkamalesh/webgo
responses.go
R302
func R302(w http.ResponseWriter, data interface{}) { SendResponse(w, data, http.StatusFound) }
go
func R302(w http.ResponseWriter, data interface{}) { SendResponse(w, data, http.StatusFound) }
[ "func", "R302", "(", "w", "http", ".", "ResponseWriter", ",", "data", "interface", "{", "}", ")", "{", "SendResponse", "(", "w", ",", "data", ",", "http", ".", "StatusFound", ")", "\n", "}" ]
// R302 - Temporary redirect
[ "R302", "-", "Temporary", "redirect" ]
e239f16b08195410eee3adc9136b297e2726005b
https://github.com/bnkamalesh/webgo/blob/e239f16b08195410eee3adc9136b297e2726005b/responses.go#L148-L150
2,378
bnkamalesh/webgo
responses.go
R403
func R403(w http.ResponseWriter, data interface{}) { SendError(w, data, http.StatusForbidden) }
go
func R403(w http.ResponseWriter, data interface{}) { SendError(w, data, http.StatusForbidden) }
[ "func", "R403", "(", "w", "http", ".", "ResponseWriter", ",", "data", "interface", "{", "}", ")", "{", "SendError", "(", "w", ",", "data", ",", "http", ".", "StatusForbidden", ")", "\n", "}" ]
// R403 - Unauthorized access
[ "R403", "-", "Unauthorized", "access" ]
e239f16b08195410eee3adc9136b297e2726005b
https://github.com/bnkamalesh/webgo/blob/e239f16b08195410eee3adc9136b297e2726005b/responses.go#L158-L160
2,379
bnkamalesh/webgo
responses.go
R404
func R404(w http.ResponseWriter, data interface{}) { SendError(w, data, http.StatusNotFound) }
go
func R404(w http.ResponseWriter, data interface{}) { SendError(w, data, http.StatusNotFound) }
[ "func", "R404", "(", "w", "http", ".", "ResponseWriter", ",", "data", "interface", "{", "}", ")", "{", "SendError", "(", "w", ",", "data", ",", "http", ".", "StatusNotFound", ")", "\n", "}" ]
// R404 - Resource not found
[ "R404", "-", "Resource", "not", "found" ]
e239f16b08195410eee3adc9136b297e2726005b
https://github.com/bnkamalesh/webgo/blob/e239f16b08195410eee3adc9136b297e2726005b/responses.go#L163-L165
2,380
bnkamalesh/webgo
responses.go
R406
func R406(w http.ResponseWriter, data interface{}) { SendError(w, data, http.StatusNotAcceptable) }
go
func R406(w http.ResponseWriter, data interface{}) { SendError(w, data, http.StatusNotAcceptable) }
[ "func", "R406", "(", "w", "http", ".", "ResponseWriter", ",", "data", "interface", "{", "}", ")", "{", "SendError", "(", "w", ",", "data", ",", "http", ".", "StatusNotAcceptable", ")", "\n", "}" ]
// R406 - Unacceptable header. For any error related to values set in header
[ "R406", "-", "Unacceptable", "header", ".", "For", "any", "error", "related", "to", "values", "set", "in", "header" ]
e239f16b08195410eee3adc9136b297e2726005b
https://github.com/bnkamalesh/webgo/blob/e239f16b08195410eee3adc9136b297e2726005b/responses.go#L168-L170
2,381
bnkamalesh/webgo
responses.go
R451
func R451(w http.ResponseWriter, data interface{}) { SendError(w, data, http.StatusUnavailableForLegalReasons) }
go
func R451(w http.ResponseWriter, data interface{}) { SendError(w, data, http.StatusUnavailableForLegalReasons) }
[ "func", "R451", "(", "w", "http", ".", "ResponseWriter", ",", "data", "interface", "{", "}", ")", "{", "SendError", "(", "w", ",", "data", ",", "http", ".", "StatusUnavailableForLegalReasons", ")", "\n", "}" ]
// R451 - Resource taken down because of a legal request
[ "R451", "-", "Resource", "taken", "down", "because", "of", "a", "legal", "request" ]
e239f16b08195410eee3adc9136b297e2726005b
https://github.com/bnkamalesh/webgo/blob/e239f16b08195410eee3adc9136b297e2726005b/responses.go#L173-L175
2,382
bnkamalesh/webgo
responses.go
R500
func R500(w http.ResponseWriter, data interface{}) { SendError(w, data, http.StatusInternalServerError) }
go
func R500(w http.ResponseWriter, data interface{}) { SendError(w, data, http.StatusInternalServerError) }
[ "func", "R500", "(", "w", "http", ".", "ResponseWriter", ",", "data", "interface", "{", "}", ")", "{", "SendError", "(", "w", ",", "data", ",", "http", ".", "StatusInternalServerError", ")", "\n", "}" ]
// R500 - Internal server error
[ "R500", "-", "Internal", "server", "error" ]
e239f16b08195410eee3adc9136b297e2726005b
https://github.com/bnkamalesh/webgo/blob/e239f16b08195410eee3adc9136b297e2726005b/responses.go#L178-L180
2,383
bnkamalesh/webgo
middleware/middleware.go
AccessLog
func AccessLog(rw http.ResponseWriter, req *http.Request, next http.HandlerFunc) { start := time.Now() w := &responseWriter{ ResponseWriter: rw, } next(w, req) end := time.Now() webgo.LOGHANDLER.Info( fmt.Sprintf( "%s %s %s %s %d", end.Format("2006-01-02 15:04:05 -0700 MST"), req.Method, req.URL.String(), end.Sub(start).String(), w.code, ), ) }
go
func AccessLog(rw http.ResponseWriter, req *http.Request, next http.HandlerFunc) { start := time.Now() w := &responseWriter{ ResponseWriter: rw, } next(w, req) end := time.Now() webgo.LOGHANDLER.Info( fmt.Sprintf( "%s %s %s %s %d", end.Format("2006-01-02 15:04:05 -0700 MST"), req.Method, req.URL.String(), end.Sub(start).String(), w.code, ), ) }
[ "func", "AccessLog", "(", "rw", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ",", "next", "http", ".", "HandlerFunc", ")", "{", "start", ":=", "time", ".", "Now", "(", ")", "\n", "w", ":=", "&", "responseWriter", "{", "ResponseWriter", ":", "rw", ",", "}", "\n", "next", "(", "w", ",", "req", ")", "\n", "end", ":=", "time", ".", "Now", "(", ")", "\n\n", "webgo", ".", "LOGHANDLER", ".", "Info", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "end", ".", "Format", "(", "\"", "\"", ")", ",", "req", ".", "Method", ",", "req", ".", "URL", ".", "String", "(", ")", ",", "end", ".", "Sub", "(", "start", ")", ".", "String", "(", ")", ",", "w", ".", "code", ",", ")", ",", ")", "\n", "}" ]
// AccessLog is a middleware which prints access log to stdout
[ "AccessLog", "is", "a", "middleware", "which", "prints", "access", "log", "to", "stdout" ]
e239f16b08195410eee3adc9136b297e2726005b
https://github.com/bnkamalesh/webgo/blob/e239f16b08195410eee3adc9136b297e2726005b/middleware/middleware.go#L26-L44
2,384
bnkamalesh/webgo
middleware/middleware.go
Cors
func Cors(allowedOrigins ...string) http.HandlerFunc { if len(allowedOrigins) == 0 { allowedOrigins = append(allowedOrigins, "*") } return func(rw http.ResponseWriter, req *http.Request) { allowed := false // Set appropriate response headers required for CORS reqOrigin := req.Header.Get(headerGetOrigin) for _, o := range allowedOrigins { // Set appropriate response headers required for CORS if o == "*" || o == reqOrigin { rw.Header().Set(headerOrigin, reqOrigin) allowed = true break } } if !allowed { webgo.SendHeader(rw, http.StatusForbidden) return } rw.Header().Set(headerMethods, allowMethods) rw.Header().Set(headerCreds, "true") // Adding allowed headers rw.Header().Set(headerAllowHeaders, allowHeaders+req.Header.Get(headerReqHeaders)) } }
go
func Cors(allowedOrigins ...string) http.HandlerFunc { if len(allowedOrigins) == 0 { allowedOrigins = append(allowedOrigins, "*") } return func(rw http.ResponseWriter, req *http.Request) { allowed := false // Set appropriate response headers required for CORS reqOrigin := req.Header.Get(headerGetOrigin) for _, o := range allowedOrigins { // Set appropriate response headers required for CORS if o == "*" || o == reqOrigin { rw.Header().Set(headerOrigin, reqOrigin) allowed = true break } } if !allowed { webgo.SendHeader(rw, http.StatusForbidden) return } rw.Header().Set(headerMethods, allowMethods) rw.Header().Set(headerCreds, "true") // Adding allowed headers rw.Header().Set(headerAllowHeaders, allowHeaders+req.Header.Get(headerReqHeaders)) } }
[ "func", "Cors", "(", "allowedOrigins", "...", "string", ")", "http", ".", "HandlerFunc", "{", "if", "len", "(", "allowedOrigins", ")", "==", "0", "{", "allowedOrigins", "=", "append", "(", "allowedOrigins", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "func", "(", "rw", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "allowed", ":=", "false", "\n", "// Set appropriate response headers required for CORS", "reqOrigin", ":=", "req", ".", "Header", ".", "Get", "(", "headerGetOrigin", ")", "\n", "for", "_", ",", "o", ":=", "range", "allowedOrigins", "{", "// Set appropriate response headers required for CORS", "if", "o", "==", "\"", "\"", "||", "o", "==", "reqOrigin", "{", "rw", ".", "Header", "(", ")", ".", "Set", "(", "headerOrigin", ",", "reqOrigin", ")", "\n", "allowed", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n\n", "if", "!", "allowed", "{", "webgo", ".", "SendHeader", "(", "rw", ",", "http", ".", "StatusForbidden", ")", "\n", "return", "\n", "}", "\n\n", "rw", ".", "Header", "(", ")", ".", "Set", "(", "headerMethods", ",", "allowMethods", ")", "\n", "rw", ".", "Header", "(", ")", ".", "Set", "(", "headerCreds", ",", "\"", "\"", ")", "\n\n", "// Adding allowed headers", "rw", ".", "Header", "(", ")", ".", "Set", "(", "headerAllowHeaders", ",", "allowHeaders", "+", "req", ".", "Header", ".", "Get", "(", "headerReqHeaders", ")", ")", "\n", "}", "\n", "}" ]
// Cors is a basic CORS middleware which can be added to individual handlers
[ "Cors", "is", "a", "basic", "CORS", "middleware", "which", "can", "be", "added", "to", "individual", "handlers" ]
e239f16b08195410eee3adc9136b297e2726005b
https://github.com/bnkamalesh/webgo/blob/e239f16b08195410eee3adc9136b297e2726005b/middleware/middleware.go#L58-L86
2,385
bnkamalesh/webgo
config.go
Load
func (cfg *Config) Load(filepath string) { file, err := ioutil.ReadFile(filepath) if err != nil { LOGHANDLER.Fatal(err) } err = json.Unmarshal(file, cfg) if err != nil { LOGHANDLER.Fatal(err) } err = cfg.Validate() if err != nil { LOGHANDLER.Fatal(ErrInvalidPort) } }
go
func (cfg *Config) Load(filepath string) { file, err := ioutil.ReadFile(filepath) if err != nil { LOGHANDLER.Fatal(err) } err = json.Unmarshal(file, cfg) if err != nil { LOGHANDLER.Fatal(err) } err = cfg.Validate() if err != nil { LOGHANDLER.Fatal(ErrInvalidPort) } }
[ "func", "(", "cfg", "*", "Config", ")", "Load", "(", "filepath", "string", ")", "{", "file", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "filepath", ")", "\n", "if", "err", "!=", "nil", "{", "LOGHANDLER", ".", "Fatal", "(", "err", ")", "\n", "}", "\n\n", "err", "=", "json", ".", "Unmarshal", "(", "file", ",", "cfg", ")", "\n", "if", "err", "!=", "nil", "{", "LOGHANDLER", ".", "Fatal", "(", "err", ")", "\n", "}", "\n\n", "err", "=", "cfg", ".", "Validate", "(", ")", "\n", "if", "err", "!=", "nil", "{", "LOGHANDLER", ".", "Fatal", "(", "ErrInvalidPort", ")", "\n", "}", "\n", "}" ]
// Load config file from the provided filepath and validate
[ "Load", "config", "file", "from", "the", "provided", "filepath", "and", "validate" ]
e239f16b08195410eee3adc9136b297e2726005b
https://github.com/bnkamalesh/webgo/blob/e239f16b08195410eee3adc9136b297e2726005b/config.go#L37-L52
2,386
bnkamalesh/webgo
config.go
Validate
func (cfg *Config) Validate() error { i, err := strconv.Atoi(cfg.Port) if err != nil { return ErrInvalidPort } if i <= 0 || i > 65535 { return ErrInvalidPort } return nil }
go
func (cfg *Config) Validate() error { i, err := strconv.Atoi(cfg.Port) if err != nil { return ErrInvalidPort } if i <= 0 || i > 65535 { return ErrInvalidPort } return nil }
[ "func", "(", "cfg", "*", "Config", ")", "Validate", "(", ")", "error", "{", "i", ",", "err", ":=", "strconv", ".", "Atoi", "(", "cfg", ".", "Port", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ErrInvalidPort", "\n", "}", "\n\n", "if", "i", "<=", "0", "||", "i", ">", "65535", "{", "return", "ErrInvalidPort", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Validate the config parsed into the Config struct
[ "Validate", "the", "config", "parsed", "into", "the", "Config", "struct" ]
e239f16b08195410eee3adc9136b297e2726005b
https://github.com/bnkamalesh/webgo/blob/e239f16b08195410eee3adc9136b297e2726005b/config.go#L55-L66
2,387
bnkamalesh/webgo
webgo.go
Context
func Context(r *http.Request) *WC { wc, _ := r.Context().Value(wgoCtxKey).(*WC) return wc }
go
func Context(r *http.Request) *WC { wc, _ := r.Context().Value(wgoCtxKey).(*WC) return wc }
[ "func", "Context", "(", "r", "*", "http", ".", "Request", ")", "*", "WC", "{", "wc", ",", "_", ":=", "r", ".", "Context", "(", ")", ".", "Value", "(", "wgoCtxKey", ")", ".", "(", "*", "WC", ")", "\n", "return", "wc", "\n", "}" ]
// Context returns the WebgoContext injected inside the HTTP request context
[ "Context", "returns", "the", "WebgoContext", "injected", "inside", "the", "HTTP", "request", "context" ]
e239f16b08195410eee3adc9136b297e2726005b
https://github.com/bnkamalesh/webgo/blob/e239f16b08195410eee3adc9136b297e2726005b/webgo.go#L35-L38
2,388
bnkamalesh/webgo
webgo.go
StartHTTPS
func (router *Router) StartHTTPS() { cfg := router.config if cfg.CertFile == "" { LOGHANDLER.Fatal("No certificate provided for HTTPS") } if cfg.KeyFile == "" { LOGHANDLER.Fatal("No key file provided for HTTPS") } host := cfg.Host if len(cfg.HTTPSPort) > 0 { host += ":" + cfg.HTTPSPort } router.httpsServer = &http.Server{ Addr: host, Handler: router, ReadTimeout: cfg.ReadTimeout, WriteTimeout: cfg.WriteTimeout, TLSConfig: &tls.Config{ InsecureSkipVerify: cfg.InsecureSkipVerify, }, } LOGHANDLER.Info("HTTPS server, listening on", host) err := router.httpsServer.ListenAndServeTLS(cfg.CertFile, cfg.KeyFile) if err != nil && err != http.ErrServerClosed { LOGHANDLER.Error("HTTPS server exited with error:", err.Error()) } }
go
func (router *Router) StartHTTPS() { cfg := router.config if cfg.CertFile == "" { LOGHANDLER.Fatal("No certificate provided for HTTPS") } if cfg.KeyFile == "" { LOGHANDLER.Fatal("No key file provided for HTTPS") } host := cfg.Host if len(cfg.HTTPSPort) > 0 { host += ":" + cfg.HTTPSPort } router.httpsServer = &http.Server{ Addr: host, Handler: router, ReadTimeout: cfg.ReadTimeout, WriteTimeout: cfg.WriteTimeout, TLSConfig: &tls.Config{ InsecureSkipVerify: cfg.InsecureSkipVerify, }, } LOGHANDLER.Info("HTTPS server, listening on", host) err := router.httpsServer.ListenAndServeTLS(cfg.CertFile, cfg.KeyFile) if err != nil && err != http.ErrServerClosed { LOGHANDLER.Error("HTTPS server exited with error:", err.Error()) } }
[ "func", "(", "router", "*", "Router", ")", "StartHTTPS", "(", ")", "{", "cfg", ":=", "router", ".", "config", "\n", "if", "cfg", ".", "CertFile", "==", "\"", "\"", "{", "LOGHANDLER", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "cfg", ".", "KeyFile", "==", "\"", "\"", "{", "LOGHANDLER", ".", "Fatal", "(", "\"", "\"", ")", "\n", "}", "\n\n", "host", ":=", "cfg", ".", "Host", "\n", "if", "len", "(", "cfg", ".", "HTTPSPort", ")", ">", "0", "{", "host", "+=", "\"", "\"", "+", "cfg", ".", "HTTPSPort", "\n", "}", "\n\n", "router", ".", "httpsServer", "=", "&", "http", ".", "Server", "{", "Addr", ":", "host", ",", "Handler", ":", "router", ",", "ReadTimeout", ":", "cfg", ".", "ReadTimeout", ",", "WriteTimeout", ":", "cfg", ".", "WriteTimeout", ",", "TLSConfig", ":", "&", "tls", ".", "Config", "{", "InsecureSkipVerify", ":", "cfg", ".", "InsecureSkipVerify", ",", "}", ",", "}", "\n\n", "LOGHANDLER", ".", "Info", "(", "\"", "\"", ",", "host", ")", "\n", "err", ":=", "router", ".", "httpsServer", ".", "ListenAndServeTLS", "(", "cfg", ".", "CertFile", ",", "cfg", ".", "KeyFile", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "http", ".", "ErrServerClosed", "{", "LOGHANDLER", ".", "Error", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}" ]
// StartHTTPS starts the server with HTTPS enabled
[ "StartHTTPS", "starts", "the", "server", "with", "HTTPS", "enabled" ]
e239f16b08195410eee3adc9136b297e2726005b
https://github.com/bnkamalesh/webgo/blob/e239f16b08195410eee3adc9136b297e2726005b/webgo.go#L41-L71
2,389
bnkamalesh/webgo
webgo.go
Start
func (router *Router) Start() { cfg := router.config host := cfg.Host if len(cfg.Port) > 0 { host += ":" + cfg.Port } router.httpServer = &http.Server{ Addr: host, Handler: router, ReadTimeout: cfg.ReadTimeout, WriteTimeout: cfg.WriteTimeout, } LOGHANDLER.Info("HTTP server, listening on", host) err := router.httpServer.ListenAndServe() if err != nil && err != http.ErrServerClosed { LOGHANDLER.Error("HTTP server exited with error:", err.Error()) } }
go
func (router *Router) Start() { cfg := router.config host := cfg.Host if len(cfg.Port) > 0 { host += ":" + cfg.Port } router.httpServer = &http.Server{ Addr: host, Handler: router, ReadTimeout: cfg.ReadTimeout, WriteTimeout: cfg.WriteTimeout, } LOGHANDLER.Info("HTTP server, listening on", host) err := router.httpServer.ListenAndServe() if err != nil && err != http.ErrServerClosed { LOGHANDLER.Error("HTTP server exited with error:", err.Error()) } }
[ "func", "(", "router", "*", "Router", ")", "Start", "(", ")", "{", "cfg", ":=", "router", ".", "config", "\n", "host", ":=", "cfg", ".", "Host", "\n\n", "if", "len", "(", "cfg", ".", "Port", ")", ">", "0", "{", "host", "+=", "\"", "\"", "+", "cfg", ".", "Port", "\n", "}", "\n\n", "router", ".", "httpServer", "=", "&", "http", ".", "Server", "{", "Addr", ":", "host", ",", "Handler", ":", "router", ",", "ReadTimeout", ":", "cfg", ".", "ReadTimeout", ",", "WriteTimeout", ":", "cfg", ".", "WriteTimeout", ",", "}", "\n", "LOGHANDLER", ".", "Info", "(", "\"", "\"", ",", "host", ")", "\n", "err", ":=", "router", ".", "httpServer", ".", "ListenAndServe", "(", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "http", ".", "ErrServerClosed", "{", "LOGHANDLER", ".", "Error", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "}" ]
// Start starts the HTTP server with the appropriate configurations
[ "Start", "starts", "the", "HTTP", "server", "with", "the", "appropriate", "configurations" ]
e239f16b08195410eee3adc9136b297e2726005b
https://github.com/bnkamalesh/webgo/blob/e239f16b08195410eee3adc9136b297e2726005b/webgo.go#L74-L93
2,390
bnkamalesh/webgo
webgo.go
Shutdown
func (router *Router) Shutdown() error { if router.httpServer == nil { return nil } timer := router.config.ShutdownTimeout ctx, cancel := context.WithTimeout(context.Background(), timer) defer cancel() err := router.httpServer.Shutdown(ctx) if err != nil { LOGHANDLER.Error(err) } return err }
go
func (router *Router) Shutdown() error { if router.httpServer == nil { return nil } timer := router.config.ShutdownTimeout ctx, cancel := context.WithTimeout(context.Background(), timer) defer cancel() err := router.httpServer.Shutdown(ctx) if err != nil { LOGHANDLER.Error(err) } return err }
[ "func", "(", "router", "*", "Router", ")", "Shutdown", "(", ")", "error", "{", "if", "router", ".", "httpServer", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "timer", ":=", "router", ".", "config", ".", "ShutdownTimeout", "\n\n", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "context", ".", "Background", "(", ")", ",", "timer", ")", "\n", "defer", "cancel", "(", ")", "\n\n", "err", ":=", "router", ".", "httpServer", ".", "Shutdown", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "LOGHANDLER", ".", "Error", "(", "err", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Shutdown gracefully shuts down HTTP server
[ "Shutdown", "gracefully", "shuts", "down", "HTTP", "server" ]
e239f16b08195410eee3adc9136b297e2726005b
https://github.com/bnkamalesh/webgo/blob/e239f16b08195410eee3adc9136b297e2726005b/webgo.go#L96-L110
2,391
bnkamalesh/webgo
webgo.go
ShutdownHTTPS
func (router *Router) ShutdownHTTPS() error { if router.httpsServer == nil { return nil } timer := router.config.ShutdownTimeout ctx, cancel := context.WithTimeout(context.Background(), timer) defer cancel() err := router.httpsServer.Shutdown(ctx) if err != nil && err != http.ErrServerClosed { LOGHANDLER.Error(err) } return err }
go
func (router *Router) ShutdownHTTPS() error { if router.httpsServer == nil { return nil } timer := router.config.ShutdownTimeout ctx, cancel := context.WithTimeout(context.Background(), timer) defer cancel() err := router.httpsServer.Shutdown(ctx) if err != nil && err != http.ErrServerClosed { LOGHANDLER.Error(err) } return err }
[ "func", "(", "router", "*", "Router", ")", "ShutdownHTTPS", "(", ")", "error", "{", "if", "router", ".", "httpsServer", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "timer", ":=", "router", ".", "config", ".", "ShutdownTimeout", "\n\n", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "context", ".", "Background", "(", ")", ",", "timer", ")", "\n", "defer", "cancel", "(", ")", "\n\n", "err", ":=", "router", ".", "httpsServer", ".", "Shutdown", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "http", ".", "ErrServerClosed", "{", "LOGHANDLER", ".", "Error", "(", "err", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// ShutdownHTTPS gracefully shuts down HTTPS server
[ "ShutdownHTTPS", "gracefully", "shuts", "down", "HTTPS", "server" ]
e239f16b08195410eee3adc9136b297e2726005b
https://github.com/bnkamalesh/webgo/blob/e239f16b08195410eee3adc9136b297e2726005b/webgo.go#L113-L127
2,392
bnkamalesh/webgo
router.go
WriteHeader
func (crw *customResponseWriter) WriteHeader(code int) { if crw.written { LOGHANDLER.Warn(errMultiHeaderWrite) return } crw.statusCode = code crw.ResponseWriter.WriteHeader(code) }
go
func (crw *customResponseWriter) WriteHeader(code int) { if crw.written { LOGHANDLER.Warn(errMultiHeaderWrite) return } crw.statusCode = code crw.ResponseWriter.WriteHeader(code) }
[ "func", "(", "crw", "*", "customResponseWriter", ")", "WriteHeader", "(", "code", "int", ")", "{", "if", "crw", ".", "written", "{", "LOGHANDLER", ".", "Warn", "(", "errMultiHeaderWrite", ")", "\n", "return", "\n", "}", "\n\n", "crw", ".", "statusCode", "=", "code", "\n", "crw", ".", "ResponseWriter", ".", "WriteHeader", "(", "code", ")", "\n", "}" ]
// WriteHeader is the interface implementation to get HTTP response code and add // it to the custom response writer
[ "WriteHeader", "is", "the", "interface", "implementation", "to", "get", "HTTP", "response", "code", "and", "add", "it", "to", "the", "custom", "response", "writer" ]
e239f16b08195410eee3adc9136b297e2726005b
https://github.com/bnkamalesh/webgo/blob/e239f16b08195410eee3adc9136b297e2726005b/router.go#L45-L53
2,393
bnkamalesh/webgo
router.go
Write
func (crw *customResponseWriter) Write(body []byte) (int, error) { if crw.written { LOGHANDLER.Warn(errMultiWrite) return 0, nil } crw.written = true return crw.ResponseWriter.Write(body) }
go
func (crw *customResponseWriter) Write(body []byte) (int, error) { if crw.written { LOGHANDLER.Warn(errMultiWrite) return 0, nil } crw.written = true return crw.ResponseWriter.Write(body) }
[ "func", "(", "crw", "*", "customResponseWriter", ")", "Write", "(", "body", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "if", "crw", ".", "written", "{", "LOGHANDLER", ".", "Warn", "(", "errMultiWrite", ")", "\n", "return", "0", ",", "nil", "\n", "}", "\n\n", "crw", ".", "written", "=", "true", "\n", "return", "crw", ".", "ResponseWriter", ".", "Write", "(", "body", ")", "\n", "}" ]
// Write is the interface implementation to respond to the HTTP request, // but check if a response was already sent.
[ "Write", "is", "the", "interface", "implementation", "to", "respond", "to", "the", "HTTP", "request", "but", "check", "if", "a", "response", "was", "already", "sent", "." ]
e239f16b08195410eee3adc9136b297e2726005b
https://github.com/bnkamalesh/webgo/blob/e239f16b08195410eee3adc9136b297e2726005b/router.go#L57-L65
2,394
bnkamalesh/webgo
router.go
computePatternStr
func (r *Route) computePatternStr(patternString string, hasWildcard bool, key string) (string, error) { regexPattern := "" patternKey := "" if hasWildcard { patternKey = fmt.Sprintf(":%s*", key) regexPattern = urlwildcard } else { patternKey = fmt.Sprintf(":%s", key) regexPattern = urlchars } patternString = strings.Replace(patternString, patternKey, regexPattern, 1) for idx, k := range r.uriKeys { if key == k { return "", errors.New( fmt.Sprintf( "%s\nURI:%s\nKey:%s, Position: %d", errDuplicateKey, r.Pattern, k, idx+1, ), ) } } r.uriKeys = append(r.uriKeys, key) return patternString, nil }
go
func (r *Route) computePatternStr(patternString string, hasWildcard bool, key string) (string, error) { regexPattern := "" patternKey := "" if hasWildcard { patternKey = fmt.Sprintf(":%s*", key) regexPattern = urlwildcard } else { patternKey = fmt.Sprintf(":%s", key) regexPattern = urlchars } patternString = strings.Replace(patternString, patternKey, regexPattern, 1) for idx, k := range r.uriKeys { if key == k { return "", errors.New( fmt.Sprintf( "%s\nURI:%s\nKey:%s, Position: %d", errDuplicateKey, r.Pattern, k, idx+1, ), ) } } r.uriKeys = append(r.uriKeys, key) return patternString, nil }
[ "func", "(", "r", "*", "Route", ")", "computePatternStr", "(", "patternString", "string", ",", "hasWildcard", "bool", ",", "key", "string", ")", "(", "string", ",", "error", ")", "{", "regexPattern", ":=", "\"", "\"", "\n", "patternKey", ":=", "\"", "\"", "\n", "if", "hasWildcard", "{", "patternKey", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "key", ")", "\n", "regexPattern", "=", "urlwildcard", "\n", "}", "else", "{", "patternKey", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "key", ")", "\n", "regexPattern", "=", "urlchars", "\n", "}", "\n\n", "patternString", "=", "strings", ".", "Replace", "(", "patternString", ",", "patternKey", ",", "regexPattern", ",", "1", ")", "\n\n", "for", "idx", ",", "k", ":=", "range", "r", ".", "uriKeys", "{", "if", "key", "==", "k", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\\n", "\"", ",", "errDuplicateKey", ",", "r", ".", "Pattern", ",", "k", ",", "idx", "+", "1", ",", ")", ",", ")", "\n", "}", "\n", "}", "\n\n", "r", ".", "uriKeys", "=", "append", "(", "r", ".", "uriKeys", ",", "key", ")", "\n", "return", "patternString", ",", "nil", "\n", "}" ]
// computePatternStr computes the pattern string required for generating the route's regex. // It also adds the URI parameter key to the route's `keys` field
[ "computePatternStr", "computes", "the", "pattern", "string", "required", "for", "generating", "the", "route", "s", "regex", ".", "It", "also", "adds", "the", "URI", "parameter", "key", "to", "the", "route", "s", "keys", "field" ]
e239f16b08195410eee3adc9136b297e2726005b
https://github.com/bnkamalesh/webgo/blob/e239f16b08195410eee3adc9136b297e2726005b/router.go#L96-L125
2,395
bnkamalesh/webgo
router.go
init
func (r *Route) init() error { patternString := r.Pattern var err error if strings.Contains(r.Pattern, ":") { // uriValues is a map of URI Key and it's respective value, // this is calculated per request key := "" hasKey := false hasWildcard := false for i := 0; i < len(r.Pattern); i++ { char := string(r.Pattern[i]) if char == ":" { hasKey = true } else if char == "*" { hasWildcard = true } else if hasKey && char != "/" { key += char } else if hasKey && len(key) > 0 { patternString, err = r.computePatternStr(patternString, hasWildcard, key) if err != nil { return err } hasWildcard, hasKey = false, false key = "" } } if hasKey && len(key) > 0 { patternString, err = r.computePatternStr(patternString, hasWildcard, key) if err != nil { return err } } } if r.TrailingSlash { patternString = fmt.Sprintf("^%s%s$", patternString, trailingSlash) } else { patternString = fmt.Sprintf("^%s$", patternString) } // compile the regex for the pattern string calculated reg, err := regexp.Compile(patternString) if err != nil { return err } r.uriPattern = reg r.uriPatternString = patternString return nil }
go
func (r *Route) init() error { patternString := r.Pattern var err error if strings.Contains(r.Pattern, ":") { // uriValues is a map of URI Key and it's respective value, // this is calculated per request key := "" hasKey := false hasWildcard := false for i := 0; i < len(r.Pattern); i++ { char := string(r.Pattern[i]) if char == ":" { hasKey = true } else if char == "*" { hasWildcard = true } else if hasKey && char != "/" { key += char } else if hasKey && len(key) > 0 { patternString, err = r.computePatternStr(patternString, hasWildcard, key) if err != nil { return err } hasWildcard, hasKey = false, false key = "" } } if hasKey && len(key) > 0 { patternString, err = r.computePatternStr(patternString, hasWildcard, key) if err != nil { return err } } } if r.TrailingSlash { patternString = fmt.Sprintf("^%s%s$", patternString, trailingSlash) } else { patternString = fmt.Sprintf("^%s$", patternString) } // compile the regex for the pattern string calculated reg, err := regexp.Compile(patternString) if err != nil { return err } r.uriPattern = reg r.uriPatternString = patternString return nil }
[ "func", "(", "r", "*", "Route", ")", "init", "(", ")", "error", "{", "patternString", ":=", "r", ".", "Pattern", "\n", "var", "err", "error", "\n", "if", "strings", ".", "Contains", "(", "r", ".", "Pattern", ",", "\"", "\"", ")", "{", "// uriValues is a map of URI Key and it's respective value,", "// this is calculated per request", "key", ":=", "\"", "\"", "\n", "hasKey", ":=", "false", "\n", "hasWildcard", ":=", "false", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "r", ".", "Pattern", ")", ";", "i", "++", "{", "char", ":=", "string", "(", "r", ".", "Pattern", "[", "i", "]", ")", "\n\n", "if", "char", "==", "\"", "\"", "{", "hasKey", "=", "true", "\n", "}", "else", "if", "char", "==", "\"", "\"", "{", "hasWildcard", "=", "true", "\n", "}", "else", "if", "hasKey", "&&", "char", "!=", "\"", "\"", "{", "key", "+=", "char", "\n", "}", "else", "if", "hasKey", "&&", "len", "(", "key", ")", ">", "0", "{", "patternString", ",", "err", "=", "r", ".", "computePatternStr", "(", "patternString", ",", "hasWildcard", ",", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "hasWildcard", ",", "hasKey", "=", "false", ",", "false", "\n", "key", "=", "\"", "\"", "\n", "}", "\n", "}", "\n\n", "if", "hasKey", "&&", "len", "(", "key", ")", ">", "0", "{", "patternString", ",", "err", "=", "r", ".", "computePatternStr", "(", "patternString", ",", "hasWildcard", ",", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "r", ".", "TrailingSlash", "{", "patternString", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "patternString", ",", "trailingSlash", ")", "\n", "}", "else", "{", "patternString", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "patternString", ")", "\n", "}", "\n\n", "// compile the regex for the pattern string calculated", "reg", ",", "err", ":=", "regexp", ".", "Compile", "(", "patternString", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "r", ".", "uriPattern", "=", "reg", "\n", "r", ".", "uriPatternString", "=", "patternString", "\n", "return", "nil", "\n", "}" ]
// init prepares the URIKeys, compile regex for the provided pattern
[ "init", "prepares", "the", "URIKeys", "compile", "regex", "for", "the", "provided", "pattern" ]
e239f16b08195410eee3adc9136b297e2726005b
https://github.com/bnkamalesh/webgo/blob/e239f16b08195410eee3adc9136b297e2726005b/router.go#L128-L180
2,396
bnkamalesh/webgo
router.go
matchAndGet
func (r *Route) matchAndGet(requestURI string) (bool, map[string]string) { if r.Pattern == requestURI { return true, nil } if !r.uriPattern.Match([]byte(requestURI)) { return false, nil } // Getting URI parameters values := r.uriPattern.FindStringSubmatch(requestURI) if len(values) == 0 { return true, nil } uriValues := make(map[string]string, len(values)-1) for i := 1; i < len(values); i++ { uriValues[r.uriKeys[i-1]] = values[i] } return true, uriValues }
go
func (r *Route) matchAndGet(requestURI string) (bool, map[string]string) { if r.Pattern == requestURI { return true, nil } if !r.uriPattern.Match([]byte(requestURI)) { return false, nil } // Getting URI parameters values := r.uriPattern.FindStringSubmatch(requestURI) if len(values) == 0 { return true, nil } uriValues := make(map[string]string, len(values)-1) for i := 1; i < len(values); i++ { uriValues[r.uriKeys[i-1]] = values[i] } return true, uriValues }
[ "func", "(", "r", "*", "Route", ")", "matchAndGet", "(", "requestURI", "string", ")", "(", "bool", ",", "map", "[", "string", "]", "string", ")", "{", "if", "r", ".", "Pattern", "==", "requestURI", "{", "return", "true", ",", "nil", "\n", "}", "\n\n", "if", "!", "r", ".", "uriPattern", ".", "Match", "(", "[", "]", "byte", "(", "requestURI", ")", ")", "{", "return", "false", ",", "nil", "\n", "}", "\n\n", "// Getting URI parameters", "values", ":=", "r", ".", "uriPattern", ".", "FindStringSubmatch", "(", "requestURI", ")", "\n", "if", "len", "(", "values", ")", "==", "0", "{", "return", "true", ",", "nil", "\n", "}", "\n\n", "uriValues", ":=", "make", "(", "map", "[", "string", "]", "string", ",", "len", "(", "values", ")", "-", "1", ")", "\n", "for", "i", ":=", "1", ";", "i", "<", "len", "(", "values", ")", ";", "i", "++", "{", "uriValues", "[", "r", ".", "uriKeys", "[", "i", "-", "1", "]", "]", "=", "values", "[", "i", "]", "\n", "}", "\n", "return", "true", ",", "uriValues", "\n\n", "}" ]
// matchAndGet returns if the request URI matches the pattern defined in a Route as well as // all the URI parameters configured for the route.
[ "matchAndGet", "returns", "if", "the", "request", "URI", "matches", "the", "pattern", "defined", "in", "a", "Route", "as", "well", "as", "all", "the", "URI", "parameters", "configured", "for", "the", "route", "." ]
e239f16b08195410eee3adc9136b297e2726005b
https://github.com/bnkamalesh/webgo/blob/e239f16b08195410eee3adc9136b297e2726005b/router.go#L184-L205
2,397
bnkamalesh/webgo
router.go
ServeHTTP
func (rtr *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) { rtr.serveHandler(rw, req) }
go
func (rtr *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) { rtr.serveHandler(rw, req) }
[ "func", "(", "rtr", "*", "Router", ")", "ServeHTTP", "(", "rw", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "rtr", ".", "serveHandler", "(", "rw", ",", "req", ")", "\n", "}" ]
// ServeHTTP is the required `ServeHTTP` implementation to listen to HTTP requests
[ "ServeHTTP", "is", "the", "required", "ServeHTTP", "implementation", "to", "listen", "to", "HTTP", "requests" ]
e239f16b08195410eee3adc9136b297e2726005b
https://github.com/bnkamalesh/webgo/blob/e239f16b08195410eee3adc9136b297e2726005b/router.go#L303-L305
2,398
bnkamalesh/webgo
router.go
Use
func (rtr *Router) Use(f func(http.ResponseWriter, *http.Request, http.HandlerFunc)) { srv := rtr.serveHandler rtr.serveHandler = func(rw http.ResponseWriter, req *http.Request) { f(rw, req, srv) } }
go
func (rtr *Router) Use(f func(http.ResponseWriter, *http.Request, http.HandlerFunc)) { srv := rtr.serveHandler rtr.serveHandler = func(rw http.ResponseWriter, req *http.Request) { f(rw, req, srv) } }
[ "func", "(", "rtr", "*", "Router", ")", "Use", "(", "f", "func", "(", "http", ".", "ResponseWriter", ",", "*", "http", ".", "Request", ",", "http", ".", "HandlerFunc", ")", ")", "{", "srv", ":=", "rtr", ".", "serveHandler", "\n", "rtr", ".", "serveHandler", "=", "func", "(", "rw", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "f", "(", "rw", ",", "req", ",", "srv", ")", "\n", "}", "\n", "}" ]
// Use adds a middleware layer
[ "Use", "adds", "a", "middleware", "layer" ]
e239f16b08195410eee3adc9136b297e2726005b
https://github.com/bnkamalesh/webgo/blob/e239f16b08195410eee3adc9136b297e2726005b/router.go#L308-L313
2,399
bnkamalesh/webgo
router.go
NewRouter
func NewRouter(cfg *Config, routes []*Route) *Router { handlers := httpHandlers(routes) r := &Router{ optHandlers: handlers[http.MethodOptions], headHandlers: handlers[http.MethodHead], getHandlers: handlers[http.MethodGet], postHandlers: handlers[http.MethodPost], putHandlers: handlers[http.MethodPut], patchHandlers: handlers[http.MethodPatch], deleteHandlers: handlers[http.MethodDelete], NotFound: http.NotFound, AppContext: make(map[string]interface{}), config: cfg, } // setting the default serve handler r.serveHandler = r.serve return r }
go
func NewRouter(cfg *Config, routes []*Route) *Router { handlers := httpHandlers(routes) r := &Router{ optHandlers: handlers[http.MethodOptions], headHandlers: handlers[http.MethodHead], getHandlers: handlers[http.MethodGet], postHandlers: handlers[http.MethodPost], putHandlers: handlers[http.MethodPut], patchHandlers: handlers[http.MethodPatch], deleteHandlers: handlers[http.MethodDelete], NotFound: http.NotFound, AppContext: make(map[string]interface{}), config: cfg, } // setting the default serve handler r.serveHandler = r.serve return r }
[ "func", "NewRouter", "(", "cfg", "*", "Config", ",", "routes", "[", "]", "*", "Route", ")", "*", "Router", "{", "handlers", ":=", "httpHandlers", "(", "routes", ")", "\n", "r", ":=", "&", "Router", "{", "optHandlers", ":", "handlers", "[", "http", ".", "MethodOptions", "]", ",", "headHandlers", ":", "handlers", "[", "http", ".", "MethodHead", "]", ",", "getHandlers", ":", "handlers", "[", "http", ".", "MethodGet", "]", ",", "postHandlers", ":", "handlers", "[", "http", ".", "MethodPost", "]", ",", "putHandlers", ":", "handlers", "[", "http", ".", "MethodPut", "]", ",", "patchHandlers", ":", "handlers", "[", "http", ".", "MethodPatch", "]", ",", "deleteHandlers", ":", "handlers", "[", "http", ".", "MethodDelete", "]", ",", "NotFound", ":", "http", ".", "NotFound", ",", "AppContext", ":", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", ",", "config", ":", "cfg", ",", "}", "\n\n", "// setting the default serve handler", "r", ".", "serveHandler", "=", "r", ".", "serve", "\n\n", "return", "r", "\n", "}" ]
// NewRouter initializes returns a new router instance with all the configurations and routes set
[ "NewRouter", "initializes", "returns", "a", "new", "router", "instance", "with", "all", "the", "configurations", "and", "routes", "set" ]
e239f16b08195410eee3adc9136b297e2726005b
https://github.com/bnkamalesh/webgo/blob/e239f16b08195410eee3adc9136b297e2726005b/router.go#L316-L336