repository_name
stringlengths 5
54
| func_path_in_repository
stringlengths 4
155
| func_name
stringlengths 1
118
| whole_func_string
stringlengths 52
3.87M
| language
stringclasses 1
value | func_code_string
stringlengths 52
3.87M
| func_code_tokens
sequencelengths 21
188k
| func_documentation_string
stringlengths 4
26.3k
| func_documentation_tokens
sequencelengths 1
3.92k
| split_name
stringclasses 1
value | func_code_url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|
timshannon/bolthold | query.go | SubQuery | func (r *RecordAccess) SubQuery(result interface{}, query *Query) error {
return findQuery(r.tx, result, query)
} | go | func (r *RecordAccess) SubQuery(result interface{}, query *Query) error {
return findQuery(r.tx, result, query)
} | [
"func",
"(",
"r",
"*",
"RecordAccess",
")",
"SubQuery",
"(",
"result",
"interface",
"{",
"}",
",",
"query",
"*",
"Query",
")",
"error",
"{",
"return",
"findQuery",
"(",
"r",
".",
"tx",
",",
"result",
",",
"query",
")",
"\n",
"}"
] | // SubQuery allows you to run another query in the same transaction for each
// record in a parent query | [
"SubQuery",
"allows",
"you",
"to",
"run",
"another",
"query",
"in",
"the",
"same",
"transaction",
"for",
"each",
"record",
"in",
"a",
"parent",
"query"
] | train | https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/query.go#L350-L352 |
timshannon/bolthold | query.go | SubAggregateQuery | func (r *RecordAccess) SubAggregateQuery(query *Query, groupBy ...string) ([]*AggregateResult, error) {
return aggregateQuery(r.tx, r.record, query, groupBy...)
} | go | func (r *RecordAccess) SubAggregateQuery(query *Query, groupBy ...string) ([]*AggregateResult, error) {
return aggregateQuery(r.tx, r.record, query, groupBy...)
} | [
"func",
"(",
"r",
"*",
"RecordAccess",
")",
"SubAggregateQuery",
"(",
"query",
"*",
"Query",
",",
"groupBy",
"...",
"string",
")",
"(",
"[",
"]",
"*",
"AggregateResult",
",",
"error",
")",
"{",
"return",
"aggregateQuery",
"(",
"r",
".",
"tx",
",",
"r",
".",
"record",
",",
"query",
",",
"groupBy",
"...",
")",
"\n",
"}"
] | // SubAggregateQuery allows you to run another aggregate query in the same transaction for each
// record in a parent query | [
"SubAggregateQuery",
"allows",
"you",
"to",
"run",
"another",
"aggregate",
"query",
"in",
"the",
"same",
"transaction",
"for",
"each",
"record",
"in",
"a",
"parent",
"query"
] | train | https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/query.go#L356-L358 |
timshannon/bolthold | query.go | MatchFunc | func (c *Criterion) MatchFunc(match MatchFunc) *Query {
if c.query.currentField == Key {
panic("Match func cannot be used against Keys, as the Key type is unknown at runtime, and there is no value compare against")
}
return c.op(fn, match)
} | go | func (c *Criterion) MatchFunc(match MatchFunc) *Query {
if c.query.currentField == Key {
panic("Match func cannot be used against Keys, as the Key type is unknown at runtime, and there is no value compare against")
}
return c.op(fn, match)
} | [
"func",
"(",
"c",
"*",
"Criterion",
")",
"MatchFunc",
"(",
"match",
"MatchFunc",
")",
"*",
"Query",
"{",
"if",
"c",
".",
"query",
".",
"currentField",
"==",
"Key",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"c",
".",
"op",
"(",
"fn",
",",
"match",
")",
"\n",
"}"
] | // MatchFunc will test if a field matches the passed in function | [
"MatchFunc",
"will",
"test",
"if",
"a",
"field",
"matches",
"the",
"passed",
"in",
"function"
] | train | https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/query.go#L361-L367 |
timshannon/bolthold | query.go | runQuerySort | func runQuerySort(tx *bolt.Tx, dataType interface{}, query *Query, action func(r *record) error) error {
// Validate sort fields
for _, field := range query.sort {
fields := strings.Split(field, ".")
current := query.dataType
for i := range fields {
var structField reflect.StructField
found := false
if current.Kind() == reflect.Ptr {
structField, found = current.Elem().FieldByName(fields[i])
} else {
structField, found = current.FieldByName(fields[i])
}
if !found {
return fmt.Errorf("The field %s does not exist in the type %s", field, query.dataType)
}
current = structField.Type
}
}
// Run query without sort, skip or limit
// apply sort, skip and limit to entire dataset
qCopy := *query
qCopy.sort = nil
qCopy.limit = 0
qCopy.skip = 0
var records []*record
err := runQuery(tx, dataType, &qCopy, nil, 0,
func(r *record) error {
records = append(records, r)
return nil
})
if err != nil {
return err
}
sort.Slice(records, func(i, j int) bool {
for _, field := range query.sort {
val, err := fieldValue(records[i].value.Elem(), field)
if err != nil {
panic(err.Error()) // shouldn't happen due to field check above
}
value := val.Interface()
val, err = fieldValue(records[j].value.Elem(), field)
if err != nil {
panic(err.Error()) // shouldn't happen due to field check above
}
other := val.Interface()
if query.reverse {
value, other = other, value
}
cmp, cerr := compare(value, other)
if cerr != nil {
// if for some reason there is an error on compare, fallback to a lexicographic compare
valS := fmt.Sprintf("%s", value)
otherS := fmt.Sprintf("%s", other)
if valS < otherS {
return true
} else if valS == otherS {
continue
}
return false
}
if cmp == -1 {
return true
} else if cmp == 0 {
continue
}
return false
}
return false
})
// apply skip and limit
limit := query.limit
skip := query.skip
if skip > len(records) {
records = records[0:0]
} else {
records = records[skip:]
}
if limit > 0 && limit <= len(records) {
records = records[:limit]
}
for i := range records {
err = action(records[i])
if err != nil {
return err
}
}
return nil
} | go | func runQuerySort(tx *bolt.Tx, dataType interface{}, query *Query, action func(r *record) error) error {
// Validate sort fields
for _, field := range query.sort {
fields := strings.Split(field, ".")
current := query.dataType
for i := range fields {
var structField reflect.StructField
found := false
if current.Kind() == reflect.Ptr {
structField, found = current.Elem().FieldByName(fields[i])
} else {
structField, found = current.FieldByName(fields[i])
}
if !found {
return fmt.Errorf("The field %s does not exist in the type %s", field, query.dataType)
}
current = structField.Type
}
}
// Run query without sort, skip or limit
// apply sort, skip and limit to entire dataset
qCopy := *query
qCopy.sort = nil
qCopy.limit = 0
qCopy.skip = 0
var records []*record
err := runQuery(tx, dataType, &qCopy, nil, 0,
func(r *record) error {
records = append(records, r)
return nil
})
if err != nil {
return err
}
sort.Slice(records, func(i, j int) bool {
for _, field := range query.sort {
val, err := fieldValue(records[i].value.Elem(), field)
if err != nil {
panic(err.Error()) // shouldn't happen due to field check above
}
value := val.Interface()
val, err = fieldValue(records[j].value.Elem(), field)
if err != nil {
panic(err.Error()) // shouldn't happen due to field check above
}
other := val.Interface()
if query.reverse {
value, other = other, value
}
cmp, cerr := compare(value, other)
if cerr != nil {
// if for some reason there is an error on compare, fallback to a lexicographic compare
valS := fmt.Sprintf("%s", value)
otherS := fmt.Sprintf("%s", other)
if valS < otherS {
return true
} else if valS == otherS {
continue
}
return false
}
if cmp == -1 {
return true
} else if cmp == 0 {
continue
}
return false
}
return false
})
// apply skip and limit
limit := query.limit
skip := query.skip
if skip > len(records) {
records = records[0:0]
} else {
records = records[skip:]
}
if limit > 0 && limit <= len(records) {
records = records[:limit]
}
for i := range records {
err = action(records[i])
if err != nil {
return err
}
}
return nil
} | [
"func",
"runQuerySort",
"(",
"tx",
"*",
"bolt",
".",
"Tx",
",",
"dataType",
"interface",
"{",
"}",
",",
"query",
"*",
"Query",
",",
"action",
"func",
"(",
"r",
"*",
"record",
")",
"error",
")",
"error",
"{",
"// Validate sort fields",
"for",
"_",
",",
"field",
":=",
"range",
"query",
".",
"sort",
"{",
"fields",
":=",
"strings",
".",
"Split",
"(",
"field",
",",
"\"",
"\"",
")",
"\n\n",
"current",
":=",
"query",
".",
"dataType",
"\n",
"for",
"i",
":=",
"range",
"fields",
"{",
"var",
"structField",
"reflect",
".",
"StructField",
"\n",
"found",
":=",
"false",
"\n",
"if",
"current",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Ptr",
"{",
"structField",
",",
"found",
"=",
"current",
".",
"Elem",
"(",
")",
".",
"FieldByName",
"(",
"fields",
"[",
"i",
"]",
")",
"\n",
"}",
"else",
"{",
"structField",
",",
"found",
"=",
"current",
".",
"FieldByName",
"(",
"fields",
"[",
"i",
"]",
")",
"\n",
"}",
"\n\n",
"if",
"!",
"found",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"field",
",",
"query",
".",
"dataType",
")",
"\n",
"}",
"\n",
"current",
"=",
"structField",
".",
"Type",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Run query without sort, skip or limit",
"// apply sort, skip and limit to entire dataset",
"qCopy",
":=",
"*",
"query",
"\n",
"qCopy",
".",
"sort",
"=",
"nil",
"\n",
"qCopy",
".",
"limit",
"=",
"0",
"\n",
"qCopy",
".",
"skip",
"=",
"0",
"\n\n",
"var",
"records",
"[",
"]",
"*",
"record",
"\n",
"err",
":=",
"runQuery",
"(",
"tx",
",",
"dataType",
",",
"&",
"qCopy",
",",
"nil",
",",
"0",
",",
"func",
"(",
"r",
"*",
"record",
")",
"error",
"{",
"records",
"=",
"append",
"(",
"records",
",",
"r",
")",
"\n\n",
"return",
"nil",
"\n",
"}",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"sort",
".",
"Slice",
"(",
"records",
",",
"func",
"(",
"i",
",",
"j",
"int",
")",
"bool",
"{",
"for",
"_",
",",
"field",
":=",
"range",
"query",
".",
"sort",
"{",
"val",
",",
"err",
":=",
"fieldValue",
"(",
"records",
"[",
"i",
"]",
".",
"value",
".",
"Elem",
"(",
")",
",",
"field",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
".",
"Error",
"(",
")",
")",
"// shouldn't happen due to field check above",
"\n",
"}",
"\n",
"value",
":=",
"val",
".",
"Interface",
"(",
")",
"\n\n",
"val",
",",
"err",
"=",
"fieldValue",
"(",
"records",
"[",
"j",
"]",
".",
"value",
".",
"Elem",
"(",
")",
",",
"field",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
".",
"Error",
"(",
")",
")",
"// shouldn't happen due to field check above",
"\n",
"}",
"\n\n",
"other",
":=",
"val",
".",
"Interface",
"(",
")",
"\n\n",
"if",
"query",
".",
"reverse",
"{",
"value",
",",
"other",
"=",
"other",
",",
"value",
"\n",
"}",
"\n\n",
"cmp",
",",
"cerr",
":=",
"compare",
"(",
"value",
",",
"other",
")",
"\n",
"if",
"cerr",
"!=",
"nil",
"{",
"// if for some reason there is an error on compare, fallback to a lexicographic compare",
"valS",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"value",
")",
"\n",
"otherS",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"other",
")",
"\n",
"if",
"valS",
"<",
"otherS",
"{",
"return",
"true",
"\n",
"}",
"else",
"if",
"valS",
"==",
"otherS",
"{",
"continue",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}",
"\n\n",
"if",
"cmp",
"==",
"-",
"1",
"{",
"return",
"true",
"\n",
"}",
"else",
"if",
"cmp",
"==",
"0",
"{",
"continue",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}",
")",
"\n\n",
"// apply skip and limit",
"limit",
":=",
"query",
".",
"limit",
"\n",
"skip",
":=",
"query",
".",
"skip",
"\n\n",
"if",
"skip",
">",
"len",
"(",
"records",
")",
"{",
"records",
"=",
"records",
"[",
"0",
":",
"0",
"]",
"\n",
"}",
"else",
"{",
"records",
"=",
"records",
"[",
"skip",
":",
"]",
"\n",
"}",
"\n\n",
"if",
"limit",
">",
"0",
"&&",
"limit",
"<=",
"len",
"(",
"records",
")",
"{",
"records",
"=",
"records",
"[",
":",
"limit",
"]",
"\n",
"}",
"\n\n",
"for",
"i",
":=",
"range",
"records",
"{",
"err",
"=",
"action",
"(",
"records",
"[",
"i",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n\n",
"}"
] | // runQuerySort runs the query without sort, skip, or limit, then applies them to the entire result set | [
"runQuerySort",
"runs",
"the",
"query",
"without",
"sort",
"skip",
"or",
"limit",
"then",
"applies",
"them",
"to",
"the",
"entire",
"result",
"set"
] | train | https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/query.go#L636-L742 |
timshannon/bolthold | aggregate.go | Group | func (a *AggregateResult) Group(result ...interface{}) {
for i := range result {
resultVal := reflect.ValueOf(result[i])
if resultVal.Kind() != reflect.Ptr {
panic("result argument must be an address")
}
if i >= len(a.group) {
panic(fmt.Sprintf("There is not %d elements in the grouping", i))
}
resultVal.Elem().Set(a.group[i])
}
} | go | func (a *AggregateResult) Group(result ...interface{}) {
for i := range result {
resultVal := reflect.ValueOf(result[i])
if resultVal.Kind() != reflect.Ptr {
panic("result argument must be an address")
}
if i >= len(a.group) {
panic(fmt.Sprintf("There is not %d elements in the grouping", i))
}
resultVal.Elem().Set(a.group[i])
}
} | [
"func",
"(",
"a",
"*",
"AggregateResult",
")",
"Group",
"(",
"result",
"...",
"interface",
"{",
"}",
")",
"{",
"for",
"i",
":=",
"range",
"result",
"{",
"resultVal",
":=",
"reflect",
".",
"ValueOf",
"(",
"result",
"[",
"i",
"]",
")",
"\n",
"if",
"resultVal",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Ptr",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"i",
">=",
"len",
"(",
"a",
".",
"group",
")",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"i",
")",
")",
"\n",
"}",
"\n\n",
"resultVal",
".",
"Elem",
"(",
")",
".",
"Set",
"(",
"a",
".",
"group",
"[",
"i",
"]",
")",
"\n",
"}",
"\n",
"}"
] | // Group returns the field grouped by in the query | [
"Group",
"returns",
"the",
"field",
"grouped",
"by",
"in",
"the",
"query"
] | train | https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/aggregate.go#L23-L36 |
timshannon/bolthold | aggregate.go | Reduction | func (a *AggregateResult) Reduction(result interface{}) {
resultVal := reflect.ValueOf(result)
if resultVal.Kind() != reflect.Ptr || resultVal.Elem().Kind() != reflect.Slice {
panic("result argument must be a slice address")
}
sliceVal := resultVal.Elem()
elType := sliceVal.Type().Elem()
for i := range a.reduction {
if elType.Kind() == reflect.Ptr {
sliceVal = reflect.Append(sliceVal, a.reduction[i])
} else {
sliceVal = reflect.Append(sliceVal, a.reduction[i].Elem())
}
}
resultVal.Elem().Set(sliceVal.Slice(0, sliceVal.Len()))
} | go | func (a *AggregateResult) Reduction(result interface{}) {
resultVal := reflect.ValueOf(result)
if resultVal.Kind() != reflect.Ptr || resultVal.Elem().Kind() != reflect.Slice {
panic("result argument must be a slice address")
}
sliceVal := resultVal.Elem()
elType := sliceVal.Type().Elem()
for i := range a.reduction {
if elType.Kind() == reflect.Ptr {
sliceVal = reflect.Append(sliceVal, a.reduction[i])
} else {
sliceVal = reflect.Append(sliceVal, a.reduction[i].Elem())
}
}
resultVal.Elem().Set(sliceVal.Slice(0, sliceVal.Len()))
} | [
"func",
"(",
"a",
"*",
"AggregateResult",
")",
"Reduction",
"(",
"result",
"interface",
"{",
"}",
")",
"{",
"resultVal",
":=",
"reflect",
".",
"ValueOf",
"(",
"result",
")",
"\n\n",
"if",
"resultVal",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Ptr",
"||",
"resultVal",
".",
"Elem",
"(",
")",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Slice",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"sliceVal",
":=",
"resultVal",
".",
"Elem",
"(",
")",
"\n\n",
"elType",
":=",
"sliceVal",
".",
"Type",
"(",
")",
".",
"Elem",
"(",
")",
"\n\n",
"for",
"i",
":=",
"range",
"a",
".",
"reduction",
"{",
"if",
"elType",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Ptr",
"{",
"sliceVal",
"=",
"reflect",
".",
"Append",
"(",
"sliceVal",
",",
"a",
".",
"reduction",
"[",
"i",
"]",
")",
"\n",
"}",
"else",
"{",
"sliceVal",
"=",
"reflect",
".",
"Append",
"(",
"sliceVal",
",",
"a",
".",
"reduction",
"[",
"i",
"]",
".",
"Elem",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"resultVal",
".",
"Elem",
"(",
")",
".",
"Set",
"(",
"sliceVal",
".",
"Slice",
"(",
"0",
",",
"sliceVal",
".",
"Len",
"(",
")",
")",
")",
"\n",
"}"
] | // Reduction is the collection of records that are part of the AggregateResult Group | [
"Reduction",
"is",
"the",
"collection",
"of",
"records",
"that",
"are",
"part",
"of",
"the",
"AggregateResult",
"Group"
] | train | https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/aggregate.go#L39-L59 |
timshannon/bolthold | aggregate.go | Sort | func (a *AggregateResult) Sort(field string) {
if !startsUpper(field) {
panic("The first letter of a field must be upper-case")
}
if a.sortby == field {
// already sorted
return
}
a.sortby = field
sort.Sort((*aggregateResultSort)(a))
} | go | func (a *AggregateResult) Sort(field string) {
if !startsUpper(field) {
panic("The first letter of a field must be upper-case")
}
if a.sortby == field {
// already sorted
return
}
a.sortby = field
sort.Sort((*aggregateResultSort)(a))
} | [
"func",
"(",
"a",
"*",
"AggregateResult",
")",
"Sort",
"(",
"field",
"string",
")",
"{",
"if",
"!",
"startsUpper",
"(",
"field",
")",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"a",
".",
"sortby",
"==",
"field",
"{",
"// already sorted",
"return",
"\n",
"}",
"\n\n",
"a",
".",
"sortby",
"=",
"field",
"\n",
"sort",
".",
"Sort",
"(",
"(",
"*",
"aggregateResultSort",
")",
"(",
"a",
")",
")",
"\n",
"}"
] | // Sort sorts the aggregate reduction by the passed in field in ascending order
// Sort is called automatically by calls to Min / Max to get the min and max values | [
"Sort",
"sorts",
"the",
"aggregate",
"reduction",
"by",
"the",
"passed",
"in",
"field",
"in",
"ascending",
"order",
"Sort",
"is",
"called",
"automatically",
"by",
"calls",
"to",
"Min",
"/",
"Max",
"to",
"get",
"the",
"min",
"and",
"max",
"values"
] | train | https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/aggregate.go#L89-L100 |
timshannon/bolthold | aggregate.go | Max | func (a *AggregateResult) Max(field string, result interface{}) {
a.Sort(field)
resultVal := reflect.ValueOf(result)
if resultVal.Kind() != reflect.Ptr {
panic("result argument must be an address")
}
if resultVal.IsNil() {
panic("result argument must not be nil")
}
resultVal.Elem().Set(a.reduction[len(a.reduction)-1].Elem())
} | go | func (a *AggregateResult) Max(field string, result interface{}) {
a.Sort(field)
resultVal := reflect.ValueOf(result)
if resultVal.Kind() != reflect.Ptr {
panic("result argument must be an address")
}
if resultVal.IsNil() {
panic("result argument must not be nil")
}
resultVal.Elem().Set(a.reduction[len(a.reduction)-1].Elem())
} | [
"func",
"(",
"a",
"*",
"AggregateResult",
")",
"Max",
"(",
"field",
"string",
",",
"result",
"interface",
"{",
"}",
")",
"{",
"a",
".",
"Sort",
"(",
"field",
")",
"\n\n",
"resultVal",
":=",
"reflect",
".",
"ValueOf",
"(",
"result",
")",
"\n",
"if",
"resultVal",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Ptr",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"resultVal",
".",
"IsNil",
"(",
")",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"resultVal",
".",
"Elem",
"(",
")",
".",
"Set",
"(",
"a",
".",
"reduction",
"[",
"len",
"(",
"a",
".",
"reduction",
")",
"-",
"1",
"]",
".",
"Elem",
"(",
")",
")",
"\n",
"}"
] | // Max Returns the maxiumum value of the Aggregate Grouping, uses the Comparer interface | [
"Max",
"Returns",
"the",
"maxiumum",
"value",
"of",
"the",
"Aggregate",
"Grouping",
"uses",
"the",
"Comparer",
"interface"
] | train | https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/aggregate.go#L103-L116 |
timshannon/bolthold | aggregate.go | Avg | func (a *AggregateResult) Avg(field string) float64 {
sum := a.Sum(field)
return sum / float64(len(a.reduction))
} | go | func (a *AggregateResult) Avg(field string) float64 {
sum := a.Sum(field)
return sum / float64(len(a.reduction))
} | [
"func",
"(",
"a",
"*",
"AggregateResult",
")",
"Avg",
"(",
"field",
"string",
")",
"float64",
"{",
"sum",
":=",
"a",
".",
"Sum",
"(",
"field",
")",
"\n",
"return",
"sum",
"/",
"float64",
"(",
"len",
"(",
"a",
".",
"reduction",
")",
")",
"\n",
"}"
] | // Avg returns the average float value of the aggregate grouping
// panics if the field cannot be converted to an float64 | [
"Avg",
"returns",
"the",
"average",
"float",
"value",
"of",
"the",
"aggregate",
"grouping",
"panics",
"if",
"the",
"field",
"cannot",
"be",
"converted",
"to",
"an",
"float64"
] | train | https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/aggregate.go#L136-L139 |
timshannon/bolthold | aggregate.go | Sum | func (a *AggregateResult) Sum(field string) float64 {
var sum float64
for i := range a.reduction {
fVal := a.reduction[i].Elem().FieldByName(field)
if !fVal.IsValid() {
panic(fmt.Sprintf("The field %s does not exist in the type %s", field, a.reduction[i].Type()))
}
sum += tryFloat(fVal)
}
return sum
} | go | func (a *AggregateResult) Sum(field string) float64 {
var sum float64
for i := range a.reduction {
fVal := a.reduction[i].Elem().FieldByName(field)
if !fVal.IsValid() {
panic(fmt.Sprintf("The field %s does not exist in the type %s", field, a.reduction[i].Type()))
}
sum += tryFloat(fVal)
}
return sum
} | [
"func",
"(",
"a",
"*",
"AggregateResult",
")",
"Sum",
"(",
"field",
"string",
")",
"float64",
"{",
"var",
"sum",
"float64",
"\n\n",
"for",
"i",
":=",
"range",
"a",
".",
"reduction",
"{",
"fVal",
":=",
"a",
".",
"reduction",
"[",
"i",
"]",
".",
"Elem",
"(",
")",
".",
"FieldByName",
"(",
"field",
")",
"\n",
"if",
"!",
"fVal",
".",
"IsValid",
"(",
")",
"{",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"field",
",",
"a",
".",
"reduction",
"[",
"i",
"]",
".",
"Type",
"(",
")",
")",
")",
"\n",
"}",
"\n\n",
"sum",
"+=",
"tryFloat",
"(",
"fVal",
")",
"\n",
"}",
"\n\n",
"return",
"sum",
"\n",
"}"
] | // Sum returns the sum value of the aggregate grouping
// panics if the field cannot be converted to an float64 | [
"Sum",
"returns",
"the",
"sum",
"value",
"of",
"the",
"aggregate",
"grouping",
"panics",
"if",
"the",
"field",
"cannot",
"be",
"converted",
"to",
"an",
"float64"
] | train | https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/aggregate.go#L143-L156 |
timshannon/bolthold | aggregate.go | FindAggregate | func (s *Store) FindAggregate(dataType interface{}, query *Query, groupBy ...string) ([]*AggregateResult, error) {
var result []*AggregateResult
var err error
err = s.Bolt().View(func(tx *bolt.Tx) error {
result, err = s.TxFindAggregate(tx, dataType, query, groupBy...)
return err
})
if err != nil {
return nil, err
}
return result, nil
} | go | func (s *Store) FindAggregate(dataType interface{}, query *Query, groupBy ...string) ([]*AggregateResult, error) {
var result []*AggregateResult
var err error
err = s.Bolt().View(func(tx *bolt.Tx) error {
result, err = s.TxFindAggregate(tx, dataType, query, groupBy...)
return err
})
if err != nil {
return nil, err
}
return result, nil
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"FindAggregate",
"(",
"dataType",
"interface",
"{",
"}",
",",
"query",
"*",
"Query",
",",
"groupBy",
"...",
"string",
")",
"(",
"[",
"]",
"*",
"AggregateResult",
",",
"error",
")",
"{",
"var",
"result",
"[",
"]",
"*",
"AggregateResult",
"\n",
"var",
"err",
"error",
"\n",
"err",
"=",
"s",
".",
"Bolt",
"(",
")",
".",
"View",
"(",
"func",
"(",
"tx",
"*",
"bolt",
".",
"Tx",
")",
"error",
"{",
"result",
",",
"err",
"=",
"s",
".",
"TxFindAggregate",
"(",
"tx",
",",
"dataType",
",",
"query",
",",
"groupBy",
"...",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // FindAggregate returns an aggregate grouping for the passed in query
// groupBy is optional | [
"FindAggregate",
"returns",
"an",
"aggregate",
"grouping",
"for",
"the",
"passed",
"in",
"query",
"groupBy",
"is",
"optional"
] | train | https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/aggregate.go#L165-L178 |
timshannon/bolthold | aggregate.go | TxFindAggregate | func (s *Store) TxFindAggregate(tx *bolt.Tx, dataType interface{}, query *Query, groupBy ...string) ([]*AggregateResult, error) {
return aggregateQuery(tx, dataType, query, groupBy...)
} | go | func (s *Store) TxFindAggregate(tx *bolt.Tx, dataType interface{}, query *Query, groupBy ...string) ([]*AggregateResult, error) {
return aggregateQuery(tx, dataType, query, groupBy...)
} | [
"func",
"(",
"s",
"*",
"Store",
")",
"TxFindAggregate",
"(",
"tx",
"*",
"bolt",
".",
"Tx",
",",
"dataType",
"interface",
"{",
"}",
",",
"query",
"*",
"Query",
",",
"groupBy",
"...",
"string",
")",
"(",
"[",
"]",
"*",
"AggregateResult",
",",
"error",
")",
"{",
"return",
"aggregateQuery",
"(",
"tx",
",",
"dataType",
",",
"query",
",",
"groupBy",
"...",
")",
"\n",
"}"
] | // TxFindAggregate is the same as FindAggregate, but you specify your own transaction
// groupBy is optional | [
"TxFindAggregate",
"is",
"the",
"same",
"as",
"FindAggregate",
"but",
"you",
"specify",
"your",
"own",
"transaction",
"groupBy",
"is",
"optional"
] | train | https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/aggregate.go#L182-L184 |
timshannon/bolthold | encode.go | DefaultEncode | func DefaultEncode(value interface{}) ([]byte, error) {
var buff bytes.Buffer
en := gob.NewEncoder(&buff)
err := en.Encode(value)
if err != nil {
return nil, err
}
return buff.Bytes(), nil
} | go | func DefaultEncode(value interface{}) ([]byte, error) {
var buff bytes.Buffer
en := gob.NewEncoder(&buff)
err := en.Encode(value)
if err != nil {
return nil, err
}
return buff.Bytes(), nil
} | [
"func",
"DefaultEncode",
"(",
"value",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"buff",
"bytes",
".",
"Buffer",
"\n\n",
"en",
":=",
"gob",
".",
"NewEncoder",
"(",
"&",
"buff",
")",
"\n\n",
"err",
":=",
"en",
".",
"Encode",
"(",
"value",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"buff",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"}"
] | // DefaultEncode is the default encoding func for bolthold (Gob) | [
"DefaultEncode",
"is",
"the",
"default",
"encoding",
"func",
"for",
"bolthold",
"(",
"Gob",
")"
] | train | https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/encode.go#L22-L33 |
timshannon/bolthold | encode.go | DefaultDecode | func DefaultDecode(data []byte, value interface{}) error {
var buff bytes.Buffer
de := gob.NewDecoder(&buff)
_, err := buff.Write(data)
if err != nil {
return err
}
return de.Decode(value)
} | go | func DefaultDecode(data []byte, value interface{}) error {
var buff bytes.Buffer
de := gob.NewDecoder(&buff)
_, err := buff.Write(data)
if err != nil {
return err
}
return de.Decode(value)
} | [
"func",
"DefaultDecode",
"(",
"data",
"[",
"]",
"byte",
",",
"value",
"interface",
"{",
"}",
")",
"error",
"{",
"var",
"buff",
"bytes",
".",
"Buffer",
"\n",
"de",
":=",
"gob",
".",
"NewDecoder",
"(",
"&",
"buff",
")",
"\n\n",
"_",
",",
"err",
":=",
"buff",
".",
"Write",
"(",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"de",
".",
"Decode",
"(",
"value",
")",
"\n",
"}"
] | // DefaultDecode is the default decoding func for bolthold (Gob) | [
"DefaultDecode",
"is",
"the",
"default",
"decoding",
"func",
"for",
"bolthold",
"(",
"Gob",
")"
] | train | https://github.com/timshannon/bolthold/blob/eed35b7556710c9108bd536193dae1ecb91f16fa/encode.go#L36-L46 |
tkanos/gonfig | gonfig.go | GetConf | func GetConf(filename string, configuration interface{}) (err error) {
configValue := reflect.ValueOf(configuration)
if typ := configValue.Type(); typ.Kind() != reflect.Ptr || typ.Elem().Kind() != reflect.Struct {
return fmt.Errorf("configuration should be a pointer to a struct type")
}
err = getFromYAML(filename, configuration)
if err == nil {
getFromEnvVariables(configuration)
}
return
} | go | func GetConf(filename string, configuration interface{}) (err error) {
configValue := reflect.ValueOf(configuration)
if typ := configValue.Type(); typ.Kind() != reflect.Ptr || typ.Elem().Kind() != reflect.Struct {
return fmt.Errorf("configuration should be a pointer to a struct type")
}
err = getFromYAML(filename, configuration)
if err == nil {
getFromEnvVariables(configuration)
}
return
} | [
"func",
"GetConf",
"(",
"filename",
"string",
",",
"configuration",
"interface",
"{",
"}",
")",
"(",
"err",
"error",
")",
"{",
"configValue",
":=",
"reflect",
".",
"ValueOf",
"(",
"configuration",
")",
"\n",
"if",
"typ",
":=",
"configValue",
".",
"Type",
"(",
")",
";",
"typ",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Ptr",
"||",
"typ",
".",
"Elem",
"(",
")",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Struct",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"err",
"=",
"getFromYAML",
"(",
"filename",
",",
"configuration",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"getFromEnvVariables",
"(",
"configuration",
")",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // GetConf aggregates all the JSON and enviornment variable values
// and puts them into the passed interface. | [
"GetConf",
"aggregates",
"all",
"the",
"JSON",
"and",
"enviornment",
"variable",
"values",
"and",
"puts",
"them",
"into",
"the",
"passed",
"interface",
"."
] | train | https://github.com/tkanos/gonfig/blob/896f3d81fadfe082262467a1c22fd43278806a02/gonfig.go#L21-L34 |
appc/spec | schema/types/semver.go | NewSemVer | func NewSemVer(s string) (*SemVer, error) {
nsv, err := semver.NewVersion(s)
if err != nil {
return nil, ErrBadSemVer
}
v := SemVer(*nsv)
if v.Empty() {
return nil, ErrNoZeroSemVer
}
return &v, nil
} | go | func NewSemVer(s string) (*SemVer, error) {
nsv, err := semver.NewVersion(s)
if err != nil {
return nil, ErrBadSemVer
}
v := SemVer(*nsv)
if v.Empty() {
return nil, ErrNoZeroSemVer
}
return &v, nil
} | [
"func",
"NewSemVer",
"(",
"s",
"string",
")",
"(",
"*",
"SemVer",
",",
"error",
")",
"{",
"nsv",
",",
"err",
":=",
"semver",
".",
"NewVersion",
"(",
"s",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"ErrBadSemVer",
"\n",
"}",
"\n",
"v",
":=",
"SemVer",
"(",
"*",
"nsv",
")",
"\n",
"if",
"v",
".",
"Empty",
"(",
")",
"{",
"return",
"nil",
",",
"ErrNoZeroSemVer",
"\n",
"}",
"\n",
"return",
"&",
"v",
",",
"nil",
"\n",
"}"
] | // NewSemVer generates a new SemVer from a string. If the given string does
// not represent a valid SemVer, nil and an error are returned. | [
"NewSemVer",
"generates",
"a",
"new",
"SemVer",
"from",
"a",
"string",
".",
"If",
"the",
"given",
"string",
"does",
"not",
"represent",
"a",
"valid",
"SemVer",
"nil",
"and",
"an",
"error",
"are",
"returned",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/semver.go#L35-L45 |
appc/spec | schema/types/semver.go | UnmarshalJSON | func (sv *SemVer) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
v, err := NewSemVer(s)
if err != nil {
return err
}
*sv = *v
return nil
} | go | func (sv *SemVer) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
v, err := NewSemVer(s)
if err != nil {
return err
}
*sv = *v
return nil
} | [
"func",
"(",
"sv",
"*",
"SemVer",
")",
"UnmarshalJSON",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"var",
"s",
"string",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"&",
"s",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"v",
",",
"err",
":=",
"NewSemVer",
"(",
"s",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"*",
"sv",
"=",
"*",
"v",
"\n",
"return",
"nil",
"\n",
"}"
] | // UnmarshalJSON implements the json.Unmarshaler interface | [
"UnmarshalJSON",
"implements",
"the",
"json",
".",
"Unmarshaler",
"interface"
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/semver.go#L72-L83 |
appc/spec | schema/types/semver.go | MarshalJSON | func (sv SemVer) MarshalJSON() ([]byte, error) {
if sv.Empty() {
return nil, ErrNoZeroSemVer
}
return json.Marshal(sv.String())
} | go | func (sv SemVer) MarshalJSON() ([]byte, error) {
if sv.Empty() {
return nil, ErrNoZeroSemVer
}
return json.Marshal(sv.String())
} | [
"func",
"(",
"sv",
"SemVer",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"sv",
".",
"Empty",
"(",
")",
"{",
"return",
"nil",
",",
"ErrNoZeroSemVer",
"\n",
"}",
"\n",
"return",
"json",
".",
"Marshal",
"(",
"sv",
".",
"String",
"(",
")",
")",
"\n",
"}"
] | // MarshalJSON implements the json.Marshaler interface | [
"MarshalJSON",
"implements",
"the",
"json",
".",
"Marshaler",
"interface"
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/semver.go#L86-L91 |
appc/spec | actool/manifest.go | parseSeccompArgs | func parseSeccompArgs(patchSeccompMode string, patchSeccompSet string) (*types.Isolator, error) {
// Parse mode flag and additional keyed arguments.
var errno, mode string
args := strings.Split(patchSeccompMode, ",")
for _, a := range args {
kv := strings.Split(a, "=")
switch len(kv) {
case 1:
// mode, either "remove" or "retain"
mode = kv[0]
case 2:
// k=v argument, only "errno" allowed for now
if kv[0] == "errno" {
errno = kv[1]
} else {
return nil, fmt.Errorf("invalid seccomp-mode optional argument: %s", a)
}
default:
return nil, fmt.Errorf("cannot parse seccomp-mode argument: %s", a)
}
}
// Instantiate an Isolator with the content specified by the --seccomp-set parameter.
var err error
var seccomp types.AsIsolator
switch mode {
case "remove":
seccomp, err = types.NewLinuxSeccompRemoveSet(errno, strings.Split(patchSeccompSet, ",")...)
case "retain":
seccomp, err = types.NewLinuxSeccompRetainSet(errno, strings.Split(patchSeccompSet, ",")...)
default:
err = fmt.Errorf("unknown seccomp mode %s", mode)
}
if err != nil {
return nil, fmt.Errorf("cannot parse seccomp isolator: %s", err)
}
seccompIsolator, err := seccomp.AsIsolator()
if err != nil {
return nil, err
}
return seccompIsolator, nil
} | go | func parseSeccompArgs(patchSeccompMode string, patchSeccompSet string) (*types.Isolator, error) {
// Parse mode flag and additional keyed arguments.
var errno, mode string
args := strings.Split(patchSeccompMode, ",")
for _, a := range args {
kv := strings.Split(a, "=")
switch len(kv) {
case 1:
// mode, either "remove" or "retain"
mode = kv[0]
case 2:
// k=v argument, only "errno" allowed for now
if kv[0] == "errno" {
errno = kv[1]
} else {
return nil, fmt.Errorf("invalid seccomp-mode optional argument: %s", a)
}
default:
return nil, fmt.Errorf("cannot parse seccomp-mode argument: %s", a)
}
}
// Instantiate an Isolator with the content specified by the --seccomp-set parameter.
var err error
var seccomp types.AsIsolator
switch mode {
case "remove":
seccomp, err = types.NewLinuxSeccompRemoveSet(errno, strings.Split(patchSeccompSet, ",")...)
case "retain":
seccomp, err = types.NewLinuxSeccompRetainSet(errno, strings.Split(patchSeccompSet, ",")...)
default:
err = fmt.Errorf("unknown seccomp mode %s", mode)
}
if err != nil {
return nil, fmt.Errorf("cannot parse seccomp isolator: %s", err)
}
seccompIsolator, err := seccomp.AsIsolator()
if err != nil {
return nil, err
}
return seccompIsolator, nil
} | [
"func",
"parseSeccompArgs",
"(",
"patchSeccompMode",
"string",
",",
"patchSeccompSet",
"string",
")",
"(",
"*",
"types",
".",
"Isolator",
",",
"error",
")",
"{",
"// Parse mode flag and additional keyed arguments.",
"var",
"errno",
",",
"mode",
"string",
"\n",
"args",
":=",
"strings",
".",
"Split",
"(",
"patchSeccompMode",
",",
"\"",
"\"",
")",
"\n",
"for",
"_",
",",
"a",
":=",
"range",
"args",
"{",
"kv",
":=",
"strings",
".",
"Split",
"(",
"a",
",",
"\"",
"\"",
")",
"\n",
"switch",
"len",
"(",
"kv",
")",
"{",
"case",
"1",
":",
"// mode, either \"remove\" or \"retain\"",
"mode",
"=",
"kv",
"[",
"0",
"]",
"\n",
"case",
"2",
":",
"// k=v argument, only \"errno\" allowed for now",
"if",
"kv",
"[",
"0",
"]",
"==",
"\"",
"\"",
"{",
"errno",
"=",
"kv",
"[",
"1",
"]",
"\n",
"}",
"else",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"a",
")",
"\n",
"}",
"\n",
"default",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"a",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Instantiate an Isolator with the content specified by the --seccomp-set parameter.",
"var",
"err",
"error",
"\n",
"var",
"seccomp",
"types",
".",
"AsIsolator",
"\n",
"switch",
"mode",
"{",
"case",
"\"",
"\"",
":",
"seccomp",
",",
"err",
"=",
"types",
".",
"NewLinuxSeccompRemoveSet",
"(",
"errno",
",",
"strings",
".",
"Split",
"(",
"patchSeccompSet",
",",
"\"",
"\"",
")",
"...",
")",
"\n",
"case",
"\"",
"\"",
":",
"seccomp",
",",
"err",
"=",
"types",
".",
"NewLinuxSeccompRetainSet",
"(",
"errno",
",",
"strings",
".",
"Split",
"(",
"patchSeccompSet",
",",
"\"",
"\"",
")",
"...",
")",
"\n",
"default",
":",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"mode",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"seccompIsolator",
",",
"err",
":=",
"seccomp",
".",
"AsIsolator",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"seccompIsolator",
",",
"nil",
"\n",
"}"
] | // parseSeccompArgs parses seccomp mode and set CLI flags, preparing an
// appropriate seccomp isolator. | [
"parseSeccompArgs",
"parses",
"seccomp",
"mode",
"and",
"set",
"CLI",
"flags",
"preparing",
"an",
"appropriate",
"seccomp",
"isolator",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/actool/manifest.go#L309-L350 |
appc/spec | actool/manifest.go | extractManifest | func extractManifest(tr *tar.Reader, tw *tar.Writer, printManifest bool, newManifest []byte) error {
Tar:
for {
hdr, err := tr.Next()
switch err {
case io.EOF:
break Tar
case nil:
if filepath.Clean(hdr.Name) == aci.ManifestFile {
var new_bytes []byte
bytes, err := ioutil.ReadAll(tr)
if err != nil {
return err
}
if printManifest && !catPrettyPrint {
fmt.Println(string(bytes))
}
im := &schema.ImageManifest{}
err = im.UnmarshalJSON(bytes)
if err != nil {
return err
}
if printManifest && catPrettyPrint {
output, err := json.MarshalIndent(im, "", " ")
if err != nil {
return err
}
fmt.Println(string(output))
}
if tw == nil {
return nil
}
if len(newManifest) == 0 {
err = patchManifest(im)
if err != nil {
return err
}
new_bytes, err = im.MarshalJSON()
if err != nil {
return err
}
} else {
new_bytes = newManifest
}
hdr.Size = int64(len(new_bytes))
err = tw.WriteHeader(hdr)
if err != nil {
return err
}
_, err = tw.Write(new_bytes)
if err != nil {
return err
}
} else if tw != nil {
err := tw.WriteHeader(hdr)
if err != nil {
return err
}
_, err = io.Copy(tw, tr)
if err != nil {
return err
}
}
default:
return fmt.Errorf("error reading tarball: %v", err)
}
}
return nil
} | go | func extractManifest(tr *tar.Reader, tw *tar.Writer, printManifest bool, newManifest []byte) error {
Tar:
for {
hdr, err := tr.Next()
switch err {
case io.EOF:
break Tar
case nil:
if filepath.Clean(hdr.Name) == aci.ManifestFile {
var new_bytes []byte
bytes, err := ioutil.ReadAll(tr)
if err != nil {
return err
}
if printManifest && !catPrettyPrint {
fmt.Println(string(bytes))
}
im := &schema.ImageManifest{}
err = im.UnmarshalJSON(bytes)
if err != nil {
return err
}
if printManifest && catPrettyPrint {
output, err := json.MarshalIndent(im, "", " ")
if err != nil {
return err
}
fmt.Println(string(output))
}
if tw == nil {
return nil
}
if len(newManifest) == 0 {
err = patchManifest(im)
if err != nil {
return err
}
new_bytes, err = im.MarshalJSON()
if err != nil {
return err
}
} else {
new_bytes = newManifest
}
hdr.Size = int64(len(new_bytes))
err = tw.WriteHeader(hdr)
if err != nil {
return err
}
_, err = tw.Write(new_bytes)
if err != nil {
return err
}
} else if tw != nil {
err := tw.WriteHeader(hdr)
if err != nil {
return err
}
_, err = io.Copy(tw, tr)
if err != nil {
return err
}
}
default:
return fmt.Errorf("error reading tarball: %v", err)
}
}
return nil
} | [
"func",
"extractManifest",
"(",
"tr",
"*",
"tar",
".",
"Reader",
",",
"tw",
"*",
"tar",
".",
"Writer",
",",
"printManifest",
"bool",
",",
"newManifest",
"[",
"]",
"byte",
")",
"error",
"{",
"Tar",
":",
"for",
"{",
"hdr",
",",
"err",
":=",
"tr",
".",
"Next",
"(",
")",
"\n",
"switch",
"err",
"{",
"case",
"io",
".",
"EOF",
":",
"break",
"Tar",
"\n",
"case",
"nil",
":",
"if",
"filepath",
".",
"Clean",
"(",
"hdr",
".",
"Name",
")",
"==",
"aci",
".",
"ManifestFile",
"{",
"var",
"new_bytes",
"[",
"]",
"byte",
"\n\n",
"bytes",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"tr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"printManifest",
"&&",
"!",
"catPrettyPrint",
"{",
"fmt",
".",
"Println",
"(",
"string",
"(",
"bytes",
")",
")",
"\n",
"}",
"\n\n",
"im",
":=",
"&",
"schema",
".",
"ImageManifest",
"{",
"}",
"\n",
"err",
"=",
"im",
".",
"UnmarshalJSON",
"(",
"bytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"printManifest",
"&&",
"catPrettyPrint",
"{",
"output",
",",
"err",
":=",
"json",
".",
"MarshalIndent",
"(",
"im",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"fmt",
".",
"Println",
"(",
"string",
"(",
"output",
")",
")",
"\n",
"}",
"\n\n",
"if",
"tw",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"newManifest",
")",
"==",
"0",
"{",
"err",
"=",
"patchManifest",
"(",
"im",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"new_bytes",
",",
"err",
"=",
"im",
".",
"MarshalJSON",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"else",
"{",
"new_bytes",
"=",
"newManifest",
"\n",
"}",
"\n\n",
"hdr",
".",
"Size",
"=",
"int64",
"(",
"len",
"(",
"new_bytes",
")",
")",
"\n",
"err",
"=",
"tw",
".",
"WriteHeader",
"(",
"hdr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"_",
",",
"err",
"=",
"tw",
".",
"Write",
"(",
"new_bytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"else",
"if",
"tw",
"!=",
"nil",
"{",
"err",
":=",
"tw",
".",
"WriteHeader",
"(",
"hdr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"io",
".",
"Copy",
"(",
"tw",
",",
"tr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"default",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // extractManifest iterates over the tar reader and locate the manifest. Once
// located, the manifest can be printed, replaced or patched. | [
"extractManifest",
"iterates",
"over",
"the",
"tar",
"reader",
"and",
"locate",
"the",
"manifest",
".",
"Once",
"located",
"the",
"manifest",
"can",
"be",
"printed",
"replaced",
"or",
"patched",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/actool/manifest.go#L354-L432 |
appc/spec | ace/validator.go | main | func main() {
if len(os.Args) != 2 {
stderr("usage: %s [main|sidekick|preStart|postStop]", os.Args[0])
os.Exit(64)
}
mode := os.Args[1]
var res results
switch strings.ToLower(mode) {
case "main":
res = validateMain()
case "sidekick":
res = validateSidekick()
case "prestart":
res = validatePrestart()
case "poststop":
res = validatePoststop()
default:
stderr("unrecognized mode: %s", mode)
os.Exit(64)
}
if len(res) == 0 {
fmt.Printf("%s OK\n", mode)
os.Exit(0)
}
fmt.Printf("%s FAIL\n", mode)
for _, err := range res {
fmt.Fprintln(os.Stderr, "==>", err)
}
os.Exit(1)
} | go | func main() {
if len(os.Args) != 2 {
stderr("usage: %s [main|sidekick|preStart|postStop]", os.Args[0])
os.Exit(64)
}
mode := os.Args[1]
var res results
switch strings.ToLower(mode) {
case "main":
res = validateMain()
case "sidekick":
res = validateSidekick()
case "prestart":
res = validatePrestart()
case "poststop":
res = validatePoststop()
default:
stderr("unrecognized mode: %s", mode)
os.Exit(64)
}
if len(res) == 0 {
fmt.Printf("%s OK\n", mode)
os.Exit(0)
}
fmt.Printf("%s FAIL\n", mode)
for _, err := range res {
fmt.Fprintln(os.Stderr, "==>", err)
}
os.Exit(1)
} | [
"func",
"main",
"(",
")",
"{",
"if",
"len",
"(",
"os",
".",
"Args",
")",
"!=",
"2",
"{",
"stderr",
"(",
"\"",
"\"",
",",
"os",
".",
"Args",
"[",
"0",
"]",
")",
"\n",
"os",
".",
"Exit",
"(",
"64",
")",
"\n",
"}",
"\n",
"mode",
":=",
"os",
".",
"Args",
"[",
"1",
"]",
"\n",
"var",
"res",
"results",
"\n",
"switch",
"strings",
".",
"ToLower",
"(",
"mode",
")",
"{",
"case",
"\"",
"\"",
":",
"res",
"=",
"validateMain",
"(",
")",
"\n",
"case",
"\"",
"\"",
":",
"res",
"=",
"validateSidekick",
"(",
")",
"\n",
"case",
"\"",
"\"",
":",
"res",
"=",
"validatePrestart",
"(",
")",
"\n",
"case",
"\"",
"\"",
":",
"res",
"=",
"validatePoststop",
"(",
")",
"\n",
"default",
":",
"stderr",
"(",
"\"",
"\"",
",",
"mode",
")",
"\n",
"os",
".",
"Exit",
"(",
"64",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"res",
")",
"==",
"0",
"{",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"mode",
")",
"\n",
"os",
".",
"Exit",
"(",
"0",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"mode",
")",
"\n",
"for",
"_",
",",
"err",
":=",
"range",
"res",
"{",
"fmt",
".",
"Fprintln",
"(",
"os",
".",
"Stderr",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"os",
".",
"Exit",
"(",
"1",
")",
"\n",
"}"
] | // main outputs diagnostic information to stderr and exits 1 if validation fails | [
"main",
"outputs",
"diagnostic",
"information",
"to",
"stderr",
"and",
"exits",
"1",
"if",
"validation",
"fails"
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/ace/validator.go#L96-L125 |
appc/spec | ace/validator.go | ValidatePath | func ValidatePath(wp string) results {
r := results{}
gp := os.Getenv("PATH")
if wp != gp {
r = append(r, fmt.Errorf("PATH not set appropriately (need %q, got %q)", wp, gp))
}
return r
} | go | func ValidatePath(wp string) results {
r := results{}
gp := os.Getenv("PATH")
if wp != gp {
r = append(r, fmt.Errorf("PATH not set appropriately (need %q, got %q)", wp, gp))
}
return r
} | [
"func",
"ValidatePath",
"(",
"wp",
"string",
")",
"results",
"{",
"r",
":=",
"results",
"{",
"}",
"\n",
"gp",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\n",
"if",
"wp",
"!=",
"gp",
"{",
"r",
"=",
"append",
"(",
"r",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"wp",
",",
"gp",
")",
")",
"\n",
"}",
"\n",
"return",
"r",
"\n",
"}"
] | // ValidatePath ensures that the PATH has been set up correctly within the
// environment in which this process is being run | [
"ValidatePath",
"ensures",
"that",
"the",
"PATH",
"has",
"been",
"set",
"up",
"correctly",
"within",
"the",
"environment",
"in",
"which",
"this",
"process",
"is",
"being",
"run"
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/ace/validator.go#L164-L171 |
appc/spec | ace/validator.go | ValidateWorkingDirectory | func ValidateWorkingDirectory(wwd string) (r results) {
gwd, err := os.Getwd()
if err != nil {
r = append(r, fmt.Errorf("error getting working directory: %v", err))
return
}
if gwd != wwd {
r = append(r, fmt.Errorf("working directory not set appropriately (need %q, got %v)", wwd, gwd))
}
return
} | go | func ValidateWorkingDirectory(wwd string) (r results) {
gwd, err := os.Getwd()
if err != nil {
r = append(r, fmt.Errorf("error getting working directory: %v", err))
return
}
if gwd != wwd {
r = append(r, fmt.Errorf("working directory not set appropriately (need %q, got %v)", wwd, gwd))
}
return
} | [
"func",
"ValidateWorkingDirectory",
"(",
"wwd",
"string",
")",
"(",
"r",
"results",
")",
"{",
"gwd",
",",
"err",
":=",
"os",
".",
"Getwd",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"r",
"=",
"append",
"(",
"r",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"gwd",
"!=",
"wwd",
"{",
"r",
"=",
"append",
"(",
"r",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"wwd",
",",
"gwd",
")",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // ValidateWorkingDirectory ensures that the process working directory is set
// to the desired path. | [
"ValidateWorkingDirectory",
"ensures",
"that",
"the",
"process",
"working",
"directory",
"is",
"set",
"to",
"the",
"desired",
"path",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/ace/validator.go#L175-L185 |
appc/spec | ace/validator.go | ValidateEnvironment | func ValidateEnvironment(wenv map[string]string) (r results) {
for wkey, wval := range wenv {
gval := os.Getenv(wkey)
if gval != wval {
err := fmt.Errorf("environment variable %q not set appropriately (need %q, got %q)", wkey, wval, gval)
r = append(r, err)
}
}
return
} | go | func ValidateEnvironment(wenv map[string]string) (r results) {
for wkey, wval := range wenv {
gval := os.Getenv(wkey)
if gval != wval {
err := fmt.Errorf("environment variable %q not set appropriately (need %q, got %q)", wkey, wval, gval)
r = append(r, err)
}
}
return
} | [
"func",
"ValidateEnvironment",
"(",
"wenv",
"map",
"[",
"string",
"]",
"string",
")",
"(",
"r",
"results",
")",
"{",
"for",
"wkey",
",",
"wval",
":=",
"range",
"wenv",
"{",
"gval",
":=",
"os",
".",
"Getenv",
"(",
"wkey",
")",
"\n",
"if",
"gval",
"!=",
"wval",
"{",
"err",
":=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"wkey",
",",
"wval",
",",
"gval",
")",
"\n",
"r",
"=",
"append",
"(",
"r",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // ValidateEnvironment ensures that the given environment contains the
// necessary/expected environment variables. | [
"ValidateEnvironment",
"ensures",
"that",
"the",
"given",
"environment",
"contains",
"the",
"necessary",
"/",
"expected",
"environment",
"variables",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/ace/validator.go#L189-L198 |
appc/spec | ace/validator.go | ValidateAppNameEnv | func ValidateAppNameEnv(want string) (r results) {
if got := os.Getenv(appNameEnv); got != want {
r = append(r, fmt.Errorf("%s not set appropriately (need %q, got %q)", appNameEnv, want, got))
}
return
} | go | func ValidateAppNameEnv(want string) (r results) {
if got := os.Getenv(appNameEnv); got != want {
r = append(r, fmt.Errorf("%s not set appropriately (need %q, got %q)", appNameEnv, want, got))
}
return
} | [
"func",
"ValidateAppNameEnv",
"(",
"want",
"string",
")",
"(",
"r",
"results",
")",
"{",
"if",
"got",
":=",
"os",
".",
"Getenv",
"(",
"appNameEnv",
")",
";",
"got",
"!=",
"want",
"{",
"r",
"=",
"append",
"(",
"r",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"appNameEnv",
",",
"want",
",",
"got",
")",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // ValidateAppNameEnv ensures that the environment variable specifying the
// entrypoint of this process is set correctly. | [
"ValidateAppNameEnv",
"ensures",
"that",
"the",
"environment",
"variable",
"specifying",
"the",
"entrypoint",
"of",
"this",
"process",
"is",
"set",
"correctly",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/ace/validator.go#L202-L207 |
appc/spec | ace/validator.go | ValidateMountpoints | func ValidateMountpoints(wmp map[string]types.MountPoint) results {
r := results{}
// TODO(jonboulle): verify actual source
for _, mp := range wmp {
if err := checkMount(mp.Path, mp.ReadOnly); err != nil {
r = append(r, err)
}
}
return r
} | go | func ValidateMountpoints(wmp map[string]types.MountPoint) results {
r := results{}
// TODO(jonboulle): verify actual source
for _, mp := range wmp {
if err := checkMount(mp.Path, mp.ReadOnly); err != nil {
r = append(r, err)
}
}
return r
} | [
"func",
"ValidateMountpoints",
"(",
"wmp",
"map",
"[",
"string",
"]",
"types",
".",
"MountPoint",
")",
"results",
"{",
"r",
":=",
"results",
"{",
"}",
"\n",
"// TODO(jonboulle): verify actual source",
"for",
"_",
",",
"mp",
":=",
"range",
"wmp",
"{",
"if",
"err",
":=",
"checkMount",
"(",
"mp",
".",
"Path",
",",
"mp",
".",
"ReadOnly",
")",
";",
"err",
"!=",
"nil",
"{",
"r",
"=",
"append",
"(",
"r",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"r",
"\n",
"}"
] | // ValidateMountpoints ensures that the given mount points are present in the
// environment in which this process is running | [
"ValidateMountpoints",
"ensures",
"that",
"the",
"given",
"mount",
"points",
"are",
"present",
"in",
"the",
"environment",
"in",
"which",
"this",
"process",
"is",
"running"
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/ace/validator.go#L211-L220 |
appc/spec | ace/validator.go | parseMountinfo | func parseMountinfo(mountinfo io.Reader, dir string) (isMounted bool, readOnly bool, err error) {
sc := bufio.NewScanner(mountinfo)
for sc.Scan() {
var (
mountID int
parentID int
majorMinor string
root string
mountPoint string
mountOptions string
)
_, err := fmt.Sscanf(sc.Text(), "%d %d %s %s %s %s",
&mountID, &parentID, &majorMinor, &root, &mountPoint, &mountOptions)
if err != nil {
return false, false, err
}
if mountPoint == dir {
isMounted = true
optionsParts := strings.Split(mountOptions, ",")
for _, o := range optionsParts {
switch o {
case "ro":
readOnly = true
case "rw":
readOnly = false
}
}
}
}
return
} | go | func parseMountinfo(mountinfo io.Reader, dir string) (isMounted bool, readOnly bool, err error) {
sc := bufio.NewScanner(mountinfo)
for sc.Scan() {
var (
mountID int
parentID int
majorMinor string
root string
mountPoint string
mountOptions string
)
_, err := fmt.Sscanf(sc.Text(), "%d %d %s %s %s %s",
&mountID, &parentID, &majorMinor, &root, &mountPoint, &mountOptions)
if err != nil {
return false, false, err
}
if mountPoint == dir {
isMounted = true
optionsParts := strings.Split(mountOptions, ",")
for _, o := range optionsParts {
switch o {
case "ro":
readOnly = true
case "rw":
readOnly = false
}
}
}
}
return
} | [
"func",
"parseMountinfo",
"(",
"mountinfo",
"io",
".",
"Reader",
",",
"dir",
"string",
")",
"(",
"isMounted",
"bool",
",",
"readOnly",
"bool",
",",
"err",
"error",
")",
"{",
"sc",
":=",
"bufio",
".",
"NewScanner",
"(",
"mountinfo",
")",
"\n",
"for",
"sc",
".",
"Scan",
"(",
")",
"{",
"var",
"(",
"mountID",
"int",
"\n",
"parentID",
"int",
"\n",
"majorMinor",
"string",
"\n",
"root",
"string",
"\n",
"mountPoint",
"string",
"\n",
"mountOptions",
"string",
"\n",
")",
"\n\n",
"_",
",",
"err",
":=",
"fmt",
".",
"Sscanf",
"(",
"sc",
".",
"Text",
"(",
")",
",",
"\"",
"\"",
",",
"&",
"mountID",
",",
"&",
"parentID",
",",
"&",
"majorMinor",
",",
"&",
"root",
",",
"&",
"mountPoint",
",",
"&",
"mountOptions",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"false",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"mountPoint",
"==",
"dir",
"{",
"isMounted",
"=",
"true",
"\n",
"optionsParts",
":=",
"strings",
".",
"Split",
"(",
"mountOptions",
",",
"\"",
"\"",
")",
"\n",
"for",
"_",
",",
"o",
":=",
"range",
"optionsParts",
"{",
"switch",
"o",
"{",
"case",
"\"",
"\"",
":",
"readOnly",
"=",
"true",
"\n",
"case",
"\"",
"\"",
":",
"readOnly",
"=",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // parseMountinfo parses a Reader representing a /proc/PID/mountinfo file and
// returns whether dir is mounted and if so, whether it is read-only or not | [
"parseMountinfo",
"parses",
"a",
"Reader",
"representing",
"a",
"/",
"proc",
"/",
"PID",
"/",
"mountinfo",
"file",
"and",
"returns",
"whether",
"dir",
"is",
"mounted",
"and",
"if",
"so",
"whether",
"it",
"is",
"read",
"-",
"only",
"or",
"not"
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/ace/validator.go#L452-L485 |
appc/spec | ace/validator.go | assertNotExistsAndCreate | func assertNotExistsAndCreate(p string) []error {
var errs []error
errs = append(errs, assertNotExists(p)...)
if err := touchFile(p); err != nil {
errs = append(errs, fmt.Errorf("error touching file %q: %v", p, err))
}
return errs
} | go | func assertNotExistsAndCreate(p string) []error {
var errs []error
errs = append(errs, assertNotExists(p)...)
if err := touchFile(p); err != nil {
errs = append(errs, fmt.Errorf("error touching file %q: %v", p, err))
}
return errs
} | [
"func",
"assertNotExistsAndCreate",
"(",
"p",
"string",
")",
"[",
"]",
"error",
"{",
"var",
"errs",
"[",
"]",
"error",
"\n",
"errs",
"=",
"append",
"(",
"errs",
",",
"assertNotExists",
"(",
"p",
")",
"...",
")",
"\n",
"if",
"err",
":=",
"touchFile",
"(",
"p",
")",
";",
"err",
"!=",
"nil",
"{",
"errs",
"=",
"append",
"(",
"errs",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"p",
",",
"err",
")",
")",
"\n",
"}",
"\n",
"return",
"errs",
"\n",
"}"
] | // assertNotExistsAndCreate asserts that a file at the given path does not
// exist, and then proceeds to create (touch) the file. It returns any errors
// encountered at either of these steps. | [
"assertNotExistsAndCreate",
"asserts",
"that",
"a",
"file",
"at",
"the",
"given",
"path",
"does",
"not",
"exist",
"and",
"then",
"proceeds",
"to",
"create",
"(",
"touch",
")",
"the",
"file",
".",
"It",
"returns",
"any",
"errors",
"encountered",
"at",
"either",
"of",
"these",
"steps",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/ace/validator.go#L490-L497 |
appc/spec | ace/validator.go | assertNotExists | func assertNotExists(p string) []error {
var errs []error
e, err := fileExists(p)
if err != nil {
errs = append(errs, fmt.Errorf("error checking %q exists: %v", p, err))
}
if e {
errs = append(errs, fmt.Errorf("file %q exists unexpectedly", p))
}
return errs
} | go | func assertNotExists(p string) []error {
var errs []error
e, err := fileExists(p)
if err != nil {
errs = append(errs, fmt.Errorf("error checking %q exists: %v", p, err))
}
if e {
errs = append(errs, fmt.Errorf("file %q exists unexpectedly", p))
}
return errs
} | [
"func",
"assertNotExists",
"(",
"p",
"string",
")",
"[",
"]",
"error",
"{",
"var",
"errs",
"[",
"]",
"error",
"\n",
"e",
",",
"err",
":=",
"fileExists",
"(",
"p",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"errs",
"=",
"append",
"(",
"errs",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"p",
",",
"err",
")",
")",
"\n",
"}",
"\n",
"if",
"e",
"{",
"errs",
"=",
"append",
"(",
"errs",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"p",
")",
")",
"\n",
"}",
"\n",
"return",
"errs",
"\n",
"}"
] | // assertNotExists asserts that a file at the given path does not exist. A
// non-empty list of errors is returned if the file exists or any error is
// encountered while checking. | [
"assertNotExists",
"asserts",
"that",
"a",
"file",
"at",
"the",
"given",
"path",
"does",
"not",
"exist",
".",
"A",
"non",
"-",
"empty",
"list",
"of",
"errors",
"is",
"returned",
"if",
"the",
"file",
"exists",
"or",
"any",
"error",
"is",
"encountered",
"while",
"checking",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/ace/validator.go#L502-L512 |
appc/spec | ace/validator.go | touchFile | func touchFile(p string) error {
_, err := os.Create(p)
return err
} | go | func touchFile(p string) error {
_, err := os.Create(p)
return err
} | [
"func",
"touchFile",
"(",
"p",
"string",
")",
"error",
"{",
"_",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"p",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // touchFile creates an empty file, returning any error encountered | [
"touchFile",
"creates",
"an",
"empty",
"file",
"returning",
"any",
"error",
"encountered"
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/ace/validator.go#L530-L533 |
appc/spec | ace/validator.go | waitForFile | func waitForFile(p string, to time.Duration) []error {
done := time.After(to)
for {
select {
case <-done:
return []error{
fmt.Errorf("timed out waiting for %s", p),
}
case <-time.After(1):
if ok, _ := fileExists(p); ok {
return nil
}
}
}
} | go | func waitForFile(p string, to time.Duration) []error {
done := time.After(to)
for {
select {
case <-done:
return []error{
fmt.Errorf("timed out waiting for %s", p),
}
case <-time.After(1):
if ok, _ := fileExists(p); ok {
return nil
}
}
}
} | [
"func",
"waitForFile",
"(",
"p",
"string",
",",
"to",
"time",
".",
"Duration",
")",
"[",
"]",
"error",
"{",
"done",
":=",
"time",
".",
"After",
"(",
"to",
")",
"\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"done",
":",
"return",
"[",
"]",
"error",
"{",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"p",
")",
",",
"}",
"\n",
"case",
"<-",
"time",
".",
"After",
"(",
"1",
")",
":",
"if",
"ok",
",",
"_",
":=",
"fileExists",
"(",
"p",
")",
";",
"ok",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // waitForFile waits for the file at the given path to appear | [
"waitForFile",
"waits",
"for",
"the",
"file",
"at",
"the",
"given",
"path",
"to",
"appear"
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/ace/validator.go#L548-L562 |
appc/spec | discovery/parse.go | NewAppFromString | func NewAppFromString(app string) (*App, error) {
var (
name string
labels map[types.ACIdentifier]string
)
preparedApp, err := prepareAppString(app)
if err != nil {
return nil, err
}
v, err := url.ParseQuery(preparedApp)
if err != nil {
return nil, err
}
labels = make(map[types.ACIdentifier]string, 0)
for key, val := range v {
if len(val) > 1 {
return nil, fmt.Errorf("label %s with multiple values %q", key, val)
}
if key == "name" {
name = val[0]
continue
}
labelName, err := types.NewACIdentifier(key)
if err != nil {
return nil, err
}
labels[*labelName] = val[0]
}
a, err := NewApp(name, labels)
if err != nil {
return nil, err
}
return a, nil
} | go | func NewAppFromString(app string) (*App, error) {
var (
name string
labels map[types.ACIdentifier]string
)
preparedApp, err := prepareAppString(app)
if err != nil {
return nil, err
}
v, err := url.ParseQuery(preparedApp)
if err != nil {
return nil, err
}
labels = make(map[types.ACIdentifier]string, 0)
for key, val := range v {
if len(val) > 1 {
return nil, fmt.Errorf("label %s with multiple values %q", key, val)
}
if key == "name" {
name = val[0]
continue
}
labelName, err := types.NewACIdentifier(key)
if err != nil {
return nil, err
}
labels[*labelName] = val[0]
}
a, err := NewApp(name, labels)
if err != nil {
return nil, err
}
return a, nil
} | [
"func",
"NewAppFromString",
"(",
"app",
"string",
")",
"(",
"*",
"App",
",",
"error",
")",
"{",
"var",
"(",
"name",
"string",
"\n",
"labels",
"map",
"[",
"types",
".",
"ACIdentifier",
"]",
"string",
"\n",
")",
"\n\n",
"preparedApp",
",",
"err",
":=",
"prepareAppString",
"(",
"app",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"v",
",",
"err",
":=",
"url",
".",
"ParseQuery",
"(",
"preparedApp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"labels",
"=",
"make",
"(",
"map",
"[",
"types",
".",
"ACIdentifier",
"]",
"string",
",",
"0",
")",
"\n",
"for",
"key",
",",
"val",
":=",
"range",
"v",
"{",
"if",
"len",
"(",
"val",
")",
">",
"1",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"key",
",",
"val",
")",
"\n",
"}",
"\n",
"if",
"key",
"==",
"\"",
"\"",
"{",
"name",
"=",
"val",
"[",
"0",
"]",
"\n",
"continue",
"\n",
"}",
"\n",
"labelName",
",",
"err",
":=",
"types",
".",
"NewACIdentifier",
"(",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"labels",
"[",
"*",
"labelName",
"]",
"=",
"val",
"[",
"0",
"]",
"\n",
"}",
"\n",
"a",
",",
"err",
":=",
"NewApp",
"(",
"name",
",",
"labels",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"a",
",",
"nil",
"\n",
"}"
] | // NewAppFromString takes a command line app parameter and returns a map of labels.
//
// Example app parameters:
// example.com/reduce-worker:1.0.0
// example.com/reduce-worker,channel=alpha,label=value
// example.com/reduce-worker:1.0.0,label=value
//
// As can be seen in above examples - colon, comma and equal sign have
// special meaning. If any of them has to be a part of a label's value
// then consider writing your own string to App parser. | [
"NewAppFromString",
"takes",
"a",
"command",
"line",
"app",
"parameter",
"and",
"returns",
"a",
"map",
"of",
"labels",
".",
"Example",
"app",
"parameters",
":",
"example",
".",
"com",
"/",
"reduce",
"-",
"worker",
":",
"1",
".",
"0",
".",
"0",
"example",
".",
"com",
"/",
"reduce",
"-",
"worker",
"channel",
"=",
"alpha",
"label",
"=",
"value",
"example",
".",
"com",
"/",
"reduce",
"-",
"worker",
":",
"1",
".",
"0",
".",
"0",
"label",
"=",
"value",
"As",
"can",
"be",
"seen",
"in",
"above",
"examples",
"-",
"colon",
"comma",
"and",
"equal",
"sign",
"have",
"special",
"meaning",
".",
"If",
"any",
"of",
"them",
"has",
"to",
"be",
"a",
"part",
"of",
"a",
"label",
"s",
"value",
"then",
"consider",
"writing",
"your",
"own",
"string",
"to",
"App",
"parser",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/discovery/parse.go#L55-L89 |
appc/spec | discovery/parse.go | String | func (a *App) String() string {
img := a.Name.String()
for n, v := range a.Labels {
img += fmt.Sprintf(",%s=%s", n, v)
}
return img
} | go | func (a *App) String() string {
img := a.Name.String()
for n, v := range a.Labels {
img += fmt.Sprintf(",%s=%s", n, v)
}
return img
} | [
"func",
"(",
"a",
"*",
"App",
")",
"String",
"(",
")",
"string",
"{",
"img",
":=",
"a",
".",
"Name",
".",
"String",
"(",
")",
"\n",
"for",
"n",
",",
"v",
":=",
"range",
"a",
".",
"Labels",
"{",
"img",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"n",
",",
"v",
")",
"\n",
"}",
"\n",
"return",
"img",
"\n",
"}"
] | // String returns the URL-like image name | [
"String",
"returns",
"the",
"URL",
"-",
"like",
"image",
"name"
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/discovery/parse.go#L124-L130 |
appc/spec | pkg/acirenderer/acirenderer.go | GetRenderedACIWithImageID | func GetRenderedACIWithImageID(imageID types.Hash, ap ACIRegistry) (RenderedACI, error) {
imgs, err := CreateDepListFromImageID(imageID, ap)
if err != nil {
return nil, err
}
return GetRenderedACIFromList(imgs, ap)
} | go | func GetRenderedACIWithImageID(imageID types.Hash, ap ACIRegistry) (RenderedACI, error) {
imgs, err := CreateDepListFromImageID(imageID, ap)
if err != nil {
return nil, err
}
return GetRenderedACIFromList(imgs, ap)
} | [
"func",
"GetRenderedACIWithImageID",
"(",
"imageID",
"types",
".",
"Hash",
",",
"ap",
"ACIRegistry",
")",
"(",
"RenderedACI",
",",
"error",
")",
"{",
"imgs",
",",
"err",
":=",
"CreateDepListFromImageID",
"(",
"imageID",
",",
"ap",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"GetRenderedACIFromList",
"(",
"imgs",
",",
"ap",
")",
"\n",
"}"
] | // GetRenderedACIWithImageID, given an imageID, starts with the matching image
// available in the store, creates the dependencies list and returns the
// RenderedACI list. | [
"GetRenderedACIWithImageID",
"given",
"an",
"imageID",
"starts",
"with",
"the",
"matching",
"image",
"available",
"in",
"the",
"store",
"creates",
"the",
"dependencies",
"list",
"and",
"returns",
"the",
"RenderedACI",
"list",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/pkg/acirenderer/acirenderer.go#L81-L87 |
appc/spec | pkg/acirenderer/acirenderer.go | GetRenderedACI | func GetRenderedACI(name types.ACIdentifier, labels types.Labels, ap ACIRegistry) (RenderedACI, error) {
imgs, err := CreateDepListFromNameLabels(name, labels, ap)
if err != nil {
return nil, err
}
return GetRenderedACIFromList(imgs, ap)
} | go | func GetRenderedACI(name types.ACIdentifier, labels types.Labels, ap ACIRegistry) (RenderedACI, error) {
imgs, err := CreateDepListFromNameLabels(name, labels, ap)
if err != nil {
return nil, err
}
return GetRenderedACIFromList(imgs, ap)
} | [
"func",
"GetRenderedACI",
"(",
"name",
"types",
".",
"ACIdentifier",
",",
"labels",
"types",
".",
"Labels",
",",
"ap",
"ACIRegistry",
")",
"(",
"RenderedACI",
",",
"error",
")",
"{",
"imgs",
",",
"err",
":=",
"CreateDepListFromNameLabels",
"(",
"name",
",",
"labels",
",",
"ap",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"GetRenderedACIFromList",
"(",
"imgs",
",",
"ap",
")",
"\n",
"}"
] | // GetRenderedACI, given an image app name and optional labels, starts with the
// best matching image available in the store, creates the dependencies list
// and returns the RenderedACI list. | [
"GetRenderedACI",
"given",
"an",
"image",
"app",
"name",
"and",
"optional",
"labels",
"starts",
"with",
"the",
"best",
"matching",
"image",
"available",
"in",
"the",
"store",
"creates",
"the",
"dependencies",
"list",
"and",
"returns",
"the",
"RenderedACI",
"list",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/pkg/acirenderer/acirenderer.go#L92-L98 |
appc/spec | pkg/acirenderer/acirenderer.go | GetRenderedACIFromList | func GetRenderedACIFromList(imgs Images, ap ACIProvider) (RenderedACI, error) {
if len(imgs) == 0 {
return nil, fmt.Errorf("image list empty")
}
allFiles := make(map[string]byte)
renderedACI := RenderedACI{}
first := true
for i, img := range imgs {
pwlm := getUpperPWLM(imgs, i)
ra, err := getACIFiles(img, ap, allFiles, pwlm)
if err != nil {
return nil, err
}
// Use the manifest from the upper ACI
if first {
ra.FileMap["manifest"] = struct{}{}
first = false
}
renderedACI = append(renderedACI, ra)
}
return renderedACI, nil
} | go | func GetRenderedACIFromList(imgs Images, ap ACIProvider) (RenderedACI, error) {
if len(imgs) == 0 {
return nil, fmt.Errorf("image list empty")
}
allFiles := make(map[string]byte)
renderedACI := RenderedACI{}
first := true
for i, img := range imgs {
pwlm := getUpperPWLM(imgs, i)
ra, err := getACIFiles(img, ap, allFiles, pwlm)
if err != nil {
return nil, err
}
// Use the manifest from the upper ACI
if first {
ra.FileMap["manifest"] = struct{}{}
first = false
}
renderedACI = append(renderedACI, ra)
}
return renderedACI, nil
} | [
"func",
"GetRenderedACIFromList",
"(",
"imgs",
"Images",
",",
"ap",
"ACIProvider",
")",
"(",
"RenderedACI",
",",
"error",
")",
"{",
"if",
"len",
"(",
"imgs",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"allFiles",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"byte",
")",
"\n",
"renderedACI",
":=",
"RenderedACI",
"{",
"}",
"\n\n",
"first",
":=",
"true",
"\n",
"for",
"i",
",",
"img",
":=",
"range",
"imgs",
"{",
"pwlm",
":=",
"getUpperPWLM",
"(",
"imgs",
",",
"i",
")",
"\n",
"ra",
",",
"err",
":=",
"getACIFiles",
"(",
"img",
",",
"ap",
",",
"allFiles",
",",
"pwlm",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// Use the manifest from the upper ACI",
"if",
"first",
"{",
"ra",
".",
"FileMap",
"[",
"\"",
"\"",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"first",
"=",
"false",
"\n",
"}",
"\n",
"renderedACI",
"=",
"append",
"(",
"renderedACI",
",",
"ra",
")",
"\n",
"}",
"\n\n",
"return",
"renderedACI",
",",
"nil",
"\n",
"}"
] | // GetRenderedACIFromList returns the RenderedACI list. All file outside rootfs
// are excluded (at the moment only "manifest"). | [
"GetRenderedACIFromList",
"returns",
"the",
"RenderedACI",
"list",
".",
"All",
"file",
"outside",
"rootfs",
"are",
"excluded",
"(",
"at",
"the",
"moment",
"only",
"manifest",
")",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/pkg/acirenderer/acirenderer.go#L102-L126 |
appc/spec | pkg/acirenderer/acirenderer.go | getUpperPWLM | func getUpperPWLM(imgs Images, pos int) map[string]struct{} {
var pwlm map[string]struct{}
curlevel := imgs[pos].Level
// Start from our position and go back ignoring the other leafs.
for i := pos; i >= 0; i-- {
img := imgs[i]
if img.Level < curlevel && len(img.Im.PathWhitelist) > 0 {
pwlm = pwlToMap(img.Im.PathWhitelist)
}
curlevel = img.Level
}
return pwlm
} | go | func getUpperPWLM(imgs Images, pos int) map[string]struct{} {
var pwlm map[string]struct{}
curlevel := imgs[pos].Level
// Start from our position and go back ignoring the other leafs.
for i := pos; i >= 0; i-- {
img := imgs[i]
if img.Level < curlevel && len(img.Im.PathWhitelist) > 0 {
pwlm = pwlToMap(img.Im.PathWhitelist)
}
curlevel = img.Level
}
return pwlm
} | [
"func",
"getUpperPWLM",
"(",
"imgs",
"Images",
",",
"pos",
"int",
")",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
"{",
"var",
"pwlm",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
"\n",
"curlevel",
":=",
"imgs",
"[",
"pos",
"]",
".",
"Level",
"\n",
"// Start from our position and go back ignoring the other leafs.",
"for",
"i",
":=",
"pos",
";",
"i",
">=",
"0",
";",
"i",
"--",
"{",
"img",
":=",
"imgs",
"[",
"i",
"]",
"\n",
"if",
"img",
".",
"Level",
"<",
"curlevel",
"&&",
"len",
"(",
"img",
".",
"Im",
".",
"PathWhitelist",
")",
">",
"0",
"{",
"pwlm",
"=",
"pwlToMap",
"(",
"img",
".",
"Im",
".",
"PathWhitelist",
")",
"\n",
"}",
"\n",
"curlevel",
"=",
"img",
".",
"Level",
"\n",
"}",
"\n",
"return",
"pwlm",
"\n",
"}"
] | // getUpperPWLM returns the pwl at the lower level for the branch where
// img[pos] lives. | [
"getUpperPWLM",
"returns",
"the",
"pwl",
"at",
"the",
"lower",
"level",
"for",
"the",
"branch",
"where",
"img",
"[",
"pos",
"]",
"lives",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/pkg/acirenderer/acirenderer.go#L130-L142 |
appc/spec | pkg/acirenderer/acirenderer.go | getACIFiles | func getACIFiles(img Image, ap ACIProvider, allFiles map[string]byte, pwlm map[string]struct{}) (*ACIFiles, error) {
rs, err := ap.ReadStream(img.Key)
if err != nil {
return nil, err
}
defer rs.Close()
hash := sha512.New()
r := io.TeeReader(rs, hash)
thispwlm := pwlToMap(img.Im.PathWhitelist)
ra := &ACIFiles{FileMap: make(map[string]struct{})}
if err = Walk(tar.NewReader(r), func(hdr *tar.Header) error {
name := hdr.Name
cleanName := filepath.Clean(name)
// Add the rootfs directory.
if cleanName == "rootfs" && hdr.Typeflag == tar.TypeDir {
ra.FileMap[cleanName] = struct{}{}
allFiles[cleanName] = hdr.Typeflag
return nil
}
// Ignore files outside /rootfs/ (at the moment only "manifest").
if !strings.HasPrefix(cleanName, "rootfs/") {
return nil
}
// Is the file in our PathWhiteList?
// If the file is a directory continue also if not in PathWhiteList
if hdr.Typeflag != tar.TypeDir {
if len(img.Im.PathWhitelist) > 0 {
if _, ok := thispwlm[cleanName]; !ok {
return nil
}
}
}
// Is the file in the lower level PathWhiteList of this img branch?
if pwlm != nil {
if _, ok := pwlm[cleanName]; !ok {
return nil
}
}
// Is the file already provided by a previous image?
if _, ok := allFiles[cleanName]; ok {
return nil
}
// Check that the parent dirs are also of type dir in the upper
// images
parentDir := filepath.Dir(cleanName)
for parentDir != "." && parentDir != "/" {
if ft, ok := allFiles[parentDir]; ok && ft != tar.TypeDir {
return nil
}
parentDir = filepath.Dir(parentDir)
}
ra.FileMap[cleanName] = struct{}{}
allFiles[cleanName] = hdr.Typeflag
return nil
}); err != nil {
return nil, err
}
// Tar does not necessarily read the complete file, so ensure we read the entirety into the hash
if _, err := io.Copy(ioutil.Discard, r); err != nil {
return nil, fmt.Errorf("error reading ACI: %v", err)
}
if g := ap.HashToKey(hash); g != img.Key {
return nil, fmt.Errorf("image hash does not match expected (%s != %s)", g, img.Key)
}
ra.Key = img.Key
return ra, nil
} | go | func getACIFiles(img Image, ap ACIProvider, allFiles map[string]byte, pwlm map[string]struct{}) (*ACIFiles, error) {
rs, err := ap.ReadStream(img.Key)
if err != nil {
return nil, err
}
defer rs.Close()
hash := sha512.New()
r := io.TeeReader(rs, hash)
thispwlm := pwlToMap(img.Im.PathWhitelist)
ra := &ACIFiles{FileMap: make(map[string]struct{})}
if err = Walk(tar.NewReader(r), func(hdr *tar.Header) error {
name := hdr.Name
cleanName := filepath.Clean(name)
// Add the rootfs directory.
if cleanName == "rootfs" && hdr.Typeflag == tar.TypeDir {
ra.FileMap[cleanName] = struct{}{}
allFiles[cleanName] = hdr.Typeflag
return nil
}
// Ignore files outside /rootfs/ (at the moment only "manifest").
if !strings.HasPrefix(cleanName, "rootfs/") {
return nil
}
// Is the file in our PathWhiteList?
// If the file is a directory continue also if not in PathWhiteList
if hdr.Typeflag != tar.TypeDir {
if len(img.Im.PathWhitelist) > 0 {
if _, ok := thispwlm[cleanName]; !ok {
return nil
}
}
}
// Is the file in the lower level PathWhiteList of this img branch?
if pwlm != nil {
if _, ok := pwlm[cleanName]; !ok {
return nil
}
}
// Is the file already provided by a previous image?
if _, ok := allFiles[cleanName]; ok {
return nil
}
// Check that the parent dirs are also of type dir in the upper
// images
parentDir := filepath.Dir(cleanName)
for parentDir != "." && parentDir != "/" {
if ft, ok := allFiles[parentDir]; ok && ft != tar.TypeDir {
return nil
}
parentDir = filepath.Dir(parentDir)
}
ra.FileMap[cleanName] = struct{}{}
allFiles[cleanName] = hdr.Typeflag
return nil
}); err != nil {
return nil, err
}
// Tar does not necessarily read the complete file, so ensure we read the entirety into the hash
if _, err := io.Copy(ioutil.Discard, r); err != nil {
return nil, fmt.Errorf("error reading ACI: %v", err)
}
if g := ap.HashToKey(hash); g != img.Key {
return nil, fmt.Errorf("image hash does not match expected (%s != %s)", g, img.Key)
}
ra.Key = img.Key
return ra, nil
} | [
"func",
"getACIFiles",
"(",
"img",
"Image",
",",
"ap",
"ACIProvider",
",",
"allFiles",
"map",
"[",
"string",
"]",
"byte",
",",
"pwlm",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
"(",
"*",
"ACIFiles",
",",
"error",
")",
"{",
"rs",
",",
"err",
":=",
"ap",
".",
"ReadStream",
"(",
"img",
".",
"Key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"rs",
".",
"Close",
"(",
")",
"\n\n",
"hash",
":=",
"sha512",
".",
"New",
"(",
")",
"\n",
"r",
":=",
"io",
".",
"TeeReader",
"(",
"rs",
",",
"hash",
")",
"\n\n",
"thispwlm",
":=",
"pwlToMap",
"(",
"img",
".",
"Im",
".",
"PathWhitelist",
")",
"\n",
"ra",
":=",
"&",
"ACIFiles",
"{",
"FileMap",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
"}",
"\n",
"if",
"err",
"=",
"Walk",
"(",
"tar",
".",
"NewReader",
"(",
"r",
")",
",",
"func",
"(",
"hdr",
"*",
"tar",
".",
"Header",
")",
"error",
"{",
"name",
":=",
"hdr",
".",
"Name",
"\n",
"cleanName",
":=",
"filepath",
".",
"Clean",
"(",
"name",
")",
"\n\n",
"// Add the rootfs directory.",
"if",
"cleanName",
"==",
"\"",
"\"",
"&&",
"hdr",
".",
"Typeflag",
"==",
"tar",
".",
"TypeDir",
"{",
"ra",
".",
"FileMap",
"[",
"cleanName",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"allFiles",
"[",
"cleanName",
"]",
"=",
"hdr",
".",
"Typeflag",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Ignore files outside /rootfs/ (at the moment only \"manifest\").",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"cleanName",
",",
"\"",
"\"",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Is the file in our PathWhiteList?",
"// If the file is a directory continue also if not in PathWhiteList",
"if",
"hdr",
".",
"Typeflag",
"!=",
"tar",
".",
"TypeDir",
"{",
"if",
"len",
"(",
"img",
".",
"Im",
".",
"PathWhitelist",
")",
">",
"0",
"{",
"if",
"_",
",",
"ok",
":=",
"thispwlm",
"[",
"cleanName",
"]",
";",
"!",
"ok",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"// Is the file in the lower level PathWhiteList of this img branch?",
"if",
"pwlm",
"!=",
"nil",
"{",
"if",
"_",
",",
"ok",
":=",
"pwlm",
"[",
"cleanName",
"]",
";",
"!",
"ok",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"// Is the file already provided by a previous image?",
"if",
"_",
",",
"ok",
":=",
"allFiles",
"[",
"cleanName",
"]",
";",
"ok",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"// Check that the parent dirs are also of type dir in the upper",
"// images",
"parentDir",
":=",
"filepath",
".",
"Dir",
"(",
"cleanName",
")",
"\n",
"for",
"parentDir",
"!=",
"\"",
"\"",
"&&",
"parentDir",
"!=",
"\"",
"\"",
"{",
"if",
"ft",
",",
"ok",
":=",
"allFiles",
"[",
"parentDir",
"]",
";",
"ok",
"&&",
"ft",
"!=",
"tar",
".",
"TypeDir",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"parentDir",
"=",
"filepath",
".",
"Dir",
"(",
"parentDir",
")",
"\n",
"}",
"\n",
"ra",
".",
"FileMap",
"[",
"cleanName",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"allFiles",
"[",
"cleanName",
"]",
"=",
"hdr",
".",
"Typeflag",
"\n",
"return",
"nil",
"\n",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Tar does not necessarily read the complete file, so ensure we read the entirety into the hash",
"if",
"_",
",",
"err",
":=",
"io",
".",
"Copy",
"(",
"ioutil",
".",
"Discard",
",",
"r",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"g",
":=",
"ap",
".",
"HashToKey",
"(",
"hash",
")",
";",
"g",
"!=",
"img",
".",
"Key",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"g",
",",
"img",
".",
"Key",
")",
"\n",
"}",
"\n\n",
"ra",
".",
"Key",
"=",
"img",
".",
"Key",
"\n",
"return",
"ra",
",",
"nil",
"\n",
"}"
] | // getACIFiles returns the ACIFiles struct for the given image. All files
// outside rootfs are excluded (at the moment only "manifest"). | [
"getACIFiles",
"returns",
"the",
"ACIFiles",
"struct",
"for",
"the",
"given",
"image",
".",
"All",
"files",
"outside",
"rootfs",
"are",
"excluded",
"(",
"at",
"the",
"moment",
"only",
"manifest",
")",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/pkg/acirenderer/acirenderer.go#L146-L220 |
appc/spec | pkg/acirenderer/acirenderer.go | pwlToMap | func pwlToMap(pwl []string) map[string]struct{} {
if len(pwl) == 0 {
return nil
}
m := make(map[string]struct{}, len(pwl))
for _, name := range pwl {
relpath := filepath.Join("rootfs", name)
m[relpath] = struct{}{}
}
return m
} | go | func pwlToMap(pwl []string) map[string]struct{} {
if len(pwl) == 0 {
return nil
}
m := make(map[string]struct{}, len(pwl))
for _, name := range pwl {
relpath := filepath.Join("rootfs", name)
m[relpath] = struct{}{}
}
return m
} | [
"func",
"pwlToMap",
"(",
"pwl",
"[",
"]",
"string",
")",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
"{",
"if",
"len",
"(",
"pwl",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"m",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
",",
"len",
"(",
"pwl",
")",
")",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"pwl",
"{",
"relpath",
":=",
"filepath",
".",
"Join",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"m",
"[",
"relpath",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"return",
"m",
"\n",
"}"
] | // pwlToMap converts a pathWhiteList slice to a map for faster search
// It will also prepend "rootfs/" to the provided paths and they will be
// relative to "/" so they can be easily compared with the tar.Header.Name
// If pwl length is 0, a nil map is returned | [
"pwlToMap",
"converts",
"a",
"pathWhiteList",
"slice",
"to",
"a",
"map",
"for",
"faster",
"search",
"It",
"will",
"also",
"prepend",
"rootfs",
"/",
"to",
"the",
"provided",
"paths",
"and",
"they",
"will",
"be",
"relative",
"to",
"/",
"so",
"they",
"can",
"be",
"easily",
"compared",
"with",
"the",
"tar",
".",
"Header",
".",
"Name",
"If",
"pwl",
"length",
"is",
"0",
"a",
"nil",
"map",
"is",
"returned"
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/pkg/acirenderer/acirenderer.go#L226-L236 |
appc/spec | schema/types/annotations.go | Get | func (a Annotations) Get(name string) (val string, ok bool) {
for _, anno := range a {
if anno.Name.String() == name {
return anno.Value, true
}
}
return "", false
} | go | func (a Annotations) Get(name string) (val string, ok bool) {
for _, anno := range a {
if anno.Name.String() == name {
return anno.Value, true
}
}
return "", false
} | [
"func",
"(",
"a",
"Annotations",
")",
"Get",
"(",
"name",
"string",
")",
"(",
"val",
"string",
",",
"ok",
"bool",
")",
"{",
"for",
"_",
",",
"anno",
":=",
"range",
"a",
"{",
"if",
"anno",
".",
"Name",
".",
"String",
"(",
")",
"==",
"name",
"{",
"return",
"anno",
".",
"Value",
",",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
",",
"false",
"\n",
"}"
] | // Retrieve the value of an annotation by the given name from Annotations, if
// it exists. | [
"Retrieve",
"the",
"value",
"of",
"an",
"annotation",
"by",
"the",
"given",
"name",
"from",
"Annotations",
"if",
"it",
"exists",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/annotations.go#L81-L88 |
appc/spec | schema/types/annotations.go | Set | func (a *Annotations) Set(name ACIdentifier, value string) {
for i, anno := range *a {
if anno.Name.Equals(name) {
(*a)[i] = Annotation{
Name: name,
Value: value,
}
return
}
}
anno := Annotation{
Name: name,
Value: value,
}
*a = append(*a, anno)
} | go | func (a *Annotations) Set(name ACIdentifier, value string) {
for i, anno := range *a {
if anno.Name.Equals(name) {
(*a)[i] = Annotation{
Name: name,
Value: value,
}
return
}
}
anno := Annotation{
Name: name,
Value: value,
}
*a = append(*a, anno)
} | [
"func",
"(",
"a",
"*",
"Annotations",
")",
"Set",
"(",
"name",
"ACIdentifier",
",",
"value",
"string",
")",
"{",
"for",
"i",
",",
"anno",
":=",
"range",
"*",
"a",
"{",
"if",
"anno",
".",
"Name",
".",
"Equals",
"(",
"name",
")",
"{",
"(",
"*",
"a",
")",
"[",
"i",
"]",
"=",
"Annotation",
"{",
"Name",
":",
"name",
",",
"Value",
":",
"value",
",",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"anno",
":=",
"Annotation",
"{",
"Name",
":",
"name",
",",
"Value",
":",
"value",
",",
"}",
"\n",
"*",
"a",
"=",
"append",
"(",
"*",
"a",
",",
"anno",
")",
"\n",
"}"
] | // Set sets the value of an annotation by the given name, overwriting if one already exists. | [
"Set",
"sets",
"the",
"value",
"of",
"an",
"annotation",
"by",
"the",
"given",
"name",
"overwriting",
"if",
"one",
"already",
"exists",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/annotations.go#L91-L106 |
appc/spec | discovery/discovery.go | DiscoverWalk | func DiscoverWalk(app App, hostHeaders map[string]http.Header, insecure InsecureOption, port uint, discoverFn DiscoverWalkFunc) (dd *discoveryData, err error) {
parts := strings.Split(string(app.Name), "/")
for i := range parts {
end := len(parts) - i
pre := strings.Join(parts[:end], "/")
dd, err = doDiscover(pre, hostHeaders, app, insecure, port)
if derr := discoverFn(pre, dd, err); derr != nil {
return dd, derr
}
}
return nil, fmt.Errorf("discovery failed")
} | go | func DiscoverWalk(app App, hostHeaders map[string]http.Header, insecure InsecureOption, port uint, discoverFn DiscoverWalkFunc) (dd *discoveryData, err error) {
parts := strings.Split(string(app.Name), "/")
for i := range parts {
end := len(parts) - i
pre := strings.Join(parts[:end], "/")
dd, err = doDiscover(pre, hostHeaders, app, insecure, port)
if derr := discoverFn(pre, dd, err); derr != nil {
return dd, derr
}
}
return nil, fmt.Errorf("discovery failed")
} | [
"func",
"DiscoverWalk",
"(",
"app",
"App",
",",
"hostHeaders",
"map",
"[",
"string",
"]",
"http",
".",
"Header",
",",
"insecure",
"InsecureOption",
",",
"port",
"uint",
",",
"discoverFn",
"DiscoverWalkFunc",
")",
"(",
"dd",
"*",
"discoveryData",
",",
"err",
"error",
")",
"{",
"parts",
":=",
"strings",
".",
"Split",
"(",
"string",
"(",
"app",
".",
"Name",
")",
",",
"\"",
"\"",
")",
"\n",
"for",
"i",
":=",
"range",
"parts",
"{",
"end",
":=",
"len",
"(",
"parts",
")",
"-",
"i",
"\n",
"pre",
":=",
"strings",
".",
"Join",
"(",
"parts",
"[",
":",
"end",
"]",
",",
"\"",
"\"",
")",
"\n\n",
"dd",
",",
"err",
"=",
"doDiscover",
"(",
"pre",
",",
"hostHeaders",
",",
"app",
",",
"insecure",
",",
"port",
")",
"\n",
"if",
"derr",
":=",
"discoverFn",
"(",
"pre",
",",
"dd",
",",
"err",
")",
";",
"derr",
"!=",
"nil",
"{",
"return",
"dd",
",",
"derr",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // DiscoverWalk will make HTTPS requests to find discovery meta tags and
// optionally will use HTTP if insecure is set. hostHeaders specifies the
// header to apply depending on the host (e.g. authentication). Based on the
// response of the discoverFn it will continue to recurse up the tree. If port
// is 0, the default port will be used. | [
"DiscoverWalk",
"will",
"make",
"HTTPS",
"requests",
"to",
"find",
"discovery",
"meta",
"tags",
"and",
"optionally",
"will",
"use",
"HTTP",
"if",
"insecure",
"is",
"set",
".",
"hostHeaders",
"specifies",
"the",
"header",
"to",
"apply",
"depending",
"on",
"the",
"host",
"(",
"e",
".",
"g",
".",
"authentication",
")",
".",
"Based",
"on",
"the",
"response",
"of",
"the",
"discoverFn",
"it",
"will",
"continue",
"to",
"recurse",
"up",
"the",
"tree",
".",
"If",
"port",
"is",
"0",
"the",
"default",
"port",
"will",
"be",
"used",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/discovery/discovery.go#L179-L192 |
appc/spec | discovery/discovery.go | DiscoverACIEndpoints | func DiscoverACIEndpoints(app App, hostHeaders map[string]http.Header, insecure InsecureOption, port uint) (ACIEndpoints, []FailedAttempt, error) {
testFn := func(pre string, dd *discoveryData, err error) error {
if len(dd.ACIEndpoints) != 0 {
return errEnough
}
return nil
}
attempts := []FailedAttempt{}
dd, err := DiscoverWalk(app, hostHeaders, insecure, port, walker(&attempts, testFn))
if err != nil && err != errEnough {
return nil, attempts, err
}
return dd.ACIEndpoints, attempts, nil
} | go | func DiscoverACIEndpoints(app App, hostHeaders map[string]http.Header, insecure InsecureOption, port uint) (ACIEndpoints, []FailedAttempt, error) {
testFn := func(pre string, dd *discoveryData, err error) error {
if len(dd.ACIEndpoints) != 0 {
return errEnough
}
return nil
}
attempts := []FailedAttempt{}
dd, err := DiscoverWalk(app, hostHeaders, insecure, port, walker(&attempts, testFn))
if err != nil && err != errEnough {
return nil, attempts, err
}
return dd.ACIEndpoints, attempts, nil
} | [
"func",
"DiscoverACIEndpoints",
"(",
"app",
"App",
",",
"hostHeaders",
"map",
"[",
"string",
"]",
"http",
".",
"Header",
",",
"insecure",
"InsecureOption",
",",
"port",
"uint",
")",
"(",
"ACIEndpoints",
",",
"[",
"]",
"FailedAttempt",
",",
"error",
")",
"{",
"testFn",
":=",
"func",
"(",
"pre",
"string",
",",
"dd",
"*",
"discoveryData",
",",
"err",
"error",
")",
"error",
"{",
"if",
"len",
"(",
"dd",
".",
"ACIEndpoints",
")",
"!=",
"0",
"{",
"return",
"errEnough",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n\n",
"attempts",
":=",
"[",
"]",
"FailedAttempt",
"{",
"}",
"\n",
"dd",
",",
"err",
":=",
"DiscoverWalk",
"(",
"app",
",",
"hostHeaders",
",",
"insecure",
",",
"port",
",",
"walker",
"(",
"&",
"attempts",
",",
"testFn",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"errEnough",
"{",
"return",
"nil",
",",
"attempts",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"dd",
".",
"ACIEndpoints",
",",
"attempts",
",",
"nil",
"\n",
"}"
] | // DiscoverACIEndpoints will make HTTPS requests to find the ac-discovery meta
// tags and optionally will use HTTP if insecure is set. hostHeaders
// specifies the header to apply depending on the host (e.g. authentication).
// It will not give up until it has exhausted the path or found an image
// discovery. If port is 0, the default port will be used. | [
"DiscoverACIEndpoints",
"will",
"make",
"HTTPS",
"requests",
"to",
"find",
"the",
"ac",
"-",
"discovery",
"meta",
"tags",
"and",
"optionally",
"will",
"use",
"HTTP",
"if",
"insecure",
"is",
"set",
".",
"hostHeaders",
"specifies",
"the",
"header",
"to",
"apply",
"depending",
"on",
"the",
"host",
"(",
"e",
".",
"g",
".",
"authentication",
")",
".",
"It",
"will",
"not",
"give",
"up",
"until",
"it",
"has",
"exhausted",
"the",
"path",
"or",
"found",
"an",
"image",
"discovery",
".",
"If",
"port",
"is",
"0",
"the",
"default",
"port",
"will",
"be",
"used",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/discovery/discovery.go#L222-L237 |
appc/spec | aci/file.go | DetectFileType | func DetectFileType(r io.Reader) (FileType, error) {
var b bytes.Buffer
n, err := io.CopyN(&b, r, readLen)
if err != nil && err != io.EOF {
return TypeUnknown, err
}
bs := b.Bytes()
switch {
case bytes.HasPrefix(bs, hdrGzip):
return TypeGzip, nil
case bytes.HasPrefix(bs, hdrBzip2):
return TypeBzip2, nil
case bytes.HasPrefix(bs, hdrXz):
return TypeXz, nil
case n > int64(tarEnd) && bytes.Equal(bs[tarOffset:tarEnd], sigTar):
return TypeTar, nil
case http.DetectContentType(bs) == textMime:
return TypeText, nil
default:
return TypeUnknown, nil
}
} | go | func DetectFileType(r io.Reader) (FileType, error) {
var b bytes.Buffer
n, err := io.CopyN(&b, r, readLen)
if err != nil && err != io.EOF {
return TypeUnknown, err
}
bs := b.Bytes()
switch {
case bytes.HasPrefix(bs, hdrGzip):
return TypeGzip, nil
case bytes.HasPrefix(bs, hdrBzip2):
return TypeBzip2, nil
case bytes.HasPrefix(bs, hdrXz):
return TypeXz, nil
case n > int64(tarEnd) && bytes.Equal(bs[tarOffset:tarEnd], sigTar):
return TypeTar, nil
case http.DetectContentType(bs) == textMime:
return TypeText, nil
default:
return TypeUnknown, nil
}
} | [
"func",
"DetectFileType",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"FileType",
",",
"error",
")",
"{",
"var",
"b",
"bytes",
".",
"Buffer",
"\n",
"n",
",",
"err",
":=",
"io",
".",
"CopyN",
"(",
"&",
"b",
",",
"r",
",",
"readLen",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"io",
".",
"EOF",
"{",
"return",
"TypeUnknown",
",",
"err",
"\n",
"}",
"\n",
"bs",
":=",
"b",
".",
"Bytes",
"(",
")",
"\n",
"switch",
"{",
"case",
"bytes",
".",
"HasPrefix",
"(",
"bs",
",",
"hdrGzip",
")",
":",
"return",
"TypeGzip",
",",
"nil",
"\n",
"case",
"bytes",
".",
"HasPrefix",
"(",
"bs",
",",
"hdrBzip2",
")",
":",
"return",
"TypeBzip2",
",",
"nil",
"\n",
"case",
"bytes",
".",
"HasPrefix",
"(",
"bs",
",",
"hdrXz",
")",
":",
"return",
"TypeXz",
",",
"nil",
"\n",
"case",
"n",
">",
"int64",
"(",
"tarEnd",
")",
"&&",
"bytes",
".",
"Equal",
"(",
"bs",
"[",
"tarOffset",
":",
"tarEnd",
"]",
",",
"sigTar",
")",
":",
"return",
"TypeTar",
",",
"nil",
"\n",
"case",
"http",
".",
"DetectContentType",
"(",
"bs",
")",
"==",
"textMime",
":",
"return",
"TypeText",
",",
"nil",
"\n",
"default",
":",
"return",
"TypeUnknown",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // DetectFileType attempts to detect the type of file that the given reader
// represents by comparing it against known file signatures (magic numbers) | [
"DetectFileType",
"attempts",
"to",
"detect",
"the",
"type",
"of",
"file",
"that",
"the",
"given",
"reader",
"represents",
"by",
"comparing",
"it",
"against",
"known",
"file",
"signatures",
"(",
"magic",
"numbers",
")"
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/aci/file.go#L83-L104 |
appc/spec | aci/file.go | NewXzReader | func NewXzReader(r io.Reader) (*XzReader, error) {
rpipe, wpipe := io.Pipe()
ex, err := exec.LookPath("xz")
if err != nil {
log.Fatalf("couldn't find xz executable: %v", err)
}
cmd := exec.Command(ex, "--decompress", "--stdout")
closech := make(chan error)
cmd.Stdin = r
cmd.Stdout = wpipe
go func() {
err := cmd.Run()
wpipe.CloseWithError(err)
closech <- err
}()
return &XzReader{rpipe, cmd, closech}, nil
} | go | func NewXzReader(r io.Reader) (*XzReader, error) {
rpipe, wpipe := io.Pipe()
ex, err := exec.LookPath("xz")
if err != nil {
log.Fatalf("couldn't find xz executable: %v", err)
}
cmd := exec.Command(ex, "--decompress", "--stdout")
closech := make(chan error)
cmd.Stdin = r
cmd.Stdout = wpipe
go func() {
err := cmd.Run()
wpipe.CloseWithError(err)
closech <- err
}()
return &XzReader{rpipe, cmd, closech}, nil
} | [
"func",
"NewXzReader",
"(",
"r",
"io",
".",
"Reader",
")",
"(",
"*",
"XzReader",
",",
"error",
")",
"{",
"rpipe",
",",
"wpipe",
":=",
"io",
".",
"Pipe",
"(",
")",
"\n",
"ex",
",",
"err",
":=",
"exec",
".",
"LookPath",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"cmd",
":=",
"exec",
".",
"Command",
"(",
"ex",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"closech",
":=",
"make",
"(",
"chan",
"error",
")",
"\n\n",
"cmd",
".",
"Stdin",
"=",
"r",
"\n",
"cmd",
".",
"Stdout",
"=",
"wpipe",
"\n\n",
"go",
"func",
"(",
")",
"{",
"err",
":=",
"cmd",
".",
"Run",
"(",
")",
"\n",
"wpipe",
".",
"CloseWithError",
"(",
"err",
")",
"\n",
"closech",
"<-",
"err",
"\n",
"}",
"(",
")",
"\n\n",
"return",
"&",
"XzReader",
"{",
"rpipe",
",",
"cmd",
",",
"closech",
"}",
",",
"nil",
"\n",
"}"
] | // NewXzReader shells out to a command line xz executable (if
// available) to decompress the given io.Reader using the xz
// compression format and returns an *XzReader.
// It is the caller's responsibility to call Close on the XzReader when done. | [
"NewXzReader",
"shells",
"out",
"to",
"a",
"command",
"line",
"xz",
"executable",
"(",
"if",
"available",
")",
"to",
"decompress",
"the",
"given",
"io",
".",
"Reader",
"using",
"the",
"xz",
"compression",
"format",
"and",
"returns",
"an",
"*",
"XzReader",
".",
"It",
"is",
"the",
"caller",
"s",
"responsibility",
"to",
"call",
"Close",
"on",
"the",
"XzReader",
"when",
"done",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/aci/file.go#L117-L137 |
appc/spec | aci/file.go | ManifestFromImage | func ManifestFromImage(rs io.ReadSeeker) (*schema.ImageManifest, error) {
var im schema.ImageManifest
tr, err := NewCompressedTarReader(rs)
if err != nil {
return nil, err
}
defer tr.Close()
for {
hdr, err := tr.Next()
switch err {
case io.EOF:
return nil, errors.New("missing manifest")
case nil:
if filepath.Clean(hdr.Name) == ManifestFile {
data, err := ioutil.ReadAll(tr)
if err != nil {
return nil, err
}
if err := im.UnmarshalJSON(data); err != nil {
return nil, err
}
return &im, nil
}
default:
return nil, fmt.Errorf("error extracting tarball: %v", err)
}
}
} | go | func ManifestFromImage(rs io.ReadSeeker) (*schema.ImageManifest, error) {
var im schema.ImageManifest
tr, err := NewCompressedTarReader(rs)
if err != nil {
return nil, err
}
defer tr.Close()
for {
hdr, err := tr.Next()
switch err {
case io.EOF:
return nil, errors.New("missing manifest")
case nil:
if filepath.Clean(hdr.Name) == ManifestFile {
data, err := ioutil.ReadAll(tr)
if err != nil {
return nil, err
}
if err := im.UnmarshalJSON(data); err != nil {
return nil, err
}
return &im, nil
}
default:
return nil, fmt.Errorf("error extracting tarball: %v", err)
}
}
} | [
"func",
"ManifestFromImage",
"(",
"rs",
"io",
".",
"ReadSeeker",
")",
"(",
"*",
"schema",
".",
"ImageManifest",
",",
"error",
")",
"{",
"var",
"im",
"schema",
".",
"ImageManifest",
"\n\n",
"tr",
",",
"err",
":=",
"NewCompressedTarReader",
"(",
"rs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"tr",
".",
"Close",
"(",
")",
"\n\n",
"for",
"{",
"hdr",
",",
"err",
":=",
"tr",
".",
"Next",
"(",
")",
"\n",
"switch",
"err",
"{",
"case",
"io",
".",
"EOF",
":",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"case",
"nil",
":",
"if",
"filepath",
".",
"Clean",
"(",
"hdr",
".",
"Name",
")",
"==",
"ManifestFile",
"{",
"data",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"tr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"im",
".",
"UnmarshalJSON",
"(",
"data",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"im",
",",
"nil",
"\n",
"}",
"\n",
"default",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // ManifestFromImage extracts a new schema.ImageManifest from the given ACI image. | [
"ManifestFromImage",
"extracts",
"a",
"new",
"schema",
".",
"ImageManifest",
"from",
"the",
"given",
"ACI",
"image",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/aci/file.go#L146-L175 |
appc/spec | aci/file.go | NewCompressedTarReader | func NewCompressedTarReader(rs io.ReadSeeker) (*TarReadCloser, error) {
cr, err := NewCompressedReader(rs)
if err != nil {
return nil, err
}
return &TarReadCloser{tar.NewReader(cr), cr}, nil
} | go | func NewCompressedTarReader(rs io.ReadSeeker) (*TarReadCloser, error) {
cr, err := NewCompressedReader(rs)
if err != nil {
return nil, err
}
return &TarReadCloser{tar.NewReader(cr), cr}, nil
} | [
"func",
"NewCompressedTarReader",
"(",
"rs",
"io",
".",
"ReadSeeker",
")",
"(",
"*",
"TarReadCloser",
",",
"error",
")",
"{",
"cr",
",",
"err",
":=",
"NewCompressedReader",
"(",
"rs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"TarReadCloser",
"{",
"tar",
".",
"NewReader",
"(",
"cr",
")",
",",
"cr",
"}",
",",
"nil",
"\n",
"}"
] | // NewCompressedTarReader creates a new TarReadCloser reading from the
// given ACI image.
// It is the caller's responsibility to call Close on the TarReadCloser
// when done. | [
"NewCompressedTarReader",
"creates",
"a",
"new",
"TarReadCloser",
"reading",
"from",
"the",
"given",
"ACI",
"image",
".",
"It",
"is",
"the",
"caller",
"s",
"responsibility",
"to",
"call",
"Close",
"on",
"the",
"TarReadCloser",
"when",
"done",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/aci/file.go#L193-L199 |
appc/spec | aci/file.go | NewCompressedReader | func NewCompressedReader(rs io.ReadSeeker) (io.ReadCloser, error) {
var (
dr io.ReadCloser
err error
)
_, err = rs.Seek(0, 0)
if err != nil {
return nil, err
}
ftype, err := DetectFileType(rs)
if err != nil {
return nil, err
}
_, err = rs.Seek(0, 0)
if err != nil {
return nil, err
}
switch ftype {
case TypeGzip:
dr, err = gzip.NewReader(rs)
if err != nil {
return nil, err
}
case TypeBzip2:
dr = ioutil.NopCloser(bzip2.NewReader(rs))
case TypeXz:
dr, err = NewXzReader(rs)
if err != nil {
return nil, err
}
case TypeTar:
dr = ioutil.NopCloser(rs)
case TypeUnknown:
return nil, errors.New("error: unknown image filetype")
default:
return nil, errors.New("no type returned from DetectFileType?")
}
return dr, nil
} | go | func NewCompressedReader(rs io.ReadSeeker) (io.ReadCloser, error) {
var (
dr io.ReadCloser
err error
)
_, err = rs.Seek(0, 0)
if err != nil {
return nil, err
}
ftype, err := DetectFileType(rs)
if err != nil {
return nil, err
}
_, err = rs.Seek(0, 0)
if err != nil {
return nil, err
}
switch ftype {
case TypeGzip:
dr, err = gzip.NewReader(rs)
if err != nil {
return nil, err
}
case TypeBzip2:
dr = ioutil.NopCloser(bzip2.NewReader(rs))
case TypeXz:
dr, err = NewXzReader(rs)
if err != nil {
return nil, err
}
case TypeTar:
dr = ioutil.NopCloser(rs)
case TypeUnknown:
return nil, errors.New("error: unknown image filetype")
default:
return nil, errors.New("no type returned from DetectFileType?")
}
return dr, nil
} | [
"func",
"NewCompressedReader",
"(",
"rs",
"io",
".",
"ReadSeeker",
")",
"(",
"io",
".",
"ReadCloser",
",",
"error",
")",
"{",
"var",
"(",
"dr",
"io",
".",
"ReadCloser",
"\n",
"err",
"error",
"\n",
")",
"\n\n",
"_",
",",
"err",
"=",
"rs",
".",
"Seek",
"(",
"0",
",",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"ftype",
",",
"err",
":=",
"DetectFileType",
"(",
"rs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"_",
",",
"err",
"=",
"rs",
".",
"Seek",
"(",
"0",
",",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"switch",
"ftype",
"{",
"case",
"TypeGzip",
":",
"dr",
",",
"err",
"=",
"gzip",
".",
"NewReader",
"(",
"rs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"case",
"TypeBzip2",
":",
"dr",
"=",
"ioutil",
".",
"NopCloser",
"(",
"bzip2",
".",
"NewReader",
"(",
"rs",
")",
")",
"\n",
"case",
"TypeXz",
":",
"dr",
",",
"err",
"=",
"NewXzReader",
"(",
"rs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"case",
"TypeTar",
":",
"dr",
"=",
"ioutil",
".",
"NopCloser",
"(",
"rs",
")",
"\n",
"case",
"TypeUnknown",
":",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"default",
":",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"dr",
",",
"nil",
"\n",
"}"
] | // NewCompressedReader creates a new io.ReaderCloser from the given ACI image.
// It is the caller's responsibility to call Close on the Reader when done. | [
"NewCompressedReader",
"creates",
"a",
"new",
"io",
".",
"ReaderCloser",
"from",
"the",
"given",
"ACI",
"image",
".",
"It",
"is",
"the",
"caller",
"s",
"responsibility",
"to",
"call",
"Close",
"on",
"the",
"Reader",
"when",
"done",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/aci/file.go#L203-L246 |
appc/spec | schema/types/resource/math.go | powInt64 | func powInt64(a, b int64) int64 {
p := int64(1)
for b > 0 {
if b&1 != 0 {
p *= a
}
b >>= 1
a *= a
}
return p
} | go | func powInt64(a, b int64) int64 {
p := int64(1)
for b > 0 {
if b&1 != 0 {
p *= a
}
b >>= 1
a *= a
}
return p
} | [
"func",
"powInt64",
"(",
"a",
",",
"b",
"int64",
")",
"int64",
"{",
"p",
":=",
"int64",
"(",
"1",
")",
"\n",
"for",
"b",
">",
"0",
"{",
"if",
"b",
"&",
"1",
"!=",
"0",
"{",
"p",
"*=",
"a",
"\n",
"}",
"\n",
"b",
">>=",
"1",
"\n",
"a",
"*=",
"a",
"\n",
"}",
"\n",
"return",
"p",
"\n",
"}"
] | // powInt64 raises a to the bth power. Is not overflow aware. | [
"powInt64",
"raises",
"a",
"to",
"the",
"bth",
"power",
".",
"Is",
"not",
"overflow",
"aware",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/resource/math.go#L251-L261 |
appc/spec | schema/types/port.go | PortFromString | func PortFromString(pt string) (*Port, error) {
var port Port
pt = "name=" + pt
ptQuery, err := common.MakeQueryString(pt)
if err != nil {
return nil, err
}
v, err := url.ParseQuery(ptQuery)
if err != nil {
return nil, err
}
for key, val := range v {
if len(val) > 1 {
return nil, fmt.Errorf("label %s with multiple values %q", key, val)
}
switch key {
case "name":
acn, err := NewACName(val[0])
if err != nil {
return nil, err
}
port.Name = *acn
case "protocol":
port.Protocol = val[0]
case "port":
p, err := strconv.ParseUint(val[0], 10, 16)
if err != nil {
return nil, err
}
port.Port = uint(p)
case "count":
cnt, err := strconv.ParseUint(val[0], 10, 16)
if err != nil {
return nil, err
}
port.Count = uint(cnt)
case "socketActivated":
sa, err := strconv.ParseBool(val[0])
if err != nil {
return nil, err
}
port.SocketActivated = sa
default:
return nil, fmt.Errorf("unknown port parameter %q", key)
}
}
err = port.assertValid()
if err != nil {
return nil, err
}
return &port, nil
} | go | func PortFromString(pt string) (*Port, error) {
var port Port
pt = "name=" + pt
ptQuery, err := common.MakeQueryString(pt)
if err != nil {
return nil, err
}
v, err := url.ParseQuery(ptQuery)
if err != nil {
return nil, err
}
for key, val := range v {
if len(val) > 1 {
return nil, fmt.Errorf("label %s with multiple values %q", key, val)
}
switch key {
case "name":
acn, err := NewACName(val[0])
if err != nil {
return nil, err
}
port.Name = *acn
case "protocol":
port.Protocol = val[0]
case "port":
p, err := strconv.ParseUint(val[0], 10, 16)
if err != nil {
return nil, err
}
port.Port = uint(p)
case "count":
cnt, err := strconv.ParseUint(val[0], 10, 16)
if err != nil {
return nil, err
}
port.Count = uint(cnt)
case "socketActivated":
sa, err := strconv.ParseBool(val[0])
if err != nil {
return nil, err
}
port.SocketActivated = sa
default:
return nil, fmt.Errorf("unknown port parameter %q", key)
}
}
err = port.assertValid()
if err != nil {
return nil, err
}
return &port, nil
} | [
"func",
"PortFromString",
"(",
"pt",
"string",
")",
"(",
"*",
"Port",
",",
"error",
")",
"{",
"var",
"port",
"Port",
"\n\n",
"pt",
"=",
"\"",
"\"",
"+",
"pt",
"\n",
"ptQuery",
",",
"err",
":=",
"common",
".",
"MakeQueryString",
"(",
"pt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"v",
",",
"err",
":=",
"url",
".",
"ParseQuery",
"(",
"ptQuery",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"for",
"key",
",",
"val",
":=",
"range",
"v",
"{",
"if",
"len",
"(",
"val",
")",
">",
"1",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"key",
",",
"val",
")",
"\n",
"}",
"\n\n",
"switch",
"key",
"{",
"case",
"\"",
"\"",
":",
"acn",
",",
"err",
":=",
"NewACName",
"(",
"val",
"[",
"0",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"port",
".",
"Name",
"=",
"*",
"acn",
"\n",
"case",
"\"",
"\"",
":",
"port",
".",
"Protocol",
"=",
"val",
"[",
"0",
"]",
"\n",
"case",
"\"",
"\"",
":",
"p",
",",
"err",
":=",
"strconv",
".",
"ParseUint",
"(",
"val",
"[",
"0",
"]",
",",
"10",
",",
"16",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"port",
".",
"Port",
"=",
"uint",
"(",
"p",
")",
"\n",
"case",
"\"",
"\"",
":",
"cnt",
",",
"err",
":=",
"strconv",
".",
"ParseUint",
"(",
"val",
"[",
"0",
"]",
",",
"10",
",",
"16",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"port",
".",
"Count",
"=",
"uint",
"(",
"cnt",
")",
"\n",
"case",
"\"",
"\"",
":",
"sa",
",",
"err",
":=",
"strconv",
".",
"ParseBool",
"(",
"val",
"[",
"0",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"port",
".",
"SocketActivated",
"=",
"sa",
"\n",
"default",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"key",
")",
"\n",
"}",
"\n",
"}",
"\n",
"err",
"=",
"port",
".",
"assertValid",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"port",
",",
"nil",
"\n",
"}"
] | // PortFromString takes a command line port parameter and returns a port
//
// It is useful for actool patch-manifest --ports
//
// Example port parameters:
// health-check,protocol=udp,port=8000
// query,protocol=tcp,port=8080,count=1,socketActivated=true | [
"PortFromString",
"takes",
"a",
"command",
"line",
"port",
"parameter",
"and",
"returns",
"a",
"port",
"It",
"is",
"useful",
"for",
"actool",
"patch",
"-",
"manifest",
"--",
"ports",
"Example",
"port",
"parameters",
":",
"health",
"-",
"check",
"protocol",
"=",
"udp",
"port",
"=",
"8000",
"query",
"protocol",
"=",
"tcp",
"port",
"=",
"8080",
"count",
"=",
"1",
"socketActivated",
"=",
"true"
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/port.go#L92-L147 |
appc/spec | schema/types/mountpoint.go | MountPointFromString | func MountPointFromString(mp string) (*MountPoint, error) {
var mount MountPoint
mp = "name=" + mp
mpQuery, err := common.MakeQueryString(mp)
if err != nil {
return nil, err
}
v, err := url.ParseQuery(mpQuery)
if err != nil {
return nil, err
}
for key, val := range v {
if len(val) > 1 {
return nil, fmt.Errorf("label %s with multiple values %q", key, val)
}
switch key {
case "name":
acn, err := NewACName(val[0])
if err != nil {
return nil, err
}
mount.Name = *acn
case "path":
mount.Path = val[0]
case "readOnly":
ro, err := strconv.ParseBool(val[0])
if err != nil {
return nil, err
}
mount.ReadOnly = ro
default:
return nil, fmt.Errorf("unknown mountpoint parameter %q", key)
}
}
err = mount.assertValid()
if err != nil {
return nil, err
}
return &mount, nil
} | go | func MountPointFromString(mp string) (*MountPoint, error) {
var mount MountPoint
mp = "name=" + mp
mpQuery, err := common.MakeQueryString(mp)
if err != nil {
return nil, err
}
v, err := url.ParseQuery(mpQuery)
if err != nil {
return nil, err
}
for key, val := range v {
if len(val) > 1 {
return nil, fmt.Errorf("label %s with multiple values %q", key, val)
}
switch key {
case "name":
acn, err := NewACName(val[0])
if err != nil {
return nil, err
}
mount.Name = *acn
case "path":
mount.Path = val[0]
case "readOnly":
ro, err := strconv.ParseBool(val[0])
if err != nil {
return nil, err
}
mount.ReadOnly = ro
default:
return nil, fmt.Errorf("unknown mountpoint parameter %q", key)
}
}
err = mount.assertValid()
if err != nil {
return nil, err
}
return &mount, nil
} | [
"func",
"MountPointFromString",
"(",
"mp",
"string",
")",
"(",
"*",
"MountPoint",
",",
"error",
")",
"{",
"var",
"mount",
"MountPoint",
"\n\n",
"mp",
"=",
"\"",
"\"",
"+",
"mp",
"\n",
"mpQuery",
",",
"err",
":=",
"common",
".",
"MakeQueryString",
"(",
"mp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"v",
",",
"err",
":=",
"url",
".",
"ParseQuery",
"(",
"mpQuery",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"for",
"key",
",",
"val",
":=",
"range",
"v",
"{",
"if",
"len",
"(",
"val",
")",
">",
"1",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"key",
",",
"val",
")",
"\n",
"}",
"\n\n",
"switch",
"key",
"{",
"case",
"\"",
"\"",
":",
"acn",
",",
"err",
":=",
"NewACName",
"(",
"val",
"[",
"0",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"mount",
".",
"Name",
"=",
"*",
"acn",
"\n",
"case",
"\"",
"\"",
":",
"mount",
".",
"Path",
"=",
"val",
"[",
"0",
"]",
"\n",
"case",
"\"",
"\"",
":",
"ro",
",",
"err",
":=",
"strconv",
".",
"ParseBool",
"(",
"val",
"[",
"0",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"mount",
".",
"ReadOnly",
"=",
"ro",
"\n",
"default",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"key",
")",
"\n",
"}",
"\n",
"}",
"\n",
"err",
"=",
"mount",
".",
"assertValid",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"mount",
",",
"nil",
"\n",
"}"
] | // MountPointFromString takes a command line mountpoint parameter and returns a mountpoint
//
// It is useful for actool patch-manifest --mounts
//
// Example mountpoint parameters:
// database,path=/tmp,readOnly=true | [
"MountPointFromString",
"takes",
"a",
"command",
"line",
"mountpoint",
"parameter",
"and",
"returns",
"a",
"mountpoint",
"It",
"is",
"useful",
"for",
"actool",
"patch",
"-",
"manifest",
"--",
"mounts",
"Example",
"mountpoint",
"parameters",
":",
"database",
"path",
"=",
"/",
"tmp",
"readOnly",
"=",
"true"
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/mountpoint.go#L49-L92 |
appc/spec | schema/types/isolator.go | assertValid | func (isolators Isolators) assertValid() error {
typesMap := make(map[ACIdentifier]bool)
for _, i := range isolators {
v := i.Value()
if v == nil {
return ErrInvalidIsolator
}
if err := v.AssertValid(); err != nil {
return err
}
if _, ok := typesMap[i.Name]; ok {
if !v.multipleAllowed() {
return fmt.Errorf(`isolators set contains too many instances of type %s"`, i.Name)
}
}
for _, c := range v.Conflicts() {
if _, found := typesMap[c]; found {
return ErrIncompatibleIsolator
}
}
typesMap[i.Name] = true
}
return nil
} | go | func (isolators Isolators) assertValid() error {
typesMap := make(map[ACIdentifier]bool)
for _, i := range isolators {
v := i.Value()
if v == nil {
return ErrInvalidIsolator
}
if err := v.AssertValid(); err != nil {
return err
}
if _, ok := typesMap[i.Name]; ok {
if !v.multipleAllowed() {
return fmt.Errorf(`isolators set contains too many instances of type %s"`, i.Name)
}
}
for _, c := range v.Conflicts() {
if _, found := typesMap[c]; found {
return ErrIncompatibleIsolator
}
}
typesMap[i.Name] = true
}
return nil
} | [
"func",
"(",
"isolators",
"Isolators",
")",
"assertValid",
"(",
")",
"error",
"{",
"typesMap",
":=",
"make",
"(",
"map",
"[",
"ACIdentifier",
"]",
"bool",
")",
"\n",
"for",
"_",
",",
"i",
":=",
"range",
"isolators",
"{",
"v",
":=",
"i",
".",
"Value",
"(",
")",
"\n",
"if",
"v",
"==",
"nil",
"{",
"return",
"ErrInvalidIsolator",
"\n",
"}",
"\n",
"if",
"err",
":=",
"v",
".",
"AssertValid",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"typesMap",
"[",
"i",
".",
"Name",
"]",
";",
"ok",
"{",
"if",
"!",
"v",
".",
"multipleAllowed",
"(",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"`isolators set contains too many instances of type %s\"`",
",",
"i",
".",
"Name",
")",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"c",
":=",
"range",
"v",
".",
"Conflicts",
"(",
")",
"{",
"if",
"_",
",",
"found",
":=",
"typesMap",
"[",
"c",
"]",
";",
"found",
"{",
"return",
"ErrIncompatibleIsolator",
"\n",
"}",
"\n",
"}",
"\n",
"typesMap",
"[",
"i",
".",
"Name",
"]",
"=",
"true",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // assertValid checks that every single isolator is valid and that
// the whole set is well built | [
"assertValid",
"checks",
"that",
"every",
"single",
"isolator",
"is",
"valid",
"and",
"that",
"the",
"whole",
"set",
"is",
"well",
"built"
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/isolator.go#L54-L77 |
appc/spec | schema/types/isolator.go | GetByName | func (is *Isolators) GetByName(name ACIdentifier) *Isolator {
var i Isolator
for j := len(*is) - 1; j >= 0; j-- {
i = []Isolator(*is)[j]
if i.Name == name {
return &i
}
}
return nil
} | go | func (is *Isolators) GetByName(name ACIdentifier) *Isolator {
var i Isolator
for j := len(*is) - 1; j >= 0; j-- {
i = []Isolator(*is)[j]
if i.Name == name {
return &i
}
}
return nil
} | [
"func",
"(",
"is",
"*",
"Isolators",
")",
"GetByName",
"(",
"name",
"ACIdentifier",
")",
"*",
"Isolator",
"{",
"var",
"i",
"Isolator",
"\n",
"for",
"j",
":=",
"len",
"(",
"*",
"is",
")",
"-",
"1",
";",
"j",
">=",
"0",
";",
"j",
"--",
"{",
"i",
"=",
"[",
"]",
"Isolator",
"(",
"*",
"is",
")",
"[",
"j",
"]",
"\n",
"if",
"i",
".",
"Name",
"==",
"name",
"{",
"return",
"&",
"i",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // GetByName returns the last isolator in the list by the given name. | [
"GetByName",
"returns",
"the",
"last",
"isolator",
"in",
"the",
"list",
"by",
"the",
"given",
"name",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/isolator.go#L80-L89 |
appc/spec | schema/types/isolator.go | ReplaceIsolatorsByName | func (is *Isolators) ReplaceIsolatorsByName(newIs Isolator, oldNames []ACIdentifier) {
var i Isolator
for j := len(*is) - 1; j >= 0; j-- {
i = []Isolator(*is)[j]
for _, name := range oldNames {
if i.Name == name {
*is = append((*is)[:j], (*is)[j+1:]...)
}
}
}
*is = append((*is)[:], newIs)
return
} | go | func (is *Isolators) ReplaceIsolatorsByName(newIs Isolator, oldNames []ACIdentifier) {
var i Isolator
for j := len(*is) - 1; j >= 0; j-- {
i = []Isolator(*is)[j]
for _, name := range oldNames {
if i.Name == name {
*is = append((*is)[:j], (*is)[j+1:]...)
}
}
}
*is = append((*is)[:], newIs)
return
} | [
"func",
"(",
"is",
"*",
"Isolators",
")",
"ReplaceIsolatorsByName",
"(",
"newIs",
"Isolator",
",",
"oldNames",
"[",
"]",
"ACIdentifier",
")",
"{",
"var",
"i",
"Isolator",
"\n",
"for",
"j",
":=",
"len",
"(",
"*",
"is",
")",
"-",
"1",
";",
"j",
">=",
"0",
";",
"j",
"--",
"{",
"i",
"=",
"[",
"]",
"Isolator",
"(",
"*",
"is",
")",
"[",
"j",
"]",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"oldNames",
"{",
"if",
"i",
".",
"Name",
"==",
"name",
"{",
"*",
"is",
"=",
"append",
"(",
"(",
"*",
"is",
")",
"[",
":",
"j",
"]",
",",
"(",
"*",
"is",
")",
"[",
"j",
"+",
"1",
":",
"]",
"...",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"*",
"is",
"=",
"append",
"(",
"(",
"*",
"is",
")",
"[",
":",
"]",
",",
"newIs",
")",
"\n",
"return",
"\n",
"}"
] | // ReplaceIsolatorsByName overrides matching isolator types with a new
// isolator, deleting them all and appending the new one instead | [
"ReplaceIsolatorsByName",
"overrides",
"matching",
"isolator",
"types",
"with",
"a",
"new",
"isolator",
"deleting",
"them",
"all",
"and",
"appending",
"the",
"new",
"one",
"instead"
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/isolator.go#L93-L105 |
appc/spec | schema/types/isolator.go | Unrecognized | func (is *Isolators) Unrecognized() Isolators {
u := Isolators{}
for _, i := range *is {
if i.value == nil {
u = append(u, i)
}
}
return u
} | go | func (is *Isolators) Unrecognized() Isolators {
u := Isolators{}
for _, i := range *is {
if i.value == nil {
u = append(u, i)
}
}
return u
} | [
"func",
"(",
"is",
"*",
"Isolators",
")",
"Unrecognized",
"(",
")",
"Isolators",
"{",
"u",
":=",
"Isolators",
"{",
"}",
"\n",
"for",
"_",
",",
"i",
":=",
"range",
"*",
"is",
"{",
"if",
"i",
".",
"value",
"==",
"nil",
"{",
"u",
"=",
"append",
"(",
"u",
",",
"i",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"u",
"\n",
"}"
] | // Unrecognized returns a set of isolators that are not recognized.
// An isolator is not recognized if it has not had an associated
// constructor registered with AddIsolatorValueConstructor. | [
"Unrecognized",
"returns",
"a",
"set",
"of",
"isolators",
"that",
"are",
"not",
"recognized",
".",
"An",
"isolator",
"is",
"not",
"recognized",
"if",
"it",
"has",
"not",
"had",
"an",
"associated",
"constructor",
"registered",
"with",
"AddIsolatorValueConstructor",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/isolator.go#L110-L118 |
appc/spec | schema/types/isolator.go | UnmarshalJSON | func (i *Isolator) UnmarshalJSON(b []byte) error {
var ii isolator
err := json.Unmarshal(b, &ii)
if err != nil {
return err
}
var dst IsolatorValue
con, ok := isolatorMap[ii.Name]
if ok {
dst = con()
err = dst.UnmarshalJSON(*ii.ValueRaw)
if err != nil {
return err
}
err = dst.AssertValid()
if err != nil {
return err
}
}
i.value = dst
i.ValueRaw = ii.ValueRaw
i.Name = ii.Name
return nil
} | go | func (i *Isolator) UnmarshalJSON(b []byte) error {
var ii isolator
err := json.Unmarshal(b, &ii)
if err != nil {
return err
}
var dst IsolatorValue
con, ok := isolatorMap[ii.Name]
if ok {
dst = con()
err = dst.UnmarshalJSON(*ii.ValueRaw)
if err != nil {
return err
}
err = dst.AssertValid()
if err != nil {
return err
}
}
i.value = dst
i.ValueRaw = ii.ValueRaw
i.Name = ii.Name
return nil
} | [
"func",
"(",
"i",
"*",
"Isolator",
")",
"UnmarshalJSON",
"(",
"b",
"[",
"]",
"byte",
")",
"error",
"{",
"var",
"ii",
"isolator",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"b",
",",
"&",
"ii",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"var",
"dst",
"IsolatorValue",
"\n",
"con",
",",
"ok",
":=",
"isolatorMap",
"[",
"ii",
".",
"Name",
"]",
"\n",
"if",
"ok",
"{",
"dst",
"=",
"con",
"(",
")",
"\n",
"err",
"=",
"dst",
".",
"UnmarshalJSON",
"(",
"*",
"ii",
".",
"ValueRaw",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"dst",
".",
"AssertValid",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"i",
".",
"value",
"=",
"dst",
"\n",
"i",
".",
"ValueRaw",
"=",
"ii",
".",
"ValueRaw",
"\n",
"i",
".",
"Name",
"=",
"ii",
".",
"Name",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // UnmarshalJSON populates this Isolator from a JSON-encoded representation. To
// unmarshal the Value of the Isolator, it will use the appropriate constructor
// as registered by AddIsolatorValueConstructor. | [
"UnmarshalJSON",
"populates",
"this",
"Isolator",
"from",
"a",
"JSON",
"-",
"encoded",
"representation",
".",
"To",
"unmarshal",
"the",
"Value",
"of",
"the",
"Isolator",
"it",
"will",
"use",
"the",
"appropriate",
"constructor",
"as",
"registered",
"by",
"AddIsolatorValueConstructor",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/isolator.go#L164-L190 |
appc/spec | schema/image.go | assertValid | func (im *ImageManifest) assertValid() error {
if im.ACKind != ImageManifestKind {
return imKindError
}
if im.ACVersion.Empty() {
return errors.New(`acVersion must be set`)
}
if im.Name.Empty() {
return errors.New(`name must be set`)
}
return nil
} | go | func (im *ImageManifest) assertValid() error {
if im.ACKind != ImageManifestKind {
return imKindError
}
if im.ACVersion.Empty() {
return errors.New(`acVersion must be set`)
}
if im.Name.Empty() {
return errors.New(`name must be set`)
}
return nil
} | [
"func",
"(",
"im",
"*",
"ImageManifest",
")",
"assertValid",
"(",
")",
"error",
"{",
"if",
"im",
".",
"ACKind",
"!=",
"ImageManifestKind",
"{",
"return",
"imKindError",
"\n",
"}",
"\n",
"if",
"im",
".",
"ACVersion",
".",
"Empty",
"(",
")",
"{",
"return",
"errors",
".",
"New",
"(",
"`acVersion must be set`",
")",
"\n",
"}",
"\n",
"if",
"im",
".",
"Name",
".",
"Empty",
"(",
")",
"{",
"return",
"errors",
".",
"New",
"(",
"`name must be set`",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // assertValid performs extra assertions on an ImageManifest to ensure that
// fields are set appropriately, etc. It is used exclusively when marshalling
// and unmarshalling an ImageManifest. Most field-specific validation is
// performed through the individual types being marshalled; assertValid()
// should only deal with higher-level validation. | [
"assertValid",
"performs",
"extra",
"assertions",
"on",
"an",
"ImageManifest",
"to",
"ensure",
"that",
"fields",
"are",
"set",
"appropriately",
"etc",
".",
"It",
"is",
"used",
"exclusively",
"when",
"marshalling",
"and",
"unmarshalling",
"an",
"ImageManifest",
".",
"Most",
"field",
"-",
"specific",
"validation",
"is",
"performed",
"through",
"the",
"individual",
"types",
"being",
"marshalled",
";",
"assertValid",
"()",
"should",
"only",
"deal",
"with",
"higher",
"-",
"level",
"validation",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/image.go#L84-L95 |
appc/spec | schema/types/labels.go | IsValidOSArch | func IsValidOSArch(labels map[ACIdentifier]string, validOSArch map[string][]string) error {
if os, ok := labels["os"]; ok {
if validArchs, ok := validOSArch[os]; !ok {
// Not a whitelisted OS. TODO: how to warn rather than fail?
validOses := make([]string, 0, len(validOSArch))
for validOs := range validOSArch {
validOses = append(validOses, validOs)
}
sort.Strings(validOses)
return fmt.Errorf(`bad os %#v (must be one of: %v)`, os, validOses)
} else {
// Whitelisted OS. We check arch here, as arch makes sense only
// when os is defined.
if arch, ok := labels["arch"]; ok {
found := false
for _, validArch := range validArchs {
if arch == validArch {
found = true
break
}
}
if !found {
return fmt.Errorf(`bad arch %#v for %v (must be one of: %v)`, arch, os, validArchs)
}
}
}
}
return nil
} | go | func IsValidOSArch(labels map[ACIdentifier]string, validOSArch map[string][]string) error {
if os, ok := labels["os"]; ok {
if validArchs, ok := validOSArch[os]; !ok {
// Not a whitelisted OS. TODO: how to warn rather than fail?
validOses := make([]string, 0, len(validOSArch))
for validOs := range validOSArch {
validOses = append(validOses, validOs)
}
sort.Strings(validOses)
return fmt.Errorf(`bad os %#v (must be one of: %v)`, os, validOses)
} else {
// Whitelisted OS. We check arch here, as arch makes sense only
// when os is defined.
if arch, ok := labels["arch"]; ok {
found := false
for _, validArch := range validArchs {
if arch == validArch {
found = true
break
}
}
if !found {
return fmt.Errorf(`bad arch %#v for %v (must be one of: %v)`, arch, os, validArchs)
}
}
}
}
return nil
} | [
"func",
"IsValidOSArch",
"(",
"labels",
"map",
"[",
"ACIdentifier",
"]",
"string",
",",
"validOSArch",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
")",
"error",
"{",
"if",
"os",
",",
"ok",
":=",
"labels",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"if",
"validArchs",
",",
"ok",
":=",
"validOSArch",
"[",
"os",
"]",
";",
"!",
"ok",
"{",
"// Not a whitelisted OS. TODO: how to warn rather than fail?",
"validOses",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"validOSArch",
")",
")",
"\n",
"for",
"validOs",
":=",
"range",
"validOSArch",
"{",
"validOses",
"=",
"append",
"(",
"validOses",
",",
"validOs",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"validOses",
")",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"`bad os %#v (must be one of: %v)`",
",",
"os",
",",
"validOses",
")",
"\n",
"}",
"else",
"{",
"// Whitelisted OS. We check arch here, as arch makes sense only",
"// when os is defined.",
"if",
"arch",
",",
"ok",
":=",
"labels",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"found",
":=",
"false",
"\n",
"for",
"_",
",",
"validArch",
":=",
"range",
"validArchs",
"{",
"if",
"arch",
"==",
"validArch",
"{",
"found",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"found",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"`bad arch %#v for %v (must be one of: %v)`",
",",
"arch",
",",
"os",
",",
"validArchs",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // IsValidOsArch checks if a OS-architecture combination is valid given a map
// of valid OS-architectures | [
"IsValidOsArch",
"checks",
"if",
"a",
"OS",
"-",
"architecture",
"combination",
"is",
"valid",
"given",
"a",
"map",
"of",
"valid",
"OS",
"-",
"architectures"
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/labels.go#L55-L83 |
appc/spec | schema/types/labels.go | Get | func (l Labels) Get(name string) (val string, ok bool) {
for _, lbl := range l {
if lbl.Name.String() == name {
return lbl.Value, true
}
}
return "", false
} | go | func (l Labels) Get(name string) (val string, ok bool) {
for _, lbl := range l {
if lbl.Name.String() == name {
return lbl.Value, true
}
}
return "", false
} | [
"func",
"(",
"l",
"Labels",
")",
"Get",
"(",
"name",
"string",
")",
"(",
"val",
"string",
",",
"ok",
"bool",
")",
"{",
"for",
"_",
",",
"lbl",
":=",
"range",
"l",
"{",
"if",
"lbl",
".",
"Name",
".",
"String",
"(",
")",
"==",
"name",
"{",
"return",
"lbl",
".",
"Value",
",",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
",",
"false",
"\n",
"}"
] | // Get retrieves the value of the label by the given name from Labels, if it exists | [
"Get",
"retrieves",
"the",
"value",
"of",
"the",
"label",
"by",
"the",
"given",
"name",
"from",
"Labels",
"if",
"it",
"exists"
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/labels.go#L121-L128 |
appc/spec | schema/types/labels.go | ToMap | func (l Labels) ToMap() map[ACIdentifier]string {
labelsMap := make(map[ACIdentifier]string)
for _, lbl := range l {
labelsMap[lbl.Name] = lbl.Value
}
return labelsMap
} | go | func (l Labels) ToMap() map[ACIdentifier]string {
labelsMap := make(map[ACIdentifier]string)
for _, lbl := range l {
labelsMap[lbl.Name] = lbl.Value
}
return labelsMap
} | [
"func",
"(",
"l",
"Labels",
")",
"ToMap",
"(",
")",
"map",
"[",
"ACIdentifier",
"]",
"string",
"{",
"labelsMap",
":=",
"make",
"(",
"map",
"[",
"ACIdentifier",
"]",
"string",
")",
"\n",
"for",
"_",
",",
"lbl",
":=",
"range",
"l",
"{",
"labelsMap",
"[",
"lbl",
".",
"Name",
"]",
"=",
"lbl",
".",
"Value",
"\n",
"}",
"\n",
"return",
"labelsMap",
"\n",
"}"
] | // ToMap creates a map[ACIdentifier]string. | [
"ToMap",
"creates",
"a",
"map",
"[",
"ACIdentifier",
"]",
"string",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/labels.go#L131-L137 |
appc/spec | schema/types/labels.go | LabelsFromMap | func LabelsFromMap(labelsMap map[ACIdentifier]string) (Labels, error) {
labels := Labels{}
for n, v := range labelsMap {
labels = append(labels, Label{Name: n, Value: v})
}
if err := labels.assertValid(); err != nil {
return nil, err
}
sort.Sort(labelsSlice(labels))
return labels, nil
} | go | func LabelsFromMap(labelsMap map[ACIdentifier]string) (Labels, error) {
labels := Labels{}
for n, v := range labelsMap {
labels = append(labels, Label{Name: n, Value: v})
}
if err := labels.assertValid(); err != nil {
return nil, err
}
sort.Sort(labelsSlice(labels))
return labels, nil
} | [
"func",
"LabelsFromMap",
"(",
"labelsMap",
"map",
"[",
"ACIdentifier",
"]",
"string",
")",
"(",
"Labels",
",",
"error",
")",
"{",
"labels",
":=",
"Labels",
"{",
"}",
"\n",
"for",
"n",
",",
"v",
":=",
"range",
"labelsMap",
"{",
"labels",
"=",
"append",
"(",
"labels",
",",
"Label",
"{",
"Name",
":",
"n",
",",
"Value",
":",
"v",
"}",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"labels",
".",
"assertValid",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"sort",
".",
"Sort",
"(",
"labelsSlice",
"(",
"labels",
")",
")",
"\n",
"return",
"labels",
",",
"nil",
"\n",
"}"
] | // LabelsFromMap creates Labels from a map[ACIdentifier]string | [
"LabelsFromMap",
"creates",
"Labels",
"from",
"a",
"map",
"[",
"ACIdentifier",
"]",
"string"
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/labels.go#L140-L150 |
appc/spec | schema/types/labels.go | ToAppcOSArch | func ToAppcOSArch(goOs string, goArch string, goArchFlavor string) (appcOs string, appcArch string, e error) {
tabularAppcToGo := map[goArchTuple]appcArchTuple{
{"linux", "amd64", ""}: {"linux", "amd64"},
{"linux", "386", ""}: {"linux", "i386"},
{"linux", "arm64", ""}: {"linux", "aarch64"},
{"linux", "arm", ""}: {"linux", "armv6l"},
{"linux", "arm", "6"}: {"linux", "armv6l"},
{"linux", "arm", "7"}: {"linux", "armv7l"},
{"linux", "ppc64", ""}: {"linux", "ppc64"},
{"linux", "ppc64le", ""}: {"linux", "ppc64le"},
{"linux", "s390x", ""}: {"linux", "s390x"},
{"freebsd", "amd64", ""}: {"freebsd", "amd64"},
{"freebsd", "386", ""}: {"freebsd", "i386"},
{"freebsd", "arm", ""}: {"freebsd", "arm"},
{"freebsd", "arm", "5"}: {"freebsd", "arm"},
{"freebsd", "arm", "6"}: {"freebsd", "arm"},
{"freebsd", "arm", "7"}: {"freebsd", "arm"},
{"darwin", "amd64", ""}: {"darwin", "x86_64"},
{"darwin", "386", ""}: {"darwin", "i386"},
}
archTuple, ok := tabularAppcToGo[goArchTuple{goOs, goArch, goArchFlavor}]
if !ok {
return "", "", fmt.Errorf("unknown arch tuple: %q - %q - %q", goOs, goArch, goArchFlavor)
}
return archTuple.appcOs, archTuple.appcArch, nil
} | go | func ToAppcOSArch(goOs string, goArch string, goArchFlavor string) (appcOs string, appcArch string, e error) {
tabularAppcToGo := map[goArchTuple]appcArchTuple{
{"linux", "amd64", ""}: {"linux", "amd64"},
{"linux", "386", ""}: {"linux", "i386"},
{"linux", "arm64", ""}: {"linux", "aarch64"},
{"linux", "arm", ""}: {"linux", "armv6l"},
{"linux", "arm", "6"}: {"linux", "armv6l"},
{"linux", "arm", "7"}: {"linux", "armv7l"},
{"linux", "ppc64", ""}: {"linux", "ppc64"},
{"linux", "ppc64le", ""}: {"linux", "ppc64le"},
{"linux", "s390x", ""}: {"linux", "s390x"},
{"freebsd", "amd64", ""}: {"freebsd", "amd64"},
{"freebsd", "386", ""}: {"freebsd", "i386"},
{"freebsd", "arm", ""}: {"freebsd", "arm"},
{"freebsd", "arm", "5"}: {"freebsd", "arm"},
{"freebsd", "arm", "6"}: {"freebsd", "arm"},
{"freebsd", "arm", "7"}: {"freebsd", "arm"},
{"darwin", "amd64", ""}: {"darwin", "x86_64"},
{"darwin", "386", ""}: {"darwin", "i386"},
}
archTuple, ok := tabularAppcToGo[goArchTuple{goOs, goArch, goArchFlavor}]
if !ok {
return "", "", fmt.Errorf("unknown arch tuple: %q - %q - %q", goOs, goArch, goArchFlavor)
}
return archTuple.appcOs, archTuple.appcArch, nil
} | [
"func",
"ToAppcOSArch",
"(",
"goOs",
"string",
",",
"goArch",
"string",
",",
"goArchFlavor",
"string",
")",
"(",
"appcOs",
"string",
",",
"appcArch",
"string",
",",
"e",
"error",
")",
"{",
"tabularAppcToGo",
":=",
"map",
"[",
"goArchTuple",
"]",
"appcArchTuple",
"{",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"}",
"\n",
"archTuple",
",",
"ok",
":=",
"tabularAppcToGo",
"[",
"goArchTuple",
"{",
"goOs",
",",
"goArch",
",",
"goArchFlavor",
"}",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"goOs",
",",
"goArch",
",",
"goArchFlavor",
")",
"\n",
"}",
"\n",
"return",
"archTuple",
".",
"appcOs",
",",
"archTuple",
".",
"appcArch",
",",
"nil",
"\n",
"}"
] | // ToAppcOSArch translates a Golang arch tuple (OS, architecture, flavor) into
// an appc arch tuple (OS, architecture) | [
"ToAppcOSArch",
"translates",
"a",
"Golang",
"arch",
"tuple",
"(",
"OS",
"architecture",
"flavor",
")",
"into",
"an",
"appc",
"arch",
"tuple",
"(",
"OS",
"architecture",
")"
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/labels.go#L154-L181 |
appc/spec | schema/types/labels.go | ToGoOSArch | func ToGoOSArch(appcOs string, appcArch string) (goOs string, goArch string, goArchFlavor string, e error) {
tabularGoToAppc := map[appcArchTuple]goArchTuple{
// {"linux", "aarch64_be"}: nil,
// {"linux", "armv7b"}: nil,
{"linux", "aarch64"}: {"linux", "arm64", ""},
{"linux", "amd64"}: {"linux", "amd64", ""},
{"linux", "armv6l"}: {"linux", "arm", "6"},
{"linux", "armv7l"}: {"linux", "arm", "7"},
{"linux", "i386"}: {"linux", "386", ""},
{"linux", "ppc64"}: {"linux", "ppc64", ""},
{"linux", "ppc64le"}: {"linux", "ppc64le", ""},
{"linux", "s390x"}: {"linux", "s390x", ""},
{"freebsd", "amd64"}: {"freebsd", "amd64", ""},
{"freebsd", "arm"}: {"freebsd", "arm", "6"},
{"freebsd", "386"}: {"freebsd", "i386", ""},
{"darwin", "amd64"}: {"darwin", "x86_64", ""},
{"darwin", "386"}: {"darwin", "i386", ""},
}
archTuple, ok := tabularGoToAppc[appcArchTuple{appcOs, appcArch}]
if !ok {
return "", "", "", fmt.Errorf("unknown arch tuple: %q - %q", appcOs, appcArch)
}
return archTuple.goOs, archTuple.goArch, archTuple.goArchFlavor, nil
} | go | func ToGoOSArch(appcOs string, appcArch string) (goOs string, goArch string, goArchFlavor string, e error) {
tabularGoToAppc := map[appcArchTuple]goArchTuple{
// {"linux", "aarch64_be"}: nil,
// {"linux", "armv7b"}: nil,
{"linux", "aarch64"}: {"linux", "arm64", ""},
{"linux", "amd64"}: {"linux", "amd64", ""},
{"linux", "armv6l"}: {"linux", "arm", "6"},
{"linux", "armv7l"}: {"linux", "arm", "7"},
{"linux", "i386"}: {"linux", "386", ""},
{"linux", "ppc64"}: {"linux", "ppc64", ""},
{"linux", "ppc64le"}: {"linux", "ppc64le", ""},
{"linux", "s390x"}: {"linux", "s390x", ""},
{"freebsd", "amd64"}: {"freebsd", "amd64", ""},
{"freebsd", "arm"}: {"freebsd", "arm", "6"},
{"freebsd", "386"}: {"freebsd", "i386", ""},
{"darwin", "amd64"}: {"darwin", "x86_64", ""},
{"darwin", "386"}: {"darwin", "i386", ""},
}
archTuple, ok := tabularGoToAppc[appcArchTuple{appcOs, appcArch}]
if !ok {
return "", "", "", fmt.Errorf("unknown arch tuple: %q - %q", appcOs, appcArch)
}
return archTuple.goOs, archTuple.goArch, archTuple.goArchFlavor, nil
} | [
"func",
"ToGoOSArch",
"(",
"appcOs",
"string",
",",
"appcArch",
"string",
")",
"(",
"goOs",
"string",
",",
"goArch",
"string",
",",
"goArchFlavor",
"string",
",",
"e",
"error",
")",
"{",
"tabularGoToAppc",
":=",
"map",
"[",
"appcArchTuple",
"]",
"goArchTuple",
"{",
"// {\"linux\", \"aarch64_be\"}: nil,",
"// {\"linux\", \"armv7b\"}: nil,",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"{",
"\"",
"\"",
",",
"\"",
"\"",
"}",
":",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
",",
"}",
"\n\n",
"archTuple",
",",
"ok",
":=",
"tabularGoToAppc",
"[",
"appcArchTuple",
"{",
"appcOs",
",",
"appcArch",
"}",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"appcOs",
",",
"appcArch",
")",
"\n",
"}",
"\n",
"return",
"archTuple",
".",
"goOs",
",",
"archTuple",
".",
"goArch",
",",
"archTuple",
".",
"goArchFlavor",
",",
"nil",
"\n",
"}"
] | // ToGoOSArch translates an appc arch tuple (OS, architecture) into
// a Golang arch tuple (OS, architecture, flavor) | [
"ToGoOSArch",
"translates",
"an",
"appc",
"arch",
"tuple",
"(",
"OS",
"architecture",
")",
"into",
"a",
"Golang",
"arch",
"tuple",
"(",
"OS",
"architecture",
"flavor",
")"
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/labels.go#L185-L211 |
appc/spec | schema/pod.go | assertValid | func (pm *PodManifest) assertValid() error {
if pm.ACKind != PodManifestKind {
return pmKindError
}
// ensure volumes names are unique (unique key)
volNames := make(map[types.ACName]bool, len(pm.Volumes))
for _, vol := range pm.Volumes {
if volNames[vol.Name] {
return fmt.Errorf("duplicate volume name %q", vol.Name)
}
volNames[vol.Name] = true
}
return nil
} | go | func (pm *PodManifest) assertValid() error {
if pm.ACKind != PodManifestKind {
return pmKindError
}
// ensure volumes names are unique (unique key)
volNames := make(map[types.ACName]bool, len(pm.Volumes))
for _, vol := range pm.Volumes {
if volNames[vol.Name] {
return fmt.Errorf("duplicate volume name %q", vol.Name)
}
volNames[vol.Name] = true
}
return nil
} | [
"func",
"(",
"pm",
"*",
"PodManifest",
")",
"assertValid",
"(",
")",
"error",
"{",
"if",
"pm",
".",
"ACKind",
"!=",
"PodManifestKind",
"{",
"return",
"pmKindError",
"\n",
"}",
"\n\n",
"// ensure volumes names are unique (unique key)",
"volNames",
":=",
"make",
"(",
"map",
"[",
"types",
".",
"ACName",
"]",
"bool",
",",
"len",
"(",
"pm",
".",
"Volumes",
")",
")",
"\n",
"for",
"_",
",",
"vol",
":=",
"range",
"pm",
".",
"Volumes",
"{",
"if",
"volNames",
"[",
"vol",
".",
"Name",
"]",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"vol",
".",
"Name",
")",
"\n",
"}",
"\n",
"volNames",
"[",
"vol",
".",
"Name",
"]",
"=",
"true",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // assertValid performs extra assertions on an PodManifest to
// ensure that fields are set appropriately, etc. It is used exclusively when
// marshalling and unmarshalling an PodManifest. Most
// field-specific validation is performed through the individual types being
// marshalled; assertValid() should only deal with higher-level validation. | [
"assertValid",
"performs",
"extra",
"assertions",
"on",
"an",
"PodManifest",
"to",
"ensure",
"that",
"fields",
"are",
"set",
"appropriately",
"etc",
".",
"It",
"is",
"used",
"exclusively",
"when",
"marshalling",
"and",
"unmarshalling",
"an",
"PodManifest",
".",
"Most",
"field",
"-",
"specific",
"validation",
"is",
"performed",
"through",
"the",
"individual",
"types",
"being",
"marshalled",
";",
"assertValid",
"()",
"should",
"only",
"deal",
"with",
"higher",
"-",
"level",
"validation",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/pod.go#L82-L96 |
appc/spec | schema/pod.go | Get | func (al AppList) Get(name types.ACName) *RuntimeApp {
for _, a := range al {
if name.Equals(a.Name) {
aa := a
return &aa
}
}
return nil
} | go | func (al AppList) Get(name types.ACName) *RuntimeApp {
for _, a := range al {
if name.Equals(a.Name) {
aa := a
return &aa
}
}
return nil
} | [
"func",
"(",
"al",
"AppList",
")",
"Get",
"(",
"name",
"types",
".",
"ACName",
")",
"*",
"RuntimeApp",
"{",
"for",
"_",
",",
"a",
":=",
"range",
"al",
"{",
"if",
"name",
".",
"Equals",
"(",
"a",
".",
"Name",
")",
"{",
"aa",
":=",
"a",
"\n",
"return",
"&",
"aa",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Get retrieves an app by the specified name from the AppList; if there is
// no such app, nil is returned. The returned *RuntimeApp MUST be considered
// read-only. | [
"Get",
"retrieves",
"an",
"app",
"by",
"the",
"specified",
"name",
"from",
"the",
"AppList",
";",
"if",
"there",
"is",
"no",
"such",
"app",
"nil",
"is",
"returned",
".",
"The",
"returned",
"*",
"RuntimeApp",
"MUST",
"be",
"considered",
"read",
"-",
"only",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/pod.go#L137-L145 |
appc/spec | schema/types/environment.go | Get | func (e Environment) Get(name string) (value string, ok bool) {
for _, env := range e {
if env.Name == name {
return env.Value, true
}
}
return "", false
} | go | func (e Environment) Get(name string) (value string, ok bool) {
for _, env := range e {
if env.Name == name {
return env.Value, true
}
}
return "", false
} | [
"func",
"(",
"e",
"Environment",
")",
"Get",
"(",
"name",
"string",
")",
"(",
"value",
"string",
",",
"ok",
"bool",
")",
"{",
"for",
"_",
",",
"env",
":=",
"range",
"e",
"{",
"if",
"env",
".",
"Name",
"==",
"name",
"{",
"return",
"env",
".",
"Value",
",",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
",",
"false",
"\n",
"}"
] | // Retrieve the value of an environment variable by the given name from
// Environment, if it exists. | [
"Retrieve",
"the",
"value",
"of",
"an",
"environment",
"variable",
"by",
"the",
"given",
"name",
"from",
"Environment",
"if",
"it",
"exists",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/environment.go#L84-L91 |
appc/spec | schema/types/environment.go | Set | func (e *Environment) Set(name string, value string) {
for i, env := range *e {
if env.Name == name {
(*e)[i] = EnvironmentVariable{
Name: name,
Value: value,
}
return
}
}
env := EnvironmentVariable{
Name: name,
Value: value,
}
*e = append(*e, env)
} | go | func (e *Environment) Set(name string, value string) {
for i, env := range *e {
if env.Name == name {
(*e)[i] = EnvironmentVariable{
Name: name,
Value: value,
}
return
}
}
env := EnvironmentVariable{
Name: name,
Value: value,
}
*e = append(*e, env)
} | [
"func",
"(",
"e",
"*",
"Environment",
")",
"Set",
"(",
"name",
"string",
",",
"value",
"string",
")",
"{",
"for",
"i",
",",
"env",
":=",
"range",
"*",
"e",
"{",
"if",
"env",
".",
"Name",
"==",
"name",
"{",
"(",
"*",
"e",
")",
"[",
"i",
"]",
"=",
"EnvironmentVariable",
"{",
"Name",
":",
"name",
",",
"Value",
":",
"value",
",",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"env",
":=",
"EnvironmentVariable",
"{",
"Name",
":",
"name",
",",
"Value",
":",
"value",
",",
"}",
"\n",
"*",
"e",
"=",
"append",
"(",
"*",
"e",
",",
"env",
")",
"\n",
"}"
] | // Set sets the value of an environment variable by the given name,
// overwriting if one already exists. | [
"Set",
"sets",
"the",
"value",
"of",
"an",
"environment",
"variable",
"by",
"the",
"given",
"name",
"overwriting",
"if",
"one",
"already",
"exists",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/environment.go#L95-L110 |
appc/spec | schema/types/uuid.go | NewUUID | func NewUUID(s string) (*UUID, error) {
s = strings.Replace(s, "-", "", -1)
if len(s) != 32 {
return nil, errors.New("bad UUID length != 32")
}
dec, err := hex.DecodeString(s)
if err != nil {
return nil, err
}
var u UUID
for i, b := range dec {
u[i] = b
}
return &u, nil
} | go | func NewUUID(s string) (*UUID, error) {
s = strings.Replace(s, "-", "", -1)
if len(s) != 32 {
return nil, errors.New("bad UUID length != 32")
}
dec, err := hex.DecodeString(s)
if err != nil {
return nil, err
}
var u UUID
for i, b := range dec {
u[i] = b
}
return &u, nil
} | [
"func",
"NewUUID",
"(",
"s",
"string",
")",
"(",
"*",
"UUID",
",",
"error",
")",
"{",
"s",
"=",
"strings",
".",
"Replace",
"(",
"s",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"-",
"1",
")",
"\n",
"if",
"len",
"(",
"s",
")",
"!=",
"32",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"dec",
",",
"err",
":=",
"hex",
".",
"DecodeString",
"(",
"s",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"var",
"u",
"UUID",
"\n",
"for",
"i",
",",
"b",
":=",
"range",
"dec",
"{",
"u",
"[",
"i",
"]",
"=",
"b",
"\n",
"}",
"\n",
"return",
"&",
"u",
",",
"nil",
"\n",
"}"
] | // NewUUID generates a new UUID from the given string. If the string does not
// represent a valid UUID, nil and an error are returned. | [
"NewUUID",
"generates",
"a",
"new",
"UUID",
"from",
"the",
"given",
"string",
".",
"If",
"the",
"string",
"does",
"not",
"represent",
"a",
"valid",
"UUID",
"nil",
"and",
"an",
"error",
"are",
"returned",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/uuid.go#L52-L66 |
appc/spec | schema/types/acidentifier.go | Set | func (n *ACIdentifier) Set(s string) error {
nn, err := NewACIdentifier(s)
if err == nil {
*n = *nn
}
return err
} | go | func (n *ACIdentifier) Set(s string) error {
nn, err := NewACIdentifier(s)
if err == nil {
*n = *nn
}
return err
} | [
"func",
"(",
"n",
"*",
"ACIdentifier",
")",
"Set",
"(",
"s",
"string",
")",
"error",
"{",
"nn",
",",
"err",
":=",
"NewACIdentifier",
"(",
"s",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"*",
"n",
"=",
"*",
"nn",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // Set sets the ACIdentifier to the given value, if it is valid; if not,
// an error is returned. | [
"Set",
"sets",
"the",
"ACIdentifier",
"to",
"the",
"given",
"value",
"if",
"it",
"is",
"valid",
";",
"if",
"not",
"an",
"error",
"is",
"returned",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/acidentifier.go#L54-L60 |
appc/spec | schema/types/acidentifier.go | Equals | func (n ACIdentifier) Equals(o ACIdentifier) bool {
return strings.ToLower(string(n)) == strings.ToLower(string(o))
} | go | func (n ACIdentifier) Equals(o ACIdentifier) bool {
return strings.ToLower(string(n)) == strings.ToLower(string(o))
} | [
"func",
"(",
"n",
"ACIdentifier",
")",
"Equals",
"(",
"o",
"ACIdentifier",
")",
"bool",
"{",
"return",
"strings",
".",
"ToLower",
"(",
"string",
"(",
"n",
")",
")",
"==",
"strings",
".",
"ToLower",
"(",
"string",
"(",
"o",
")",
")",
"\n",
"}"
] | // Equals checks whether a given ACIdentifier is equal to this one. | [
"Equals",
"checks",
"whether",
"a",
"given",
"ACIdentifier",
"is",
"equal",
"to",
"this",
"one",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/acidentifier.go#L63-L65 |
appc/spec | schema/types/acidentifier.go | NewACIdentifier | func NewACIdentifier(s string) (*ACIdentifier, error) {
n := ACIdentifier(s)
if err := n.assertValid(); err != nil {
return nil, err
}
return &n, nil
} | go | func NewACIdentifier(s string) (*ACIdentifier, error) {
n := ACIdentifier(s)
if err := n.assertValid(); err != nil {
return nil, err
}
return &n, nil
} | [
"func",
"NewACIdentifier",
"(",
"s",
"string",
")",
"(",
"*",
"ACIdentifier",
",",
"error",
")",
"{",
"n",
":=",
"ACIdentifier",
"(",
"s",
")",
"\n",
"if",
"err",
":=",
"n",
".",
"assertValid",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"n",
",",
"nil",
"\n",
"}"
] | // NewACIdentifier generates a new ACIdentifier from a string. If the given string is
// not a valid ACIdentifier, nil and an error are returned. | [
"NewACIdentifier",
"generates",
"a",
"new",
"ACIdentifier",
"from",
"a",
"string",
".",
"If",
"the",
"given",
"string",
"is",
"not",
"a",
"valid",
"ACIdentifier",
"nil",
"and",
"an",
"error",
"are",
"returned",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/acidentifier.go#L74-L80 |
appc/spec | schema/types/acidentifier.go | MustACIdentifier | func MustACIdentifier(s string) *ACIdentifier {
n, err := NewACIdentifier(s)
if err != nil {
panic(err)
}
return n
} | go | func MustACIdentifier(s string) *ACIdentifier {
n, err := NewACIdentifier(s)
if err != nil {
panic(err)
}
return n
} | [
"func",
"MustACIdentifier",
"(",
"s",
"string",
")",
"*",
"ACIdentifier",
"{",
"n",
",",
"err",
":=",
"NewACIdentifier",
"(",
"s",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"n",
"\n",
"}"
] | // MustACIdentifier generates a new ACIdentifier from a string, If the given string is
// not a valid ACIdentifier, it panics. | [
"MustACIdentifier",
"generates",
"a",
"new",
"ACIdentifier",
"from",
"a",
"string",
"If",
"the",
"given",
"string",
"is",
"not",
"a",
"valid",
"ACIdentifier",
"it",
"panics",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/acidentifier.go#L84-L90 |
appc/spec | schema/types/acidentifier.go | UnmarshalJSON | func (n *ACIdentifier) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
nn, err := NewACIdentifier(s)
if err != nil {
return err
}
*n = *nn
return nil
} | go | func (n *ACIdentifier) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
nn, err := NewACIdentifier(s)
if err != nil {
return err
}
*n = *nn
return nil
} | [
"func",
"(",
"n",
"*",
"ACIdentifier",
")",
"UnmarshalJSON",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"var",
"s",
"string",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"&",
"s",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"nn",
",",
"err",
":=",
"NewACIdentifier",
"(",
"s",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"*",
"n",
"=",
"*",
"nn",
"\n",
"return",
"nil",
"\n",
"}"
] | // UnmarshalJSON implements the json.Unmarshaler interface | [
"UnmarshalJSON",
"implements",
"the",
"json",
".",
"Unmarshaler",
"interface"
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/acidentifier.go#L107-L118 |
appc/spec | schema/types/acidentifier.go | SanitizeACIdentifier | func SanitizeACIdentifier(s string) (string, error) {
s = strings.ToLower(s)
s = invalidACIdentifierChars.ReplaceAllString(s, "_")
s = invalidACIdentifierEdges.ReplaceAllString(s, "")
if s == "" {
return "", errors.New("must contain at least one valid character")
}
return s, nil
} | go | func SanitizeACIdentifier(s string) (string, error) {
s = strings.ToLower(s)
s = invalidACIdentifierChars.ReplaceAllString(s, "_")
s = invalidACIdentifierEdges.ReplaceAllString(s, "")
if s == "" {
return "", errors.New("must contain at least one valid character")
}
return s, nil
} | [
"func",
"SanitizeACIdentifier",
"(",
"s",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"s",
"=",
"strings",
".",
"ToLower",
"(",
"s",
")",
"\n",
"s",
"=",
"invalidACIdentifierChars",
".",
"ReplaceAllString",
"(",
"s",
",",
"\"",
"\"",
")",
"\n",
"s",
"=",
"invalidACIdentifierEdges",
".",
"ReplaceAllString",
"(",
"s",
",",
"\"",
"\"",
")",
"\n\n",
"if",
"s",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"s",
",",
"nil",
"\n",
"}"
] | // SanitizeACIdentifier replaces every invalid ACIdentifier character in s with an underscore
// making it a legal ACIdentifier string. If the character is an upper case letter it
// replaces it with its lower case. It also removes illegal edge characters
// (hyphens, period, underscore, tilde and slash).
//
// This is a helper function and its algorithm is not part of the spec. It
// should not be called without the user explicitly asking for a suggestion. | [
"SanitizeACIdentifier",
"replaces",
"every",
"invalid",
"ACIdentifier",
"character",
"in",
"s",
"with",
"an",
"underscore",
"making",
"it",
"a",
"legal",
"ACIdentifier",
"string",
".",
"If",
"the",
"character",
"is",
"an",
"upper",
"case",
"letter",
"it",
"replaces",
"it",
"with",
"its",
"lower",
"case",
".",
"It",
"also",
"removes",
"illegal",
"edge",
"characters",
"(",
"hyphens",
"period",
"underscore",
"tilde",
"and",
"slash",
")",
".",
"This",
"is",
"a",
"helper",
"function",
"and",
"its",
"algorithm",
"is",
"not",
"part",
"of",
"the",
"spec",
".",
"It",
"should",
"not",
"be",
"called",
"without",
"the",
"user",
"explicitly",
"asking",
"for",
"a",
"suggestion",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/acidentifier.go#L135-L145 |
appc/spec | schema/types/volume.go | VolumeFromString | func VolumeFromString(vp string) (*Volume, error) {
vp = "name=" + vp
vpQuery, err := common.MakeQueryString(vp)
if err != nil {
return nil, err
}
v, err := url.ParseQuery(vpQuery)
if err != nil {
return nil, err
}
return VolumeFromParams(v)
} | go | func VolumeFromString(vp string) (*Volume, error) {
vp = "name=" + vp
vpQuery, err := common.MakeQueryString(vp)
if err != nil {
return nil, err
}
v, err := url.ParseQuery(vpQuery)
if err != nil {
return nil, err
}
return VolumeFromParams(v)
} | [
"func",
"VolumeFromString",
"(",
"vp",
"string",
")",
"(",
"*",
"Volume",
",",
"error",
")",
"{",
"vp",
"=",
"\"",
"\"",
"+",
"vp",
"\n",
"vpQuery",
",",
"err",
":=",
"common",
".",
"MakeQueryString",
"(",
"vp",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"v",
",",
"err",
":=",
"url",
".",
"ParseQuery",
"(",
"vpQuery",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"VolumeFromParams",
"(",
"v",
")",
"\n",
"}"
] | // VolumeFromString takes a command line volume parameter and returns a volume
//
// Example volume parameters:
// database,kind=host,source=/tmp,readOnly=true,recursive=true | [
"VolumeFromString",
"takes",
"a",
"command",
"line",
"volume",
"parameter",
"and",
"returns",
"a",
"volume",
"Example",
"volume",
"parameters",
":",
"database",
"kind",
"=",
"host",
"source",
"=",
"/",
"tmp",
"readOnly",
"=",
"true",
"recursive",
"=",
"true"
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/volume.go#L158-L170 |
appc/spec | schema/types/volume.go | maybeSetDefaults | func maybeSetDefaults(vol *Volume) {
if vol.Kind == "empty" {
if vol.Mode == nil {
m := emptyVolumeDefaultMode
vol.Mode = &m
}
if vol.UID == nil {
u := emptyVolumeDefaultUID
vol.UID = &u
}
if vol.GID == nil {
g := emptyVolumeDefaultGID
vol.GID = &g
}
}
} | go | func maybeSetDefaults(vol *Volume) {
if vol.Kind == "empty" {
if vol.Mode == nil {
m := emptyVolumeDefaultMode
vol.Mode = &m
}
if vol.UID == nil {
u := emptyVolumeDefaultUID
vol.UID = &u
}
if vol.GID == nil {
g := emptyVolumeDefaultGID
vol.GID = &g
}
}
} | [
"func",
"maybeSetDefaults",
"(",
"vol",
"*",
"Volume",
")",
"{",
"if",
"vol",
".",
"Kind",
"==",
"\"",
"\"",
"{",
"if",
"vol",
".",
"Mode",
"==",
"nil",
"{",
"m",
":=",
"emptyVolumeDefaultMode",
"\n",
"vol",
".",
"Mode",
"=",
"&",
"m",
"\n",
"}",
"\n",
"if",
"vol",
".",
"UID",
"==",
"nil",
"{",
"u",
":=",
"emptyVolumeDefaultUID",
"\n",
"vol",
".",
"UID",
"=",
"&",
"u",
"\n",
"}",
"\n",
"if",
"vol",
".",
"GID",
"==",
"nil",
"{",
"g",
":=",
"emptyVolumeDefaultGID",
"\n",
"vol",
".",
"GID",
"=",
"&",
"g",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // maybeSetDefaults sets the correct default values for certain fields on a
// Volume if they are not already been set. These fields are not
// pre-populated on all Volumes as the Volume type is polymorphic. | [
"maybeSetDefaults",
"sets",
"the",
"correct",
"default",
"values",
"for",
"certain",
"fields",
"on",
"a",
"Volume",
"if",
"they",
"are",
"not",
"already",
"been",
"set",
".",
"These",
"fields",
"are",
"not",
"pre",
"-",
"populated",
"on",
"all",
"Volumes",
"as",
"the",
"Volume",
"type",
"is",
"polymorphic",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/volume.go#L234-L249 |
appc/spec | schema/types/acname.go | Set | func (n *ACName) Set(s string) error {
nn, err := NewACName(s)
if err == nil {
*n = *nn
}
return err
} | go | func (n *ACName) Set(s string) error {
nn, err := NewACName(s)
if err == nil {
*n = *nn
}
return err
} | [
"func",
"(",
"n",
"*",
"ACName",
")",
"Set",
"(",
"s",
"string",
")",
"error",
"{",
"nn",
",",
"err",
":=",
"NewACName",
"(",
"s",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"*",
"n",
"=",
"*",
"nn",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // Set sets the ACName to the given value, if it is valid; if not,
// an error is returned. | [
"Set",
"sets",
"the",
"ACName",
"to",
"the",
"given",
"value",
"if",
"it",
"is",
"valid",
";",
"if",
"not",
"an",
"error",
"is",
"returned",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/acname.go#L54-L60 |
appc/spec | schema/types/acname.go | Equals | func (n ACName) Equals(o ACName) bool {
return strings.ToLower(string(n)) == strings.ToLower(string(o))
} | go | func (n ACName) Equals(o ACName) bool {
return strings.ToLower(string(n)) == strings.ToLower(string(o))
} | [
"func",
"(",
"n",
"ACName",
")",
"Equals",
"(",
"o",
"ACName",
")",
"bool",
"{",
"return",
"strings",
".",
"ToLower",
"(",
"string",
"(",
"n",
")",
")",
"==",
"strings",
".",
"ToLower",
"(",
"string",
"(",
"o",
")",
")",
"\n",
"}"
] | // Equals checks whether a given ACName is equal to this one. | [
"Equals",
"checks",
"whether",
"a",
"given",
"ACName",
"is",
"equal",
"to",
"this",
"one",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/acname.go#L63-L65 |
appc/spec | schema/types/acname.go | NewACName | func NewACName(s string) (*ACName, error) {
n := ACName(s)
if err := n.assertValid(); err != nil {
return nil, err
}
return &n, nil
} | go | func NewACName(s string) (*ACName, error) {
n := ACName(s)
if err := n.assertValid(); err != nil {
return nil, err
}
return &n, nil
} | [
"func",
"NewACName",
"(",
"s",
"string",
")",
"(",
"*",
"ACName",
",",
"error",
")",
"{",
"n",
":=",
"ACName",
"(",
"s",
")",
"\n",
"if",
"err",
":=",
"n",
".",
"assertValid",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"n",
",",
"nil",
"\n",
"}"
] | // NewACName generates a new ACName from a string. If the given string is
// not a valid ACName, nil and an error are returned. | [
"NewACName",
"generates",
"a",
"new",
"ACName",
"from",
"a",
"string",
".",
"If",
"the",
"given",
"string",
"is",
"not",
"a",
"valid",
"ACName",
"nil",
"and",
"an",
"error",
"are",
"returned",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/acname.go#L74-L80 |
appc/spec | schema/types/acname.go | MustACName | func MustACName(s string) *ACName {
n, err := NewACName(s)
if err != nil {
panic(err)
}
return n
} | go | func MustACName(s string) *ACName {
n, err := NewACName(s)
if err != nil {
panic(err)
}
return n
} | [
"func",
"MustACName",
"(",
"s",
"string",
")",
"*",
"ACName",
"{",
"n",
",",
"err",
":=",
"NewACName",
"(",
"s",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"n",
"\n",
"}"
] | // MustACName generates a new ACName from a string, If the given string is
// not a valid ACName, it panics. | [
"MustACName",
"generates",
"a",
"new",
"ACName",
"from",
"a",
"string",
"If",
"the",
"given",
"string",
"is",
"not",
"a",
"valid",
"ACName",
"it",
"panics",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/acname.go#L84-L90 |
appc/spec | schema/types/acname.go | UnmarshalJSON | func (n *ACName) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
nn, err := NewACName(s)
if err != nil {
return err
}
*n = *nn
return nil
} | go | func (n *ACName) UnmarshalJSON(data []byte) error {
var s string
if err := json.Unmarshal(data, &s); err != nil {
return err
}
nn, err := NewACName(s)
if err != nil {
return err
}
*n = *nn
return nil
} | [
"func",
"(",
"n",
"*",
"ACName",
")",
"UnmarshalJSON",
"(",
"data",
"[",
"]",
"byte",
")",
"error",
"{",
"var",
"s",
"string",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"&",
"s",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"nn",
",",
"err",
":=",
"NewACName",
"(",
"s",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"*",
"n",
"=",
"*",
"nn",
"\n",
"return",
"nil",
"\n",
"}"
] | // UnmarshalJSON implements the json.Unmarshaler interface | [
"UnmarshalJSON",
"implements",
"the",
"json",
".",
"Unmarshaler",
"interface"
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/acname.go#L107-L118 |
appc/spec | schema/types/acname.go | MarshalJSON | func (n ACName) MarshalJSON() ([]byte, error) {
if err := n.assertValid(); err != nil {
return nil, err
}
return json.Marshal(n.String())
} | go | func (n ACName) MarshalJSON() ([]byte, error) {
if err := n.assertValid(); err != nil {
return nil, err
}
return json.Marshal(n.String())
} | [
"func",
"(",
"n",
"ACName",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"err",
":=",
"n",
".",
"assertValid",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"json",
".",
"Marshal",
"(",
"n",
".",
"String",
"(",
")",
")",
"\n",
"}"
] | // MarshalJSON implements the json.Marshaler interface | [
"MarshalJSON",
"implements",
"the",
"json",
".",
"Marshaler",
"interface"
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/acname.go#L121-L126 |
appc/spec | schema/types/acname.go | SanitizeACName | func SanitizeACName(s string) (string, error) {
s = strings.ToLower(s)
s = invalidACNameChars.ReplaceAllString(s, "-")
s = invalidACNameEdges.ReplaceAllString(s, "")
if s == "" {
return "", errors.New("must contain at least one valid character")
}
return s, nil
} | go | func SanitizeACName(s string) (string, error) {
s = strings.ToLower(s)
s = invalidACNameChars.ReplaceAllString(s, "-")
s = invalidACNameEdges.ReplaceAllString(s, "")
if s == "" {
return "", errors.New("must contain at least one valid character")
}
return s, nil
} | [
"func",
"SanitizeACName",
"(",
"s",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"s",
"=",
"strings",
".",
"ToLower",
"(",
"s",
")",
"\n",
"s",
"=",
"invalidACNameChars",
".",
"ReplaceAllString",
"(",
"s",
",",
"\"",
"\"",
")",
"\n",
"s",
"=",
"invalidACNameEdges",
".",
"ReplaceAllString",
"(",
"s",
",",
"\"",
"\"",
")",
"\n\n",
"if",
"s",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"return",
"s",
",",
"nil",
"\n",
"}"
] | // SanitizeACName replaces every invalid ACName character in s with a dash
// making it a legal ACName string. If the character is an upper case letter it
// replaces it with its lower case. It also removes illegal edge characters
// (hyphens).
//
// This is a helper function and its algorithm is not part of the spec. It
// should not be called without the user explicitly asking for a suggestion. | [
"SanitizeACName",
"replaces",
"every",
"invalid",
"ACName",
"character",
"in",
"s",
"with",
"a",
"dash",
"making",
"it",
"a",
"legal",
"ACName",
"string",
".",
"If",
"the",
"character",
"is",
"an",
"upper",
"case",
"letter",
"it",
"replaces",
"it",
"with",
"its",
"lower",
"case",
".",
"It",
"also",
"removes",
"illegal",
"edge",
"characters",
"(",
"hyphens",
")",
".",
"This",
"is",
"a",
"helper",
"function",
"and",
"its",
"algorithm",
"is",
"not",
"part",
"of",
"the",
"spec",
".",
"It",
"should",
"not",
"be",
"called",
"without",
"the",
"user",
"explicitly",
"asking",
"for",
"a",
"suggestion",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/schema/types/acname.go#L135-L145 |
appc/spec | aci/layout.go | ValidateLayout | func ValidateLayout(dir string) error {
fi, err := os.Stat(dir)
if err != nil {
return fmt.Errorf("error accessing layout: %v", err)
}
if !fi.IsDir() {
return fmt.Errorf("given path %q is not a directory", dir)
}
var flist []string
var imOK, rfsOK bool
var im io.Reader
walkLayout := func(fpath string, fi os.FileInfo, err error) error {
rpath, err := filepath.Rel(dir, fpath)
if err != nil {
return err
}
switch rpath {
case ".":
case ManifestFile:
im, err = os.Open(fpath)
if err != nil {
return err
}
imOK = true
case RootfsDir:
if !fi.IsDir() {
return errors.New("rootfs is not a directory")
}
rfsOK = true
default:
flist = append(flist, rpath)
}
return nil
}
if err := filepath.Walk(dir, walkLayout); err != nil {
return err
}
return validate(imOK, im, rfsOK, flist)
} | go | func ValidateLayout(dir string) error {
fi, err := os.Stat(dir)
if err != nil {
return fmt.Errorf("error accessing layout: %v", err)
}
if !fi.IsDir() {
return fmt.Errorf("given path %q is not a directory", dir)
}
var flist []string
var imOK, rfsOK bool
var im io.Reader
walkLayout := func(fpath string, fi os.FileInfo, err error) error {
rpath, err := filepath.Rel(dir, fpath)
if err != nil {
return err
}
switch rpath {
case ".":
case ManifestFile:
im, err = os.Open(fpath)
if err != nil {
return err
}
imOK = true
case RootfsDir:
if !fi.IsDir() {
return errors.New("rootfs is not a directory")
}
rfsOK = true
default:
flist = append(flist, rpath)
}
return nil
}
if err := filepath.Walk(dir, walkLayout); err != nil {
return err
}
return validate(imOK, im, rfsOK, flist)
} | [
"func",
"ValidateLayout",
"(",
"dir",
"string",
")",
"error",
"{",
"fi",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"dir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"!",
"fi",
".",
"IsDir",
"(",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"dir",
")",
"\n",
"}",
"\n",
"var",
"flist",
"[",
"]",
"string",
"\n",
"var",
"imOK",
",",
"rfsOK",
"bool",
"\n",
"var",
"im",
"io",
".",
"Reader",
"\n",
"walkLayout",
":=",
"func",
"(",
"fpath",
"string",
",",
"fi",
"os",
".",
"FileInfo",
",",
"err",
"error",
")",
"error",
"{",
"rpath",
",",
"err",
":=",
"filepath",
".",
"Rel",
"(",
"dir",
",",
"fpath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"switch",
"rpath",
"{",
"case",
"\"",
"\"",
":",
"case",
"ManifestFile",
":",
"im",
",",
"err",
"=",
"os",
".",
"Open",
"(",
"fpath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"imOK",
"=",
"true",
"\n",
"case",
"RootfsDir",
":",
"if",
"!",
"fi",
".",
"IsDir",
"(",
")",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"rfsOK",
"=",
"true",
"\n",
"default",
":",
"flist",
"=",
"append",
"(",
"flist",
",",
"rpath",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"err",
":=",
"filepath",
".",
"Walk",
"(",
"dir",
",",
"walkLayout",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"validate",
"(",
"imOK",
",",
"im",
",",
"rfsOK",
",",
"flist",
")",
"\n",
"}"
] | // ValidateLayout takes a directory and validates that the layout of the directory
// matches that expected by the Application Container Image format.
// If any errors are encountered during the validation, it will abort and
// return the first one. | [
"ValidateLayout",
"takes",
"a",
"directory",
"and",
"validates",
"that",
"the",
"layout",
"of",
"the",
"directory",
"matches",
"that",
"expected",
"by",
"the",
"Application",
"Container",
"Image",
"format",
".",
"If",
"any",
"errors",
"are",
"encountered",
"during",
"the",
"validation",
"it",
"will",
"abort",
"and",
"return",
"the",
"first",
"one",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/aci/layout.go#L70-L108 |
appc/spec | aci/layout.go | ValidateArchive | func ValidateArchive(tr *tar.Reader) error {
var fseen map[string]bool = make(map[string]bool)
var imOK, rfsOK bool
var im bytes.Buffer
Tar:
for {
hdr, err := tr.Next()
switch {
case err == nil:
case err == io.EOF:
break Tar
default:
return err
}
name := filepath.Clean(hdr.Name)
switch name {
case ".":
case ManifestFile:
_, err := io.Copy(&im, tr)
if err != nil {
return err
}
imOK = true
case RootfsDir:
if !hdr.FileInfo().IsDir() {
return fmt.Errorf("rootfs is not a directory")
}
rfsOK = true
default:
if _, seen := fseen[name]; seen {
return fmt.Errorf("duplicate file entry in archive: %s", name)
}
fseen[name] = true
}
}
var flist []string
for key := range fseen {
flist = append(flist, key)
}
return validate(imOK, &im, rfsOK, flist)
} | go | func ValidateArchive(tr *tar.Reader) error {
var fseen map[string]bool = make(map[string]bool)
var imOK, rfsOK bool
var im bytes.Buffer
Tar:
for {
hdr, err := tr.Next()
switch {
case err == nil:
case err == io.EOF:
break Tar
default:
return err
}
name := filepath.Clean(hdr.Name)
switch name {
case ".":
case ManifestFile:
_, err := io.Copy(&im, tr)
if err != nil {
return err
}
imOK = true
case RootfsDir:
if !hdr.FileInfo().IsDir() {
return fmt.Errorf("rootfs is not a directory")
}
rfsOK = true
default:
if _, seen := fseen[name]; seen {
return fmt.Errorf("duplicate file entry in archive: %s", name)
}
fseen[name] = true
}
}
var flist []string
for key := range fseen {
flist = append(flist, key)
}
return validate(imOK, &im, rfsOK, flist)
} | [
"func",
"ValidateArchive",
"(",
"tr",
"*",
"tar",
".",
"Reader",
")",
"error",
"{",
"var",
"fseen",
"map",
"[",
"string",
"]",
"bool",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"bool",
")",
"\n",
"var",
"imOK",
",",
"rfsOK",
"bool",
"\n",
"var",
"im",
"bytes",
".",
"Buffer",
"\n",
"Tar",
":",
"for",
"{",
"hdr",
",",
"err",
":=",
"tr",
".",
"Next",
"(",
")",
"\n",
"switch",
"{",
"case",
"err",
"==",
"nil",
":",
"case",
"err",
"==",
"io",
".",
"EOF",
":",
"break",
"Tar",
"\n",
"default",
":",
"return",
"err",
"\n",
"}",
"\n",
"name",
":=",
"filepath",
".",
"Clean",
"(",
"hdr",
".",
"Name",
")",
"\n",
"switch",
"name",
"{",
"case",
"\"",
"\"",
":",
"case",
"ManifestFile",
":",
"_",
",",
"err",
":=",
"io",
".",
"Copy",
"(",
"&",
"im",
",",
"tr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"imOK",
"=",
"true",
"\n",
"case",
"RootfsDir",
":",
"if",
"!",
"hdr",
".",
"FileInfo",
"(",
")",
".",
"IsDir",
"(",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"rfsOK",
"=",
"true",
"\n",
"default",
":",
"if",
"_",
",",
"seen",
":=",
"fseen",
"[",
"name",
"]",
";",
"seen",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n",
"fseen",
"[",
"name",
"]",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"var",
"flist",
"[",
"]",
"string",
"\n",
"for",
"key",
":=",
"range",
"fseen",
"{",
"flist",
"=",
"append",
"(",
"flist",
",",
"key",
")",
"\n",
"}",
"\n",
"return",
"validate",
"(",
"imOK",
",",
"&",
"im",
",",
"rfsOK",
",",
"flist",
")",
"\n",
"}"
] | // ValidateArchive takes a *tar.Reader and validates that the layout of the
// filesystem the reader encapsulates matches that expected by the
// Application Container Image format. If any errors are encountered during
// the validation, it will abort and return the first one. | [
"ValidateArchive",
"takes",
"a",
"*",
"tar",
".",
"Reader",
"and",
"validates",
"that",
"the",
"layout",
"of",
"the",
"filesystem",
"the",
"reader",
"encapsulates",
"matches",
"that",
"expected",
"by",
"the",
"Application",
"Container",
"Image",
"format",
".",
"If",
"any",
"errors",
"are",
"encountered",
"during",
"the",
"validation",
"it",
"will",
"abort",
"and",
"return",
"the",
"first",
"one",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/aci/layout.go#L114-L154 |
appc/spec | pkg/acirenderer/resolve.go | CreateDepListFromImageID | func CreateDepListFromImageID(imageID types.Hash, ap ACIRegistry) (Images, error) {
key, err := ap.ResolveKey(imageID.String())
if err != nil {
return nil, err
}
return createDepList(key, ap)
} | go | func CreateDepListFromImageID(imageID types.Hash, ap ACIRegistry) (Images, error) {
key, err := ap.ResolveKey(imageID.String())
if err != nil {
return nil, err
}
return createDepList(key, ap)
} | [
"func",
"CreateDepListFromImageID",
"(",
"imageID",
"types",
".",
"Hash",
",",
"ap",
"ACIRegistry",
")",
"(",
"Images",
",",
"error",
")",
"{",
"key",
",",
"err",
":=",
"ap",
".",
"ResolveKey",
"(",
"imageID",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"createDepList",
"(",
"key",
",",
"ap",
")",
"\n",
"}"
] | // CreateDepListFromImageID returns the flat dependency tree of the image with
// the provided imageID | [
"CreateDepListFromImageID",
"returns",
"the",
"flat",
"dependency",
"tree",
"of",
"the",
"image",
"with",
"the",
"provided",
"imageID"
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/pkg/acirenderer/resolve.go#L25-L31 |
appc/spec | pkg/acirenderer/resolve.go | CreateDepListFromNameLabels | func CreateDepListFromNameLabels(name types.ACIdentifier, labels types.Labels, ap ACIRegistry) (Images, error) {
key, err := ap.GetACI(name, labels)
if err != nil {
return nil, err
}
return createDepList(key, ap)
} | go | func CreateDepListFromNameLabels(name types.ACIdentifier, labels types.Labels, ap ACIRegistry) (Images, error) {
key, err := ap.GetACI(name, labels)
if err != nil {
return nil, err
}
return createDepList(key, ap)
} | [
"func",
"CreateDepListFromNameLabels",
"(",
"name",
"types",
".",
"ACIdentifier",
",",
"labels",
"types",
".",
"Labels",
",",
"ap",
"ACIRegistry",
")",
"(",
"Images",
",",
"error",
")",
"{",
"key",
",",
"err",
":=",
"ap",
".",
"GetACI",
"(",
"name",
",",
"labels",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"createDepList",
"(",
"key",
",",
"ap",
")",
"\n",
"}"
] | // CreateDepListFromNameLabels returns the flat dependency tree of the image
// with the provided app name and optional labels. | [
"CreateDepListFromNameLabels",
"returns",
"the",
"flat",
"dependency",
"tree",
"of",
"the",
"image",
"with",
"the",
"provided",
"app",
"name",
"and",
"optional",
"labels",
"."
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/pkg/acirenderer/resolve.go#L35-L41 |
appc/spec | pkg/acirenderer/resolve.go | createDepList | func createDepList(key string, ap ACIRegistry) (Images, error) {
imgsl := list.New()
im, err := ap.GetImageManifest(key)
if err != nil {
return nil, err
}
img := Image{Im: im, Key: key, Level: 0}
imgsl.PushFront(img)
// Create a flat dependency tree. Use a LinkedList to be able to
// insert elements in the list while working on it.
for el := imgsl.Front(); el != nil; el = el.Next() {
img := el.Value.(Image)
dependencies := img.Im.Dependencies
for _, d := range dependencies {
var depimg Image
var depKey string
if d.ImageID != nil && !d.ImageID.Empty() {
depKey, err = ap.ResolveKey(d.ImageID.String())
if err != nil {
return nil, err
}
} else {
var err error
depKey, err = ap.GetACI(d.ImageName, d.Labels)
if err != nil {
return nil, err
}
}
im, err := ap.GetImageManifest(depKey)
if err != nil {
return nil, err
}
depimg = Image{Im: im, Key: depKey, Level: img.Level + 1}
imgsl.InsertAfter(depimg, el)
}
}
imgs := Images{}
for el := imgsl.Front(); el != nil; el = el.Next() {
imgs = append(imgs, el.Value.(Image))
}
return imgs, nil
} | go | func createDepList(key string, ap ACIRegistry) (Images, error) {
imgsl := list.New()
im, err := ap.GetImageManifest(key)
if err != nil {
return nil, err
}
img := Image{Im: im, Key: key, Level: 0}
imgsl.PushFront(img)
// Create a flat dependency tree. Use a LinkedList to be able to
// insert elements in the list while working on it.
for el := imgsl.Front(); el != nil; el = el.Next() {
img := el.Value.(Image)
dependencies := img.Im.Dependencies
for _, d := range dependencies {
var depimg Image
var depKey string
if d.ImageID != nil && !d.ImageID.Empty() {
depKey, err = ap.ResolveKey(d.ImageID.String())
if err != nil {
return nil, err
}
} else {
var err error
depKey, err = ap.GetACI(d.ImageName, d.Labels)
if err != nil {
return nil, err
}
}
im, err := ap.GetImageManifest(depKey)
if err != nil {
return nil, err
}
depimg = Image{Im: im, Key: depKey, Level: img.Level + 1}
imgsl.InsertAfter(depimg, el)
}
}
imgs := Images{}
for el := imgsl.Front(); el != nil; el = el.Next() {
imgs = append(imgs, el.Value.(Image))
}
return imgs, nil
} | [
"func",
"createDepList",
"(",
"key",
"string",
",",
"ap",
"ACIRegistry",
")",
"(",
"Images",
",",
"error",
")",
"{",
"imgsl",
":=",
"list",
".",
"New",
"(",
")",
"\n",
"im",
",",
"err",
":=",
"ap",
".",
"GetImageManifest",
"(",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"img",
":=",
"Image",
"{",
"Im",
":",
"im",
",",
"Key",
":",
"key",
",",
"Level",
":",
"0",
"}",
"\n",
"imgsl",
".",
"PushFront",
"(",
"img",
")",
"\n\n",
"// Create a flat dependency tree. Use a LinkedList to be able to",
"// insert elements in the list while working on it.",
"for",
"el",
":=",
"imgsl",
".",
"Front",
"(",
")",
";",
"el",
"!=",
"nil",
";",
"el",
"=",
"el",
".",
"Next",
"(",
")",
"{",
"img",
":=",
"el",
".",
"Value",
".",
"(",
"Image",
")",
"\n",
"dependencies",
":=",
"img",
".",
"Im",
".",
"Dependencies",
"\n",
"for",
"_",
",",
"d",
":=",
"range",
"dependencies",
"{",
"var",
"depimg",
"Image",
"\n",
"var",
"depKey",
"string",
"\n",
"if",
"d",
".",
"ImageID",
"!=",
"nil",
"&&",
"!",
"d",
".",
"ImageID",
".",
"Empty",
"(",
")",
"{",
"depKey",
",",
"err",
"=",
"ap",
".",
"ResolveKey",
"(",
"d",
".",
"ImageID",
".",
"String",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"else",
"{",
"var",
"err",
"error",
"\n",
"depKey",
",",
"err",
"=",
"ap",
".",
"GetACI",
"(",
"d",
".",
"ImageName",
",",
"d",
".",
"Labels",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"im",
",",
"err",
":=",
"ap",
".",
"GetImageManifest",
"(",
"depKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"depimg",
"=",
"Image",
"{",
"Im",
":",
"im",
",",
"Key",
":",
"depKey",
",",
"Level",
":",
"img",
".",
"Level",
"+",
"1",
"}",
"\n",
"imgsl",
".",
"InsertAfter",
"(",
"depimg",
",",
"el",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"imgs",
":=",
"Images",
"{",
"}",
"\n",
"for",
"el",
":=",
"imgsl",
".",
"Front",
"(",
")",
";",
"el",
"!=",
"nil",
";",
"el",
"=",
"el",
".",
"Next",
"(",
")",
"{",
"imgs",
"=",
"append",
"(",
"imgs",
",",
"el",
".",
"Value",
".",
"(",
"Image",
")",
")",
"\n",
"}",
"\n",
"return",
"imgs",
",",
"nil",
"\n",
"}"
] | // createDepList returns the flat dependency tree as a list of Image type | [
"createDepList",
"returns",
"the",
"flat",
"dependency",
"tree",
"as",
"a",
"list",
"of",
"Image",
"type"
] | train | https://github.com/appc/spec/blob/259c2eebc32df77c016974d5e8eed390d5a81500/pkg/acirenderer/resolve.go#L44-L88 |
gocraft/web | static_middleware.go | StaticMiddleware | func StaticMiddleware(path string, option ...StaticOption) func(ResponseWriter, *Request, NextMiddlewareFunc) {
return StaticMiddlewareFromDir(http.Dir(path), option...)
} | go | func StaticMiddleware(path string, option ...StaticOption) func(ResponseWriter, *Request, NextMiddlewareFunc) {
return StaticMiddlewareFromDir(http.Dir(path), option...)
} | [
"func",
"StaticMiddleware",
"(",
"path",
"string",
",",
"option",
"...",
"StaticOption",
")",
"func",
"(",
"ResponseWriter",
",",
"*",
"Request",
",",
"NextMiddlewareFunc",
")",
"{",
"return",
"StaticMiddlewareFromDir",
"(",
"http",
".",
"Dir",
"(",
"path",
")",
",",
"option",
"...",
")",
"\n",
"}"
] | // StaticMiddleware is the same as StaticMiddlewareFromDir, but accepts a
// path string for backwards compatibility. | [
"StaticMiddleware",
"is",
"the",
"same",
"as",
"StaticMiddlewareFromDir",
"but",
"accepts",
"a",
"path",
"string",
"for",
"backwards",
"compatibility",
"."
] | train | https://github.com/gocraft/web/blob/9707327fb69b5b93fd722c6b4259a7b414bedac5/static_middleware.go#L19-L21 |
gocraft/web | static_middleware.go | StaticMiddlewareFromDir | func StaticMiddlewareFromDir(dir http.FileSystem, options ...StaticOption) func(ResponseWriter, *Request, NextMiddlewareFunc) {
var option StaticOption
if len(options) > 0 {
option = options[0]
}
return func(w ResponseWriter, req *Request, next NextMiddlewareFunc) {
if req.Method != "GET" && req.Method != "HEAD" {
next(w, req)
return
}
file := req.URL.Path
if option.Prefix != "" {
if !strings.HasPrefix(file, option.Prefix) {
next(w, req)
return
}
file = file[len(option.Prefix):]
}
f, err := dir.Open(file)
if err != nil {
next(w, req)
return
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
next(w, req)
return
}
// If the file is a directory, try to serve an index file.
// If no index is available, DO NOT serve the directory to avoid
// Content-Length issues. Simply skip to the next middleware, and return
// a 404 if no route with the same name is handled.
if fi.IsDir() {
if option.IndexFile != "" {
file = filepath.Join(file, option.IndexFile)
f, err = dir.Open(file)
if err != nil {
next(w, req)
return
}
defer f.Close()
fi, err = f.Stat()
if err != nil || fi.IsDir() {
next(w, req)
return
}
} else {
next(w, req)
return
}
}
http.ServeContent(w, req.Request, file, fi.ModTime(), f)
}
} | go | func StaticMiddlewareFromDir(dir http.FileSystem, options ...StaticOption) func(ResponseWriter, *Request, NextMiddlewareFunc) {
var option StaticOption
if len(options) > 0 {
option = options[0]
}
return func(w ResponseWriter, req *Request, next NextMiddlewareFunc) {
if req.Method != "GET" && req.Method != "HEAD" {
next(w, req)
return
}
file := req.URL.Path
if option.Prefix != "" {
if !strings.HasPrefix(file, option.Prefix) {
next(w, req)
return
}
file = file[len(option.Prefix):]
}
f, err := dir.Open(file)
if err != nil {
next(w, req)
return
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
next(w, req)
return
}
// If the file is a directory, try to serve an index file.
// If no index is available, DO NOT serve the directory to avoid
// Content-Length issues. Simply skip to the next middleware, and return
// a 404 if no route with the same name is handled.
if fi.IsDir() {
if option.IndexFile != "" {
file = filepath.Join(file, option.IndexFile)
f, err = dir.Open(file)
if err != nil {
next(w, req)
return
}
defer f.Close()
fi, err = f.Stat()
if err != nil || fi.IsDir() {
next(w, req)
return
}
} else {
next(w, req)
return
}
}
http.ServeContent(w, req.Request, file, fi.ModTime(), f)
}
} | [
"func",
"StaticMiddlewareFromDir",
"(",
"dir",
"http",
".",
"FileSystem",
",",
"options",
"...",
"StaticOption",
")",
"func",
"(",
"ResponseWriter",
",",
"*",
"Request",
",",
"NextMiddlewareFunc",
")",
"{",
"var",
"option",
"StaticOption",
"\n",
"if",
"len",
"(",
"options",
")",
">",
"0",
"{",
"option",
"=",
"options",
"[",
"0",
"]",
"\n",
"}",
"\n",
"return",
"func",
"(",
"w",
"ResponseWriter",
",",
"req",
"*",
"Request",
",",
"next",
"NextMiddlewareFunc",
")",
"{",
"if",
"req",
".",
"Method",
"!=",
"\"",
"\"",
"&&",
"req",
".",
"Method",
"!=",
"\"",
"\"",
"{",
"next",
"(",
"w",
",",
"req",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"file",
":=",
"req",
".",
"URL",
".",
"Path",
"\n",
"if",
"option",
".",
"Prefix",
"!=",
"\"",
"\"",
"{",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"file",
",",
"option",
".",
"Prefix",
")",
"{",
"next",
"(",
"w",
",",
"req",
")",
"\n",
"return",
"\n",
"}",
"\n",
"file",
"=",
"file",
"[",
"len",
"(",
"option",
".",
"Prefix",
")",
":",
"]",
"\n",
"}",
"\n\n",
"f",
",",
"err",
":=",
"dir",
".",
"Open",
"(",
"file",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"next",
"(",
"w",
",",
"req",
")",
"\n",
"return",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n\n",
"fi",
",",
"err",
":=",
"f",
".",
"Stat",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"next",
"(",
"w",
",",
"req",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// If the file is a directory, try to serve an index file.",
"// If no index is available, DO NOT serve the directory to avoid",
"// Content-Length issues. Simply skip to the next middleware, and return",
"// a 404 if no route with the same name is handled. ",
"if",
"fi",
".",
"IsDir",
"(",
")",
"{",
"if",
"option",
".",
"IndexFile",
"!=",
"\"",
"\"",
"{",
"file",
"=",
"filepath",
".",
"Join",
"(",
"file",
",",
"option",
".",
"IndexFile",
")",
"\n",
"f",
",",
"err",
"=",
"dir",
".",
"Open",
"(",
"file",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"next",
"(",
"w",
",",
"req",
")",
"\n",
"return",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n\n",
"fi",
",",
"err",
"=",
"f",
".",
"Stat",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"fi",
".",
"IsDir",
"(",
")",
"{",
"next",
"(",
"w",
",",
"req",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"else",
"{",
"next",
"(",
"w",
",",
"req",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"http",
".",
"ServeContent",
"(",
"w",
",",
"req",
".",
"Request",
",",
"file",
",",
"fi",
".",
"ModTime",
"(",
")",
",",
"f",
")",
"\n",
"}",
"\n",
"}"
] | // StaticMiddlewareFromDir returns a middleware that serves static files from the specified http.FileSystem.
// This middleware is great for development because each file is read from disk each time and no
// special caching or cache headers are sent.
//
// If a path is requested which maps to a folder with an index.html folder on your filesystem,
// then that index.html file will be served. | [
"StaticMiddlewareFromDir",
"returns",
"a",
"middleware",
"that",
"serves",
"static",
"files",
"from",
"the",
"specified",
"http",
".",
"FileSystem",
".",
"This",
"middleware",
"is",
"great",
"for",
"development",
"because",
"each",
"file",
"is",
"read",
"from",
"disk",
"each",
"time",
"and",
"no",
"special",
"caching",
"or",
"cache",
"headers",
"are",
"sent",
".",
"If",
"a",
"path",
"is",
"requested",
"which",
"maps",
"to",
"a",
"folder",
"with",
"an",
"index",
".",
"html",
"folder",
"on",
"your",
"filesystem",
"then",
"that",
"index",
".",
"html",
"file",
"will",
"be",
"served",
"."
] | train | https://github.com/gocraft/web/blob/9707327fb69b5b93fd722c6b4259a7b414bedac5/static_middleware.go#L29-L88 |
gocraft/web | router_setup.go | New | func New(ctx interface{}) *Router {
validateContext(ctx, nil)
r := &Router{}
r.contextType = reflect.TypeOf(ctx)
r.pathPrefix = "/"
r.maxChildrenDepth = 1
r.root = make(map[httpMethod]*pathNode)
for _, method := range httpMethods {
r.root[method] = newPathNode()
}
return r
} | go | func New(ctx interface{}) *Router {
validateContext(ctx, nil)
r := &Router{}
r.contextType = reflect.TypeOf(ctx)
r.pathPrefix = "/"
r.maxChildrenDepth = 1
r.root = make(map[httpMethod]*pathNode)
for _, method := range httpMethods {
r.root[method] = newPathNode()
}
return r
} | [
"func",
"New",
"(",
"ctx",
"interface",
"{",
"}",
")",
"*",
"Router",
"{",
"validateContext",
"(",
"ctx",
",",
"nil",
")",
"\n\n",
"r",
":=",
"&",
"Router",
"{",
"}",
"\n",
"r",
".",
"contextType",
"=",
"reflect",
".",
"TypeOf",
"(",
"ctx",
")",
"\n",
"r",
".",
"pathPrefix",
"=",
"\"",
"\"",
"\n",
"r",
".",
"maxChildrenDepth",
"=",
"1",
"\n",
"r",
".",
"root",
"=",
"make",
"(",
"map",
"[",
"httpMethod",
"]",
"*",
"pathNode",
")",
"\n",
"for",
"_",
",",
"method",
":=",
"range",
"httpMethods",
"{",
"r",
".",
"root",
"[",
"method",
"]",
"=",
"newPathNode",
"(",
")",
"\n",
"}",
"\n",
"return",
"r",
"\n",
"}"
] | // New returns a new router with context type ctx. ctx should be a struct instance,
// whose purpose is to communicate type information. On each request, an instance of this
// context type will be automatically allocated and sent to handlers. | [
"New",
"returns",
"a",
"new",
"router",
"with",
"context",
"type",
"ctx",
".",
"ctx",
"should",
"be",
"a",
"struct",
"instance",
"whose",
"purpose",
"is",
"to",
"communicate",
"type",
"information",
".",
"On",
"each",
"request",
"an",
"instance",
"of",
"this",
"context",
"type",
"will",
"be",
"automatically",
"allocated",
"and",
"sent",
"to",
"handlers",
"."
] | train | https://github.com/gocraft/web/blob/9707327fb69b5b93fd722c6b4259a7b414bedac5/router_setup.go#L91-L103 |
gocraft/web | router_setup.go | NewWithPrefix | func NewWithPrefix(ctx interface{}, pathPrefix string) *Router {
r := New(ctx)
r.pathPrefix = pathPrefix
return r
} | go | func NewWithPrefix(ctx interface{}, pathPrefix string) *Router {
r := New(ctx)
r.pathPrefix = pathPrefix
return r
} | [
"func",
"NewWithPrefix",
"(",
"ctx",
"interface",
"{",
"}",
",",
"pathPrefix",
"string",
")",
"*",
"Router",
"{",
"r",
":=",
"New",
"(",
"ctx",
")",
"\n",
"r",
".",
"pathPrefix",
"=",
"pathPrefix",
"\n\n",
"return",
"r",
"\n",
"}"
] | // NewWithPrefix returns a new router (see New) but each route will have an implicit prefix.
// For instance, with pathPrefix = "/api/v2", all routes under this router will begin with "/api/v2". | [
"NewWithPrefix",
"returns",
"a",
"new",
"router",
"(",
"see",
"New",
")",
"but",
"each",
"route",
"will",
"have",
"an",
"implicit",
"prefix",
".",
"For",
"instance",
"with",
"pathPrefix",
"=",
"/",
"api",
"/",
"v2",
"all",
"routes",
"under",
"this",
"router",
"will",
"begin",
"with",
"/",
"api",
"/",
"v2",
"."
] | train | https://github.com/gocraft/web/blob/9707327fb69b5b93fd722c6b4259a7b414bedac5/router_setup.go#L107-L112 |
gocraft/web | router_setup.go | Subrouter | func (r *Router) Subrouter(ctx interface{}, pathPrefix string) *Router {
validateContext(ctx, r.contextType)
// Create new router, link up hierarchy
newRouter := &Router{parent: r}
r.children = append(r.children, newRouter)
// Increment maxChildrenDepth if this is the first child of the router
if len(r.children) == 1 {
curParent := r
for curParent != nil {
curParent.maxChildrenDepth = curParent.depth()
curParent = curParent.parent
}
}
newRouter.contextType = reflect.TypeOf(ctx)
newRouter.pathPrefix = appendPath(r.pathPrefix, pathPrefix)
newRouter.root = r.root
return newRouter
} | go | func (r *Router) Subrouter(ctx interface{}, pathPrefix string) *Router {
validateContext(ctx, r.contextType)
// Create new router, link up hierarchy
newRouter := &Router{parent: r}
r.children = append(r.children, newRouter)
// Increment maxChildrenDepth if this is the first child of the router
if len(r.children) == 1 {
curParent := r
for curParent != nil {
curParent.maxChildrenDepth = curParent.depth()
curParent = curParent.parent
}
}
newRouter.contextType = reflect.TypeOf(ctx)
newRouter.pathPrefix = appendPath(r.pathPrefix, pathPrefix)
newRouter.root = r.root
return newRouter
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"Subrouter",
"(",
"ctx",
"interface",
"{",
"}",
",",
"pathPrefix",
"string",
")",
"*",
"Router",
"{",
"validateContext",
"(",
"ctx",
",",
"r",
".",
"contextType",
")",
"\n\n",
"// Create new router, link up hierarchy",
"newRouter",
":=",
"&",
"Router",
"{",
"parent",
":",
"r",
"}",
"\n",
"r",
".",
"children",
"=",
"append",
"(",
"r",
".",
"children",
",",
"newRouter",
")",
"\n\n",
"// Increment maxChildrenDepth if this is the first child of the router",
"if",
"len",
"(",
"r",
".",
"children",
")",
"==",
"1",
"{",
"curParent",
":=",
"r",
"\n",
"for",
"curParent",
"!=",
"nil",
"{",
"curParent",
".",
"maxChildrenDepth",
"=",
"curParent",
".",
"depth",
"(",
")",
"\n",
"curParent",
"=",
"curParent",
".",
"parent",
"\n",
"}",
"\n",
"}",
"\n\n",
"newRouter",
".",
"contextType",
"=",
"reflect",
".",
"TypeOf",
"(",
"ctx",
")",
"\n",
"newRouter",
".",
"pathPrefix",
"=",
"appendPath",
"(",
"r",
".",
"pathPrefix",
",",
"pathPrefix",
")",
"\n",
"newRouter",
".",
"root",
"=",
"r",
".",
"root",
"\n\n",
"return",
"newRouter",
"\n",
"}"
] | // Subrouter attaches a new subrouter to the specified router and returns it.
// You can use the same context or pass a new one. If you pass a new one, it must
// embed a pointer to the previous context in the first slot. You can also pass
// a pathPrefix that each route will have. If "" is passed, then no path prefix is applied. | [
"Subrouter",
"attaches",
"a",
"new",
"subrouter",
"to",
"the",
"specified",
"router",
"and",
"returns",
"it",
".",
"You",
"can",
"use",
"the",
"same",
"context",
"or",
"pass",
"a",
"new",
"one",
".",
"If",
"you",
"pass",
"a",
"new",
"one",
"it",
"must",
"embed",
"a",
"pointer",
"to",
"the",
"previous",
"context",
"in",
"the",
"first",
"slot",
".",
"You",
"can",
"also",
"pass",
"a",
"pathPrefix",
"that",
"each",
"route",
"will",
"have",
".",
"If",
"is",
"passed",
"then",
"no",
"path",
"prefix",
"is",
"applied",
"."
] | train | https://github.com/gocraft/web/blob/9707327fb69b5b93fd722c6b4259a7b414bedac5/router_setup.go#L118-L139 |
gocraft/web | router_setup.go | Middleware | func (r *Router) Middleware(fn interface{}) *Router {
vfn := reflect.ValueOf(fn)
validateMiddleware(vfn, r.contextType)
if vfn.Type().NumIn() == 3 {
r.middleware = append(r.middleware, &middlewareHandler{Generic: true, GenericMiddleware: fn.(func(ResponseWriter, *Request, NextMiddlewareFunc))})
} else {
r.middleware = append(r.middleware, &middlewareHandler{Generic: false, DynamicMiddleware: vfn})
}
return r
} | go | func (r *Router) Middleware(fn interface{}) *Router {
vfn := reflect.ValueOf(fn)
validateMiddleware(vfn, r.contextType)
if vfn.Type().NumIn() == 3 {
r.middleware = append(r.middleware, &middlewareHandler{Generic: true, GenericMiddleware: fn.(func(ResponseWriter, *Request, NextMiddlewareFunc))})
} else {
r.middleware = append(r.middleware, &middlewareHandler{Generic: false, DynamicMiddleware: vfn})
}
return r
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"Middleware",
"(",
"fn",
"interface",
"{",
"}",
")",
"*",
"Router",
"{",
"vfn",
":=",
"reflect",
".",
"ValueOf",
"(",
"fn",
")",
"\n",
"validateMiddleware",
"(",
"vfn",
",",
"r",
".",
"contextType",
")",
"\n",
"if",
"vfn",
".",
"Type",
"(",
")",
".",
"NumIn",
"(",
")",
"==",
"3",
"{",
"r",
".",
"middleware",
"=",
"append",
"(",
"r",
".",
"middleware",
",",
"&",
"middlewareHandler",
"{",
"Generic",
":",
"true",
",",
"GenericMiddleware",
":",
"fn",
".",
"(",
"func",
"(",
"ResponseWriter",
",",
"*",
"Request",
",",
"NextMiddlewareFunc",
")",
")",
"}",
")",
"\n",
"}",
"else",
"{",
"r",
".",
"middleware",
"=",
"append",
"(",
"r",
".",
"middleware",
",",
"&",
"middlewareHandler",
"{",
"Generic",
":",
"false",
",",
"DynamicMiddleware",
":",
"vfn",
"}",
")",
"\n",
"}",
"\n\n",
"return",
"r",
"\n",
"}"
] | // Middleware adds the specified middleware tot he router and returns the router. | [
"Middleware",
"adds",
"the",
"specified",
"middleware",
"tot",
"he",
"router",
"and",
"returns",
"the",
"router",
"."
] | train | https://github.com/gocraft/web/blob/9707327fb69b5b93fd722c6b4259a7b414bedac5/router_setup.go#L142-L152 |
gocraft/web | router_setup.go | Error | func (r *Router) Error(fn interface{}) *Router {
vfn := reflect.ValueOf(fn)
validateErrorHandler(vfn, r.contextType)
r.errorHandler = vfn
return r
} | go | func (r *Router) Error(fn interface{}) *Router {
vfn := reflect.ValueOf(fn)
validateErrorHandler(vfn, r.contextType)
r.errorHandler = vfn
return r
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"Error",
"(",
"fn",
"interface",
"{",
"}",
")",
"*",
"Router",
"{",
"vfn",
":=",
"reflect",
".",
"ValueOf",
"(",
"fn",
")",
"\n",
"validateErrorHandler",
"(",
"vfn",
",",
"r",
".",
"contextType",
")",
"\n",
"r",
".",
"errorHandler",
"=",
"vfn",
"\n",
"return",
"r",
"\n",
"}"
] | // Error sets the specified function as the error handler (when panics happen) and returns the router. | [
"Error",
"sets",
"the",
"specified",
"function",
"as",
"the",
"error",
"handler",
"(",
"when",
"panics",
"happen",
")",
"and",
"returns",
"the",
"router",
"."
] | train | https://github.com/gocraft/web/blob/9707327fb69b5b93fd722c6b4259a7b414bedac5/router_setup.go#L155-L160 |
gocraft/web | router_setup.go | NotFound | func (r *Router) NotFound(fn interface{}) *Router {
if r.parent != nil {
panic("You can only set a NotFoundHandler on the root router.")
}
vfn := reflect.ValueOf(fn)
validateNotFoundHandler(vfn, r.contextType)
r.notFoundHandler = vfn
return r
} | go | func (r *Router) NotFound(fn interface{}) *Router {
if r.parent != nil {
panic("You can only set a NotFoundHandler on the root router.")
}
vfn := reflect.ValueOf(fn)
validateNotFoundHandler(vfn, r.contextType)
r.notFoundHandler = vfn
return r
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"NotFound",
"(",
"fn",
"interface",
"{",
"}",
")",
"*",
"Router",
"{",
"if",
"r",
".",
"parent",
"!=",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"vfn",
":=",
"reflect",
".",
"ValueOf",
"(",
"fn",
")",
"\n",
"validateNotFoundHandler",
"(",
"vfn",
",",
"r",
".",
"contextType",
")",
"\n",
"r",
".",
"notFoundHandler",
"=",
"vfn",
"\n",
"return",
"r",
"\n",
"}"
] | // NotFound sets the specified function as the not-found handler (when no route matches) and returns the router.
// Note that only the root router can have a NotFound handler. | [
"NotFound",
"sets",
"the",
"specified",
"function",
"as",
"the",
"not",
"-",
"found",
"handler",
"(",
"when",
"no",
"route",
"matches",
")",
"and",
"returns",
"the",
"router",
".",
"Note",
"that",
"only",
"the",
"root",
"router",
"can",
"have",
"a",
"NotFound",
"handler",
"."
] | train | https://github.com/gocraft/web/blob/9707327fb69b5b93fd722c6b4259a7b414bedac5/router_setup.go#L164-L172 |
gocraft/web | router_setup.go | OptionsHandler | func (r *Router) OptionsHandler(fn interface{}) *Router {
if r.parent != nil {
panic("You can only set an OptionsHandler on the root router.")
}
vfn := reflect.ValueOf(fn)
validateOptionsHandler(vfn, r.contextType)
r.optionsHandler = vfn
return r
} | go | func (r *Router) OptionsHandler(fn interface{}) *Router {
if r.parent != nil {
panic("You can only set an OptionsHandler on the root router.")
}
vfn := reflect.ValueOf(fn)
validateOptionsHandler(vfn, r.contextType)
r.optionsHandler = vfn
return r
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"OptionsHandler",
"(",
"fn",
"interface",
"{",
"}",
")",
"*",
"Router",
"{",
"if",
"r",
".",
"parent",
"!=",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"vfn",
":=",
"reflect",
".",
"ValueOf",
"(",
"fn",
")",
"\n",
"validateOptionsHandler",
"(",
"vfn",
",",
"r",
".",
"contextType",
")",
"\n",
"r",
".",
"optionsHandler",
"=",
"vfn",
"\n",
"return",
"r",
"\n",
"}"
] | // OptionsHandler sets the specified function as the options handler and returns the router.
// Note that only the root router can have a OptionsHandler handler. | [
"OptionsHandler",
"sets",
"the",
"specified",
"function",
"as",
"the",
"options",
"handler",
"and",
"returns",
"the",
"router",
".",
"Note",
"that",
"only",
"the",
"root",
"router",
"can",
"have",
"a",
"OptionsHandler",
"handler",
"."
] | train | https://github.com/gocraft/web/blob/9707327fb69b5b93fd722c6b4259a7b414bedac5/router_setup.go#L176-L184 |
gocraft/web | router_setup.go | Get | func (r *Router) Get(path string, fn interface{}) *Router {
return r.addRoute(httpMethodGet, path, fn)
} | go | func (r *Router) Get(path string, fn interface{}) *Router {
return r.addRoute(httpMethodGet, path, fn)
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"Get",
"(",
"path",
"string",
",",
"fn",
"interface",
"{",
"}",
")",
"*",
"Router",
"{",
"return",
"r",
".",
"addRoute",
"(",
"httpMethodGet",
",",
"path",
",",
"fn",
")",
"\n",
"}"
] | // Get will add a route to the router that matches on GET requests and the specified path. | [
"Get",
"will",
"add",
"a",
"route",
"to",
"the",
"router",
"that",
"matches",
"on",
"GET",
"requests",
"and",
"the",
"specified",
"path",
"."
] | train | https://github.com/gocraft/web/blob/9707327fb69b5b93fd722c6b4259a7b414bedac5/router_setup.go#L187-L189 |
gocraft/web | router_setup.go | Post | func (r *Router) Post(path string, fn interface{}) *Router {
return r.addRoute(httpMethodPost, path, fn)
} | go | func (r *Router) Post(path string, fn interface{}) *Router {
return r.addRoute(httpMethodPost, path, fn)
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"Post",
"(",
"path",
"string",
",",
"fn",
"interface",
"{",
"}",
")",
"*",
"Router",
"{",
"return",
"r",
".",
"addRoute",
"(",
"httpMethodPost",
",",
"path",
",",
"fn",
")",
"\n",
"}"
] | // Post will add a route to the router that matches on POST requests and the specified path. | [
"Post",
"will",
"add",
"a",
"route",
"to",
"the",
"router",
"that",
"matches",
"on",
"POST",
"requests",
"and",
"the",
"specified",
"path",
"."
] | train | https://github.com/gocraft/web/blob/9707327fb69b5b93fd722c6b4259a7b414bedac5/router_setup.go#L192-L194 |
gocraft/web | router_setup.go | Put | func (r *Router) Put(path string, fn interface{}) *Router {
return r.addRoute(httpMethodPut, path, fn)
} | go | func (r *Router) Put(path string, fn interface{}) *Router {
return r.addRoute(httpMethodPut, path, fn)
} | [
"func",
"(",
"r",
"*",
"Router",
")",
"Put",
"(",
"path",
"string",
",",
"fn",
"interface",
"{",
"}",
")",
"*",
"Router",
"{",
"return",
"r",
".",
"addRoute",
"(",
"httpMethodPut",
",",
"path",
",",
"fn",
")",
"\n",
"}"
] | // Put will add a route to the router that matches on PUT requests and the specified path. | [
"Put",
"will",
"add",
"a",
"route",
"to",
"the",
"router",
"that",
"matches",
"on",
"PUT",
"requests",
"and",
"the",
"specified",
"path",
"."
] | train | https://github.com/gocraft/web/blob/9707327fb69b5b93fd722c6b4259a7b414bedac5/router_setup.go#L197-L199 |