repo
stringlengths 5
67
| path
stringlengths 4
218
| func_name
stringlengths 0
151
| original_string
stringlengths 52
373k
| language
stringclasses 6
values | code
stringlengths 52
373k
| code_tokens
listlengths 10
512
| docstring
stringlengths 3
47.2k
| docstring_tokens
listlengths 3
234
| sha
stringlengths 40
40
| url
stringlengths 85
339
| partition
stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
google/go-cmp
|
cmp/path.go
|
Key
|
func (si SliceIndex) Key() int {
if si.xkey != si.ykey {
return -1
}
return si.xkey
}
|
go
|
func (si SliceIndex) Key() int {
if si.xkey != si.ykey {
return -1
}
return si.xkey
}
|
[
"func",
"(",
"si",
"SliceIndex",
")",
"Key",
"(",
")",
"int",
"{",
"if",
"si",
".",
"xkey",
"!=",
"si",
".",
"ykey",
"{",
"return",
"-",
"1",
"\n",
"}",
"\n",
"return",
"si",
".",
"xkey",
"\n",
"}"
] |
// Key is the index key; it may return -1 if in a split state
|
[
"Key",
"is",
"the",
"index",
"key",
";",
"it",
"may",
"return",
"-",
"1",
"if",
"in",
"a",
"split",
"state"
] |
6f77996f0c42f7b84e5a2b252227263f93432e9b
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/path.go#L231-L236
|
test
|
google/go-cmp
|
cmp/report.go
|
String
|
func (r *defaultReporter) String() string {
assert(r.root != nil && r.curr == nil)
if r.root.NumDiff == 0 {
return ""
}
return formatOptions{}.FormatDiff(r.root).String()
}
|
go
|
func (r *defaultReporter) String() string {
assert(r.root != nil && r.curr == nil)
if r.root.NumDiff == 0 {
return ""
}
return formatOptions{}.FormatDiff(r.root).String()
}
|
[
"func",
"(",
"r",
"*",
"defaultReporter",
")",
"String",
"(",
")",
"string",
"{",
"assert",
"(",
"r",
".",
"root",
"!=",
"nil",
"&&",
"r",
".",
"curr",
"==",
"nil",
")",
"\n",
"if",
"r",
".",
"root",
".",
"NumDiff",
"==",
"0",
"{",
"return",
"\"\"",
"\n",
"}",
"\n",
"return",
"formatOptions",
"{",
"}",
".",
"FormatDiff",
"(",
"r",
".",
"root",
")",
".",
"String",
"(",
")",
"\n",
"}"
] |
// String provides a full report of the differences detected as a structured
// literal in pseudo-Go syntax. String may only be called after the entire tree
// has been traversed.
|
[
"String",
"provides",
"a",
"full",
"report",
"of",
"the",
"differences",
"detected",
"as",
"a",
"structured",
"literal",
"in",
"pseudo",
"-",
"Go",
"syntax",
".",
"String",
"may",
"only",
"be",
"called",
"after",
"the",
"entire",
"tree",
"has",
"been",
"traversed",
"."
] |
6f77996f0c42f7b84e5a2b252227263f93432e9b
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/report.go#L39-L45
|
test
|
google/go-cmp
|
cmp/report_reflect.go
|
FormatType
|
func (opts formatOptions) FormatType(t reflect.Type, s textNode) textNode {
// Check whether to emit the type or not.
switch opts.TypeMode {
case autoType:
switch t.Kind() {
case reflect.Struct, reflect.Slice, reflect.Array, reflect.Map:
if s.Equal(textNil) {
return s
}
default:
return s
}
case elideType:
return s
}
// Determine the type label, applying special handling for unnamed types.
typeName := t.String()
if t.Name() == "" {
// According to Go grammar, certain type literals contain symbols that
// do not strongly bind to the next lexicographical token (e.g., *T).
switch t.Kind() {
case reflect.Chan, reflect.Func, reflect.Ptr:
typeName = "(" + typeName + ")"
}
typeName = strings.Replace(typeName, "struct {", "struct{", -1)
typeName = strings.Replace(typeName, "interface {", "interface{", -1)
}
// Avoid wrap the value in parenthesis if unnecessary.
if s, ok := s.(textWrap); ok {
hasParens := strings.HasPrefix(s.Prefix, "(") && strings.HasSuffix(s.Suffix, ")")
hasBraces := strings.HasPrefix(s.Prefix, "{") && strings.HasSuffix(s.Suffix, "}")
if hasParens || hasBraces {
return textWrap{typeName, s, ""}
}
}
return textWrap{typeName + "(", s, ")"}
}
|
go
|
func (opts formatOptions) FormatType(t reflect.Type, s textNode) textNode {
// Check whether to emit the type or not.
switch opts.TypeMode {
case autoType:
switch t.Kind() {
case reflect.Struct, reflect.Slice, reflect.Array, reflect.Map:
if s.Equal(textNil) {
return s
}
default:
return s
}
case elideType:
return s
}
// Determine the type label, applying special handling for unnamed types.
typeName := t.String()
if t.Name() == "" {
// According to Go grammar, certain type literals contain symbols that
// do not strongly bind to the next lexicographical token (e.g., *T).
switch t.Kind() {
case reflect.Chan, reflect.Func, reflect.Ptr:
typeName = "(" + typeName + ")"
}
typeName = strings.Replace(typeName, "struct {", "struct{", -1)
typeName = strings.Replace(typeName, "interface {", "interface{", -1)
}
// Avoid wrap the value in parenthesis if unnecessary.
if s, ok := s.(textWrap); ok {
hasParens := strings.HasPrefix(s.Prefix, "(") && strings.HasSuffix(s.Suffix, ")")
hasBraces := strings.HasPrefix(s.Prefix, "{") && strings.HasSuffix(s.Suffix, "}")
if hasParens || hasBraces {
return textWrap{typeName, s, ""}
}
}
return textWrap{typeName + "(", s, ")"}
}
|
[
"func",
"(",
"opts",
"formatOptions",
")",
"FormatType",
"(",
"t",
"reflect",
".",
"Type",
",",
"s",
"textNode",
")",
"textNode",
"{",
"switch",
"opts",
".",
"TypeMode",
"{",
"case",
"autoType",
":",
"switch",
"t",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Struct",
",",
"reflect",
".",
"Slice",
",",
"reflect",
".",
"Array",
",",
"reflect",
".",
"Map",
":",
"if",
"s",
".",
"Equal",
"(",
"textNil",
")",
"{",
"return",
"s",
"\n",
"}",
"\n",
"default",
":",
"return",
"s",
"\n",
"}",
"\n",
"case",
"elideType",
":",
"return",
"s",
"\n",
"}",
"\n",
"typeName",
":=",
"t",
".",
"String",
"(",
")",
"\n",
"if",
"t",
".",
"Name",
"(",
")",
"==",
"\"\"",
"{",
"switch",
"t",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Chan",
",",
"reflect",
".",
"Func",
",",
"reflect",
".",
"Ptr",
":",
"typeName",
"=",
"\"(\"",
"+",
"typeName",
"+",
"\")\"",
"\n",
"}",
"\n",
"typeName",
"=",
"strings",
".",
"Replace",
"(",
"typeName",
",",
"\"struct {\"",
",",
"\"struct{\"",
",",
"-",
"1",
")",
"\n",
"typeName",
"=",
"strings",
".",
"Replace",
"(",
"typeName",
",",
"\"interface {\"",
",",
"\"interface{\"",
",",
"-",
"1",
")",
"\n",
"}",
"\n",
"if",
"s",
",",
"ok",
":=",
"s",
".",
"(",
"textWrap",
")",
";",
"ok",
"{",
"hasParens",
":=",
"strings",
".",
"HasPrefix",
"(",
"s",
".",
"Prefix",
",",
"\"(\"",
")",
"&&",
"strings",
".",
"HasSuffix",
"(",
"s",
".",
"Suffix",
",",
"\")\"",
")",
"\n",
"hasBraces",
":=",
"strings",
".",
"HasPrefix",
"(",
"s",
".",
"Prefix",
",",
"\"{\"",
")",
"&&",
"strings",
".",
"HasSuffix",
"(",
"s",
".",
"Suffix",
",",
"\"}\"",
")",
"\n",
"if",
"hasParens",
"||",
"hasBraces",
"{",
"return",
"textWrap",
"{",
"typeName",
",",
"s",
",",
"\"\"",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"textWrap",
"{",
"typeName",
"+",
"\"(\"",
",",
"s",
",",
"\")\"",
"}",
"\n",
"}"
] |
// FormatType prints the type as if it were wrapping s.
// This may return s as-is depending on the current type and TypeMode mode.
|
[
"FormatType",
"prints",
"the",
"type",
"as",
"if",
"it",
"were",
"wrapping",
"s",
".",
"This",
"may",
"return",
"s",
"as",
"-",
"is",
"depending",
"on",
"the",
"current",
"type",
"and",
"TypeMode",
"mode",
"."
] |
6f77996f0c42f7b84e5a2b252227263f93432e9b
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/report_reflect.go#L35-L73
|
test
|
google/go-cmp
|
cmp/report_reflect.go
|
formatMapKey
|
func formatMapKey(v reflect.Value) string {
var opts formatOptions
opts.TypeMode = elideType
opts.AvoidStringer = true
opts.ShallowPointers = true
s := opts.FormatValue(v, visitedPointers{}).String()
return strings.TrimSpace(s)
}
|
go
|
func formatMapKey(v reflect.Value) string {
var opts formatOptions
opts.TypeMode = elideType
opts.AvoidStringer = true
opts.ShallowPointers = true
s := opts.FormatValue(v, visitedPointers{}).String()
return strings.TrimSpace(s)
}
|
[
"func",
"formatMapKey",
"(",
"v",
"reflect",
".",
"Value",
")",
"string",
"{",
"var",
"opts",
"formatOptions",
"\n",
"opts",
".",
"TypeMode",
"=",
"elideType",
"\n",
"opts",
".",
"AvoidStringer",
"=",
"true",
"\n",
"opts",
".",
"ShallowPointers",
"=",
"true",
"\n",
"s",
":=",
"opts",
".",
"FormatValue",
"(",
"v",
",",
"visitedPointers",
"{",
"}",
")",
".",
"String",
"(",
")",
"\n",
"return",
"strings",
".",
"TrimSpace",
"(",
"s",
")",
"\n",
"}"
] |
// formatMapKey formats v as if it were a map key.
// The result is guaranteed to be a single line.
|
[
"formatMapKey",
"formats",
"v",
"as",
"if",
"it",
"were",
"a",
"map",
"key",
".",
"The",
"result",
"is",
"guaranteed",
"to",
"be",
"a",
"single",
"line",
"."
] |
6f77996f0c42f7b84e5a2b252227263f93432e9b
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/report_reflect.go#L208-L215
|
test
|
google/go-cmp
|
cmp/report_reflect.go
|
formatString
|
func formatString(s string) string {
// Use quoted string if it the same length as a raw string literal.
// Otherwise, attempt to use the raw string form.
qs := strconv.Quote(s)
if len(qs) == 1+len(s)+1 {
return qs
}
// Disallow newlines to ensure output is a single line.
// Only allow printable runes for readability purposes.
rawInvalid := func(r rune) bool {
return r == '`' || r == '\n' || !(unicode.IsPrint(r) || r == '\t')
}
if strings.IndexFunc(s, rawInvalid) < 0 {
return "`" + s + "`"
}
return qs
}
|
go
|
func formatString(s string) string {
// Use quoted string if it the same length as a raw string literal.
// Otherwise, attempt to use the raw string form.
qs := strconv.Quote(s)
if len(qs) == 1+len(s)+1 {
return qs
}
// Disallow newlines to ensure output is a single line.
// Only allow printable runes for readability purposes.
rawInvalid := func(r rune) bool {
return r == '`' || r == '\n' || !(unicode.IsPrint(r) || r == '\t')
}
if strings.IndexFunc(s, rawInvalid) < 0 {
return "`" + s + "`"
}
return qs
}
|
[
"func",
"formatString",
"(",
"s",
"string",
")",
"string",
"{",
"qs",
":=",
"strconv",
".",
"Quote",
"(",
"s",
")",
"\n",
"if",
"len",
"(",
"qs",
")",
"==",
"1",
"+",
"len",
"(",
"s",
")",
"+",
"1",
"{",
"return",
"qs",
"\n",
"}",
"\n",
"rawInvalid",
":=",
"func",
"(",
"r",
"rune",
")",
"bool",
"{",
"return",
"r",
"==",
"'`'",
"||",
"r",
"==",
"'\\n'",
"||",
"!",
"(",
"unicode",
".",
"IsPrint",
"(",
"r",
")",
"||",
"r",
"==",
"'\\t'",
")",
"\n",
"}",
"\n",
"if",
"strings",
".",
"IndexFunc",
"(",
"s",
",",
"rawInvalid",
")",
"<",
"0",
"{",
"return",
"\"`\"",
"+",
"s",
"+",
"\"`\"",
"\n",
"}",
"\n",
"return",
"qs",
"\n",
"}"
] |
// formatString prints s as a double-quoted or backtick-quoted string.
|
[
"formatString",
"prints",
"s",
"as",
"a",
"double",
"-",
"quoted",
"or",
"backtick",
"-",
"quoted",
"string",
"."
] |
6f77996f0c42f7b84e5a2b252227263f93432e9b
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/report_reflect.go#L218-L235
|
test
|
google/go-cmp
|
cmp/report_reflect.go
|
formatHex
|
func formatHex(u uint64) string {
var f string
switch {
case u <= 0xff:
f = "0x%02x"
case u <= 0xffff:
f = "0x%04x"
case u <= 0xffffff:
f = "0x%06x"
case u <= 0xffffffff:
f = "0x%08x"
case u <= 0xffffffffff:
f = "0x%010x"
case u <= 0xffffffffffff:
f = "0x%012x"
case u <= 0xffffffffffffff:
f = "0x%014x"
case u <= 0xffffffffffffffff:
f = "0x%016x"
}
return fmt.Sprintf(f, u)
}
|
go
|
func formatHex(u uint64) string {
var f string
switch {
case u <= 0xff:
f = "0x%02x"
case u <= 0xffff:
f = "0x%04x"
case u <= 0xffffff:
f = "0x%06x"
case u <= 0xffffffff:
f = "0x%08x"
case u <= 0xffffffffff:
f = "0x%010x"
case u <= 0xffffffffffff:
f = "0x%012x"
case u <= 0xffffffffffffff:
f = "0x%014x"
case u <= 0xffffffffffffffff:
f = "0x%016x"
}
return fmt.Sprintf(f, u)
}
|
[
"func",
"formatHex",
"(",
"u",
"uint64",
")",
"string",
"{",
"var",
"f",
"string",
"\n",
"switch",
"{",
"case",
"u",
"<=",
"0xff",
":",
"f",
"=",
"\"0x%02x\"",
"\n",
"case",
"u",
"<=",
"0xffff",
":",
"f",
"=",
"\"0x%04x\"",
"\n",
"case",
"u",
"<=",
"0xffffff",
":",
"f",
"=",
"\"0x%06x\"",
"\n",
"case",
"u",
"<=",
"0xffffffff",
":",
"f",
"=",
"\"0x%08x\"",
"\n",
"case",
"u",
"<=",
"0xffffffffff",
":",
"f",
"=",
"\"0x%010x\"",
"\n",
"case",
"u",
"<=",
"0xffffffffffff",
":",
"f",
"=",
"\"0x%012x\"",
"\n",
"case",
"u",
"<=",
"0xffffffffffffff",
":",
"f",
"=",
"\"0x%014x\"",
"\n",
"case",
"u",
"<=",
"0xffffffffffffffff",
":",
"f",
"=",
"\"0x%016x\"",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"f",
",",
"u",
")",
"\n",
"}"
] |
// formatHex prints u as a hexadecimal integer in Go notation.
|
[
"formatHex",
"prints",
"u",
"as",
"a",
"hexadecimal",
"integer",
"in",
"Go",
"notation",
"."
] |
6f77996f0c42f7b84e5a2b252227263f93432e9b
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/report_reflect.go#L238-L259
|
test
|
google/go-cmp
|
cmp/report_reflect.go
|
formatPointer
|
func formatPointer(v reflect.Value) string {
p := v.Pointer()
if flags.Deterministic {
p = 0xdeadf00f // Only used for stable testing purposes
}
return fmt.Sprintf("⟪0x%x⟫", p)
}
|
go
|
func formatPointer(v reflect.Value) string {
p := v.Pointer()
if flags.Deterministic {
p = 0xdeadf00f // Only used for stable testing purposes
}
return fmt.Sprintf("⟪0x%x⟫", p)
}
|
[
"func",
"formatPointer",
"(",
"v",
"reflect",
".",
"Value",
")",
"string",
"{",
"p",
":=",
"v",
".",
"Pointer",
"(",
")",
"\n",
"if",
"flags",
".",
"Deterministic",
"{",
"p",
"=",
"0xdeadf00f",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"⟪0x%x⟫\", p)",
",",
"identifier",
")",
"\n",
"}"
] |
// formatPointer prints the address of the pointer.
|
[
"formatPointer",
"prints",
"the",
"address",
"of",
"the",
"pointer",
"."
] |
6f77996f0c42f7b84e5a2b252227263f93432e9b
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/report_reflect.go#L262-L268
|
test
|
google/go-cmp
|
cmp/report_reflect.go
|
Visit
|
func (m visitedPointers) Visit(v reflect.Value) bool {
p := value.PointerOf(v)
_, visited := m[p]
m[p] = struct{}{}
return visited
}
|
go
|
func (m visitedPointers) Visit(v reflect.Value) bool {
p := value.PointerOf(v)
_, visited := m[p]
m[p] = struct{}{}
return visited
}
|
[
"func",
"(",
"m",
"visitedPointers",
")",
"Visit",
"(",
"v",
"reflect",
".",
"Value",
")",
"bool",
"{",
"p",
":=",
"value",
".",
"PointerOf",
"(",
"v",
")",
"\n",
"_",
",",
"visited",
":=",
"m",
"[",
"p",
"]",
"\n",
"m",
"[",
"p",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"return",
"visited",
"\n",
"}"
] |
// Visit inserts pointer v into the visited map and reports whether it had
// already been visited before.
|
[
"Visit",
"inserts",
"pointer",
"v",
"into",
"the",
"visited",
"map",
"and",
"reports",
"whether",
"it",
"had",
"already",
"been",
"visited",
"before",
"."
] |
6f77996f0c42f7b84e5a2b252227263f93432e9b
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/report_reflect.go#L274-L279
|
test
|
google/go-cmp
|
cmp/export_unsafe.go
|
retrieveUnexportedField
|
func retrieveUnexportedField(v reflect.Value, f reflect.StructField) reflect.Value {
return reflect.NewAt(f.Type, unsafe.Pointer(v.UnsafeAddr()+f.Offset)).Elem()
}
|
go
|
func retrieveUnexportedField(v reflect.Value, f reflect.StructField) reflect.Value {
return reflect.NewAt(f.Type, unsafe.Pointer(v.UnsafeAddr()+f.Offset)).Elem()
}
|
[
"func",
"retrieveUnexportedField",
"(",
"v",
"reflect",
".",
"Value",
",",
"f",
"reflect",
".",
"StructField",
")",
"reflect",
".",
"Value",
"{",
"return",
"reflect",
".",
"NewAt",
"(",
"f",
".",
"Type",
",",
"unsafe",
".",
"Pointer",
"(",
"v",
".",
"UnsafeAddr",
"(",
")",
"+",
"f",
".",
"Offset",
")",
")",
".",
"Elem",
"(",
")",
"\n",
"}"
] |
// retrieveUnexportedField uses unsafe to forcibly retrieve any field from
// a struct such that the value has read-write permissions.
//
// The parent struct, v, must be addressable, while f must be a StructField
// describing the field to retrieve.
|
[
"retrieveUnexportedField",
"uses",
"unsafe",
"to",
"forcibly",
"retrieve",
"any",
"field",
"from",
"a",
"struct",
"such",
"that",
"the",
"value",
"has",
"read",
"-",
"write",
"permissions",
".",
"The",
"parent",
"struct",
"v",
"must",
"be",
"addressable",
"while",
"f",
"must",
"be",
"a",
"StructField",
"describing",
"the",
"field",
"to",
"retrieve",
"."
] |
6f77996f0c42f7b84e5a2b252227263f93432e9b
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/export_unsafe.go#L21-L23
|
test
|
google/go-cmp
|
cmp/cmpopts/struct_filter.go
|
insert
|
func (ft *fieldTree) insert(cname []string) {
if ft.sub == nil {
ft.sub = make(map[string]fieldTree)
}
if len(cname) == 0 {
ft.ok = true
return
}
sub := ft.sub[cname[0]]
sub.insert(cname[1:])
ft.sub[cname[0]] = sub
}
|
go
|
func (ft *fieldTree) insert(cname []string) {
if ft.sub == nil {
ft.sub = make(map[string]fieldTree)
}
if len(cname) == 0 {
ft.ok = true
return
}
sub := ft.sub[cname[0]]
sub.insert(cname[1:])
ft.sub[cname[0]] = sub
}
|
[
"func",
"(",
"ft",
"*",
"fieldTree",
")",
"insert",
"(",
"cname",
"[",
"]",
"string",
")",
"{",
"if",
"ft",
".",
"sub",
"==",
"nil",
"{",
"ft",
".",
"sub",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"fieldTree",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"cname",
")",
"==",
"0",
"{",
"ft",
".",
"ok",
"=",
"true",
"\n",
"return",
"\n",
"}",
"\n",
"sub",
":=",
"ft",
".",
"sub",
"[",
"cname",
"[",
"0",
"]",
"]",
"\n",
"sub",
".",
"insert",
"(",
"cname",
"[",
"1",
":",
"]",
")",
"\n",
"ft",
".",
"sub",
"[",
"cname",
"[",
"0",
"]",
"]",
"=",
"sub",
"\n",
"}"
] |
// insert inserts a sequence of field accesses into the tree.
|
[
"insert",
"inserts",
"a",
"sequence",
"of",
"field",
"accesses",
"into",
"the",
"tree",
"."
] |
6f77996f0c42f7b84e5a2b252227263f93432e9b
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/cmpopts/struct_filter.go#L95-L106
|
test
|
google/go-cmp
|
cmp/cmpopts/struct_filter.go
|
matchPrefix
|
func (ft fieldTree) matchPrefix(p cmp.Path) bool {
for _, ps := range p {
switch ps := ps.(type) {
case cmp.StructField:
ft = ft.sub[ps.Name()]
if ft.ok {
return true
}
if len(ft.sub) == 0 {
return false
}
case cmp.Indirect:
default:
return false
}
}
return false
}
|
go
|
func (ft fieldTree) matchPrefix(p cmp.Path) bool {
for _, ps := range p {
switch ps := ps.(type) {
case cmp.StructField:
ft = ft.sub[ps.Name()]
if ft.ok {
return true
}
if len(ft.sub) == 0 {
return false
}
case cmp.Indirect:
default:
return false
}
}
return false
}
|
[
"func",
"(",
"ft",
"fieldTree",
")",
"matchPrefix",
"(",
"p",
"cmp",
".",
"Path",
")",
"bool",
"{",
"for",
"_",
",",
"ps",
":=",
"range",
"p",
"{",
"switch",
"ps",
":=",
"ps",
".",
"(",
"type",
")",
"{",
"case",
"cmp",
".",
"StructField",
":",
"ft",
"=",
"ft",
".",
"sub",
"[",
"ps",
".",
"Name",
"(",
")",
"]",
"\n",
"if",
"ft",
".",
"ok",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"len",
"(",
"ft",
".",
"sub",
")",
"==",
"0",
"{",
"return",
"false",
"\n",
"}",
"\n",
"case",
"cmp",
".",
"Indirect",
":",
"default",
":",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// matchPrefix reports whether any selector in the fieldTree matches
// the start of path p.
|
[
"matchPrefix",
"reports",
"whether",
"any",
"selector",
"in",
"the",
"fieldTree",
"matches",
"the",
"start",
"of",
"path",
"p",
"."
] |
6f77996f0c42f7b84e5a2b252227263f93432e9b
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/cmpopts/struct_filter.go#L110-L127
|
test
|
google/go-cmp
|
cmp/cmpopts/struct_filter.go
|
canonicalName
|
func canonicalName(t reflect.Type, sel string) ([]string, error) {
var name string
sel = strings.TrimPrefix(sel, ".")
if sel == "" {
return nil, fmt.Errorf("name must not be empty")
}
if i := strings.IndexByte(sel, '.'); i < 0 {
name, sel = sel, ""
} else {
name, sel = sel[:i], sel[i:]
}
// Type must be a struct or pointer to struct.
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.Kind() != reflect.Struct {
return nil, fmt.Errorf("%v must be a struct", t)
}
// Find the canonical name for this current field name.
// If the field exists in an embedded struct, then it will be expanded.
if !isExported(name) {
// Disallow unexported fields:
// * To discourage people from actually touching unexported fields
// * FieldByName is buggy (https://golang.org/issue/4876)
return []string{name}, fmt.Errorf("name must be exported")
}
sf, ok := t.FieldByName(name)
if !ok {
return []string{name}, fmt.Errorf("does not exist")
}
var ss []string
for i := range sf.Index {
ss = append(ss, t.FieldByIndex(sf.Index[:i+1]).Name)
}
if sel == "" {
return ss, nil
}
ssPost, err := canonicalName(sf.Type, sel)
return append(ss, ssPost...), err
}
|
go
|
func canonicalName(t reflect.Type, sel string) ([]string, error) {
var name string
sel = strings.TrimPrefix(sel, ".")
if sel == "" {
return nil, fmt.Errorf("name must not be empty")
}
if i := strings.IndexByte(sel, '.'); i < 0 {
name, sel = sel, ""
} else {
name, sel = sel[:i], sel[i:]
}
// Type must be a struct or pointer to struct.
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.Kind() != reflect.Struct {
return nil, fmt.Errorf("%v must be a struct", t)
}
// Find the canonical name for this current field name.
// If the field exists in an embedded struct, then it will be expanded.
if !isExported(name) {
// Disallow unexported fields:
// * To discourage people from actually touching unexported fields
// * FieldByName is buggy (https://golang.org/issue/4876)
return []string{name}, fmt.Errorf("name must be exported")
}
sf, ok := t.FieldByName(name)
if !ok {
return []string{name}, fmt.Errorf("does not exist")
}
var ss []string
for i := range sf.Index {
ss = append(ss, t.FieldByIndex(sf.Index[:i+1]).Name)
}
if sel == "" {
return ss, nil
}
ssPost, err := canonicalName(sf.Type, sel)
return append(ss, ssPost...), err
}
|
[
"func",
"canonicalName",
"(",
"t",
"reflect",
".",
"Type",
",",
"sel",
"string",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"var",
"name",
"string",
"\n",
"sel",
"=",
"strings",
".",
"TrimPrefix",
"(",
"sel",
",",
"\".\"",
")",
"\n",
"if",
"sel",
"==",
"\"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"name must not be empty\"",
")",
"\n",
"}",
"\n",
"if",
"i",
":=",
"strings",
".",
"IndexByte",
"(",
"sel",
",",
"'.'",
")",
";",
"i",
"<",
"0",
"{",
"name",
",",
"sel",
"=",
"sel",
",",
"\"\"",
"\n",
"}",
"else",
"{",
"name",
",",
"sel",
"=",
"sel",
"[",
":",
"i",
"]",
",",
"sel",
"[",
"i",
":",
"]",
"\n",
"}",
"\n",
"if",
"t",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Ptr",
"{",
"t",
"=",
"t",
".",
"Elem",
"(",
")",
"\n",
"}",
"\n",
"if",
"t",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Struct",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"%v must be a struct\"",
",",
"t",
")",
"\n",
"}",
"\n",
"if",
"!",
"isExported",
"(",
"name",
")",
"{",
"return",
"[",
"]",
"string",
"{",
"name",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"name must be exported\"",
")",
"\n",
"}",
"\n",
"sf",
",",
"ok",
":=",
"t",
".",
"FieldByName",
"(",
"name",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"[",
"]",
"string",
"{",
"name",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"does not exist\"",
")",
"\n",
"}",
"\n",
"var",
"ss",
"[",
"]",
"string",
"\n",
"for",
"i",
":=",
"range",
"sf",
".",
"Index",
"{",
"ss",
"=",
"append",
"(",
"ss",
",",
"t",
".",
"FieldByIndex",
"(",
"sf",
".",
"Index",
"[",
":",
"i",
"+",
"1",
"]",
")",
".",
"Name",
")",
"\n",
"}",
"\n",
"if",
"sel",
"==",
"\"\"",
"{",
"return",
"ss",
",",
"nil",
"\n",
"}",
"\n",
"ssPost",
",",
"err",
":=",
"canonicalName",
"(",
"sf",
".",
"Type",
",",
"sel",
")",
"\n",
"return",
"append",
"(",
"ss",
",",
"ssPost",
"...",
")",
",",
"err",
"\n",
"}"
] |
// canonicalName returns a list of identifiers where any struct field access
// through an embedded field is expanded to include the names of the embedded
// types themselves.
//
// For example, suppose field "Foo" is not directly in the parent struct,
// but actually from an embedded struct of type "Bar". Then, the canonical name
// of "Foo" is actually "Bar.Foo".
//
// Suppose field "Foo" is not directly in the parent struct, but actually
// a field in two different embedded structs of types "Bar" and "Baz".
// Then the selector "Foo" causes a panic since it is ambiguous which one it
// refers to. The user must specify either "Bar.Foo" or "Baz.Foo".
|
[
"canonicalName",
"returns",
"a",
"list",
"of",
"identifiers",
"where",
"any",
"struct",
"field",
"access",
"through",
"an",
"embedded",
"field",
"is",
"expanded",
"to",
"include",
"the",
"names",
"of",
"the",
"embedded",
"types",
"themselves",
".",
"For",
"example",
"suppose",
"field",
"Foo",
"is",
"not",
"directly",
"in",
"the",
"parent",
"struct",
"but",
"actually",
"from",
"an",
"embedded",
"struct",
"of",
"type",
"Bar",
".",
"Then",
"the",
"canonical",
"name",
"of",
"Foo",
"is",
"actually",
"Bar",
".",
"Foo",
".",
"Suppose",
"field",
"Foo",
"is",
"not",
"directly",
"in",
"the",
"parent",
"struct",
"but",
"actually",
"a",
"field",
"in",
"two",
"different",
"embedded",
"structs",
"of",
"types",
"Bar",
"and",
"Baz",
".",
"Then",
"the",
"selector",
"Foo",
"causes",
"a",
"panic",
"since",
"it",
"is",
"ambiguous",
"which",
"one",
"it",
"refers",
"to",
".",
"The",
"user",
"must",
"specify",
"either",
"Bar",
".",
"Foo",
"or",
"Baz",
".",
"Foo",
"."
] |
6f77996f0c42f7b84e5a2b252227263f93432e9b
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/cmpopts/struct_filter.go#L141-L182
|
test
|
google/go-cmp
|
cmp/options.go
|
FilterPath
|
func FilterPath(f func(Path) bool, opt Option) Option {
if f == nil {
panic("invalid path filter function")
}
if opt := normalizeOption(opt); opt != nil {
return &pathFilter{fnc: f, opt: opt}
}
return nil
}
|
go
|
func FilterPath(f func(Path) bool, opt Option) Option {
if f == nil {
panic("invalid path filter function")
}
if opt := normalizeOption(opt); opt != nil {
return &pathFilter{fnc: f, opt: opt}
}
return nil
}
|
[
"func",
"FilterPath",
"(",
"f",
"func",
"(",
"Path",
")",
"bool",
",",
"opt",
"Option",
")",
"Option",
"{",
"if",
"f",
"==",
"nil",
"{",
"panic",
"(",
"\"invalid path filter function\"",
")",
"\n",
"}",
"\n",
"if",
"opt",
":=",
"normalizeOption",
"(",
"opt",
")",
";",
"opt",
"!=",
"nil",
"{",
"return",
"&",
"pathFilter",
"{",
"fnc",
":",
"f",
",",
"opt",
":",
"opt",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// FilterPath returns a new Option where opt is only evaluated if filter f
// returns true for the current Path in the value tree.
//
// This filter is called even if a slice element or map entry is missing and
// provides an opportunity to ignore such cases. The filter function must be
// symmetric such that the filter result is identical regardless of whether the
// missing value is from x or y.
//
// The option passed in may be an Ignore, Transformer, Comparer, Options, or
// a previously filtered Option.
|
[
"FilterPath",
"returns",
"a",
"new",
"Option",
"where",
"opt",
"is",
"only",
"evaluated",
"if",
"filter",
"f",
"returns",
"true",
"for",
"the",
"current",
"Path",
"in",
"the",
"value",
"tree",
".",
"This",
"filter",
"is",
"called",
"even",
"if",
"a",
"slice",
"element",
"or",
"map",
"entry",
"is",
"missing",
"and",
"provides",
"an",
"opportunity",
"to",
"ignore",
"such",
"cases",
".",
"The",
"filter",
"function",
"must",
"be",
"symmetric",
"such",
"that",
"the",
"filter",
"result",
"is",
"identical",
"regardless",
"of",
"whether",
"the",
"missing",
"value",
"is",
"from",
"x",
"or",
"y",
".",
"The",
"option",
"passed",
"in",
"may",
"be",
"an",
"Ignore",
"Transformer",
"Comparer",
"Options",
"or",
"a",
"previously",
"filtered",
"Option",
"."
] |
6f77996f0c42f7b84e5a2b252227263f93432e9b
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/options.go#L116-L124
|
test
|
google/go-cmp
|
cmp/options.go
|
normalizeOption
|
func normalizeOption(src Option) Option {
switch opts := flattenOptions(nil, Options{src}); len(opts) {
case 0:
return nil
case 1:
return opts[0]
default:
return opts
}
}
|
go
|
func normalizeOption(src Option) Option {
switch opts := flattenOptions(nil, Options{src}); len(opts) {
case 0:
return nil
case 1:
return opts[0]
default:
return opts
}
}
|
[
"func",
"normalizeOption",
"(",
"src",
"Option",
")",
"Option",
"{",
"switch",
"opts",
":=",
"flattenOptions",
"(",
"nil",
",",
"Options",
"{",
"src",
"}",
")",
";",
"len",
"(",
"opts",
")",
"{",
"case",
"0",
":",
"return",
"nil",
"\n",
"case",
"1",
":",
"return",
"opts",
"[",
"0",
"]",
"\n",
"default",
":",
"return",
"opts",
"\n",
"}",
"\n",
"}"
] |
// normalizeOption normalizes the input options such that all Options groups
// are flattened and groups with a single element are reduced to that element.
// Only coreOptions and Options containing coreOptions are allowed.
|
[
"normalizeOption",
"normalizes",
"the",
"input",
"options",
"such",
"that",
"all",
"Options",
"groups",
"are",
"flattened",
"and",
"groups",
"with",
"a",
"single",
"element",
"are",
"reduced",
"to",
"that",
"element",
".",
"Only",
"coreOptions",
"and",
"Options",
"containing",
"coreOptions",
"are",
"allowed",
"."
] |
6f77996f0c42f7b84e5a2b252227263f93432e9b
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/options.go#L497-L506
|
test
|
google/go-cmp
|
cmp/options.go
|
flattenOptions
|
func flattenOptions(dst, src Options) Options {
for _, opt := range src {
switch opt := opt.(type) {
case nil:
continue
case Options:
dst = flattenOptions(dst, opt)
case coreOption:
dst = append(dst, opt)
default:
panic(fmt.Sprintf("invalid option type: %T", opt))
}
}
return dst
}
|
go
|
func flattenOptions(dst, src Options) Options {
for _, opt := range src {
switch opt := opt.(type) {
case nil:
continue
case Options:
dst = flattenOptions(dst, opt)
case coreOption:
dst = append(dst, opt)
default:
panic(fmt.Sprintf("invalid option type: %T", opt))
}
}
return dst
}
|
[
"func",
"flattenOptions",
"(",
"dst",
",",
"src",
"Options",
")",
"Options",
"{",
"for",
"_",
",",
"opt",
":=",
"range",
"src",
"{",
"switch",
"opt",
":=",
"opt",
".",
"(",
"type",
")",
"{",
"case",
"nil",
":",
"continue",
"\n",
"case",
"Options",
":",
"dst",
"=",
"flattenOptions",
"(",
"dst",
",",
"opt",
")",
"\n",
"case",
"coreOption",
":",
"dst",
"=",
"append",
"(",
"dst",
",",
"opt",
")",
"\n",
"default",
":",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"invalid option type: %T\"",
",",
"opt",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"dst",
"\n",
"}"
] |
// flattenOptions copies all options in src to dst as a flat list.
// Only coreOptions and Options containing coreOptions are allowed.
|
[
"flattenOptions",
"copies",
"all",
"options",
"in",
"src",
"to",
"dst",
"as",
"a",
"flat",
"list",
".",
"Only",
"coreOptions",
"and",
"Options",
"containing",
"coreOptions",
"are",
"allowed",
"."
] |
6f77996f0c42f7b84e5a2b252227263f93432e9b
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/options.go#L510-L524
|
test
|
google/go-cmp
|
cmp/report_slices.go
|
CanFormatDiffSlice
|
func (opts formatOptions) CanFormatDiffSlice(v *valueNode) bool {
switch {
case opts.DiffMode != diffUnknown:
return false // Must be formatting in diff mode
case v.NumDiff == 0:
return false // No differences detected
case v.NumIgnored+v.NumCompared+v.NumTransformed > 0:
// TODO: Handle the case where someone uses bytes.Equal on a large slice.
return false // Some custom option was used to determined equality
case !v.ValueX.IsValid() || !v.ValueY.IsValid():
return false // Both values must be valid
}
switch t := v.Type; t.Kind() {
case reflect.String:
case reflect.Array, reflect.Slice:
// Only slices of primitive types have specialized handling.
switch t.Elem().Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr,
reflect.Bool, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128:
default:
return false
}
// If a sufficient number of elements already differ,
// use specialized formatting even if length requirement is not met.
if v.NumDiff > v.NumSame {
return true
}
default:
return false
}
// Use specialized string diffing for longer slices or strings.
const minLength = 64
return v.ValueX.Len() >= minLength && v.ValueY.Len() >= minLength
}
|
go
|
func (opts formatOptions) CanFormatDiffSlice(v *valueNode) bool {
switch {
case opts.DiffMode != diffUnknown:
return false // Must be formatting in diff mode
case v.NumDiff == 0:
return false // No differences detected
case v.NumIgnored+v.NumCompared+v.NumTransformed > 0:
// TODO: Handle the case where someone uses bytes.Equal on a large slice.
return false // Some custom option was used to determined equality
case !v.ValueX.IsValid() || !v.ValueY.IsValid():
return false // Both values must be valid
}
switch t := v.Type; t.Kind() {
case reflect.String:
case reflect.Array, reflect.Slice:
// Only slices of primitive types have specialized handling.
switch t.Elem().Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr,
reflect.Bool, reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128:
default:
return false
}
// If a sufficient number of elements already differ,
// use specialized formatting even if length requirement is not met.
if v.NumDiff > v.NumSame {
return true
}
default:
return false
}
// Use specialized string diffing for longer slices or strings.
const minLength = 64
return v.ValueX.Len() >= minLength && v.ValueY.Len() >= minLength
}
|
[
"func",
"(",
"opts",
"formatOptions",
")",
"CanFormatDiffSlice",
"(",
"v",
"*",
"valueNode",
")",
"bool",
"{",
"switch",
"{",
"case",
"opts",
".",
"DiffMode",
"!=",
"diffUnknown",
":",
"return",
"false",
"\n",
"case",
"v",
".",
"NumDiff",
"==",
"0",
":",
"return",
"false",
"\n",
"case",
"v",
".",
"NumIgnored",
"+",
"v",
".",
"NumCompared",
"+",
"v",
".",
"NumTransformed",
">",
"0",
":",
"return",
"false",
"\n",
"case",
"!",
"v",
".",
"ValueX",
".",
"IsValid",
"(",
")",
"||",
"!",
"v",
".",
"ValueY",
".",
"IsValid",
"(",
")",
":",
"return",
"false",
"\n",
"}",
"\n",
"switch",
"t",
":=",
"v",
".",
"Type",
";",
"t",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"String",
":",
"case",
"reflect",
".",
"Array",
",",
"reflect",
".",
"Slice",
":",
"switch",
"t",
".",
"Elem",
"(",
")",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Int",
",",
"reflect",
".",
"Int8",
",",
"reflect",
".",
"Int16",
",",
"reflect",
".",
"Int32",
",",
"reflect",
".",
"Int64",
",",
"reflect",
".",
"Uint",
",",
"reflect",
".",
"Uint8",
",",
"reflect",
".",
"Uint16",
",",
"reflect",
".",
"Uint32",
",",
"reflect",
".",
"Uint64",
",",
"reflect",
".",
"Uintptr",
",",
"reflect",
".",
"Bool",
",",
"reflect",
".",
"Float32",
",",
"reflect",
".",
"Float64",
",",
"reflect",
".",
"Complex64",
",",
"reflect",
".",
"Complex128",
":",
"default",
":",
"return",
"false",
"\n",
"}",
"\n",
"if",
"v",
".",
"NumDiff",
">",
"v",
".",
"NumSame",
"{",
"return",
"true",
"\n",
"}",
"\n",
"default",
":",
"return",
"false",
"\n",
"}",
"\n",
"const",
"minLength",
"=",
"64",
"\n",
"return",
"v",
".",
"ValueX",
".",
"Len",
"(",
")",
">=",
"minLength",
"&&",
"v",
".",
"ValueY",
".",
"Len",
"(",
")",
">=",
"minLength",
"\n",
"}"
] |
// CanFormatDiffSlice reports whether we support custom formatting for nodes
// that are slices of primitive kinds or strings.
|
[
"CanFormatDiffSlice",
"reports",
"whether",
"we",
"support",
"custom",
"formatting",
"for",
"nodes",
"that",
"are",
"slices",
"of",
"primitive",
"kinds",
"or",
"strings",
"."
] |
6f77996f0c42f7b84e5a2b252227263f93432e9b
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/report_slices.go#L20-L57
|
test
|
google/go-cmp
|
cmp/report_slices.go
|
formatASCII
|
func formatASCII(s string) string {
b := bytes.Repeat([]byte{'.'}, len(s))
for i := 0; i < len(s); i++ {
if ' ' <= s[i] && s[i] <= '~' {
b[i] = s[i]
}
}
return string(b)
}
|
go
|
func formatASCII(s string) string {
b := bytes.Repeat([]byte{'.'}, len(s))
for i := 0; i < len(s); i++ {
if ' ' <= s[i] && s[i] <= '~' {
b[i] = s[i]
}
}
return string(b)
}
|
[
"func",
"formatASCII",
"(",
"s",
"string",
")",
"string",
"{",
"b",
":=",
"bytes",
".",
"Repeat",
"(",
"[",
"]",
"byte",
"{",
"'.'",
"}",
",",
"len",
"(",
"s",
")",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"len",
"(",
"s",
")",
";",
"i",
"++",
"{",
"if",
"' '",
"<=",
"s",
"[",
"i",
"]",
"&&",
"s",
"[",
"i",
"]",
"<=",
"'~'",
"{",
"b",
"[",
"i",
"]",
"=",
"s",
"[",
"i",
"]",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"string",
"(",
"b",
")",
"\n",
"}"
] |
// formatASCII formats s as an ASCII string.
// This is useful for printing binary strings in a semi-legible way.
|
[
"formatASCII",
"formats",
"s",
"as",
"an",
"ASCII",
"string",
".",
"This",
"is",
"useful",
"for",
"printing",
"binary",
"strings",
"in",
"a",
"semi",
"-",
"legible",
"way",
"."
] |
6f77996f0c42f7b84e5a2b252227263f93432e9b
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/report_slices.go#L214-L222
|
test
|
google/go-cmp
|
cmp/report_slices.go
|
coalesceAdjacentEdits
|
func coalesceAdjacentEdits(name string, es diff.EditScript) (groups []diffStats) {
var prevCase int // Arbitrary index into which case last occurred
lastStats := func(i int) *diffStats {
if prevCase != i {
groups = append(groups, diffStats{Name: name})
prevCase = i
}
return &groups[len(groups)-1]
}
for _, e := range es {
switch e {
case diff.Identity:
lastStats(1).NumIdentical++
case diff.UniqueX:
lastStats(2).NumRemoved++
case diff.UniqueY:
lastStats(2).NumInserted++
case diff.Modified:
lastStats(2).NumModified++
}
}
return groups
}
|
go
|
func coalesceAdjacentEdits(name string, es diff.EditScript) (groups []diffStats) {
var prevCase int // Arbitrary index into which case last occurred
lastStats := func(i int) *diffStats {
if prevCase != i {
groups = append(groups, diffStats{Name: name})
prevCase = i
}
return &groups[len(groups)-1]
}
for _, e := range es {
switch e {
case diff.Identity:
lastStats(1).NumIdentical++
case diff.UniqueX:
lastStats(2).NumRemoved++
case diff.UniqueY:
lastStats(2).NumInserted++
case diff.Modified:
lastStats(2).NumModified++
}
}
return groups
}
|
[
"func",
"coalesceAdjacentEdits",
"(",
"name",
"string",
",",
"es",
"diff",
".",
"EditScript",
")",
"(",
"groups",
"[",
"]",
"diffStats",
")",
"{",
"var",
"prevCase",
"int",
"\n",
"lastStats",
":=",
"func",
"(",
"i",
"int",
")",
"*",
"diffStats",
"{",
"if",
"prevCase",
"!=",
"i",
"{",
"groups",
"=",
"append",
"(",
"groups",
",",
"diffStats",
"{",
"Name",
":",
"name",
"}",
")",
"\n",
"prevCase",
"=",
"i",
"\n",
"}",
"\n",
"return",
"&",
"groups",
"[",
"len",
"(",
"groups",
")",
"-",
"1",
"]",
"\n",
"}",
"\n",
"for",
"_",
",",
"e",
":=",
"range",
"es",
"{",
"switch",
"e",
"{",
"case",
"diff",
".",
"Identity",
":",
"lastStats",
"(",
"1",
")",
".",
"NumIdentical",
"++",
"\n",
"case",
"diff",
".",
"UniqueX",
":",
"lastStats",
"(",
"2",
")",
".",
"NumRemoved",
"++",
"\n",
"case",
"diff",
".",
"UniqueY",
":",
"lastStats",
"(",
"2",
")",
".",
"NumInserted",
"++",
"\n",
"case",
"diff",
".",
"Modified",
":",
"lastStats",
"(",
"2",
")",
".",
"NumModified",
"++",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"groups",
"\n",
"}"
] |
// coalesceAdjacentEdits coalesces the list of edits into groups of adjacent
// equal or unequal counts.
|
[
"coalesceAdjacentEdits",
"coalesces",
"the",
"list",
"of",
"edits",
"into",
"groups",
"of",
"adjacent",
"equal",
"or",
"unequal",
"counts",
"."
] |
6f77996f0c42f7b84e5a2b252227263f93432e9b
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/report_slices.go#L287-L309
|
test
|
google/go-cmp
|
cmp/internal/value/sort.go
|
SortKeys
|
func SortKeys(vs []reflect.Value) []reflect.Value {
if len(vs) == 0 {
return vs
}
// Sort the map keys.
sort.Slice(vs, func(i, j int) bool { return isLess(vs[i], vs[j]) })
// Deduplicate keys (fails for NaNs).
vs2 := vs[:1]
for _, v := range vs[1:] {
if isLess(vs2[len(vs2)-1], v) {
vs2 = append(vs2, v)
}
}
return vs2
}
|
go
|
func SortKeys(vs []reflect.Value) []reflect.Value {
if len(vs) == 0 {
return vs
}
// Sort the map keys.
sort.Slice(vs, func(i, j int) bool { return isLess(vs[i], vs[j]) })
// Deduplicate keys (fails for NaNs).
vs2 := vs[:1]
for _, v := range vs[1:] {
if isLess(vs2[len(vs2)-1], v) {
vs2 = append(vs2, v)
}
}
return vs2
}
|
[
"func",
"SortKeys",
"(",
"vs",
"[",
"]",
"reflect",
".",
"Value",
")",
"[",
"]",
"reflect",
".",
"Value",
"{",
"if",
"len",
"(",
"vs",
")",
"==",
"0",
"{",
"return",
"vs",
"\n",
"}",
"\n",
"sort",
".",
"Slice",
"(",
"vs",
",",
"func",
"(",
"i",
",",
"j",
"int",
")",
"bool",
"{",
"return",
"isLess",
"(",
"vs",
"[",
"i",
"]",
",",
"vs",
"[",
"j",
"]",
")",
"}",
")",
"\n",
"vs2",
":=",
"vs",
"[",
":",
"1",
"]",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"vs",
"[",
"1",
":",
"]",
"{",
"if",
"isLess",
"(",
"vs2",
"[",
"len",
"(",
"vs2",
")",
"-",
"1",
"]",
",",
"v",
")",
"{",
"vs2",
"=",
"append",
"(",
"vs2",
",",
"v",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"vs2",
"\n",
"}"
] |
// SortKeys sorts a list of map keys, deduplicating keys if necessary.
// The type of each value must be comparable.
|
[
"SortKeys",
"sorts",
"a",
"list",
"of",
"map",
"keys",
"deduplicating",
"keys",
"if",
"necessary",
".",
"The",
"type",
"of",
"each",
"value",
"must",
"be",
"comparable",
"."
] |
6f77996f0c42f7b84e5a2b252227263f93432e9b
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/internal/value/sort.go#L16-L32
|
test
|
google/go-cmp
|
cmp/report_compare.go
|
FormatDiff
|
func (opts formatOptions) FormatDiff(v *valueNode) textNode {
// Check whether we have specialized formatting for this node.
// This is not necessary, but helpful for producing more readable outputs.
if opts.CanFormatDiffSlice(v) {
return opts.FormatDiffSlice(v)
}
// For leaf nodes, format the value based on the reflect.Values alone.
if v.MaxDepth == 0 {
switch opts.DiffMode {
case diffUnknown, diffIdentical:
// Format Equal.
if v.NumDiff == 0 {
outx := opts.FormatValue(v.ValueX, visitedPointers{})
outy := opts.FormatValue(v.ValueY, visitedPointers{})
if v.NumIgnored > 0 && v.NumSame == 0 {
return textEllipsis
} else if outx.Len() < outy.Len() {
return outx
} else {
return outy
}
}
// Format unequal.
assert(opts.DiffMode == diffUnknown)
var list textList
outx := opts.WithTypeMode(elideType).FormatValue(v.ValueX, visitedPointers{})
outy := opts.WithTypeMode(elideType).FormatValue(v.ValueY, visitedPointers{})
if outx != nil {
list = append(list, textRecord{Diff: '-', Value: outx})
}
if outy != nil {
list = append(list, textRecord{Diff: '+', Value: outy})
}
return opts.WithTypeMode(emitType).FormatType(v.Type, list)
case diffRemoved:
return opts.FormatValue(v.ValueX, visitedPointers{})
case diffInserted:
return opts.FormatValue(v.ValueY, visitedPointers{})
default:
panic("invalid diff mode")
}
}
// Descend into the child value node.
if v.TransformerName != "" {
out := opts.WithTypeMode(emitType).FormatDiff(v.Value)
out = textWrap{"Inverse(" + v.TransformerName + ", ", out, ")"}
return opts.FormatType(v.Type, out)
} else {
switch k := v.Type.Kind(); k {
case reflect.Struct, reflect.Array, reflect.Slice, reflect.Map:
return opts.FormatType(v.Type, opts.formatDiffList(v.Records, k))
case reflect.Ptr:
return textWrap{"&", opts.FormatDiff(v.Value), ""}
case reflect.Interface:
return opts.WithTypeMode(emitType).FormatDiff(v.Value)
default:
panic(fmt.Sprintf("%v cannot have children", k))
}
}
}
|
go
|
func (opts formatOptions) FormatDiff(v *valueNode) textNode {
// Check whether we have specialized formatting for this node.
// This is not necessary, but helpful for producing more readable outputs.
if opts.CanFormatDiffSlice(v) {
return opts.FormatDiffSlice(v)
}
// For leaf nodes, format the value based on the reflect.Values alone.
if v.MaxDepth == 0 {
switch opts.DiffMode {
case diffUnknown, diffIdentical:
// Format Equal.
if v.NumDiff == 0 {
outx := opts.FormatValue(v.ValueX, visitedPointers{})
outy := opts.FormatValue(v.ValueY, visitedPointers{})
if v.NumIgnored > 0 && v.NumSame == 0 {
return textEllipsis
} else if outx.Len() < outy.Len() {
return outx
} else {
return outy
}
}
// Format unequal.
assert(opts.DiffMode == diffUnknown)
var list textList
outx := opts.WithTypeMode(elideType).FormatValue(v.ValueX, visitedPointers{})
outy := opts.WithTypeMode(elideType).FormatValue(v.ValueY, visitedPointers{})
if outx != nil {
list = append(list, textRecord{Diff: '-', Value: outx})
}
if outy != nil {
list = append(list, textRecord{Diff: '+', Value: outy})
}
return opts.WithTypeMode(emitType).FormatType(v.Type, list)
case diffRemoved:
return opts.FormatValue(v.ValueX, visitedPointers{})
case diffInserted:
return opts.FormatValue(v.ValueY, visitedPointers{})
default:
panic("invalid diff mode")
}
}
// Descend into the child value node.
if v.TransformerName != "" {
out := opts.WithTypeMode(emitType).FormatDiff(v.Value)
out = textWrap{"Inverse(" + v.TransformerName + ", ", out, ")"}
return opts.FormatType(v.Type, out)
} else {
switch k := v.Type.Kind(); k {
case reflect.Struct, reflect.Array, reflect.Slice, reflect.Map:
return opts.FormatType(v.Type, opts.formatDiffList(v.Records, k))
case reflect.Ptr:
return textWrap{"&", opts.FormatDiff(v.Value), ""}
case reflect.Interface:
return opts.WithTypeMode(emitType).FormatDiff(v.Value)
default:
panic(fmt.Sprintf("%v cannot have children", k))
}
}
}
|
[
"func",
"(",
"opts",
"formatOptions",
")",
"FormatDiff",
"(",
"v",
"*",
"valueNode",
")",
"textNode",
"{",
"if",
"opts",
".",
"CanFormatDiffSlice",
"(",
"v",
")",
"{",
"return",
"opts",
".",
"FormatDiffSlice",
"(",
"v",
")",
"\n",
"}",
"\n",
"if",
"v",
".",
"MaxDepth",
"==",
"0",
"{",
"switch",
"opts",
".",
"DiffMode",
"{",
"case",
"diffUnknown",
",",
"diffIdentical",
":",
"if",
"v",
".",
"NumDiff",
"==",
"0",
"{",
"outx",
":=",
"opts",
".",
"FormatValue",
"(",
"v",
".",
"ValueX",
",",
"visitedPointers",
"{",
"}",
")",
"\n",
"outy",
":=",
"opts",
".",
"FormatValue",
"(",
"v",
".",
"ValueY",
",",
"visitedPointers",
"{",
"}",
")",
"\n",
"if",
"v",
".",
"NumIgnored",
">",
"0",
"&&",
"v",
".",
"NumSame",
"==",
"0",
"{",
"return",
"textEllipsis",
"\n",
"}",
"else",
"if",
"outx",
".",
"Len",
"(",
")",
"<",
"outy",
".",
"Len",
"(",
")",
"{",
"return",
"outx",
"\n",
"}",
"else",
"{",
"return",
"outy",
"\n",
"}",
"\n",
"}",
"\n",
"assert",
"(",
"opts",
".",
"DiffMode",
"==",
"diffUnknown",
")",
"\n",
"var",
"list",
"textList",
"\n",
"outx",
":=",
"opts",
".",
"WithTypeMode",
"(",
"elideType",
")",
".",
"FormatValue",
"(",
"v",
".",
"ValueX",
",",
"visitedPointers",
"{",
"}",
")",
"\n",
"outy",
":=",
"opts",
".",
"WithTypeMode",
"(",
"elideType",
")",
".",
"FormatValue",
"(",
"v",
".",
"ValueY",
",",
"visitedPointers",
"{",
"}",
")",
"\n",
"if",
"outx",
"!=",
"nil",
"{",
"list",
"=",
"append",
"(",
"list",
",",
"textRecord",
"{",
"Diff",
":",
"'-'",
",",
"Value",
":",
"outx",
"}",
")",
"\n",
"}",
"\n",
"if",
"outy",
"!=",
"nil",
"{",
"list",
"=",
"append",
"(",
"list",
",",
"textRecord",
"{",
"Diff",
":",
"'+'",
",",
"Value",
":",
"outy",
"}",
")",
"\n",
"}",
"\n",
"return",
"opts",
".",
"WithTypeMode",
"(",
"emitType",
")",
".",
"FormatType",
"(",
"v",
".",
"Type",
",",
"list",
")",
"\n",
"case",
"diffRemoved",
":",
"return",
"opts",
".",
"FormatValue",
"(",
"v",
".",
"ValueX",
",",
"visitedPointers",
"{",
"}",
")",
"\n",
"case",
"diffInserted",
":",
"return",
"opts",
".",
"FormatValue",
"(",
"v",
".",
"ValueY",
",",
"visitedPointers",
"{",
"}",
")",
"\n",
"default",
":",
"panic",
"(",
"\"invalid diff mode\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"v",
".",
"TransformerName",
"!=",
"\"\"",
"{",
"out",
":=",
"opts",
".",
"WithTypeMode",
"(",
"emitType",
")",
".",
"FormatDiff",
"(",
"v",
".",
"Value",
")",
"\n",
"out",
"=",
"textWrap",
"{",
"\"Inverse(\"",
"+",
"v",
".",
"TransformerName",
"+",
"\", \"",
",",
"out",
",",
"\")\"",
"}",
"\n",
"return",
"opts",
".",
"FormatType",
"(",
"v",
".",
"Type",
",",
"out",
")",
"\n",
"}",
"else",
"{",
"switch",
"k",
":=",
"v",
".",
"Type",
".",
"Kind",
"(",
")",
";",
"k",
"{",
"case",
"reflect",
".",
"Struct",
",",
"reflect",
".",
"Array",
",",
"reflect",
".",
"Slice",
",",
"reflect",
".",
"Map",
":",
"return",
"opts",
".",
"FormatType",
"(",
"v",
".",
"Type",
",",
"opts",
".",
"formatDiffList",
"(",
"v",
".",
"Records",
",",
"k",
")",
")",
"\n",
"case",
"reflect",
".",
"Ptr",
":",
"return",
"textWrap",
"{",
"\"&\"",
",",
"opts",
".",
"FormatDiff",
"(",
"v",
".",
"Value",
")",
",",
"\"\"",
"}",
"\n",
"case",
"reflect",
".",
"Interface",
":",
"return",
"opts",
".",
"WithTypeMode",
"(",
"emitType",
")",
".",
"FormatDiff",
"(",
"v",
".",
"Value",
")",
"\n",
"default",
":",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"%v cannot have children\"",
",",
"k",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// FormatDiff converts a valueNode tree into a textNode tree, where the later
// is a textual representation of the differences detected in the former.
|
[
"FormatDiff",
"converts",
"a",
"valueNode",
"tree",
"into",
"a",
"textNode",
"tree",
"where",
"the",
"later",
"is",
"a",
"textual",
"representation",
"of",
"the",
"differences",
"detected",
"in",
"the",
"former",
"."
] |
6f77996f0c42f7b84e5a2b252227263f93432e9b
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/report_compare.go#L77-L139
|
test
|
google/go-cmp
|
cmp/report_compare.go
|
coalesceAdjacentRecords
|
func coalesceAdjacentRecords(name string, recs []reportRecord) (groups []diffStats) {
var prevCase int // Arbitrary index into which case last occurred
lastStats := func(i int) *diffStats {
if prevCase != i {
groups = append(groups, diffStats{Name: name})
prevCase = i
}
return &groups[len(groups)-1]
}
for _, r := range recs {
switch rv := r.Value; {
case rv.NumIgnored > 0 && rv.NumSame+rv.NumDiff == 0:
lastStats(1).NumIgnored++
case rv.NumDiff == 0:
lastStats(1).NumIdentical++
case rv.NumDiff > 0 && !rv.ValueY.IsValid():
lastStats(2).NumRemoved++
case rv.NumDiff > 0 && !rv.ValueX.IsValid():
lastStats(2).NumInserted++
default:
lastStats(2).NumModified++
}
}
return groups
}
|
go
|
func coalesceAdjacentRecords(name string, recs []reportRecord) (groups []diffStats) {
var prevCase int // Arbitrary index into which case last occurred
lastStats := func(i int) *diffStats {
if prevCase != i {
groups = append(groups, diffStats{Name: name})
prevCase = i
}
return &groups[len(groups)-1]
}
for _, r := range recs {
switch rv := r.Value; {
case rv.NumIgnored > 0 && rv.NumSame+rv.NumDiff == 0:
lastStats(1).NumIgnored++
case rv.NumDiff == 0:
lastStats(1).NumIdentical++
case rv.NumDiff > 0 && !rv.ValueY.IsValid():
lastStats(2).NumRemoved++
case rv.NumDiff > 0 && !rv.ValueX.IsValid():
lastStats(2).NumInserted++
default:
lastStats(2).NumModified++
}
}
return groups
}
|
[
"func",
"coalesceAdjacentRecords",
"(",
"name",
"string",
",",
"recs",
"[",
"]",
"reportRecord",
")",
"(",
"groups",
"[",
"]",
"diffStats",
")",
"{",
"var",
"prevCase",
"int",
"\n",
"lastStats",
":=",
"func",
"(",
"i",
"int",
")",
"*",
"diffStats",
"{",
"if",
"prevCase",
"!=",
"i",
"{",
"groups",
"=",
"append",
"(",
"groups",
",",
"diffStats",
"{",
"Name",
":",
"name",
"}",
")",
"\n",
"prevCase",
"=",
"i",
"\n",
"}",
"\n",
"return",
"&",
"groups",
"[",
"len",
"(",
"groups",
")",
"-",
"1",
"]",
"\n",
"}",
"\n",
"for",
"_",
",",
"r",
":=",
"range",
"recs",
"{",
"switch",
"rv",
":=",
"r",
".",
"Value",
";",
"{",
"case",
"rv",
".",
"NumIgnored",
">",
"0",
"&&",
"rv",
".",
"NumSame",
"+",
"rv",
".",
"NumDiff",
"==",
"0",
":",
"lastStats",
"(",
"1",
")",
".",
"NumIgnored",
"++",
"\n",
"case",
"rv",
".",
"NumDiff",
"==",
"0",
":",
"lastStats",
"(",
"1",
")",
".",
"NumIdentical",
"++",
"\n",
"case",
"rv",
".",
"NumDiff",
">",
"0",
"&&",
"!",
"rv",
".",
"ValueY",
".",
"IsValid",
"(",
")",
":",
"lastStats",
"(",
"2",
")",
".",
"NumRemoved",
"++",
"\n",
"case",
"rv",
".",
"NumDiff",
">",
"0",
"&&",
"!",
"rv",
".",
"ValueX",
".",
"IsValid",
"(",
")",
":",
"lastStats",
"(",
"2",
")",
".",
"NumInserted",
"++",
"\n",
"default",
":",
"lastStats",
"(",
"2",
")",
".",
"NumModified",
"++",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"groups",
"\n",
"}"
] |
// coalesceAdjacentRecords coalesces the list of records into groups of
// adjacent equal, or unequal counts.
|
[
"coalesceAdjacentRecords",
"coalesces",
"the",
"list",
"of",
"records",
"into",
"groups",
"of",
"adjacent",
"equal",
"or",
"unequal",
"counts",
"."
] |
6f77996f0c42f7b84e5a2b252227263f93432e9b
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/report_compare.go#L272-L296
|
test
|
google/go-cmp
|
cmp/compare.go
|
Diff
|
func Diff(x, y interface{}, opts ...Option) string {
r := new(defaultReporter)
eq := Equal(x, y, Options(opts), Reporter(r))
d := r.String()
if (d == "") != eq {
panic("inconsistent difference and equality results")
}
return d
}
|
go
|
func Diff(x, y interface{}, opts ...Option) string {
r := new(defaultReporter)
eq := Equal(x, y, Options(opts), Reporter(r))
d := r.String()
if (d == "") != eq {
panic("inconsistent difference and equality results")
}
return d
}
|
[
"func",
"Diff",
"(",
"x",
",",
"y",
"interface",
"{",
"}",
",",
"opts",
"...",
"Option",
")",
"string",
"{",
"r",
":=",
"new",
"(",
"defaultReporter",
")",
"\n",
"eq",
":=",
"Equal",
"(",
"x",
",",
"y",
",",
"Options",
"(",
"opts",
")",
",",
"Reporter",
"(",
"r",
")",
")",
"\n",
"d",
":=",
"r",
".",
"String",
"(",
")",
"\n",
"if",
"(",
"d",
"==",
"\"\"",
")",
"!=",
"eq",
"{",
"panic",
"(",
"\"inconsistent difference and equality results\"",
")",
"\n",
"}",
"\n",
"return",
"d",
"\n",
"}"
] |
// Diff returns a human-readable report of the differences between two values.
// It returns an empty string if and only if Equal returns true for the same
// input values and options.
//
// The output is displayed as a literal in pseudo-Go syntax.
// At the start of each line, a "-" prefix indicates an element removed from x,
// a "+" prefix to indicates an element added to y, and the lack of a prefix
// indicates an element common to both x and y. If possible, the output
// uses fmt.Stringer.String or error.Error methods to produce more humanly
// readable outputs. In such cases, the string is prefixed with either an
// 's' or 'e' character, respectively, to indicate that the method was called.
//
// Do not depend on this output being stable. If you need the ability to
// programmatically interpret the difference, consider using a custom Reporter.
|
[
"Diff",
"returns",
"a",
"human",
"-",
"readable",
"report",
"of",
"the",
"differences",
"between",
"two",
"values",
".",
"It",
"returns",
"an",
"empty",
"string",
"if",
"and",
"only",
"if",
"Equal",
"returns",
"true",
"for",
"the",
"same",
"input",
"values",
"and",
"options",
".",
"The",
"output",
"is",
"displayed",
"as",
"a",
"literal",
"in",
"pseudo",
"-",
"Go",
"syntax",
".",
"At",
"the",
"start",
"of",
"each",
"line",
"a",
"-",
"prefix",
"indicates",
"an",
"element",
"removed",
"from",
"x",
"a",
"+",
"prefix",
"to",
"indicates",
"an",
"element",
"added",
"to",
"y",
"and",
"the",
"lack",
"of",
"a",
"prefix",
"indicates",
"an",
"element",
"common",
"to",
"both",
"x",
"and",
"y",
".",
"If",
"possible",
"the",
"output",
"uses",
"fmt",
".",
"Stringer",
".",
"String",
"or",
"error",
".",
"Error",
"methods",
"to",
"produce",
"more",
"humanly",
"readable",
"outputs",
".",
"In",
"such",
"cases",
"the",
"string",
"is",
"prefixed",
"with",
"either",
"an",
"s",
"or",
"e",
"character",
"respectively",
"to",
"indicate",
"that",
"the",
"method",
"was",
"called",
".",
"Do",
"not",
"depend",
"on",
"this",
"output",
"being",
"stable",
".",
"If",
"you",
"need",
"the",
"ability",
"to",
"programmatically",
"interpret",
"the",
"difference",
"consider",
"using",
"a",
"custom",
"Reporter",
"."
] |
6f77996f0c42f7b84e5a2b252227263f93432e9b
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/compare.go#L125-L133
|
test
|
google/go-cmp
|
cmp/compare.go
|
statelessCompare
|
func (s *state) statelessCompare(step PathStep) diff.Result {
// We do not save and restore the curPath because all of the compareX
// methods should properly push and pop from the path.
// It is an implementation bug if the contents of curPath differs from
// when calling this function to when returning from it.
oldResult, oldReporters := s.result, s.reporters
s.result = diff.Result{} // Reset result
s.reporters = nil // Remove reporters to avoid spurious printouts
s.compareAny(step)
res := s.result
s.result, s.reporters = oldResult, oldReporters
return res
}
|
go
|
func (s *state) statelessCompare(step PathStep) diff.Result {
// We do not save and restore the curPath because all of the compareX
// methods should properly push and pop from the path.
// It is an implementation bug if the contents of curPath differs from
// when calling this function to when returning from it.
oldResult, oldReporters := s.result, s.reporters
s.result = diff.Result{} // Reset result
s.reporters = nil // Remove reporters to avoid spurious printouts
s.compareAny(step)
res := s.result
s.result, s.reporters = oldResult, oldReporters
return res
}
|
[
"func",
"(",
"s",
"*",
"state",
")",
"statelessCompare",
"(",
"step",
"PathStep",
")",
"diff",
".",
"Result",
"{",
"oldResult",
",",
"oldReporters",
":=",
"s",
".",
"result",
",",
"s",
".",
"reporters",
"\n",
"s",
".",
"result",
"=",
"diff",
".",
"Result",
"{",
"}",
"\n",
"s",
".",
"reporters",
"=",
"nil",
"\n",
"s",
".",
"compareAny",
"(",
"step",
")",
"\n",
"res",
":=",
"s",
".",
"result",
"\n",
"s",
".",
"result",
",",
"s",
".",
"reporters",
"=",
"oldResult",
",",
"oldReporters",
"\n",
"return",
"res",
"\n",
"}"
] |
// statelessCompare compares two values and returns the result.
// This function is stateless in that it does not alter the current result,
// or output to any registered reporters.
|
[
"statelessCompare",
"compares",
"two",
"values",
"and",
"returns",
"the",
"result",
".",
"This",
"function",
"is",
"stateless",
"in",
"that",
"it",
"does",
"not",
"alter",
"the",
"current",
"result",
"or",
"output",
"to",
"any",
"registered",
"reporters",
"."
] |
6f77996f0c42f7b84e5a2b252227263f93432e9b
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/compare.go#L194-L207
|
test
|
google/go-cmp
|
cmp/compare.go
|
sanitizeValue
|
func sanitizeValue(v reflect.Value, t reflect.Type) reflect.Value {
// TODO(dsnet): Workaround for reflect bug (https://golang.org/issue/22143).
if !flags.AtLeastGo110 {
if v.Kind() == reflect.Interface && v.IsNil() && v.Type() != t {
return reflect.New(t).Elem()
}
}
return v
}
|
go
|
func sanitizeValue(v reflect.Value, t reflect.Type) reflect.Value {
// TODO(dsnet): Workaround for reflect bug (https://golang.org/issue/22143).
if !flags.AtLeastGo110 {
if v.Kind() == reflect.Interface && v.IsNil() && v.Type() != t {
return reflect.New(t).Elem()
}
}
return v
}
|
[
"func",
"sanitizeValue",
"(",
"v",
"reflect",
".",
"Value",
",",
"t",
"reflect",
".",
"Type",
")",
"reflect",
".",
"Value",
"{",
"if",
"!",
"flags",
".",
"AtLeastGo110",
"{",
"if",
"v",
".",
"Kind",
"(",
")",
"==",
"reflect",
".",
"Interface",
"&&",
"v",
".",
"IsNil",
"(",
")",
"&&",
"v",
".",
"Type",
"(",
")",
"!=",
"t",
"{",
"return",
"reflect",
".",
"New",
"(",
"t",
")",
".",
"Elem",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"v",
"\n",
"}"
] |
// sanitizeValue converts nil interfaces of type T to those of type R,
// assuming that T is assignable to R.
// Otherwise, it returns the input value as is.
|
[
"sanitizeValue",
"converts",
"nil",
"interfaces",
"of",
"type",
"T",
"to",
"those",
"of",
"type",
"R",
"assuming",
"that",
"T",
"is",
"assignable",
"to",
"R",
".",
"Otherwise",
"it",
"returns",
"the",
"input",
"value",
"as",
"is",
"."
] |
6f77996f0c42f7b84e5a2b252227263f93432e9b
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/compare.go#L344-L352
|
test
|
google/go-cmp
|
cmp/compare.go
|
Check
|
func (rc *recChecker) Check(p Path) {
const minLen = 1 << 16
if rc.next == 0 {
rc.next = minLen
}
if len(p) < rc.next {
return
}
rc.next <<= 1
// Check whether the same transformer has appeared at least twice.
var ss []string
m := map[Option]int{}
for _, ps := range p {
if t, ok := ps.(Transform); ok {
t := t.Option()
if m[t] == 1 { // Transformer was used exactly once before
tf := t.(*transformer).fnc.Type()
ss = append(ss, fmt.Sprintf("%v: %v => %v", t, tf.In(0), tf.Out(0)))
}
m[t]++
}
}
if len(ss) > 0 {
const warning = "recursive set of Transformers detected"
const help = "consider using cmpopts.AcyclicTransformer"
set := strings.Join(ss, "\n\t")
panic(fmt.Sprintf("%s:\n\t%s\n%s", warning, set, help))
}
}
|
go
|
func (rc *recChecker) Check(p Path) {
const minLen = 1 << 16
if rc.next == 0 {
rc.next = minLen
}
if len(p) < rc.next {
return
}
rc.next <<= 1
// Check whether the same transformer has appeared at least twice.
var ss []string
m := map[Option]int{}
for _, ps := range p {
if t, ok := ps.(Transform); ok {
t := t.Option()
if m[t] == 1 { // Transformer was used exactly once before
tf := t.(*transformer).fnc.Type()
ss = append(ss, fmt.Sprintf("%v: %v => %v", t, tf.In(0), tf.Out(0)))
}
m[t]++
}
}
if len(ss) > 0 {
const warning = "recursive set of Transformers detected"
const help = "consider using cmpopts.AcyclicTransformer"
set := strings.Join(ss, "\n\t")
panic(fmt.Sprintf("%s:\n\t%s\n%s", warning, set, help))
}
}
|
[
"func",
"(",
"rc",
"*",
"recChecker",
")",
"Check",
"(",
"p",
"Path",
")",
"{",
"const",
"minLen",
"=",
"1",
"<<",
"16",
"\n",
"if",
"rc",
".",
"next",
"==",
"0",
"{",
"rc",
".",
"next",
"=",
"minLen",
"\n",
"}",
"\n",
"if",
"len",
"(",
"p",
")",
"<",
"rc",
".",
"next",
"{",
"return",
"\n",
"}",
"\n",
"rc",
".",
"next",
"<<=",
"1",
"\n",
"var",
"ss",
"[",
"]",
"string",
"\n",
"m",
":=",
"map",
"[",
"Option",
"]",
"int",
"{",
"}",
"\n",
"for",
"_",
",",
"ps",
":=",
"range",
"p",
"{",
"if",
"t",
",",
"ok",
":=",
"ps",
".",
"(",
"Transform",
")",
";",
"ok",
"{",
"t",
":=",
"t",
".",
"Option",
"(",
")",
"\n",
"if",
"m",
"[",
"t",
"]",
"==",
"1",
"{",
"tf",
":=",
"t",
".",
"(",
"*",
"transformer",
")",
".",
"fnc",
".",
"Type",
"(",
")",
"\n",
"ss",
"=",
"append",
"(",
"ss",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%v: %v => %v\"",
",",
"t",
",",
"tf",
".",
"In",
"(",
"0",
")",
",",
"tf",
".",
"Out",
"(",
"0",
")",
")",
")",
"\n",
"}",
"\n",
"m",
"[",
"t",
"]",
"++",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"ss",
")",
">",
"0",
"{",
"const",
"warning",
"=",
"\"recursive set of Transformers detected\"",
"\n",
"const",
"help",
"=",
"\"consider using cmpopts.AcyclicTransformer\"",
"\n",
"set",
":=",
"strings",
".",
"Join",
"(",
"ss",
",",
"\"\\n\\t\"",
")",
"\n",
"\\n",
"\n",
"}",
"\n",
"}"
] |
// Check scans the Path for any recursive transformers and panics when any
// recursive transformers are detected. Note that the presence of a
// recursive Transformer does not necessarily imply an infinite cycle.
// As such, this check only activates after some minimal number of path steps.
|
[
"Check",
"scans",
"the",
"Path",
"for",
"any",
"recursive",
"transformers",
"and",
"panics",
"when",
"any",
"recursive",
"transformers",
"are",
"detected",
".",
"Note",
"that",
"the",
"presence",
"of",
"a",
"recursive",
"Transformer",
"does",
"not",
"necessarily",
"imply",
"an",
"infinite",
"cycle",
".",
"As",
"such",
"this",
"check",
"only",
"activates",
"after",
"some",
"minimal",
"number",
"of",
"path",
"steps",
"."
] |
6f77996f0c42f7b84e5a2b252227263f93432e9b
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/compare.go#L552-L581
|
test
|
google/go-cmp
|
cmp/compare.go
|
makeAddressable
|
func makeAddressable(v reflect.Value) reflect.Value {
if v.CanAddr() {
return v
}
vc := reflect.New(v.Type()).Elem()
vc.Set(v)
return vc
}
|
go
|
func makeAddressable(v reflect.Value) reflect.Value {
if v.CanAddr() {
return v
}
vc := reflect.New(v.Type()).Elem()
vc.Set(v)
return vc
}
|
[
"func",
"makeAddressable",
"(",
"v",
"reflect",
".",
"Value",
")",
"reflect",
".",
"Value",
"{",
"if",
"v",
".",
"CanAddr",
"(",
")",
"{",
"return",
"v",
"\n",
"}",
"\n",
"vc",
":=",
"reflect",
".",
"New",
"(",
"v",
".",
"Type",
"(",
")",
")",
".",
"Elem",
"(",
")",
"\n",
"vc",
".",
"Set",
"(",
"v",
")",
"\n",
"return",
"vc",
"\n",
"}"
] |
// makeAddressable returns a value that is always addressable.
// It returns the input verbatim if it is already addressable,
// otherwise it creates a new value and returns an addressable copy.
|
[
"makeAddressable",
"returns",
"a",
"value",
"that",
"is",
"always",
"addressable",
".",
"It",
"returns",
"the",
"input",
"verbatim",
"if",
"it",
"is",
"already",
"addressable",
"otherwise",
"it",
"creates",
"a",
"new",
"value",
"and",
"returns",
"an",
"addressable",
"copy",
"."
] |
6f77996f0c42f7b84e5a2b252227263f93432e9b
|
https://github.com/google/go-cmp/blob/6f77996f0c42f7b84e5a2b252227263f93432e9b/cmp/compare.go#L609-L616
|
test
|
opentracing/opentracing-go
|
log/field.go
|
Marshal
|
func (lf Field) Marshal(visitor Encoder) {
switch lf.fieldType {
case stringType:
visitor.EmitString(lf.key, lf.stringVal)
case boolType:
visitor.EmitBool(lf.key, lf.numericVal != 0)
case intType:
visitor.EmitInt(lf.key, int(lf.numericVal))
case int32Type:
visitor.EmitInt32(lf.key, int32(lf.numericVal))
case int64Type:
visitor.EmitInt64(lf.key, int64(lf.numericVal))
case uint32Type:
visitor.EmitUint32(lf.key, uint32(lf.numericVal))
case uint64Type:
visitor.EmitUint64(lf.key, uint64(lf.numericVal))
case float32Type:
visitor.EmitFloat32(lf.key, math.Float32frombits(uint32(lf.numericVal)))
case float64Type:
visitor.EmitFloat64(lf.key, math.Float64frombits(uint64(lf.numericVal)))
case errorType:
if err, ok := lf.interfaceVal.(error); ok {
visitor.EmitString(lf.key, err.Error())
} else {
visitor.EmitString(lf.key, "<nil>")
}
case objectType:
visitor.EmitObject(lf.key, lf.interfaceVal)
case lazyLoggerType:
visitor.EmitLazyLogger(lf.interfaceVal.(LazyLogger))
case noopType:
// intentionally left blank
}
}
|
go
|
func (lf Field) Marshal(visitor Encoder) {
switch lf.fieldType {
case stringType:
visitor.EmitString(lf.key, lf.stringVal)
case boolType:
visitor.EmitBool(lf.key, lf.numericVal != 0)
case intType:
visitor.EmitInt(lf.key, int(lf.numericVal))
case int32Type:
visitor.EmitInt32(lf.key, int32(lf.numericVal))
case int64Type:
visitor.EmitInt64(lf.key, int64(lf.numericVal))
case uint32Type:
visitor.EmitUint32(lf.key, uint32(lf.numericVal))
case uint64Type:
visitor.EmitUint64(lf.key, uint64(lf.numericVal))
case float32Type:
visitor.EmitFloat32(lf.key, math.Float32frombits(uint32(lf.numericVal)))
case float64Type:
visitor.EmitFloat64(lf.key, math.Float64frombits(uint64(lf.numericVal)))
case errorType:
if err, ok := lf.interfaceVal.(error); ok {
visitor.EmitString(lf.key, err.Error())
} else {
visitor.EmitString(lf.key, "<nil>")
}
case objectType:
visitor.EmitObject(lf.key, lf.interfaceVal)
case lazyLoggerType:
visitor.EmitLazyLogger(lf.interfaceVal.(LazyLogger))
case noopType:
// intentionally left blank
}
}
|
[
"func",
"(",
"lf",
"Field",
")",
"Marshal",
"(",
"visitor",
"Encoder",
")",
"{",
"switch",
"lf",
".",
"fieldType",
"{",
"case",
"stringType",
":",
"visitor",
".",
"EmitString",
"(",
"lf",
".",
"key",
",",
"lf",
".",
"stringVal",
")",
"\n",
"case",
"boolType",
":",
"visitor",
".",
"EmitBool",
"(",
"lf",
".",
"key",
",",
"lf",
".",
"numericVal",
"!=",
"0",
")",
"\n",
"case",
"intType",
":",
"visitor",
".",
"EmitInt",
"(",
"lf",
".",
"key",
",",
"int",
"(",
"lf",
".",
"numericVal",
")",
")",
"\n",
"case",
"int32Type",
":",
"visitor",
".",
"EmitInt32",
"(",
"lf",
".",
"key",
",",
"int32",
"(",
"lf",
".",
"numericVal",
")",
")",
"\n",
"case",
"int64Type",
":",
"visitor",
".",
"EmitInt64",
"(",
"lf",
".",
"key",
",",
"int64",
"(",
"lf",
".",
"numericVal",
")",
")",
"\n",
"case",
"uint32Type",
":",
"visitor",
".",
"EmitUint32",
"(",
"lf",
".",
"key",
",",
"uint32",
"(",
"lf",
".",
"numericVal",
")",
")",
"\n",
"case",
"uint64Type",
":",
"visitor",
".",
"EmitUint64",
"(",
"lf",
".",
"key",
",",
"uint64",
"(",
"lf",
".",
"numericVal",
")",
")",
"\n",
"case",
"float32Type",
":",
"visitor",
".",
"EmitFloat32",
"(",
"lf",
".",
"key",
",",
"math",
".",
"Float32frombits",
"(",
"uint32",
"(",
"lf",
".",
"numericVal",
")",
")",
")",
"\n",
"case",
"float64Type",
":",
"visitor",
".",
"EmitFloat64",
"(",
"lf",
".",
"key",
",",
"math",
".",
"Float64frombits",
"(",
"uint64",
"(",
"lf",
".",
"numericVal",
")",
")",
")",
"\n",
"case",
"errorType",
":",
"if",
"err",
",",
"ok",
":=",
"lf",
".",
"interfaceVal",
".",
"(",
"error",
")",
";",
"ok",
"{",
"visitor",
".",
"EmitString",
"(",
"lf",
".",
"key",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"else",
"{",
"visitor",
".",
"EmitString",
"(",
"lf",
".",
"key",
",",
"\"<nil>\"",
")",
"\n",
"}",
"\n",
"case",
"objectType",
":",
"visitor",
".",
"EmitObject",
"(",
"lf",
".",
"key",
",",
"lf",
".",
"interfaceVal",
")",
"\n",
"case",
"lazyLoggerType",
":",
"visitor",
".",
"EmitLazyLogger",
"(",
"lf",
".",
"interfaceVal",
".",
"(",
"LazyLogger",
")",
")",
"\n",
"case",
"noopType",
":",
"}",
"\n",
"}"
] |
// Marshal passes a Field instance through to the appropriate
// field-type-specific method of an Encoder.
|
[
"Marshal",
"passes",
"a",
"Field",
"instance",
"through",
"to",
"the",
"appropriate",
"field",
"-",
"type",
"-",
"specific",
"method",
"of",
"an",
"Encoder",
"."
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/log/field.go#L196-L229
|
test
|
opentracing/opentracing-go
|
log/field.go
|
String
|
func (lf Field) String() string {
return fmt.Sprint(lf.key, ":", lf.Value())
}
|
go
|
func (lf Field) String() string {
return fmt.Sprint(lf.key, ":", lf.Value())
}
|
[
"func",
"(",
"lf",
"Field",
")",
"String",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprint",
"(",
"lf",
".",
"key",
",",
"\":\"",
",",
"lf",
".",
"Value",
"(",
")",
")",
"\n",
"}"
] |
// String returns a string representation of the key and value.
|
[
"String",
"returns",
"a",
"string",
"representation",
"of",
"the",
"key",
"and",
"value",
"."
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/log/field.go#L267-L269
|
test
|
opentracing/opentracing-go
|
tracer.go
|
Set
|
func (t Tag) Set(s Span) {
s.SetTag(t.Key, t.Value)
}
|
go
|
func (t Tag) Set(s Span) {
s.SetTag(t.Key, t.Value)
}
|
[
"func",
"(",
"t",
"Tag",
")",
"Set",
"(",
"s",
"Span",
")",
"{",
"s",
".",
"SetTag",
"(",
"t",
".",
"Key",
",",
"t",
".",
"Value",
")",
"\n",
"}"
] |
// Set applies the tag to an existing Span.
|
[
"Set",
"applies",
"the",
"tag",
"to",
"an",
"existing",
"Span",
"."
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/tracer.go#L302-L304
|
test
|
opentracing/opentracing-go
|
mocktracer/propagation.go
|
Inject
|
func (t *TextMapPropagator) Inject(spanContext MockSpanContext, carrier interface{}) error {
writer, ok := carrier.(opentracing.TextMapWriter)
if !ok {
return opentracing.ErrInvalidCarrier
}
// Ids:
writer.Set(mockTextMapIdsPrefix+"traceid", strconv.Itoa(spanContext.TraceID))
writer.Set(mockTextMapIdsPrefix+"spanid", strconv.Itoa(spanContext.SpanID))
writer.Set(mockTextMapIdsPrefix+"sampled", fmt.Sprint(spanContext.Sampled))
// Baggage:
for baggageKey, baggageVal := range spanContext.Baggage {
safeVal := baggageVal
if t.HTTPHeaders {
safeVal = url.QueryEscape(baggageVal)
}
writer.Set(mockTextMapBaggagePrefix+baggageKey, safeVal)
}
return nil
}
|
go
|
func (t *TextMapPropagator) Inject(spanContext MockSpanContext, carrier interface{}) error {
writer, ok := carrier.(opentracing.TextMapWriter)
if !ok {
return opentracing.ErrInvalidCarrier
}
// Ids:
writer.Set(mockTextMapIdsPrefix+"traceid", strconv.Itoa(spanContext.TraceID))
writer.Set(mockTextMapIdsPrefix+"spanid", strconv.Itoa(spanContext.SpanID))
writer.Set(mockTextMapIdsPrefix+"sampled", fmt.Sprint(spanContext.Sampled))
// Baggage:
for baggageKey, baggageVal := range spanContext.Baggage {
safeVal := baggageVal
if t.HTTPHeaders {
safeVal = url.QueryEscape(baggageVal)
}
writer.Set(mockTextMapBaggagePrefix+baggageKey, safeVal)
}
return nil
}
|
[
"func",
"(",
"t",
"*",
"TextMapPropagator",
")",
"Inject",
"(",
"spanContext",
"MockSpanContext",
",",
"carrier",
"interface",
"{",
"}",
")",
"error",
"{",
"writer",
",",
"ok",
":=",
"carrier",
".",
"(",
"opentracing",
".",
"TextMapWriter",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"opentracing",
".",
"ErrInvalidCarrier",
"\n",
"}",
"\n",
"writer",
".",
"Set",
"(",
"mockTextMapIdsPrefix",
"+",
"\"traceid\"",
",",
"strconv",
".",
"Itoa",
"(",
"spanContext",
".",
"TraceID",
")",
")",
"\n",
"writer",
".",
"Set",
"(",
"mockTextMapIdsPrefix",
"+",
"\"spanid\"",
",",
"strconv",
".",
"Itoa",
"(",
"spanContext",
".",
"SpanID",
")",
")",
"\n",
"writer",
".",
"Set",
"(",
"mockTextMapIdsPrefix",
"+",
"\"sampled\"",
",",
"fmt",
".",
"Sprint",
"(",
"spanContext",
".",
"Sampled",
")",
")",
"\n",
"for",
"baggageKey",
",",
"baggageVal",
":=",
"range",
"spanContext",
".",
"Baggage",
"{",
"safeVal",
":=",
"baggageVal",
"\n",
"if",
"t",
".",
"HTTPHeaders",
"{",
"safeVal",
"=",
"url",
".",
"QueryEscape",
"(",
"baggageVal",
")",
"\n",
"}",
"\n",
"writer",
".",
"Set",
"(",
"mockTextMapBaggagePrefix",
"+",
"baggageKey",
",",
"safeVal",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// Inject implements the Injector interface
|
[
"Inject",
"implements",
"the",
"Injector",
"interface"
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/propagation.go#L47-L65
|
test
|
opentracing/opentracing-go
|
mocktracer/propagation.go
|
Extract
|
func (t *TextMapPropagator) Extract(carrier interface{}) (MockSpanContext, error) {
reader, ok := carrier.(opentracing.TextMapReader)
if !ok {
return emptyContext, opentracing.ErrInvalidCarrier
}
rval := MockSpanContext{0, 0, true, nil}
err := reader.ForeachKey(func(key, val string) error {
lowerKey := strings.ToLower(key)
switch {
case lowerKey == mockTextMapIdsPrefix+"traceid":
// Ids:
i, err := strconv.Atoi(val)
if err != nil {
return err
}
rval.TraceID = i
case lowerKey == mockTextMapIdsPrefix+"spanid":
// Ids:
i, err := strconv.Atoi(val)
if err != nil {
return err
}
rval.SpanID = i
case lowerKey == mockTextMapIdsPrefix+"sampled":
b, err := strconv.ParseBool(val)
if err != nil {
return err
}
rval.Sampled = b
case strings.HasPrefix(lowerKey, mockTextMapBaggagePrefix):
// Baggage:
if rval.Baggage == nil {
rval.Baggage = make(map[string]string)
}
safeVal := val
if t.HTTPHeaders {
// unescape errors are ignored, nothing can be done
if rawVal, err := url.QueryUnescape(val); err == nil {
safeVal = rawVal
}
}
rval.Baggage[lowerKey[len(mockTextMapBaggagePrefix):]] = safeVal
}
return nil
})
if rval.TraceID == 0 || rval.SpanID == 0 {
return emptyContext, opentracing.ErrSpanContextNotFound
}
if err != nil {
return emptyContext, err
}
return rval, nil
}
|
go
|
func (t *TextMapPropagator) Extract(carrier interface{}) (MockSpanContext, error) {
reader, ok := carrier.(opentracing.TextMapReader)
if !ok {
return emptyContext, opentracing.ErrInvalidCarrier
}
rval := MockSpanContext{0, 0, true, nil}
err := reader.ForeachKey(func(key, val string) error {
lowerKey := strings.ToLower(key)
switch {
case lowerKey == mockTextMapIdsPrefix+"traceid":
// Ids:
i, err := strconv.Atoi(val)
if err != nil {
return err
}
rval.TraceID = i
case lowerKey == mockTextMapIdsPrefix+"spanid":
// Ids:
i, err := strconv.Atoi(val)
if err != nil {
return err
}
rval.SpanID = i
case lowerKey == mockTextMapIdsPrefix+"sampled":
b, err := strconv.ParseBool(val)
if err != nil {
return err
}
rval.Sampled = b
case strings.HasPrefix(lowerKey, mockTextMapBaggagePrefix):
// Baggage:
if rval.Baggage == nil {
rval.Baggage = make(map[string]string)
}
safeVal := val
if t.HTTPHeaders {
// unescape errors are ignored, nothing can be done
if rawVal, err := url.QueryUnescape(val); err == nil {
safeVal = rawVal
}
}
rval.Baggage[lowerKey[len(mockTextMapBaggagePrefix):]] = safeVal
}
return nil
})
if rval.TraceID == 0 || rval.SpanID == 0 {
return emptyContext, opentracing.ErrSpanContextNotFound
}
if err != nil {
return emptyContext, err
}
return rval, nil
}
|
[
"func",
"(",
"t",
"*",
"TextMapPropagator",
")",
"Extract",
"(",
"carrier",
"interface",
"{",
"}",
")",
"(",
"MockSpanContext",
",",
"error",
")",
"{",
"reader",
",",
"ok",
":=",
"carrier",
".",
"(",
"opentracing",
".",
"TextMapReader",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"emptyContext",
",",
"opentracing",
".",
"ErrInvalidCarrier",
"\n",
"}",
"\n",
"rval",
":=",
"MockSpanContext",
"{",
"0",
",",
"0",
",",
"true",
",",
"nil",
"}",
"\n",
"err",
":=",
"reader",
".",
"ForeachKey",
"(",
"func",
"(",
"key",
",",
"val",
"string",
")",
"error",
"{",
"lowerKey",
":=",
"strings",
".",
"ToLower",
"(",
"key",
")",
"\n",
"switch",
"{",
"case",
"lowerKey",
"==",
"mockTextMapIdsPrefix",
"+",
"\"traceid\"",
":",
"i",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"val",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"rval",
".",
"TraceID",
"=",
"i",
"\n",
"case",
"lowerKey",
"==",
"mockTextMapIdsPrefix",
"+",
"\"spanid\"",
":",
"i",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"val",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"rval",
".",
"SpanID",
"=",
"i",
"\n",
"case",
"lowerKey",
"==",
"mockTextMapIdsPrefix",
"+",
"\"sampled\"",
":",
"b",
",",
"err",
":=",
"strconv",
".",
"ParseBool",
"(",
"val",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"rval",
".",
"Sampled",
"=",
"b",
"\n",
"case",
"strings",
".",
"HasPrefix",
"(",
"lowerKey",
",",
"mockTextMapBaggagePrefix",
")",
":",
"if",
"rval",
".",
"Baggage",
"==",
"nil",
"{",
"rval",
".",
"Baggage",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"}",
"\n",
"safeVal",
":=",
"val",
"\n",
"if",
"t",
".",
"HTTPHeaders",
"{",
"if",
"rawVal",
",",
"err",
":=",
"url",
".",
"QueryUnescape",
"(",
"val",
")",
";",
"err",
"==",
"nil",
"{",
"safeVal",
"=",
"rawVal",
"\n",
"}",
"\n",
"}",
"\n",
"rval",
".",
"Baggage",
"[",
"lowerKey",
"[",
"len",
"(",
"mockTextMapBaggagePrefix",
")",
":",
"]",
"]",
"=",
"safeVal",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"if",
"rval",
".",
"TraceID",
"==",
"0",
"||",
"rval",
".",
"SpanID",
"==",
"0",
"{",
"return",
"emptyContext",
",",
"opentracing",
".",
"ErrSpanContextNotFound",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"emptyContext",
",",
"err",
"\n",
"}",
"\n",
"return",
"rval",
",",
"nil",
"\n",
"}"
] |
// Extract implements the Extractor interface
|
[
"Extract",
"implements",
"the",
"Extractor",
"interface"
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/propagation.go#L68-L120
|
test
|
opentracing/opentracing-go
|
span.go
|
ToLogRecord
|
func (ld *LogData) ToLogRecord() LogRecord {
var literalTimestamp time.Time
if ld.Timestamp.IsZero() {
literalTimestamp = time.Now()
} else {
literalTimestamp = ld.Timestamp
}
rval := LogRecord{
Timestamp: literalTimestamp,
}
if ld.Payload == nil {
rval.Fields = []log.Field{
log.String("event", ld.Event),
}
} else {
rval.Fields = []log.Field{
log.String("event", ld.Event),
log.Object("payload", ld.Payload),
}
}
return rval
}
|
go
|
func (ld *LogData) ToLogRecord() LogRecord {
var literalTimestamp time.Time
if ld.Timestamp.IsZero() {
literalTimestamp = time.Now()
} else {
literalTimestamp = ld.Timestamp
}
rval := LogRecord{
Timestamp: literalTimestamp,
}
if ld.Payload == nil {
rval.Fields = []log.Field{
log.String("event", ld.Event),
}
} else {
rval.Fields = []log.Field{
log.String("event", ld.Event),
log.Object("payload", ld.Payload),
}
}
return rval
}
|
[
"func",
"(",
"ld",
"*",
"LogData",
")",
"ToLogRecord",
"(",
")",
"LogRecord",
"{",
"var",
"literalTimestamp",
"time",
".",
"Time",
"\n",
"if",
"ld",
".",
"Timestamp",
".",
"IsZero",
"(",
")",
"{",
"literalTimestamp",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"}",
"else",
"{",
"literalTimestamp",
"=",
"ld",
".",
"Timestamp",
"\n",
"}",
"\n",
"rval",
":=",
"LogRecord",
"{",
"Timestamp",
":",
"literalTimestamp",
",",
"}",
"\n",
"if",
"ld",
".",
"Payload",
"==",
"nil",
"{",
"rval",
".",
"Fields",
"=",
"[",
"]",
"log",
".",
"Field",
"{",
"log",
".",
"String",
"(",
"\"event\"",
",",
"ld",
".",
"Event",
")",
",",
"}",
"\n",
"}",
"else",
"{",
"rval",
".",
"Fields",
"=",
"[",
"]",
"log",
".",
"Field",
"{",
"log",
".",
"String",
"(",
"\"event\"",
",",
"ld",
".",
"Event",
")",
",",
"log",
".",
"Object",
"(",
"\"payload\"",
",",
"ld",
".",
"Payload",
")",
",",
"}",
"\n",
"}",
"\n",
"return",
"rval",
"\n",
"}"
] |
// ToLogRecord converts a deprecated LogData to a non-deprecated LogRecord
|
[
"ToLogRecord",
"converts",
"a",
"deprecated",
"LogData",
"to",
"a",
"non",
"-",
"deprecated",
"LogRecord"
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/span.go#L168-L189
|
test
|
opentracing/opentracing-go
|
mocktracer/mocktracer.go
|
New
|
func New() *MockTracer {
t := &MockTracer{
finishedSpans: []*MockSpan{},
injectors: make(map[interface{}]Injector),
extractors: make(map[interface{}]Extractor),
}
// register default injectors/extractors
textPropagator := new(TextMapPropagator)
t.RegisterInjector(opentracing.TextMap, textPropagator)
t.RegisterExtractor(opentracing.TextMap, textPropagator)
httpPropagator := &TextMapPropagator{HTTPHeaders: true}
t.RegisterInjector(opentracing.HTTPHeaders, httpPropagator)
t.RegisterExtractor(opentracing.HTTPHeaders, httpPropagator)
return t
}
|
go
|
func New() *MockTracer {
t := &MockTracer{
finishedSpans: []*MockSpan{},
injectors: make(map[interface{}]Injector),
extractors: make(map[interface{}]Extractor),
}
// register default injectors/extractors
textPropagator := new(TextMapPropagator)
t.RegisterInjector(opentracing.TextMap, textPropagator)
t.RegisterExtractor(opentracing.TextMap, textPropagator)
httpPropagator := &TextMapPropagator{HTTPHeaders: true}
t.RegisterInjector(opentracing.HTTPHeaders, httpPropagator)
t.RegisterExtractor(opentracing.HTTPHeaders, httpPropagator)
return t
}
|
[
"func",
"New",
"(",
")",
"*",
"MockTracer",
"{",
"t",
":=",
"&",
"MockTracer",
"{",
"finishedSpans",
":",
"[",
"]",
"*",
"MockSpan",
"{",
"}",
",",
"injectors",
":",
"make",
"(",
"map",
"[",
"interface",
"{",
"}",
"]",
"Injector",
")",
",",
"extractors",
":",
"make",
"(",
"map",
"[",
"interface",
"{",
"}",
"]",
"Extractor",
")",
",",
"}",
"\n",
"textPropagator",
":=",
"new",
"(",
"TextMapPropagator",
")",
"\n",
"t",
".",
"RegisterInjector",
"(",
"opentracing",
".",
"TextMap",
",",
"textPropagator",
")",
"\n",
"t",
".",
"RegisterExtractor",
"(",
"opentracing",
".",
"TextMap",
",",
"textPropagator",
")",
"\n",
"httpPropagator",
":=",
"&",
"TextMapPropagator",
"{",
"HTTPHeaders",
":",
"true",
"}",
"\n",
"t",
".",
"RegisterInjector",
"(",
"opentracing",
".",
"HTTPHeaders",
",",
"httpPropagator",
")",
"\n",
"t",
".",
"RegisterExtractor",
"(",
"opentracing",
".",
"HTTPHeaders",
",",
"httpPropagator",
")",
"\n",
"return",
"t",
"\n",
"}"
] |
// New returns a MockTracer opentracing.Tracer implementation that's intended
// to facilitate tests of OpenTracing instrumentation.
|
[
"New",
"returns",
"a",
"MockTracer",
"opentracing",
".",
"Tracer",
"implementation",
"that",
"s",
"intended",
"to",
"facilitate",
"tests",
"of",
"OpenTracing",
"instrumentation",
"."
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mocktracer.go#L11-L28
|
test
|
opentracing/opentracing-go
|
mocktracer/mocktracer.go
|
StartSpan
|
func (t *MockTracer) StartSpan(operationName string, opts ...opentracing.StartSpanOption) opentracing.Span {
sso := opentracing.StartSpanOptions{}
for _, o := range opts {
o.Apply(&sso)
}
return newMockSpan(t, operationName, sso)
}
|
go
|
func (t *MockTracer) StartSpan(operationName string, opts ...opentracing.StartSpanOption) opentracing.Span {
sso := opentracing.StartSpanOptions{}
for _, o := range opts {
o.Apply(&sso)
}
return newMockSpan(t, operationName, sso)
}
|
[
"func",
"(",
"t",
"*",
"MockTracer",
")",
"StartSpan",
"(",
"operationName",
"string",
",",
"opts",
"...",
"opentracing",
".",
"StartSpanOption",
")",
"opentracing",
".",
"Span",
"{",
"sso",
":=",
"opentracing",
".",
"StartSpanOptions",
"{",
"}",
"\n",
"for",
"_",
",",
"o",
":=",
"range",
"opts",
"{",
"o",
".",
"Apply",
"(",
"&",
"sso",
")",
"\n",
"}",
"\n",
"return",
"newMockSpan",
"(",
"t",
",",
"operationName",
",",
"sso",
")",
"\n",
"}"
] |
// StartSpan belongs to the Tracer interface.
|
[
"StartSpan",
"belongs",
"to",
"the",
"Tracer",
"interface",
"."
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mocktracer.go#L61-L67
|
test
|
opentracing/opentracing-go
|
mocktracer/mocktracer.go
|
RegisterInjector
|
func (t *MockTracer) RegisterInjector(format interface{}, injector Injector) {
t.injectors[format] = injector
}
|
go
|
func (t *MockTracer) RegisterInjector(format interface{}, injector Injector) {
t.injectors[format] = injector
}
|
[
"func",
"(",
"t",
"*",
"MockTracer",
")",
"RegisterInjector",
"(",
"format",
"interface",
"{",
"}",
",",
"injector",
"Injector",
")",
"{",
"t",
".",
"injectors",
"[",
"format",
"]",
"=",
"injector",
"\n",
"}"
] |
// RegisterInjector registers injector for given format
|
[
"RegisterInjector",
"registers",
"injector",
"for",
"given",
"format"
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mocktracer.go#L70-L72
|
test
|
opentracing/opentracing-go
|
mocktracer/mocktracer.go
|
RegisterExtractor
|
func (t *MockTracer) RegisterExtractor(format interface{}, extractor Extractor) {
t.extractors[format] = extractor
}
|
go
|
func (t *MockTracer) RegisterExtractor(format interface{}, extractor Extractor) {
t.extractors[format] = extractor
}
|
[
"func",
"(",
"t",
"*",
"MockTracer",
")",
"RegisterExtractor",
"(",
"format",
"interface",
"{",
"}",
",",
"extractor",
"Extractor",
")",
"{",
"t",
".",
"extractors",
"[",
"format",
"]",
"=",
"extractor",
"\n",
"}"
] |
// RegisterExtractor registers extractor for given format
|
[
"RegisterExtractor",
"registers",
"extractor",
"for",
"given",
"format"
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mocktracer.go#L75-L77
|
test
|
opentracing/opentracing-go
|
mocktracer/mocktracer.go
|
Inject
|
func (t *MockTracer) Inject(sm opentracing.SpanContext, format interface{}, carrier interface{}) error {
spanContext, ok := sm.(MockSpanContext)
if !ok {
return opentracing.ErrInvalidCarrier
}
injector, ok := t.injectors[format]
if !ok {
return opentracing.ErrUnsupportedFormat
}
return injector.Inject(spanContext, carrier)
}
|
go
|
func (t *MockTracer) Inject(sm opentracing.SpanContext, format interface{}, carrier interface{}) error {
spanContext, ok := sm.(MockSpanContext)
if !ok {
return opentracing.ErrInvalidCarrier
}
injector, ok := t.injectors[format]
if !ok {
return opentracing.ErrUnsupportedFormat
}
return injector.Inject(spanContext, carrier)
}
|
[
"func",
"(",
"t",
"*",
"MockTracer",
")",
"Inject",
"(",
"sm",
"opentracing",
".",
"SpanContext",
",",
"format",
"interface",
"{",
"}",
",",
"carrier",
"interface",
"{",
"}",
")",
"error",
"{",
"spanContext",
",",
"ok",
":=",
"sm",
".",
"(",
"MockSpanContext",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"opentracing",
".",
"ErrInvalidCarrier",
"\n",
"}",
"\n",
"injector",
",",
"ok",
":=",
"t",
".",
"injectors",
"[",
"format",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"opentracing",
".",
"ErrUnsupportedFormat",
"\n",
"}",
"\n",
"return",
"injector",
".",
"Inject",
"(",
"spanContext",
",",
"carrier",
")",
"\n",
"}"
] |
// Inject belongs to the Tracer interface.
|
[
"Inject",
"belongs",
"to",
"the",
"Tracer",
"interface",
"."
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mocktracer.go#L80-L90
|
test
|
opentracing/opentracing-go
|
mocktracer/mocktracer.go
|
Extract
|
func (t *MockTracer) Extract(format interface{}, carrier interface{}) (opentracing.SpanContext, error) {
extractor, ok := t.extractors[format]
if !ok {
return nil, opentracing.ErrUnsupportedFormat
}
return extractor.Extract(carrier)
}
|
go
|
func (t *MockTracer) Extract(format interface{}, carrier interface{}) (opentracing.SpanContext, error) {
extractor, ok := t.extractors[format]
if !ok {
return nil, opentracing.ErrUnsupportedFormat
}
return extractor.Extract(carrier)
}
|
[
"func",
"(",
"t",
"*",
"MockTracer",
")",
"Extract",
"(",
"format",
"interface",
"{",
"}",
",",
"carrier",
"interface",
"{",
"}",
")",
"(",
"opentracing",
".",
"SpanContext",
",",
"error",
")",
"{",
"extractor",
",",
"ok",
":=",
"t",
".",
"extractors",
"[",
"format",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"opentracing",
".",
"ErrUnsupportedFormat",
"\n",
"}",
"\n",
"return",
"extractor",
".",
"Extract",
"(",
"carrier",
")",
"\n",
"}"
] |
// Extract belongs to the Tracer interface.
|
[
"Extract",
"belongs",
"to",
"the",
"Tracer",
"interface",
"."
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mocktracer.go#L93-L99
|
test
|
opentracing/opentracing-go
|
gocontext.go
|
ContextWithSpan
|
func ContextWithSpan(ctx context.Context, span Span) context.Context {
return context.WithValue(ctx, activeSpanKey, span)
}
|
go
|
func ContextWithSpan(ctx context.Context, span Span) context.Context {
return context.WithValue(ctx, activeSpanKey, span)
}
|
[
"func",
"ContextWithSpan",
"(",
"ctx",
"context",
".",
"Context",
",",
"span",
"Span",
")",
"context",
".",
"Context",
"{",
"return",
"context",
".",
"WithValue",
"(",
"ctx",
",",
"activeSpanKey",
",",
"span",
")",
"\n",
"}"
] |
// ContextWithSpan returns a new `context.Context` that holds a reference to
// `span`'s SpanContext.
|
[
"ContextWithSpan",
"returns",
"a",
"new",
"context",
".",
"Context",
"that",
"holds",
"a",
"reference",
"to",
"span",
"s",
"SpanContext",
"."
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/gocontext.go#L11-L13
|
test
|
opentracing/opentracing-go
|
ext/tags.go
|
Set
|
func (tag uint32TagName) Set(span opentracing.Span, value uint32) {
span.SetTag(string(tag), value)
}
|
go
|
func (tag uint32TagName) Set(span opentracing.Span, value uint32) {
span.SetTag(string(tag), value)
}
|
[
"func",
"(",
"tag",
"uint32TagName",
")",
"Set",
"(",
"span",
"opentracing",
".",
"Span",
",",
"value",
"uint32",
")",
"{",
"span",
".",
"SetTag",
"(",
"string",
"(",
"tag",
")",
",",
"value",
")",
"\n",
"}"
] |
// Set adds a uint32 tag to the `span`
|
[
"Set",
"adds",
"a",
"uint32",
"tag",
"to",
"the",
"span"
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/ext/tags.go#L178-L180
|
test
|
opentracing/opentracing-go
|
ext/tags.go
|
Set
|
func (tag uint16TagName) Set(span opentracing.Span, value uint16) {
span.SetTag(string(tag), value)
}
|
go
|
func (tag uint16TagName) Set(span opentracing.Span, value uint16) {
span.SetTag(string(tag), value)
}
|
[
"func",
"(",
"tag",
"uint16TagName",
")",
"Set",
"(",
"span",
"opentracing",
".",
"Span",
",",
"value",
"uint16",
")",
"{",
"span",
".",
"SetTag",
"(",
"string",
"(",
"tag",
")",
",",
"value",
")",
"\n",
"}"
] |
// Set adds a uint16 tag to the `span`
|
[
"Set",
"adds",
"a",
"uint16",
"tag",
"to",
"the",
"span"
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/ext/tags.go#L187-L189
|
test
|
opentracing/opentracing-go
|
ext/tags.go
|
Set
|
func (tag boolTagName) Set(span opentracing.Span, value bool) {
span.SetTag(string(tag), value)
}
|
go
|
func (tag boolTagName) Set(span opentracing.Span, value bool) {
span.SetTag(string(tag), value)
}
|
[
"func",
"(",
"tag",
"boolTagName",
")",
"Set",
"(",
"span",
"opentracing",
".",
"Span",
",",
"value",
"bool",
")",
"{",
"span",
".",
"SetTag",
"(",
"string",
"(",
"tag",
")",
",",
"value",
")",
"\n",
"}"
] |
// Add adds a bool tag to the `span`
|
[
"Add",
"adds",
"a",
"bool",
"tag",
"to",
"the",
"span"
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/ext/tags.go#L196-L198
|
test
|
opentracing/opentracing-go
|
ext/tags.go
|
SetString
|
func (tag ipv4Tag) SetString(span opentracing.Span, value string) {
span.SetTag(string(tag), value)
}
|
go
|
func (tag ipv4Tag) SetString(span opentracing.Span, value string) {
span.SetTag(string(tag), value)
}
|
[
"func",
"(",
"tag",
"ipv4Tag",
")",
"SetString",
"(",
"span",
"opentracing",
".",
"Span",
",",
"value",
"string",
")",
"{",
"span",
".",
"SetTag",
"(",
"string",
"(",
"tag",
")",
",",
"value",
")",
"\n",
"}"
] |
// SetString records IP v4 host address of the peer as a .-separated tuple to the `span`. E.g., "127.0.0.1"
|
[
"SetString",
"records",
"IP",
"v4",
"host",
"address",
"of",
"the",
"peer",
"as",
"a",
".",
"-",
"separated",
"tuple",
"to",
"the",
"span",
".",
"E",
".",
"g",
".",
"127",
".",
"0",
".",
"0",
".",
"1"
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/ext/tags.go#L208-L210
|
test
|
opentracing/opentracing-go
|
mocktracer/mocklogrecord.go
|
EmitString
|
func (m *MockKeyValue) EmitString(key, value string) {
m.Key = key
m.ValueKind = reflect.TypeOf(value).Kind()
m.ValueString = fmt.Sprint(value)
}
|
go
|
func (m *MockKeyValue) EmitString(key, value string) {
m.Key = key
m.ValueKind = reflect.TypeOf(value).Kind()
m.ValueString = fmt.Sprint(value)
}
|
[
"func",
"(",
"m",
"*",
"MockKeyValue",
")",
"EmitString",
"(",
"key",
",",
"value",
"string",
")",
"{",
"m",
".",
"Key",
"=",
"key",
"\n",
"m",
".",
"ValueKind",
"=",
"reflect",
".",
"TypeOf",
"(",
"value",
")",
".",
"Kind",
"(",
")",
"\n",
"m",
".",
"ValueString",
"=",
"fmt",
".",
"Sprint",
"(",
"value",
")",
"\n",
"}"
] |
// EmitString belongs to the log.Encoder interface
|
[
"EmitString",
"belongs",
"to",
"the",
"log",
".",
"Encoder",
"interface"
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mocklogrecord.go#L29-L33
|
test
|
opentracing/opentracing-go
|
mocktracer/mocklogrecord.go
|
EmitLazyLogger
|
func (m *MockKeyValue) EmitLazyLogger(value log.LazyLogger) {
var meta MockKeyValue
value(&meta)
m.Key = meta.Key
m.ValueKind = meta.ValueKind
m.ValueString = meta.ValueString
}
|
go
|
func (m *MockKeyValue) EmitLazyLogger(value log.LazyLogger) {
var meta MockKeyValue
value(&meta)
m.Key = meta.Key
m.ValueKind = meta.ValueKind
m.ValueString = meta.ValueString
}
|
[
"func",
"(",
"m",
"*",
"MockKeyValue",
")",
"EmitLazyLogger",
"(",
"value",
"log",
".",
"LazyLogger",
")",
"{",
"var",
"meta",
"MockKeyValue",
"\n",
"value",
"(",
"&",
"meta",
")",
"\n",
"m",
".",
"Key",
"=",
"meta",
".",
"Key",
"\n",
"m",
".",
"ValueKind",
"=",
"meta",
".",
"ValueKind",
"\n",
"m",
".",
"ValueString",
"=",
"meta",
".",
"ValueString",
"\n",
"}"
] |
// EmitLazyLogger belongs to the log.Encoder interface
|
[
"EmitLazyLogger",
"belongs",
"to",
"the",
"log",
".",
"Encoder",
"interface"
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mocklogrecord.go#L99-L105
|
test
|
opentracing/opentracing-go
|
harness/api_checkers.go
|
RunAPIChecks
|
func RunAPIChecks(
t *testing.T,
newTracer func() (tracer opentracing.Tracer, closer func()),
opts ...APICheckOption,
) {
s := &APICheckSuite{newTracer: newTracer}
for _, opt := range opts {
opt(s)
}
suite.Run(t, s)
}
|
go
|
func RunAPIChecks(
t *testing.T,
newTracer func() (tracer opentracing.Tracer, closer func()),
opts ...APICheckOption,
) {
s := &APICheckSuite{newTracer: newTracer}
for _, opt := range opts {
opt(s)
}
suite.Run(t, s)
}
|
[
"func",
"RunAPIChecks",
"(",
"t",
"*",
"testing",
".",
"T",
",",
"newTracer",
"func",
"(",
")",
"(",
"tracer",
"opentracing",
".",
"Tracer",
",",
"closer",
"func",
"(",
")",
")",
",",
"opts",
"...",
"APICheckOption",
",",
")",
"{",
"s",
":=",
"&",
"APICheckSuite",
"{",
"newTracer",
":",
"newTracer",
"}",
"\n",
"for",
"_",
",",
"opt",
":=",
"range",
"opts",
"{",
"opt",
"(",
"s",
")",
"\n",
"}",
"\n",
"suite",
".",
"Run",
"(",
"t",
",",
"s",
")",
"\n",
"}"
] |
// RunAPIChecks runs a test suite to check a Tracer against the OpenTracing API.
// It is provided a function that will be executed to create and destroy a tracer for each test
// in the suite, and the given APICheckOption functional options `opts`.
|
[
"RunAPIChecks",
"runs",
"a",
"test",
"suite",
"to",
"check",
"a",
"Tracer",
"against",
"the",
"OpenTracing",
"API",
".",
"It",
"is",
"provided",
"a",
"function",
"that",
"will",
"be",
"executed",
"to",
"create",
"and",
"destroy",
"a",
"tracer",
"for",
"each",
"test",
"in",
"the",
"suite",
"and",
"the",
"given",
"APICheckOption",
"functional",
"options",
"opts",
"."
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/harness/api_checkers.go#L63-L73
|
test
|
opentracing/opentracing-go
|
harness/api_checkers.go
|
CheckBaggageValues
|
func CheckBaggageValues(val bool) APICheckOption {
return func(s *APICheckSuite) {
s.opts.CheckBaggageValues = val
}
}
|
go
|
func CheckBaggageValues(val bool) APICheckOption {
return func(s *APICheckSuite) {
s.opts.CheckBaggageValues = val
}
}
|
[
"func",
"CheckBaggageValues",
"(",
"val",
"bool",
")",
"APICheckOption",
"{",
"return",
"func",
"(",
"s",
"*",
"APICheckSuite",
")",
"{",
"s",
".",
"opts",
".",
"CheckBaggageValues",
"=",
"val",
"\n",
"}",
"\n",
"}"
] |
// CheckBaggageValues returns an option that sets whether to check for propagation of baggage values.
|
[
"CheckBaggageValues",
"returns",
"an",
"option",
"that",
"sets",
"whether",
"to",
"check",
"for",
"propagation",
"of",
"baggage",
"values",
"."
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/harness/api_checkers.go#L79-L83
|
test
|
opentracing/opentracing-go
|
harness/api_checkers.go
|
CheckExtract
|
func CheckExtract(val bool) APICheckOption {
return func(s *APICheckSuite) {
s.opts.CheckExtract = val
}
}
|
go
|
func CheckExtract(val bool) APICheckOption {
return func(s *APICheckSuite) {
s.opts.CheckExtract = val
}
}
|
[
"func",
"CheckExtract",
"(",
"val",
"bool",
")",
"APICheckOption",
"{",
"return",
"func",
"(",
"s",
"*",
"APICheckSuite",
")",
"{",
"s",
".",
"opts",
".",
"CheckExtract",
"=",
"val",
"\n",
"}",
"\n",
"}"
] |
// CheckExtract returns an option that sets whether to check if extracting contexts from carriers works.
|
[
"CheckExtract",
"returns",
"an",
"option",
"that",
"sets",
"whether",
"to",
"check",
"if",
"extracting",
"contexts",
"from",
"carriers",
"works",
"."
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/harness/api_checkers.go#L86-L90
|
test
|
opentracing/opentracing-go
|
harness/api_checkers.go
|
CheckInject
|
func CheckInject(val bool) APICheckOption {
return func(s *APICheckSuite) {
s.opts.CheckInject = val
}
}
|
go
|
func CheckInject(val bool) APICheckOption {
return func(s *APICheckSuite) {
s.opts.CheckInject = val
}
}
|
[
"func",
"CheckInject",
"(",
"val",
"bool",
")",
"APICheckOption",
"{",
"return",
"func",
"(",
"s",
"*",
"APICheckSuite",
")",
"{",
"s",
".",
"opts",
".",
"CheckInject",
"=",
"val",
"\n",
"}",
"\n",
"}"
] |
// CheckInject returns an option that sets whether to check if injecting contexts works.
|
[
"CheckInject",
"returns",
"an",
"option",
"that",
"sets",
"whether",
"to",
"check",
"if",
"injecting",
"contexts",
"works",
"."
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/harness/api_checkers.go#L93-L97
|
test
|
opentracing/opentracing-go
|
harness/api_checkers.go
|
CheckEverything
|
func CheckEverything() APICheckOption {
return func(s *APICheckSuite) {
s.opts.CheckBaggageValues = true
s.opts.CheckExtract = true
s.opts.CheckInject = true
}
}
|
go
|
func CheckEverything() APICheckOption {
return func(s *APICheckSuite) {
s.opts.CheckBaggageValues = true
s.opts.CheckExtract = true
s.opts.CheckInject = true
}
}
|
[
"func",
"CheckEverything",
"(",
")",
"APICheckOption",
"{",
"return",
"func",
"(",
"s",
"*",
"APICheckSuite",
")",
"{",
"s",
".",
"opts",
".",
"CheckBaggageValues",
"=",
"true",
"\n",
"s",
".",
"opts",
".",
"CheckExtract",
"=",
"true",
"\n",
"s",
".",
"opts",
".",
"CheckInject",
"=",
"true",
"\n",
"}",
"\n",
"}"
] |
// CheckEverything returns an option that enables all API checks.
|
[
"CheckEverything",
"returns",
"an",
"option",
"that",
"enables",
"all",
"API",
"checks",
"."
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/harness/api_checkers.go#L100-L106
|
test
|
opentracing/opentracing-go
|
harness/api_checkers.go
|
UseProbe
|
func UseProbe(probe APICheckProbe) APICheckOption {
return func(s *APICheckSuite) {
s.opts.Probe = probe
}
}
|
go
|
func UseProbe(probe APICheckProbe) APICheckOption {
return func(s *APICheckSuite) {
s.opts.Probe = probe
}
}
|
[
"func",
"UseProbe",
"(",
"probe",
"APICheckProbe",
")",
"APICheckOption",
"{",
"return",
"func",
"(",
"s",
"*",
"APICheckSuite",
")",
"{",
"s",
".",
"opts",
".",
"Probe",
"=",
"probe",
"\n",
"}",
"\n",
"}"
] |
// UseProbe returns an option that specifies an APICheckProbe implementation to use.
|
[
"UseProbe",
"returns",
"an",
"option",
"that",
"specifies",
"an",
"APICheckProbe",
"implementation",
"to",
"use",
"."
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/harness/api_checkers.go#L109-L113
|
test
|
opentracing/opentracing-go
|
mocktracer/mockspan.go
|
WithBaggageItem
|
func (c MockSpanContext) WithBaggageItem(key, value string) MockSpanContext {
var newBaggage map[string]string
if c.Baggage == nil {
newBaggage = map[string]string{key: value}
} else {
newBaggage = make(map[string]string, len(c.Baggage)+1)
for k, v := range c.Baggage {
newBaggage[k] = v
}
newBaggage[key] = value
}
// Use positional parameters so the compiler will help catch new fields.
return MockSpanContext{c.TraceID, c.SpanID, c.Sampled, newBaggage}
}
|
go
|
func (c MockSpanContext) WithBaggageItem(key, value string) MockSpanContext {
var newBaggage map[string]string
if c.Baggage == nil {
newBaggage = map[string]string{key: value}
} else {
newBaggage = make(map[string]string, len(c.Baggage)+1)
for k, v := range c.Baggage {
newBaggage[k] = v
}
newBaggage[key] = value
}
// Use positional parameters so the compiler will help catch new fields.
return MockSpanContext{c.TraceID, c.SpanID, c.Sampled, newBaggage}
}
|
[
"func",
"(",
"c",
"MockSpanContext",
")",
"WithBaggageItem",
"(",
"key",
",",
"value",
"string",
")",
"MockSpanContext",
"{",
"var",
"newBaggage",
"map",
"[",
"string",
"]",
"string",
"\n",
"if",
"c",
".",
"Baggage",
"==",
"nil",
"{",
"newBaggage",
"=",
"map",
"[",
"string",
"]",
"string",
"{",
"key",
":",
"value",
"}",
"\n",
"}",
"else",
"{",
"newBaggage",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"len",
"(",
"c",
".",
"Baggage",
")",
"+",
"1",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"c",
".",
"Baggage",
"{",
"newBaggage",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"newBaggage",
"[",
"key",
"]",
"=",
"value",
"\n",
"}",
"\n",
"return",
"MockSpanContext",
"{",
"c",
".",
"TraceID",
",",
"c",
".",
"SpanID",
",",
"c",
".",
"Sampled",
",",
"newBaggage",
"}",
"\n",
"}"
] |
// WithBaggageItem creates a new context with an extra baggage item.
|
[
"WithBaggageItem",
"creates",
"a",
"new",
"context",
"with",
"an",
"extra",
"baggage",
"item",
"."
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mockspan.go#L44-L57
|
test
|
opentracing/opentracing-go
|
mocktracer/mockspan.go
|
Tags
|
func (s *MockSpan) Tags() map[string]interface{} {
s.RLock()
defer s.RUnlock()
tags := make(map[string]interface{})
for k, v := range s.tags {
tags[k] = v
}
return tags
}
|
go
|
func (s *MockSpan) Tags() map[string]interface{} {
s.RLock()
defer s.RUnlock()
tags := make(map[string]interface{})
for k, v := range s.tags {
tags[k] = v
}
return tags
}
|
[
"func",
"(",
"s",
"*",
"MockSpan",
")",
"Tags",
"(",
")",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"s",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"RUnlock",
"(",
")",
"\n",
"tags",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"s",
".",
"tags",
"{",
"tags",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"return",
"tags",
"\n",
"}"
] |
// Tags returns a copy of tags accumulated by the span so far
|
[
"Tags",
"returns",
"a",
"copy",
"of",
"tags",
"accumulated",
"by",
"the",
"span",
"so",
"far"
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mockspan.go#L110-L118
|
test
|
opentracing/opentracing-go
|
mocktracer/mockspan.go
|
Tag
|
func (s *MockSpan) Tag(k string) interface{} {
s.RLock()
defer s.RUnlock()
return s.tags[k]
}
|
go
|
func (s *MockSpan) Tag(k string) interface{} {
s.RLock()
defer s.RUnlock()
return s.tags[k]
}
|
[
"func",
"(",
"s",
"*",
"MockSpan",
")",
"Tag",
"(",
"k",
"string",
")",
"interface",
"{",
"}",
"{",
"s",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"s",
".",
"tags",
"[",
"k",
"]",
"\n",
"}"
] |
// Tag returns a single tag
|
[
"Tag",
"returns",
"a",
"single",
"tag"
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mockspan.go#L121-L125
|
test
|
opentracing/opentracing-go
|
mocktracer/mockspan.go
|
Logs
|
func (s *MockSpan) Logs() []MockLogRecord {
s.RLock()
defer s.RUnlock()
logs := make([]MockLogRecord, len(s.logs))
copy(logs, s.logs)
return logs
}
|
go
|
func (s *MockSpan) Logs() []MockLogRecord {
s.RLock()
defer s.RUnlock()
logs := make([]MockLogRecord, len(s.logs))
copy(logs, s.logs)
return logs
}
|
[
"func",
"(",
"s",
"*",
"MockSpan",
")",
"Logs",
"(",
")",
"[",
"]",
"MockLogRecord",
"{",
"s",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"RUnlock",
"(",
")",
"\n",
"logs",
":=",
"make",
"(",
"[",
"]",
"MockLogRecord",
",",
"len",
"(",
"s",
".",
"logs",
")",
")",
"\n",
"copy",
"(",
"logs",
",",
"s",
".",
"logs",
")",
"\n",
"return",
"logs",
"\n",
"}"
] |
// Logs returns a copy of logs accumulated in the span so far
|
[
"Logs",
"returns",
"a",
"copy",
"of",
"logs",
"accumulated",
"in",
"the",
"span",
"so",
"far"
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mockspan.go#L128-L134
|
test
|
opentracing/opentracing-go
|
mocktracer/mockspan.go
|
Context
|
func (s *MockSpan) Context() opentracing.SpanContext {
s.Lock()
defer s.Unlock()
return s.SpanContext
}
|
go
|
func (s *MockSpan) Context() opentracing.SpanContext {
s.Lock()
defer s.Unlock()
return s.SpanContext
}
|
[
"func",
"(",
"s",
"*",
"MockSpan",
")",
"Context",
"(",
")",
"opentracing",
".",
"SpanContext",
"{",
"s",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"Unlock",
"(",
")",
"\n",
"return",
"s",
".",
"SpanContext",
"\n",
"}"
] |
// Context belongs to the Span interface
|
[
"Context",
"belongs",
"to",
"the",
"Span",
"interface"
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mockspan.go#L137-L141
|
test
|
opentracing/opentracing-go
|
mocktracer/mockspan.go
|
SetTag
|
func (s *MockSpan) SetTag(key string, value interface{}) opentracing.Span {
s.Lock()
defer s.Unlock()
if key == string(ext.SamplingPriority) {
if v, ok := value.(uint16); ok {
s.SpanContext.Sampled = v > 0
return s
}
if v, ok := value.(int); ok {
s.SpanContext.Sampled = v > 0
return s
}
}
s.tags[key] = value
return s
}
|
go
|
func (s *MockSpan) SetTag(key string, value interface{}) opentracing.Span {
s.Lock()
defer s.Unlock()
if key == string(ext.SamplingPriority) {
if v, ok := value.(uint16); ok {
s.SpanContext.Sampled = v > 0
return s
}
if v, ok := value.(int); ok {
s.SpanContext.Sampled = v > 0
return s
}
}
s.tags[key] = value
return s
}
|
[
"func",
"(",
"s",
"*",
"MockSpan",
")",
"SetTag",
"(",
"key",
"string",
",",
"value",
"interface",
"{",
"}",
")",
"opentracing",
".",
"Span",
"{",
"s",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"Unlock",
"(",
")",
"\n",
"if",
"key",
"==",
"string",
"(",
"ext",
".",
"SamplingPriority",
")",
"{",
"if",
"v",
",",
"ok",
":=",
"value",
".",
"(",
"uint16",
")",
";",
"ok",
"{",
"s",
".",
"SpanContext",
".",
"Sampled",
"=",
"v",
">",
"0",
"\n",
"return",
"s",
"\n",
"}",
"\n",
"if",
"v",
",",
"ok",
":=",
"value",
".",
"(",
"int",
")",
";",
"ok",
"{",
"s",
".",
"SpanContext",
".",
"Sampled",
"=",
"v",
">",
"0",
"\n",
"return",
"s",
"\n",
"}",
"\n",
"}",
"\n",
"s",
".",
"tags",
"[",
"key",
"]",
"=",
"value",
"\n",
"return",
"s",
"\n",
"}"
] |
// SetTag belongs to the Span interface
|
[
"SetTag",
"belongs",
"to",
"the",
"Span",
"interface"
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mockspan.go#L144-L159
|
test
|
opentracing/opentracing-go
|
mocktracer/mockspan.go
|
SetBaggageItem
|
func (s *MockSpan) SetBaggageItem(key, val string) opentracing.Span {
s.Lock()
defer s.Unlock()
s.SpanContext = s.SpanContext.WithBaggageItem(key, val)
return s
}
|
go
|
func (s *MockSpan) SetBaggageItem(key, val string) opentracing.Span {
s.Lock()
defer s.Unlock()
s.SpanContext = s.SpanContext.WithBaggageItem(key, val)
return s
}
|
[
"func",
"(",
"s",
"*",
"MockSpan",
")",
"SetBaggageItem",
"(",
"key",
",",
"val",
"string",
")",
"opentracing",
".",
"Span",
"{",
"s",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"Unlock",
"(",
")",
"\n",
"s",
".",
"SpanContext",
"=",
"s",
".",
"SpanContext",
".",
"WithBaggageItem",
"(",
"key",
",",
"val",
")",
"\n",
"return",
"s",
"\n",
"}"
] |
// SetBaggageItem belongs to the Span interface
|
[
"SetBaggageItem",
"belongs",
"to",
"the",
"Span",
"interface"
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mockspan.go#L162-L167
|
test
|
opentracing/opentracing-go
|
mocktracer/mockspan.go
|
BaggageItem
|
func (s *MockSpan) BaggageItem(key string) string {
s.RLock()
defer s.RUnlock()
return s.SpanContext.Baggage[key]
}
|
go
|
func (s *MockSpan) BaggageItem(key string) string {
s.RLock()
defer s.RUnlock()
return s.SpanContext.Baggage[key]
}
|
[
"func",
"(",
"s",
"*",
"MockSpan",
")",
"BaggageItem",
"(",
"key",
"string",
")",
"string",
"{",
"s",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"s",
".",
"SpanContext",
".",
"Baggage",
"[",
"key",
"]",
"\n",
"}"
] |
// BaggageItem belongs to the Span interface
|
[
"BaggageItem",
"belongs",
"to",
"the",
"Span",
"interface"
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mockspan.go#L170-L174
|
test
|
opentracing/opentracing-go
|
mocktracer/mockspan.go
|
Finish
|
func (s *MockSpan) Finish() {
s.Lock()
s.FinishTime = time.Now()
s.Unlock()
s.tracer.recordSpan(s)
}
|
go
|
func (s *MockSpan) Finish() {
s.Lock()
s.FinishTime = time.Now()
s.Unlock()
s.tracer.recordSpan(s)
}
|
[
"func",
"(",
"s",
"*",
"MockSpan",
")",
"Finish",
"(",
")",
"{",
"s",
".",
"Lock",
"(",
")",
"\n",
"s",
".",
"FinishTime",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"s",
".",
"Unlock",
"(",
")",
"\n",
"s",
".",
"tracer",
".",
"recordSpan",
"(",
"s",
")",
"\n",
"}"
] |
// Finish belongs to the Span interface
|
[
"Finish",
"belongs",
"to",
"the",
"Span",
"interface"
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mockspan.go#L177-L182
|
test
|
opentracing/opentracing-go
|
mocktracer/mockspan.go
|
FinishWithOptions
|
func (s *MockSpan) FinishWithOptions(opts opentracing.FinishOptions) {
s.Lock()
s.FinishTime = opts.FinishTime
s.Unlock()
// Handle any late-bound LogRecords.
for _, lr := range opts.LogRecords {
s.logFieldsWithTimestamp(lr.Timestamp, lr.Fields...)
}
// Handle (deprecated) BulkLogData.
for _, ld := range opts.BulkLogData {
if ld.Payload != nil {
s.logFieldsWithTimestamp(
ld.Timestamp,
log.String("event", ld.Event),
log.Object("payload", ld.Payload))
} else {
s.logFieldsWithTimestamp(
ld.Timestamp,
log.String("event", ld.Event))
}
}
s.tracer.recordSpan(s)
}
|
go
|
func (s *MockSpan) FinishWithOptions(opts opentracing.FinishOptions) {
s.Lock()
s.FinishTime = opts.FinishTime
s.Unlock()
// Handle any late-bound LogRecords.
for _, lr := range opts.LogRecords {
s.logFieldsWithTimestamp(lr.Timestamp, lr.Fields...)
}
// Handle (deprecated) BulkLogData.
for _, ld := range opts.BulkLogData {
if ld.Payload != nil {
s.logFieldsWithTimestamp(
ld.Timestamp,
log.String("event", ld.Event),
log.Object("payload", ld.Payload))
} else {
s.logFieldsWithTimestamp(
ld.Timestamp,
log.String("event", ld.Event))
}
}
s.tracer.recordSpan(s)
}
|
[
"func",
"(",
"s",
"*",
"MockSpan",
")",
"FinishWithOptions",
"(",
"opts",
"opentracing",
".",
"FinishOptions",
")",
"{",
"s",
".",
"Lock",
"(",
")",
"\n",
"s",
".",
"FinishTime",
"=",
"opts",
".",
"FinishTime",
"\n",
"s",
".",
"Unlock",
"(",
")",
"\n",
"for",
"_",
",",
"lr",
":=",
"range",
"opts",
".",
"LogRecords",
"{",
"s",
".",
"logFieldsWithTimestamp",
"(",
"lr",
".",
"Timestamp",
",",
"lr",
".",
"Fields",
"...",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"ld",
":=",
"range",
"opts",
".",
"BulkLogData",
"{",
"if",
"ld",
".",
"Payload",
"!=",
"nil",
"{",
"s",
".",
"logFieldsWithTimestamp",
"(",
"ld",
".",
"Timestamp",
",",
"log",
".",
"String",
"(",
"\"event\"",
",",
"ld",
".",
"Event",
")",
",",
"log",
".",
"Object",
"(",
"\"payload\"",
",",
"ld",
".",
"Payload",
")",
")",
"\n",
"}",
"else",
"{",
"s",
".",
"logFieldsWithTimestamp",
"(",
"ld",
".",
"Timestamp",
",",
"log",
".",
"String",
"(",
"\"event\"",
",",
"ld",
".",
"Event",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"s",
".",
"tracer",
".",
"recordSpan",
"(",
"s",
")",
"\n",
"}"
] |
// FinishWithOptions belongs to the Span interface
|
[
"FinishWithOptions",
"belongs",
"to",
"the",
"Span",
"interface"
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mockspan.go#L185-L209
|
test
|
opentracing/opentracing-go
|
mocktracer/mockspan.go
|
String
|
func (s *MockSpan) String() string {
return fmt.Sprintf(
"traceId=%d, spanId=%d, parentId=%d, sampled=%t, name=%s",
s.SpanContext.TraceID, s.SpanContext.SpanID, s.ParentID,
s.SpanContext.Sampled, s.OperationName)
}
|
go
|
func (s *MockSpan) String() string {
return fmt.Sprintf(
"traceId=%d, spanId=%d, parentId=%d, sampled=%t, name=%s",
s.SpanContext.TraceID, s.SpanContext.SpanID, s.ParentID,
s.SpanContext.Sampled, s.OperationName)
}
|
[
"func",
"(",
"s",
"*",
"MockSpan",
")",
"String",
"(",
")",
"string",
"{",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"traceId=%d, spanId=%d, parentId=%d, sampled=%t, name=%s\"",
",",
"s",
".",
"SpanContext",
".",
"TraceID",
",",
"s",
".",
"SpanContext",
".",
"SpanID",
",",
"s",
".",
"ParentID",
",",
"s",
".",
"SpanContext",
".",
"Sampled",
",",
"s",
".",
"OperationName",
")",
"\n",
"}"
] |
// String allows printing span for debugging
|
[
"String",
"allows",
"printing",
"span",
"for",
"debugging"
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mockspan.go#L212-L217
|
test
|
opentracing/opentracing-go
|
mocktracer/mockspan.go
|
LogFields
|
func (s *MockSpan) LogFields(fields ...log.Field) {
s.logFieldsWithTimestamp(time.Now(), fields...)
}
|
go
|
func (s *MockSpan) LogFields(fields ...log.Field) {
s.logFieldsWithTimestamp(time.Now(), fields...)
}
|
[
"func",
"(",
"s",
"*",
"MockSpan",
")",
"LogFields",
"(",
"fields",
"...",
"log",
".",
"Field",
")",
"{",
"s",
".",
"logFieldsWithTimestamp",
"(",
"time",
".",
"Now",
"(",
")",
",",
"fields",
"...",
")",
"\n",
"}"
] |
// LogFields belongs to the Span interface
|
[
"LogFields",
"belongs",
"to",
"the",
"Span",
"interface"
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mockspan.go#L220-L222
|
test
|
opentracing/opentracing-go
|
mocktracer/mockspan.go
|
logFieldsWithTimestamp
|
func (s *MockSpan) logFieldsWithTimestamp(ts time.Time, fields ...log.Field) {
lr := MockLogRecord{
Timestamp: ts,
Fields: make([]MockKeyValue, len(fields)),
}
for i, f := range fields {
outField := &(lr.Fields[i])
f.Marshal(outField)
}
s.Lock()
defer s.Unlock()
s.logs = append(s.logs, lr)
}
|
go
|
func (s *MockSpan) logFieldsWithTimestamp(ts time.Time, fields ...log.Field) {
lr := MockLogRecord{
Timestamp: ts,
Fields: make([]MockKeyValue, len(fields)),
}
for i, f := range fields {
outField := &(lr.Fields[i])
f.Marshal(outField)
}
s.Lock()
defer s.Unlock()
s.logs = append(s.logs, lr)
}
|
[
"func",
"(",
"s",
"*",
"MockSpan",
")",
"logFieldsWithTimestamp",
"(",
"ts",
"time",
".",
"Time",
",",
"fields",
"...",
"log",
".",
"Field",
")",
"{",
"lr",
":=",
"MockLogRecord",
"{",
"Timestamp",
":",
"ts",
",",
"Fields",
":",
"make",
"(",
"[",
"]",
"MockKeyValue",
",",
"len",
"(",
"fields",
")",
")",
",",
"}",
"\n",
"for",
"i",
",",
"f",
":=",
"range",
"fields",
"{",
"outField",
":=",
"&",
"(",
"lr",
".",
"Fields",
"[",
"i",
"]",
")",
"\n",
"f",
".",
"Marshal",
"(",
"outField",
")",
"\n",
"}",
"\n",
"s",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"Unlock",
"(",
")",
"\n",
"s",
".",
"logs",
"=",
"append",
"(",
"s",
".",
"logs",
",",
"lr",
")",
"\n",
"}"
] |
// The caller MUST NOT hold s.Lock
|
[
"The",
"caller",
"MUST",
"NOT",
"hold",
"s",
".",
"Lock"
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mockspan.go#L225-L238
|
test
|
opentracing/opentracing-go
|
mocktracer/mockspan.go
|
LogKV
|
func (s *MockSpan) LogKV(keyValues ...interface{}) {
if len(keyValues)%2 != 0 {
s.LogFields(log.Error(fmt.Errorf("Non-even keyValues len: %v", len(keyValues))))
return
}
fields, err := log.InterleavedKVToFields(keyValues...)
if err != nil {
s.LogFields(log.Error(err), log.String("function", "LogKV"))
return
}
s.LogFields(fields...)
}
|
go
|
func (s *MockSpan) LogKV(keyValues ...interface{}) {
if len(keyValues)%2 != 0 {
s.LogFields(log.Error(fmt.Errorf("Non-even keyValues len: %v", len(keyValues))))
return
}
fields, err := log.InterleavedKVToFields(keyValues...)
if err != nil {
s.LogFields(log.Error(err), log.String("function", "LogKV"))
return
}
s.LogFields(fields...)
}
|
[
"func",
"(",
"s",
"*",
"MockSpan",
")",
"LogKV",
"(",
"keyValues",
"...",
"interface",
"{",
"}",
")",
"{",
"if",
"len",
"(",
"keyValues",
")",
"%",
"2",
"!=",
"0",
"{",
"s",
".",
"LogFields",
"(",
"log",
".",
"Error",
"(",
"fmt",
".",
"Errorf",
"(",
"\"Non-even keyValues len: %v\"",
",",
"len",
"(",
"keyValues",
")",
")",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"fields",
",",
"err",
":=",
"log",
".",
"InterleavedKVToFields",
"(",
"keyValues",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"s",
".",
"LogFields",
"(",
"log",
".",
"Error",
"(",
"err",
")",
",",
"log",
".",
"String",
"(",
"\"function\"",
",",
"\"LogKV\"",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"s",
".",
"LogFields",
"(",
"fields",
"...",
")",
"\n",
"}"
] |
// LogKV belongs to the Span interface.
//
// This implementations coerces all "values" to strings, though that is not
// something all implementations need to do. Indeed, a motivated person can and
// probably should have this do a typed switch on the values.
|
[
"LogKV",
"belongs",
"to",
"the",
"Span",
"interface",
".",
"This",
"implementations",
"coerces",
"all",
"values",
"to",
"strings",
"though",
"that",
"is",
"not",
"something",
"all",
"implementations",
"need",
"to",
"do",
".",
"Indeed",
"a",
"motivated",
"person",
"can",
"and",
"probably",
"should",
"have",
"this",
"do",
"a",
"typed",
"switch",
"on",
"the",
"values",
"."
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mockspan.go#L245-L256
|
test
|
opentracing/opentracing-go
|
mocktracer/mockspan.go
|
LogEvent
|
func (s *MockSpan) LogEvent(event string) {
s.LogFields(log.String("event", event))
}
|
go
|
func (s *MockSpan) LogEvent(event string) {
s.LogFields(log.String("event", event))
}
|
[
"func",
"(",
"s",
"*",
"MockSpan",
")",
"LogEvent",
"(",
"event",
"string",
")",
"{",
"s",
".",
"LogFields",
"(",
"log",
".",
"String",
"(",
"\"event\"",
",",
"event",
")",
")",
"\n",
"}"
] |
// LogEvent belongs to the Span interface
|
[
"LogEvent",
"belongs",
"to",
"the",
"Span",
"interface"
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mockspan.go#L259-L261
|
test
|
opentracing/opentracing-go
|
mocktracer/mockspan.go
|
LogEventWithPayload
|
func (s *MockSpan) LogEventWithPayload(event string, payload interface{}) {
s.LogFields(log.String("event", event), log.Object("payload", payload))
}
|
go
|
func (s *MockSpan) LogEventWithPayload(event string, payload interface{}) {
s.LogFields(log.String("event", event), log.Object("payload", payload))
}
|
[
"func",
"(",
"s",
"*",
"MockSpan",
")",
"LogEventWithPayload",
"(",
"event",
"string",
",",
"payload",
"interface",
"{",
"}",
")",
"{",
"s",
".",
"LogFields",
"(",
"log",
".",
"String",
"(",
"\"event\"",
",",
"event",
")",
",",
"log",
".",
"Object",
"(",
"\"payload\"",
",",
"payload",
")",
")",
"\n",
"}"
] |
// LogEventWithPayload belongs to the Span interface
|
[
"LogEventWithPayload",
"belongs",
"to",
"the",
"Span",
"interface"
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mockspan.go#L264-L266
|
test
|
opentracing/opentracing-go
|
mocktracer/mockspan.go
|
SetOperationName
|
func (s *MockSpan) SetOperationName(operationName string) opentracing.Span {
s.Lock()
defer s.Unlock()
s.OperationName = operationName
return s
}
|
go
|
func (s *MockSpan) SetOperationName(operationName string) opentracing.Span {
s.Lock()
defer s.Unlock()
s.OperationName = operationName
return s
}
|
[
"func",
"(",
"s",
"*",
"MockSpan",
")",
"SetOperationName",
"(",
"operationName",
"string",
")",
"opentracing",
".",
"Span",
"{",
"s",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"Unlock",
"(",
")",
"\n",
"s",
".",
"OperationName",
"=",
"operationName",
"\n",
"return",
"s",
"\n",
"}"
] |
// SetOperationName belongs to the Span interface
|
[
"SetOperationName",
"belongs",
"to",
"the",
"Span",
"interface"
] |
659c90643e714681897ec2521c60567dd21da733
|
https://github.com/opentracing/opentracing-go/blob/659c90643e714681897ec2521c60567dd21da733/mocktracer/mockspan.go#L274-L279
|
test
|
containers/image
|
docker/lookaside.go
|
registriesDirPath
|
func registriesDirPath(sys *types.SystemContext) string {
if sys != nil {
if sys.RegistriesDirPath != "" {
return sys.RegistriesDirPath
}
if sys.RootForImplicitAbsolutePaths != "" {
return filepath.Join(sys.RootForImplicitAbsolutePaths, systemRegistriesDirPath)
}
}
return systemRegistriesDirPath
}
|
go
|
func registriesDirPath(sys *types.SystemContext) string {
if sys != nil {
if sys.RegistriesDirPath != "" {
return sys.RegistriesDirPath
}
if sys.RootForImplicitAbsolutePaths != "" {
return filepath.Join(sys.RootForImplicitAbsolutePaths, systemRegistriesDirPath)
}
}
return systemRegistriesDirPath
}
|
[
"func",
"registriesDirPath",
"(",
"sys",
"*",
"types",
".",
"SystemContext",
")",
"string",
"{",
"if",
"sys",
"!=",
"nil",
"{",
"if",
"sys",
".",
"RegistriesDirPath",
"!=",
"\"\"",
"{",
"return",
"sys",
".",
"RegistriesDirPath",
"\n",
"}",
"\n",
"if",
"sys",
".",
"RootForImplicitAbsolutePaths",
"!=",
"\"\"",
"{",
"return",
"filepath",
".",
"Join",
"(",
"sys",
".",
"RootForImplicitAbsolutePaths",
",",
"systemRegistriesDirPath",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"systemRegistriesDirPath",
"\n",
"}"
] |
// registriesDirPath returns a path to registries.d
|
[
"registriesDirPath",
"returns",
"a",
"path",
"to",
"registries",
".",
"d"
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/lookaside.go#L77-L87
|
test
|
containers/image
|
docker/lookaside.go
|
loadAndMergeConfig
|
func loadAndMergeConfig(dirPath string) (*registryConfiguration, error) {
mergedConfig := registryConfiguration{Docker: map[string]registryNamespace{}}
dockerDefaultMergedFrom := ""
nsMergedFrom := map[string]string{}
dir, err := os.Open(dirPath)
if err != nil {
if os.IsNotExist(err) {
return &mergedConfig, nil
}
return nil, err
}
configNames, err := dir.Readdirnames(0)
if err != nil {
return nil, err
}
for _, configName := range configNames {
if !strings.HasSuffix(configName, ".yaml") {
continue
}
configPath := filepath.Join(dirPath, configName)
configBytes, err := ioutil.ReadFile(configPath)
if err != nil {
return nil, err
}
var config registryConfiguration
err = yaml.Unmarshal(configBytes, &config)
if err != nil {
return nil, errors.Wrapf(err, "Error parsing %s", configPath)
}
if config.DefaultDocker != nil {
if mergedConfig.DefaultDocker != nil {
return nil, errors.Errorf(`Error parsing signature storage configuration: "default-docker" defined both in "%s" and "%s"`,
dockerDefaultMergedFrom, configPath)
}
mergedConfig.DefaultDocker = config.DefaultDocker
dockerDefaultMergedFrom = configPath
}
for nsName, nsConfig := range config.Docker { // includes config.Docker == nil
if _, ok := mergedConfig.Docker[nsName]; ok {
return nil, errors.Errorf(`Error parsing signature storage configuration: "docker" namespace "%s" defined both in "%s" and "%s"`,
nsName, nsMergedFrom[nsName], configPath)
}
mergedConfig.Docker[nsName] = nsConfig
nsMergedFrom[nsName] = configPath
}
}
return &mergedConfig, nil
}
|
go
|
func loadAndMergeConfig(dirPath string) (*registryConfiguration, error) {
mergedConfig := registryConfiguration{Docker: map[string]registryNamespace{}}
dockerDefaultMergedFrom := ""
nsMergedFrom := map[string]string{}
dir, err := os.Open(dirPath)
if err != nil {
if os.IsNotExist(err) {
return &mergedConfig, nil
}
return nil, err
}
configNames, err := dir.Readdirnames(0)
if err != nil {
return nil, err
}
for _, configName := range configNames {
if !strings.HasSuffix(configName, ".yaml") {
continue
}
configPath := filepath.Join(dirPath, configName)
configBytes, err := ioutil.ReadFile(configPath)
if err != nil {
return nil, err
}
var config registryConfiguration
err = yaml.Unmarshal(configBytes, &config)
if err != nil {
return nil, errors.Wrapf(err, "Error parsing %s", configPath)
}
if config.DefaultDocker != nil {
if mergedConfig.DefaultDocker != nil {
return nil, errors.Errorf(`Error parsing signature storage configuration: "default-docker" defined both in "%s" and "%s"`,
dockerDefaultMergedFrom, configPath)
}
mergedConfig.DefaultDocker = config.DefaultDocker
dockerDefaultMergedFrom = configPath
}
for nsName, nsConfig := range config.Docker { // includes config.Docker == nil
if _, ok := mergedConfig.Docker[nsName]; ok {
return nil, errors.Errorf(`Error parsing signature storage configuration: "docker" namespace "%s" defined both in "%s" and "%s"`,
nsName, nsMergedFrom[nsName], configPath)
}
mergedConfig.Docker[nsName] = nsConfig
nsMergedFrom[nsName] = configPath
}
}
return &mergedConfig, nil
}
|
[
"func",
"loadAndMergeConfig",
"(",
"dirPath",
"string",
")",
"(",
"*",
"registryConfiguration",
",",
"error",
")",
"{",
"mergedConfig",
":=",
"registryConfiguration",
"{",
"Docker",
":",
"map",
"[",
"string",
"]",
"registryNamespace",
"{",
"}",
"}",
"\n",
"dockerDefaultMergedFrom",
":=",
"\"\"",
"\n",
"nsMergedFrom",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"dir",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"dirPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"&",
"mergedConfig",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"configNames",
",",
"err",
":=",
"dir",
".",
"Readdirnames",
"(",
"0",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"configName",
":=",
"range",
"configNames",
"{",
"if",
"!",
"strings",
".",
"HasSuffix",
"(",
"configName",
",",
"\".yaml\"",
")",
"{",
"continue",
"\n",
"}",
"\n",
"configPath",
":=",
"filepath",
".",
"Join",
"(",
"dirPath",
",",
"configName",
")",
"\n",
"configBytes",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"configPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"var",
"config",
"registryConfiguration",
"\n",
"err",
"=",
"yaml",
".",
"Unmarshal",
"(",
"configBytes",
",",
"&",
"config",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"Error parsing %s\"",
",",
"configPath",
")",
"\n",
"}",
"\n",
"if",
"config",
".",
"DefaultDocker",
"!=",
"nil",
"{",
"if",
"mergedConfig",
".",
"DefaultDocker",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"`Error parsing signature storage configuration: \"default-docker\" defined both in \"%s\" and \"%s\"`",
",",
"dockerDefaultMergedFrom",
",",
"configPath",
")",
"\n",
"}",
"\n",
"mergedConfig",
".",
"DefaultDocker",
"=",
"config",
".",
"DefaultDocker",
"\n",
"dockerDefaultMergedFrom",
"=",
"configPath",
"\n",
"}",
"\n",
"for",
"nsName",
",",
"nsConfig",
":=",
"range",
"config",
".",
"Docker",
"{",
"if",
"_",
",",
"ok",
":=",
"mergedConfig",
".",
"Docker",
"[",
"nsName",
"]",
";",
"ok",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"`Error parsing signature storage configuration: \"docker\" namespace \"%s\" defined both in \"%s\" and \"%s\"`",
",",
"nsName",
",",
"nsMergedFrom",
"[",
"nsName",
"]",
",",
"configPath",
")",
"\n",
"}",
"\n",
"mergedConfig",
".",
"Docker",
"[",
"nsName",
"]",
"=",
"nsConfig",
"\n",
"nsMergedFrom",
"[",
"nsName",
"]",
"=",
"configPath",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"&",
"mergedConfig",
",",
"nil",
"\n",
"}"
] |
// loadAndMergeConfig loads configuration files in dirPath
|
[
"loadAndMergeConfig",
"loads",
"configuration",
"files",
"in",
"dirPath"
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/lookaside.go#L90-L142
|
test
|
containers/image
|
openshift/openshift_transport.go
|
ParseReference
|
func ParseReference(ref string) (types.ImageReference, error) {
r, err := reference.ParseNormalizedNamed(ref)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse image reference %q", ref)
}
tagged, ok := r.(reference.NamedTagged)
if !ok {
return nil, errors.Errorf("invalid image reference %s, expected format: 'hostname/namespace/stream:tag'", ref)
}
return NewReference(tagged)
}
|
go
|
func ParseReference(ref string) (types.ImageReference, error) {
r, err := reference.ParseNormalizedNamed(ref)
if err != nil {
return nil, errors.Wrapf(err, "failed to parse image reference %q", ref)
}
tagged, ok := r.(reference.NamedTagged)
if !ok {
return nil, errors.Errorf("invalid image reference %s, expected format: 'hostname/namespace/stream:tag'", ref)
}
return NewReference(tagged)
}
|
[
"func",
"ParseReference",
"(",
"ref",
"string",
")",
"(",
"types",
".",
"ImageReference",
",",
"error",
")",
"{",
"r",
",",
"err",
":=",
"reference",
".",
"ParseNormalizedNamed",
"(",
"ref",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"failed to parse image reference %q\"",
",",
"ref",
")",
"\n",
"}",
"\n",
"tagged",
",",
"ok",
":=",
"r",
".",
"(",
"reference",
".",
"NamedTagged",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"invalid image reference %s, expected format: 'hostname/namespace/stream:tag'\"",
",",
"ref",
")",
"\n",
"}",
"\n",
"return",
"NewReference",
"(",
"tagged",
")",
"\n",
"}"
] |
// ParseReference converts a string, which should not start with the ImageTransport.Name prefix, into an OpenShift ImageReference.
|
[
"ParseReference",
"converts",
"a",
"string",
"which",
"should",
"not",
"start",
"with",
"the",
"ImageTransport",
".",
"Name",
"prefix",
"into",
"an",
"OpenShift",
"ImageReference",
"."
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift_transport.go#L59-L69
|
test
|
containers/image
|
openshift/openshift_transport.go
|
NewReference
|
func NewReference(dockerRef reference.NamedTagged) (types.ImageReference, error) {
r := strings.SplitN(reference.Path(dockerRef), "/", 3)
if len(r) != 2 {
return nil, errors.Errorf("invalid image reference: %s, expected format: 'hostname/namespace/stream:tag'",
reference.FamiliarString(dockerRef))
}
return openshiftReference{
namespace: r[0],
stream: r[1],
dockerReference: dockerRef,
}, nil
}
|
go
|
func NewReference(dockerRef reference.NamedTagged) (types.ImageReference, error) {
r := strings.SplitN(reference.Path(dockerRef), "/", 3)
if len(r) != 2 {
return nil, errors.Errorf("invalid image reference: %s, expected format: 'hostname/namespace/stream:tag'",
reference.FamiliarString(dockerRef))
}
return openshiftReference{
namespace: r[0],
stream: r[1],
dockerReference: dockerRef,
}, nil
}
|
[
"func",
"NewReference",
"(",
"dockerRef",
"reference",
".",
"NamedTagged",
")",
"(",
"types",
".",
"ImageReference",
",",
"error",
")",
"{",
"r",
":=",
"strings",
".",
"SplitN",
"(",
"reference",
".",
"Path",
"(",
"dockerRef",
")",
",",
"\"/\"",
",",
"3",
")",
"\n",
"if",
"len",
"(",
"r",
")",
"!=",
"2",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"invalid image reference: %s, expected format: 'hostname/namespace/stream:tag'\"",
",",
"reference",
".",
"FamiliarString",
"(",
"dockerRef",
")",
")",
"\n",
"}",
"\n",
"return",
"openshiftReference",
"{",
"namespace",
":",
"r",
"[",
"0",
"]",
",",
"stream",
":",
"r",
"[",
"1",
"]",
",",
"dockerReference",
":",
"dockerRef",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// NewReference returns an OpenShift reference for a reference.NamedTagged
|
[
"NewReference",
"returns",
"an",
"OpenShift",
"reference",
"for",
"a",
"reference",
".",
"NamedTagged"
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift_transport.go#L72-L83
|
test
|
containers/image
|
docker/docker_client.go
|
CheckAuth
|
func CheckAuth(ctx context.Context, sys *types.SystemContext, username, password, registry string) error {
client, err := newDockerClient(sys, registry, registry)
if err != nil {
return errors.Wrapf(err, "error creating new docker client")
}
client.username = username
client.password = password
resp, err := client.makeRequest(ctx, "GET", "/v2/", nil, nil, v2Auth, nil)
if err != nil {
return err
}
defer resp.Body.Close()
switch resp.StatusCode {
case http.StatusOK:
return nil
case http.StatusUnauthorized:
return ErrUnauthorizedForCredentials
default:
return errors.Errorf("error occured with status code %d (%s)", resp.StatusCode, http.StatusText(resp.StatusCode))
}
}
|
go
|
func CheckAuth(ctx context.Context, sys *types.SystemContext, username, password, registry string) error {
client, err := newDockerClient(sys, registry, registry)
if err != nil {
return errors.Wrapf(err, "error creating new docker client")
}
client.username = username
client.password = password
resp, err := client.makeRequest(ctx, "GET", "/v2/", nil, nil, v2Auth, nil)
if err != nil {
return err
}
defer resp.Body.Close()
switch resp.StatusCode {
case http.StatusOK:
return nil
case http.StatusUnauthorized:
return ErrUnauthorizedForCredentials
default:
return errors.Errorf("error occured with status code %d (%s)", resp.StatusCode, http.StatusText(resp.StatusCode))
}
}
|
[
"func",
"CheckAuth",
"(",
"ctx",
"context",
".",
"Context",
",",
"sys",
"*",
"types",
".",
"SystemContext",
",",
"username",
",",
"password",
",",
"registry",
"string",
")",
"error",
"{",
"client",
",",
"err",
":=",
"newDockerClient",
"(",
"sys",
",",
"registry",
",",
"registry",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"error creating new docker client\"",
")",
"\n",
"}",
"\n",
"client",
".",
"username",
"=",
"username",
"\n",
"client",
".",
"password",
"=",
"password",
"\n",
"resp",
",",
"err",
":=",
"client",
".",
"makeRequest",
"(",
"ctx",
",",
"\"GET\"",
",",
"\"/v2/\"",
",",
"nil",
",",
"nil",
",",
"v2Auth",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"switch",
"resp",
".",
"StatusCode",
"{",
"case",
"http",
".",
"StatusOK",
":",
"return",
"nil",
"\n",
"case",
"http",
".",
"StatusUnauthorized",
":",
"return",
"ErrUnauthorizedForCredentials",
"\n",
"default",
":",
"return",
"errors",
".",
"Errorf",
"(",
"\"error occured with status code %d (%s)\"",
",",
"resp",
".",
"StatusCode",
",",
"http",
".",
"StatusText",
"(",
"resp",
".",
"StatusCode",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// CheckAuth validates the credentials by attempting to log into the registry
// returns an error if an error occurred while making the http request or the status code received was 401
|
[
"CheckAuth",
"validates",
"the",
"credentials",
"by",
"attempting",
"to",
"log",
"into",
"the",
"registry",
"returns",
"an",
"error",
"if",
"an",
"error",
"occurred",
"while",
"making",
"the",
"http",
"request",
"or",
"the",
"status",
"code",
"received",
"was",
"401"
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_client.go#L270-L292
|
test
|
containers/image
|
docker/docker_client.go
|
doHTTP
|
func (c *dockerClient) doHTTP(req *http.Request) (*http.Response, error) {
tr := tlsclientconfig.NewTransport()
tr.TLSClientConfig = c.tlsClientConfig
httpClient := &http.Client{Transport: tr}
return httpClient.Do(req)
}
|
go
|
func (c *dockerClient) doHTTP(req *http.Request) (*http.Response, error) {
tr := tlsclientconfig.NewTransport()
tr.TLSClientConfig = c.tlsClientConfig
httpClient := &http.Client{Transport: tr}
return httpClient.Do(req)
}
|
[
"func",
"(",
"c",
"*",
"dockerClient",
")",
"doHTTP",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"(",
"*",
"http",
".",
"Response",
",",
"error",
")",
"{",
"tr",
":=",
"tlsclientconfig",
".",
"NewTransport",
"(",
")",
"\n",
"tr",
".",
"TLSClientConfig",
"=",
"c",
".",
"tlsClientConfig",
"\n",
"httpClient",
":=",
"&",
"http",
".",
"Client",
"{",
"Transport",
":",
"tr",
"}",
"\n",
"return",
"httpClient",
".",
"Do",
"(",
"req",
")",
"\n",
"}"
] |
// doHttp uses the clients internal TLS configuration for doing the
// provided HTTP request. It returns the response and an error on failure.
|
[
"doHttp",
"uses",
"the",
"clients",
"internal",
"TLS",
"configuration",
"for",
"doing",
"the",
"provided",
"HTTP",
"request",
".",
"It",
"returns",
"the",
"response",
"and",
"an",
"error",
"on",
"failure",
"."
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_client.go#L449-L454
|
test
|
containers/image
|
docker/docker_client.go
|
detectPropertiesHelper
|
func (c *dockerClient) detectPropertiesHelper(ctx context.Context) error {
if c.scheme != "" {
return nil
}
// We overwrite the TLS clients `InsecureSkipVerify` only if explicitly
// specified by the system context
if c.sys != nil && c.sys.DockerInsecureSkipTLSVerify != types.OptionalBoolUndefined {
c.tlsClientConfig.InsecureSkipVerify = c.sys.DockerInsecureSkipTLSVerify == types.OptionalBoolTrue
}
ping := func(scheme string) error {
url := fmt.Sprintf(resolvedPingV2URL, scheme, c.registry)
resp, err := c.makeRequestToResolvedURL(ctx, "GET", url, nil, nil, -1, noAuth, nil)
if err != nil {
logrus.Debugf("Ping %s err %s (%#v)", url, err.Error(), err)
return err
}
defer resp.Body.Close()
logrus.Debugf("Ping %s status %d", url, resp.StatusCode)
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusUnauthorized {
return errors.Errorf("error pinging registry %s, response code %d (%s)", c.registry, resp.StatusCode, http.StatusText(resp.StatusCode))
}
c.challenges = parseAuthHeader(resp.Header)
c.scheme = scheme
c.supportsSignatures = resp.Header.Get("X-Registry-Supports-Signatures") == "1"
return nil
}
err := ping("https")
if err != nil && c.tlsClientConfig.InsecureSkipVerify {
err = ping("http")
}
if err != nil {
err = errors.Wrap(err, "pinging docker registry returned")
if c.sys != nil && c.sys.DockerDisableV1Ping {
return err
}
// best effort to understand if we're talking to a V1 registry
pingV1 := func(scheme string) bool {
url := fmt.Sprintf(resolvedPingV1URL, scheme, c.registry)
resp, err := c.makeRequestToResolvedURL(ctx, "GET", url, nil, nil, -1, noAuth, nil)
if err != nil {
logrus.Debugf("Ping %s err %s (%#v)", url, err.Error(), err)
return false
}
defer resp.Body.Close()
logrus.Debugf("Ping %s status %d", url, resp.StatusCode)
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusUnauthorized {
return false
}
return true
}
isV1 := pingV1("https")
if !isV1 && c.tlsClientConfig.InsecureSkipVerify {
isV1 = pingV1("http")
}
if isV1 {
err = ErrV1NotSupported
}
}
return err
}
|
go
|
func (c *dockerClient) detectPropertiesHelper(ctx context.Context) error {
if c.scheme != "" {
return nil
}
// We overwrite the TLS clients `InsecureSkipVerify` only if explicitly
// specified by the system context
if c.sys != nil && c.sys.DockerInsecureSkipTLSVerify != types.OptionalBoolUndefined {
c.tlsClientConfig.InsecureSkipVerify = c.sys.DockerInsecureSkipTLSVerify == types.OptionalBoolTrue
}
ping := func(scheme string) error {
url := fmt.Sprintf(resolvedPingV2URL, scheme, c.registry)
resp, err := c.makeRequestToResolvedURL(ctx, "GET", url, nil, nil, -1, noAuth, nil)
if err != nil {
logrus.Debugf("Ping %s err %s (%#v)", url, err.Error(), err)
return err
}
defer resp.Body.Close()
logrus.Debugf("Ping %s status %d", url, resp.StatusCode)
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusUnauthorized {
return errors.Errorf("error pinging registry %s, response code %d (%s)", c.registry, resp.StatusCode, http.StatusText(resp.StatusCode))
}
c.challenges = parseAuthHeader(resp.Header)
c.scheme = scheme
c.supportsSignatures = resp.Header.Get("X-Registry-Supports-Signatures") == "1"
return nil
}
err := ping("https")
if err != nil && c.tlsClientConfig.InsecureSkipVerify {
err = ping("http")
}
if err != nil {
err = errors.Wrap(err, "pinging docker registry returned")
if c.sys != nil && c.sys.DockerDisableV1Ping {
return err
}
// best effort to understand if we're talking to a V1 registry
pingV1 := func(scheme string) bool {
url := fmt.Sprintf(resolvedPingV1URL, scheme, c.registry)
resp, err := c.makeRequestToResolvedURL(ctx, "GET", url, nil, nil, -1, noAuth, nil)
if err != nil {
logrus.Debugf("Ping %s err %s (%#v)", url, err.Error(), err)
return false
}
defer resp.Body.Close()
logrus.Debugf("Ping %s status %d", url, resp.StatusCode)
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusUnauthorized {
return false
}
return true
}
isV1 := pingV1("https")
if !isV1 && c.tlsClientConfig.InsecureSkipVerify {
isV1 = pingV1("http")
}
if isV1 {
err = ErrV1NotSupported
}
}
return err
}
|
[
"func",
"(",
"c",
"*",
"dockerClient",
")",
"detectPropertiesHelper",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"if",
"c",
".",
"scheme",
"!=",
"\"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"c",
".",
"sys",
"!=",
"nil",
"&&",
"c",
".",
"sys",
".",
"DockerInsecureSkipTLSVerify",
"!=",
"types",
".",
"OptionalBoolUndefined",
"{",
"c",
".",
"tlsClientConfig",
".",
"InsecureSkipVerify",
"=",
"c",
".",
"sys",
".",
"DockerInsecureSkipTLSVerify",
"==",
"types",
".",
"OptionalBoolTrue",
"\n",
"}",
"\n",
"ping",
":=",
"func",
"(",
"scheme",
"string",
")",
"error",
"{",
"url",
":=",
"fmt",
".",
"Sprintf",
"(",
"resolvedPingV2URL",
",",
"scheme",
",",
"c",
".",
"registry",
")",
"\n",
"resp",
",",
"err",
":=",
"c",
".",
"makeRequestToResolvedURL",
"(",
"ctx",
",",
"\"GET\"",
",",
"url",
",",
"nil",
",",
"nil",
",",
"-",
"1",
",",
"noAuth",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Debugf",
"(",
"\"Ping %s err %s (%#v)\"",
",",
"url",
",",
"err",
".",
"Error",
"(",
")",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"logrus",
".",
"Debugf",
"(",
"\"Ping %s status %d\"",
",",
"url",
",",
"resp",
".",
"StatusCode",
")",
"\n",
"if",
"resp",
".",
"StatusCode",
"!=",
"http",
".",
"StatusOK",
"&&",
"resp",
".",
"StatusCode",
"!=",
"http",
".",
"StatusUnauthorized",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"error pinging registry %s, response code %d (%s)\"",
",",
"c",
".",
"registry",
",",
"resp",
".",
"StatusCode",
",",
"http",
".",
"StatusText",
"(",
"resp",
".",
"StatusCode",
")",
")",
"\n",
"}",
"\n",
"c",
".",
"challenges",
"=",
"parseAuthHeader",
"(",
"resp",
".",
"Header",
")",
"\n",
"c",
".",
"scheme",
"=",
"scheme",
"\n",
"c",
".",
"supportsSignatures",
"=",
"resp",
".",
"Header",
".",
"Get",
"(",
"\"X-Registry-Supports-Signatures\"",
")",
"==",
"\"1\"",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"err",
":=",
"ping",
"(",
"\"https\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"c",
".",
"tlsClientConfig",
".",
"InsecureSkipVerify",
"{",
"err",
"=",
"ping",
"(",
"\"http\"",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"err",
"=",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"pinging docker registry returned\"",
")",
"\n",
"if",
"c",
".",
"sys",
"!=",
"nil",
"&&",
"c",
".",
"sys",
".",
"DockerDisableV1Ping",
"{",
"return",
"err",
"\n",
"}",
"\n",
"pingV1",
":=",
"func",
"(",
"scheme",
"string",
")",
"bool",
"{",
"url",
":=",
"fmt",
".",
"Sprintf",
"(",
"resolvedPingV1URL",
",",
"scheme",
",",
"c",
".",
"registry",
")",
"\n",
"resp",
",",
"err",
":=",
"c",
".",
"makeRequestToResolvedURL",
"(",
"ctx",
",",
"\"GET\"",
",",
"url",
",",
"nil",
",",
"nil",
",",
"-",
"1",
",",
"noAuth",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logrus",
".",
"Debugf",
"(",
"\"Ping %s err %s (%#v)\"",
",",
"url",
",",
"err",
".",
"Error",
"(",
")",
",",
"err",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"logrus",
".",
"Debugf",
"(",
"\"Ping %s status %d\"",
",",
"url",
",",
"resp",
".",
"StatusCode",
")",
"\n",
"if",
"resp",
".",
"StatusCode",
"!=",
"http",
".",
"StatusOK",
"&&",
"resp",
".",
"StatusCode",
"!=",
"http",
".",
"StatusUnauthorized",
"{",
"return",
"false",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"isV1",
":=",
"pingV1",
"(",
"\"https\"",
")",
"\n",
"if",
"!",
"isV1",
"&&",
"c",
".",
"tlsClientConfig",
".",
"InsecureSkipVerify",
"{",
"isV1",
"=",
"pingV1",
"(",
"\"http\"",
")",
"\n",
"}",
"\n",
"if",
"isV1",
"{",
"err",
"=",
"ErrV1NotSupported",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] |
// detectPropertiesHelper performs the work of detectProperties which executes
// it at most once.
|
[
"detectPropertiesHelper",
"performs",
"the",
"work",
"of",
"detectProperties",
"which",
"executes",
"it",
"at",
"most",
"once",
"."
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_client.go#L560-L621
|
test
|
containers/image
|
docker/docker_client.go
|
detectProperties
|
func (c *dockerClient) detectProperties(ctx context.Context) error {
c.detectPropertiesOnce.Do(func() { c.detectPropertiesError = c.detectPropertiesHelper(ctx) })
return c.detectPropertiesError
}
|
go
|
func (c *dockerClient) detectProperties(ctx context.Context) error {
c.detectPropertiesOnce.Do(func() { c.detectPropertiesError = c.detectPropertiesHelper(ctx) })
return c.detectPropertiesError
}
|
[
"func",
"(",
"c",
"*",
"dockerClient",
")",
"detectProperties",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"c",
".",
"detectPropertiesOnce",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"c",
".",
"detectPropertiesError",
"=",
"c",
".",
"detectPropertiesHelper",
"(",
"ctx",
")",
"}",
")",
"\n",
"return",
"c",
".",
"detectPropertiesError",
"\n",
"}"
] |
// detectProperties detects various properties of the registry.
// See the dockerClient documentation for members which are affected by this.
|
[
"detectProperties",
"detects",
"various",
"properties",
"of",
"the",
"registry",
".",
"See",
"the",
"dockerClient",
"documentation",
"for",
"members",
"which",
"are",
"affected",
"by",
"this",
"."
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_client.go#L625-L628
|
test
|
containers/image
|
docker/docker_client.go
|
getExtensionsSignatures
|
func (c *dockerClient) getExtensionsSignatures(ctx context.Context, ref dockerReference, manifestDigest digest.Digest) (*extensionSignatureList, error) {
path := fmt.Sprintf(extensionsSignaturePath, reference.Path(ref.ref), manifestDigest)
res, err := c.makeRequest(ctx, "GET", path, nil, nil, v2Auth, nil)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return nil, errors.Wrapf(client.HandleErrorResponse(res), "Error downloading signatures for %s in %s", manifestDigest, ref.ref.Name())
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
var parsedBody extensionSignatureList
if err := json.Unmarshal(body, &parsedBody); err != nil {
return nil, errors.Wrapf(err, "Error decoding signature list")
}
return &parsedBody, nil
}
|
go
|
func (c *dockerClient) getExtensionsSignatures(ctx context.Context, ref dockerReference, manifestDigest digest.Digest) (*extensionSignatureList, error) {
path := fmt.Sprintf(extensionsSignaturePath, reference.Path(ref.ref), manifestDigest)
res, err := c.makeRequest(ctx, "GET", path, nil, nil, v2Auth, nil)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return nil, errors.Wrapf(client.HandleErrorResponse(res), "Error downloading signatures for %s in %s", manifestDigest, ref.ref.Name())
}
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
var parsedBody extensionSignatureList
if err := json.Unmarshal(body, &parsedBody); err != nil {
return nil, errors.Wrapf(err, "Error decoding signature list")
}
return &parsedBody, nil
}
|
[
"func",
"(",
"c",
"*",
"dockerClient",
")",
"getExtensionsSignatures",
"(",
"ctx",
"context",
".",
"Context",
",",
"ref",
"dockerReference",
",",
"manifestDigest",
"digest",
".",
"Digest",
")",
"(",
"*",
"extensionSignatureList",
",",
"error",
")",
"{",
"path",
":=",
"fmt",
".",
"Sprintf",
"(",
"extensionsSignaturePath",
",",
"reference",
".",
"Path",
"(",
"ref",
".",
"ref",
")",
",",
"manifestDigest",
")",
"\n",
"res",
",",
"err",
":=",
"c",
".",
"makeRequest",
"(",
"ctx",
",",
"\"GET\"",
",",
"path",
",",
"nil",
",",
"nil",
",",
"v2Auth",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"res",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"if",
"res",
".",
"StatusCode",
"!=",
"http",
".",
"StatusOK",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrapf",
"(",
"client",
".",
"HandleErrorResponse",
"(",
"res",
")",
",",
"\"Error downloading signatures for %s in %s\"",
",",
"manifestDigest",
",",
"ref",
".",
"ref",
".",
"Name",
"(",
")",
")",
"\n",
"}",
"\n",
"body",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"res",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"var",
"parsedBody",
"extensionSignatureList",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"body",
",",
"&",
"parsedBody",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"Error decoding signature list\"",
")",
"\n",
"}",
"\n",
"return",
"&",
"parsedBody",
",",
"nil",
"\n",
"}"
] |
// getExtensionsSignatures returns signatures from the X-Registry-Supports-Signatures API extension,
// using the original data structures.
|
[
"getExtensionsSignatures",
"returns",
"signatures",
"from",
"the",
"X",
"-",
"Registry",
"-",
"Supports",
"-",
"Signatures",
"API",
"extension",
"using",
"the",
"original",
"data",
"structures",
"."
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_client.go#L632-L652
|
test
|
containers/image
|
pkg/tlsclientconfig/tlsclientconfig.go
|
NewTransport
|
func NewTransport() *http.Transport {
direct := &net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: direct.Dial,
TLSHandshakeTimeout: 10 * time.Second,
// TODO(dmcgowan): Call close idle connections when complete and use keep alive
DisableKeepAlives: true,
}
proxyDialer, err := sockets.DialerFromEnvironment(direct)
if err == nil {
tr.Dial = proxyDialer.Dial
}
return tr
}
|
go
|
func NewTransport() *http.Transport {
direct := &net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
Dial: direct.Dial,
TLSHandshakeTimeout: 10 * time.Second,
// TODO(dmcgowan): Call close idle connections when complete and use keep alive
DisableKeepAlives: true,
}
proxyDialer, err := sockets.DialerFromEnvironment(direct)
if err == nil {
tr.Dial = proxyDialer.Dial
}
return tr
}
|
[
"func",
"NewTransport",
"(",
")",
"*",
"http",
".",
"Transport",
"{",
"direct",
":=",
"&",
"net",
".",
"Dialer",
"{",
"Timeout",
":",
"30",
"*",
"time",
".",
"Second",
",",
"KeepAlive",
":",
"30",
"*",
"time",
".",
"Second",
",",
"DualStack",
":",
"true",
",",
"}",
"\n",
"tr",
":=",
"&",
"http",
".",
"Transport",
"{",
"Proxy",
":",
"http",
".",
"ProxyFromEnvironment",
",",
"Dial",
":",
"direct",
".",
"Dial",
",",
"TLSHandshakeTimeout",
":",
"10",
"*",
"time",
".",
"Second",
",",
"DisableKeepAlives",
":",
"true",
",",
"}",
"\n",
"proxyDialer",
",",
"err",
":=",
"sockets",
".",
"DialerFromEnvironment",
"(",
"direct",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"tr",
".",
"Dial",
"=",
"proxyDialer",
".",
"Dial",
"\n",
"}",
"\n",
"return",
"tr",
"\n",
"}"
] |
// NewTransport Creates a default transport
|
[
"NewTransport",
"Creates",
"a",
"default",
"transport"
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/tlsclientconfig/tlsclientconfig.go#L94-L112
|
test
|
containers/image
|
pkg/sysregistries/system_registries.go
|
readRegistryConf
|
func readRegistryConf(sys *types.SystemContext) ([]byte, error) {
return ioutil.ReadFile(RegistriesConfPath(sys))
}
|
go
|
func readRegistryConf(sys *types.SystemContext) ([]byte, error) {
return ioutil.ReadFile(RegistriesConfPath(sys))
}
|
[
"func",
"readRegistryConf",
"(",
"sys",
"*",
"types",
".",
"SystemContext",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"return",
"ioutil",
".",
"ReadFile",
"(",
"RegistriesConfPath",
"(",
"sys",
")",
")",
"\n",
"}"
] |
// Reads the global registry file from the filesystem. Returns
// a byte array
|
[
"Reads",
"the",
"global",
"registry",
"file",
"from",
"the",
"filesystem",
".",
"Returns",
"a",
"byte",
"array"
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/sysregistries/system_registries.go#L44-L46
|
test
|
containers/image
|
pkg/sysregistries/system_registries.go
|
GetRegistries
|
func GetRegistries(sys *types.SystemContext) ([]string, error) {
config, err := loadRegistryConf(sys)
if err != nil {
return nil, err
}
return config.Registries.Search.Registries, nil
}
|
go
|
func GetRegistries(sys *types.SystemContext) ([]string, error) {
config, err := loadRegistryConf(sys)
if err != nil {
return nil, err
}
return config.Registries.Search.Registries, nil
}
|
[
"func",
"GetRegistries",
"(",
"sys",
"*",
"types",
".",
"SystemContext",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"config",
",",
"err",
":=",
"loadRegistryConf",
"(",
"sys",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"config",
".",
"Registries",
".",
"Search",
".",
"Registries",
",",
"nil",
"\n",
"}"
] |
// GetRegistries returns an array of strings that contain the names
// of the registries as defined in the system-wide
// registries file. it returns an empty array if none are
// defined
|
[
"GetRegistries",
"returns",
"an",
"array",
"of",
"strings",
"that",
"contain",
"the",
"names",
"of",
"the",
"registries",
"as",
"defined",
"in",
"the",
"system",
"-",
"wide",
"registries",
"file",
".",
"it",
"returns",
"an",
"empty",
"array",
"if",
"none",
"are",
"defined"
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/sysregistries/system_registries.go#L72-L78
|
test
|
containers/image
|
pkg/sysregistries/system_registries.go
|
GetInsecureRegistries
|
func GetInsecureRegistries(sys *types.SystemContext) ([]string, error) {
config, err := loadRegistryConf(sys)
if err != nil {
return nil, err
}
return config.Registries.Insecure.Registries, nil
}
|
go
|
func GetInsecureRegistries(sys *types.SystemContext) ([]string, error) {
config, err := loadRegistryConf(sys)
if err != nil {
return nil, err
}
return config.Registries.Insecure.Registries, nil
}
|
[
"func",
"GetInsecureRegistries",
"(",
"sys",
"*",
"types",
".",
"SystemContext",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"config",
",",
"err",
":=",
"loadRegistryConf",
"(",
"sys",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"config",
".",
"Registries",
".",
"Insecure",
".",
"Registries",
",",
"nil",
"\n",
"}"
] |
// GetInsecureRegistries returns an array of strings that contain the names
// of the insecure registries as defined in the system-wide
// registries file. it returns an empty array if none are
// defined
|
[
"GetInsecureRegistries",
"returns",
"an",
"array",
"of",
"strings",
"that",
"contain",
"the",
"names",
"of",
"the",
"insecure",
"registries",
"as",
"defined",
"in",
"the",
"system",
"-",
"wide",
"registries",
"file",
".",
"it",
"returns",
"an",
"empty",
"array",
"if",
"none",
"are",
"defined"
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/sysregistries/system_registries.go#L84-L90
|
test
|
containers/image
|
pkg/sysregistries/system_registries.go
|
RegistriesConfPath
|
func RegistriesConfPath(ctx *types.SystemContext) string {
path := systemRegistriesConfPath
if ctx != nil {
if ctx.SystemRegistriesConfPath != "" {
path = ctx.SystemRegistriesConfPath
} else if ctx.RootForImplicitAbsolutePaths != "" {
path = filepath.Join(ctx.RootForImplicitAbsolutePaths, systemRegistriesConfPath)
}
}
return path
}
|
go
|
func RegistriesConfPath(ctx *types.SystemContext) string {
path := systemRegistriesConfPath
if ctx != nil {
if ctx.SystemRegistriesConfPath != "" {
path = ctx.SystemRegistriesConfPath
} else if ctx.RootForImplicitAbsolutePaths != "" {
path = filepath.Join(ctx.RootForImplicitAbsolutePaths, systemRegistriesConfPath)
}
}
return path
}
|
[
"func",
"RegistriesConfPath",
"(",
"ctx",
"*",
"types",
".",
"SystemContext",
")",
"string",
"{",
"path",
":=",
"systemRegistriesConfPath",
"\n",
"if",
"ctx",
"!=",
"nil",
"{",
"if",
"ctx",
".",
"SystemRegistriesConfPath",
"!=",
"\"\"",
"{",
"path",
"=",
"ctx",
".",
"SystemRegistriesConfPath",
"\n",
"}",
"else",
"if",
"ctx",
".",
"RootForImplicitAbsolutePaths",
"!=",
"\"\"",
"{",
"path",
"=",
"filepath",
".",
"Join",
"(",
"ctx",
".",
"RootForImplicitAbsolutePaths",
",",
"systemRegistriesConfPath",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"path",
"\n",
"}"
] |
// RegistriesConfPath is the path to the system-wide registry configuration file
|
[
"RegistriesConfPath",
"is",
"the",
"path",
"to",
"the",
"system",
"-",
"wide",
"registry",
"configuration",
"file"
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/sysregistries/system_registries.go#L93-L103
|
test
|
containers/image
|
types/types.go
|
NewOptionalBool
|
func NewOptionalBool(b bool) OptionalBool {
o := OptionalBoolFalse
if b == true {
o = OptionalBoolTrue
}
return o
}
|
go
|
func NewOptionalBool(b bool) OptionalBool {
o := OptionalBoolFalse
if b == true {
o = OptionalBoolTrue
}
return o
}
|
[
"func",
"NewOptionalBool",
"(",
"b",
"bool",
")",
"OptionalBool",
"{",
"o",
":=",
"OptionalBoolFalse",
"\n",
"if",
"b",
"==",
"true",
"{",
"o",
"=",
"OptionalBoolTrue",
"\n",
"}",
"\n",
"return",
"o",
"\n",
"}"
] |
// NewOptionalBool converts the input bool into either OptionalBoolTrue or
// OptionalBoolFalse. The function is meant to avoid boilerplate code of users.
|
[
"NewOptionalBool",
"converts",
"the",
"input",
"bool",
"into",
"either",
"OptionalBoolTrue",
"or",
"OptionalBoolFalse",
".",
"The",
"function",
"is",
"meant",
"to",
"avoid",
"boilerplate",
"code",
"of",
"users",
"."
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/types/types.go#L425-L431
|
test
|
containers/image
|
signature/policy_eval.go
|
changeState
|
func (pc *PolicyContext) changeState(expected, new policyContextState) error {
if pc.state != expected {
return errors.Errorf(`"Invalid PolicyContext state, expected "%s", found "%s"`, expected, pc.state)
}
pc.state = new
return nil
}
|
go
|
func (pc *PolicyContext) changeState(expected, new policyContextState) error {
if pc.state != expected {
return errors.Errorf(`"Invalid PolicyContext state, expected "%s", found "%s"`, expected, pc.state)
}
pc.state = new
return nil
}
|
[
"func",
"(",
"pc",
"*",
"PolicyContext",
")",
"changeState",
"(",
"expected",
",",
"new",
"policyContextState",
")",
"error",
"{",
"if",
"pc",
".",
"state",
"!=",
"expected",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"`\"Invalid PolicyContext state, expected \"%s\", found \"%s\"`",
",",
"expected",
",",
"pc",
".",
"state",
")",
"\n",
"}",
"\n",
"pc",
".",
"state",
"=",
"new",
"\n",
"return",
"nil",
"\n",
"}"
] |
// changeContextState changes pc.state, or fails if the state is unexpected
|
[
"changeContextState",
"changes",
"pc",
".",
"state",
"or",
"fails",
"if",
"the",
"state",
"is",
"unexpected"
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_eval.go#L97-L103
|
test
|
containers/image
|
signature/policy_eval.go
|
Destroy
|
func (pc *PolicyContext) Destroy() error {
if err := pc.changeState(pcReady, pcDestroying); err != nil {
return err
}
// FIXME: destroy
return pc.changeState(pcDestroying, pcDestroyed)
}
|
go
|
func (pc *PolicyContext) Destroy() error {
if err := pc.changeState(pcReady, pcDestroying); err != nil {
return err
}
// FIXME: destroy
return pc.changeState(pcDestroying, pcDestroyed)
}
|
[
"func",
"(",
"pc",
"*",
"PolicyContext",
")",
"Destroy",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"pc",
".",
"changeState",
"(",
"pcReady",
",",
"pcDestroying",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"pc",
".",
"changeState",
"(",
"pcDestroying",
",",
"pcDestroyed",
")",
"\n",
"}"
] |
// Destroy should be called when the user of the context is done with it.
|
[
"Destroy",
"should",
"be",
"called",
"when",
"the",
"user",
"of",
"the",
"context",
"is",
"done",
"with",
"it",
"."
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_eval.go#L120-L126
|
test
|
containers/image
|
signature/policy_eval.go
|
policyIdentityLogName
|
func policyIdentityLogName(ref types.ImageReference) string {
return ref.Transport().Name() + ":" + ref.PolicyConfigurationIdentity()
}
|
go
|
func policyIdentityLogName(ref types.ImageReference) string {
return ref.Transport().Name() + ":" + ref.PolicyConfigurationIdentity()
}
|
[
"func",
"policyIdentityLogName",
"(",
"ref",
"types",
".",
"ImageReference",
")",
"string",
"{",
"return",
"ref",
".",
"Transport",
"(",
")",
".",
"Name",
"(",
")",
"+",
"\":\"",
"+",
"ref",
".",
"PolicyConfigurationIdentity",
"(",
")",
"\n",
"}"
] |
// policyIdentityLogName returns a string description of the image identity for policy purposes.
// ONLY use this for log messages, not for any decisions!
|
[
"policyIdentityLogName",
"returns",
"a",
"string",
"description",
"of",
"the",
"image",
"identity",
"for",
"policy",
"purposes",
".",
"ONLY",
"use",
"this",
"for",
"log",
"messages",
"not",
"for",
"any",
"decisions!"
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_eval.go#L130-L132
|
test
|
containers/image
|
signature/policy_eval.go
|
requirementsForImageRef
|
func (pc *PolicyContext) requirementsForImageRef(ref types.ImageReference) PolicyRequirements {
// Do we have a PolicyTransportScopes for this transport?
transportName := ref.Transport().Name()
if transportScopes, ok := pc.Policy.Transports[transportName]; ok {
// Look for a full match.
identity := ref.PolicyConfigurationIdentity()
if req, ok := transportScopes[identity]; ok {
logrus.Debugf(` Using transport "%s" policy section %s`, transportName, identity)
return req
}
// Look for a match of the possible parent namespaces.
for _, name := range ref.PolicyConfigurationNamespaces() {
if req, ok := transportScopes[name]; ok {
logrus.Debugf(` Using transport "%s" specific policy section %s`, transportName, name)
return req
}
}
// Look for a default match for the transport.
if req, ok := transportScopes[""]; ok {
logrus.Debugf(` Using transport "%s" policy section ""`, transportName)
return req
}
}
logrus.Debugf(" Using default policy section")
return pc.Policy.Default
}
|
go
|
func (pc *PolicyContext) requirementsForImageRef(ref types.ImageReference) PolicyRequirements {
// Do we have a PolicyTransportScopes for this transport?
transportName := ref.Transport().Name()
if transportScopes, ok := pc.Policy.Transports[transportName]; ok {
// Look for a full match.
identity := ref.PolicyConfigurationIdentity()
if req, ok := transportScopes[identity]; ok {
logrus.Debugf(` Using transport "%s" policy section %s`, transportName, identity)
return req
}
// Look for a match of the possible parent namespaces.
for _, name := range ref.PolicyConfigurationNamespaces() {
if req, ok := transportScopes[name]; ok {
logrus.Debugf(` Using transport "%s" specific policy section %s`, transportName, name)
return req
}
}
// Look for a default match for the transport.
if req, ok := transportScopes[""]; ok {
logrus.Debugf(` Using transport "%s" policy section ""`, transportName)
return req
}
}
logrus.Debugf(" Using default policy section")
return pc.Policy.Default
}
|
[
"func",
"(",
"pc",
"*",
"PolicyContext",
")",
"requirementsForImageRef",
"(",
"ref",
"types",
".",
"ImageReference",
")",
"PolicyRequirements",
"{",
"transportName",
":=",
"ref",
".",
"Transport",
"(",
")",
".",
"Name",
"(",
")",
"\n",
"if",
"transportScopes",
",",
"ok",
":=",
"pc",
".",
"Policy",
".",
"Transports",
"[",
"transportName",
"]",
";",
"ok",
"{",
"identity",
":=",
"ref",
".",
"PolicyConfigurationIdentity",
"(",
")",
"\n",
"if",
"req",
",",
"ok",
":=",
"transportScopes",
"[",
"identity",
"]",
";",
"ok",
"{",
"logrus",
".",
"Debugf",
"(",
"` Using transport \"%s\" policy section %s`",
",",
"transportName",
",",
"identity",
")",
"\n",
"return",
"req",
"\n",
"}",
"\n",
"for",
"_",
",",
"name",
":=",
"range",
"ref",
".",
"PolicyConfigurationNamespaces",
"(",
")",
"{",
"if",
"req",
",",
"ok",
":=",
"transportScopes",
"[",
"name",
"]",
";",
"ok",
"{",
"logrus",
".",
"Debugf",
"(",
"` Using transport \"%s\" specific policy section %s`",
",",
"transportName",
",",
"name",
")",
"\n",
"return",
"req",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"req",
",",
"ok",
":=",
"transportScopes",
"[",
"\"\"",
"]",
";",
"ok",
"{",
"logrus",
".",
"Debugf",
"(",
"` Using transport \"%s\" policy section \"\"`",
",",
"transportName",
")",
"\n",
"return",
"req",
"\n",
"}",
"\n",
"}",
"\n",
"logrus",
".",
"Debugf",
"(",
"\" Using default policy section\"",
")",
"\n",
"return",
"pc",
".",
"Policy",
".",
"Default",
"\n",
"}"
] |
// requirementsForImageRef selects the appropriate requirements for ref.
|
[
"requirementsForImageRef",
"selects",
"the",
"appropriate",
"requirements",
"for",
"ref",
"."
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_eval.go#L135-L163
|
test
|
containers/image
|
transports/alltransports/alltransports.go
|
ParseImageName
|
func ParseImageName(imgName string) (types.ImageReference, error) {
parts := strings.SplitN(imgName, ":", 2)
if len(parts) != 2 {
return nil, errors.Errorf(`Invalid image name "%s", expected colon-separated transport:reference`, imgName)
}
transport := transports.Get(parts[0])
if transport == nil {
return nil, errors.Errorf(`Invalid image name "%s", unknown transport "%s"`, imgName, parts[0])
}
return transport.ParseReference(parts[1])
}
|
go
|
func ParseImageName(imgName string) (types.ImageReference, error) {
parts := strings.SplitN(imgName, ":", 2)
if len(parts) != 2 {
return nil, errors.Errorf(`Invalid image name "%s", expected colon-separated transport:reference`, imgName)
}
transport := transports.Get(parts[0])
if transport == nil {
return nil, errors.Errorf(`Invalid image name "%s", unknown transport "%s"`, imgName, parts[0])
}
return transport.ParseReference(parts[1])
}
|
[
"func",
"ParseImageName",
"(",
"imgName",
"string",
")",
"(",
"types",
".",
"ImageReference",
",",
"error",
")",
"{",
"parts",
":=",
"strings",
".",
"SplitN",
"(",
"imgName",
",",
"\":\"",
",",
"2",
")",
"\n",
"if",
"len",
"(",
"parts",
")",
"!=",
"2",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"`Invalid image name \"%s\", expected colon-separated transport:reference`",
",",
"imgName",
")",
"\n",
"}",
"\n",
"transport",
":=",
"transports",
".",
"Get",
"(",
"parts",
"[",
"0",
"]",
")",
"\n",
"if",
"transport",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"`Invalid image name \"%s\", unknown transport \"%s\"`",
",",
"imgName",
",",
"parts",
"[",
"0",
"]",
")",
"\n",
"}",
"\n",
"return",
"transport",
".",
"ParseReference",
"(",
"parts",
"[",
"1",
"]",
")",
"\n",
"}"
] |
// ParseImageName converts a URL-like image name to a types.ImageReference.
|
[
"ParseImageName",
"converts",
"a",
"URL",
"-",
"like",
"image",
"name",
"to",
"a",
"types",
".",
"ImageReference",
"."
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/transports/alltransports/alltransports.go#L24-L34
|
test
|
containers/image
|
manifest/oci.go
|
BlobInfoFromOCI1Descriptor
|
func BlobInfoFromOCI1Descriptor(desc imgspecv1.Descriptor) types.BlobInfo {
return types.BlobInfo{
Digest: desc.Digest,
Size: desc.Size,
URLs: desc.URLs,
Annotations: desc.Annotations,
MediaType: desc.MediaType,
}
}
|
go
|
func BlobInfoFromOCI1Descriptor(desc imgspecv1.Descriptor) types.BlobInfo {
return types.BlobInfo{
Digest: desc.Digest,
Size: desc.Size,
URLs: desc.URLs,
Annotations: desc.Annotations,
MediaType: desc.MediaType,
}
}
|
[
"func",
"BlobInfoFromOCI1Descriptor",
"(",
"desc",
"imgspecv1",
".",
"Descriptor",
")",
"types",
".",
"BlobInfo",
"{",
"return",
"types",
".",
"BlobInfo",
"{",
"Digest",
":",
"desc",
".",
"Digest",
",",
"Size",
":",
"desc",
".",
"Size",
",",
"URLs",
":",
"desc",
".",
"URLs",
",",
"Annotations",
":",
"desc",
".",
"Annotations",
",",
"MediaType",
":",
"desc",
".",
"MediaType",
",",
"}",
"\n",
"}"
] |
// BlobInfoFromOCI1Descriptor returns a types.BlobInfo based on the input OCI1 descriptor.
|
[
"BlobInfoFromOCI1Descriptor",
"returns",
"a",
"types",
".",
"BlobInfo",
"based",
"on",
"the",
"input",
"OCI1",
"descriptor",
"."
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/manifest/oci.go#L14-L22
|
test
|
containers/image
|
manifest/oci.go
|
OCI1FromManifest
|
func OCI1FromManifest(manifest []byte) (*OCI1, error) {
oci1 := OCI1{}
if err := json.Unmarshal(manifest, &oci1); err != nil {
return nil, err
}
return &oci1, nil
}
|
go
|
func OCI1FromManifest(manifest []byte) (*OCI1, error) {
oci1 := OCI1{}
if err := json.Unmarshal(manifest, &oci1); err != nil {
return nil, err
}
return &oci1, nil
}
|
[
"func",
"OCI1FromManifest",
"(",
"manifest",
"[",
"]",
"byte",
")",
"(",
"*",
"OCI1",
",",
"error",
")",
"{",
"oci1",
":=",
"OCI1",
"{",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"manifest",
",",
"&",
"oci1",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"oci1",
",",
"nil",
"\n",
"}"
] |
// OCI1FromManifest creates an OCI1 manifest instance from a manifest blob.
|
[
"OCI1FromManifest",
"creates",
"an",
"OCI1",
"manifest",
"instance",
"from",
"a",
"manifest",
"blob",
"."
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/manifest/oci.go#L31-L37
|
test
|
containers/image
|
manifest/oci.go
|
OCI1FromComponents
|
func OCI1FromComponents(config imgspecv1.Descriptor, layers []imgspecv1.Descriptor) *OCI1 {
return &OCI1{
imgspecv1.Manifest{
Versioned: specs.Versioned{SchemaVersion: 2},
Config: config,
Layers: layers,
},
}
}
|
go
|
func OCI1FromComponents(config imgspecv1.Descriptor, layers []imgspecv1.Descriptor) *OCI1 {
return &OCI1{
imgspecv1.Manifest{
Versioned: specs.Versioned{SchemaVersion: 2},
Config: config,
Layers: layers,
},
}
}
|
[
"func",
"OCI1FromComponents",
"(",
"config",
"imgspecv1",
".",
"Descriptor",
",",
"layers",
"[",
"]",
"imgspecv1",
".",
"Descriptor",
")",
"*",
"OCI1",
"{",
"return",
"&",
"OCI1",
"{",
"imgspecv1",
".",
"Manifest",
"{",
"Versioned",
":",
"specs",
".",
"Versioned",
"{",
"SchemaVersion",
":",
"2",
"}",
",",
"Config",
":",
"config",
",",
"Layers",
":",
"layers",
",",
"}",
",",
"}",
"\n",
"}"
] |
// OCI1FromComponents creates an OCI1 manifest instance from the supplied data.
|
[
"OCI1FromComponents",
"creates",
"an",
"OCI1",
"manifest",
"instance",
"from",
"the",
"supplied",
"data",
"."
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/manifest/oci.go#L40-L48
|
test
|
containers/image
|
docker/docker_transport.go
|
newReference
|
func newReference(ref reference.Named) (dockerReference, error) {
if reference.IsNameOnly(ref) {
return dockerReference{}, errors.Errorf("Docker reference %s has neither a tag nor a digest", reference.FamiliarString(ref))
}
// A github.com/distribution/reference value can have a tag and a digest at the same time!
// The docker/distribution API does not really support that (we can’t ask for an image with a specific
// tag and digest), so fail. This MAY be accepted in the future.
// (Even if it were supported, the semantics of policy namespaces are unclear - should we drop
// the tag or the digest first?)
_, isTagged := ref.(reference.NamedTagged)
_, isDigested := ref.(reference.Canonical)
if isTagged && isDigested {
return dockerReference{}, errors.Errorf("Docker references with both a tag and digest are currently not supported")
}
return dockerReference{
ref: ref,
}, nil
}
|
go
|
func newReference(ref reference.Named) (dockerReference, error) {
if reference.IsNameOnly(ref) {
return dockerReference{}, errors.Errorf("Docker reference %s has neither a tag nor a digest", reference.FamiliarString(ref))
}
// A github.com/distribution/reference value can have a tag and a digest at the same time!
// The docker/distribution API does not really support that (we can’t ask for an image with a specific
// tag and digest), so fail. This MAY be accepted in the future.
// (Even if it were supported, the semantics of policy namespaces are unclear - should we drop
// the tag or the digest first?)
_, isTagged := ref.(reference.NamedTagged)
_, isDigested := ref.(reference.Canonical)
if isTagged && isDigested {
return dockerReference{}, errors.Errorf("Docker references with both a tag and digest are currently not supported")
}
return dockerReference{
ref: ref,
}, nil
}
|
[
"func",
"newReference",
"(",
"ref",
"reference",
".",
"Named",
")",
"(",
"dockerReference",
",",
"error",
")",
"{",
"if",
"reference",
".",
"IsNameOnly",
"(",
"ref",
")",
"{",
"return",
"dockerReference",
"{",
"}",
",",
"errors",
".",
"Errorf",
"(",
"\"Docker reference %s has neither a tag nor a digest\"",
",",
"reference",
".",
"FamiliarString",
"(",
"ref",
")",
")",
"\n",
"}",
"\n",
"_",
",",
"isTagged",
":=",
"ref",
".",
"(",
"reference",
".",
"NamedTagged",
")",
"\n",
"_",
",",
"isDigested",
":=",
"ref",
".",
"(",
"reference",
".",
"Canonical",
")",
"\n",
"if",
"isTagged",
"&&",
"isDigested",
"{",
"return",
"dockerReference",
"{",
"}",
",",
"errors",
".",
"Errorf",
"(",
"\"Docker references with both a tag and digest are currently not supported\"",
")",
"\n",
"}",
"\n",
"return",
"dockerReference",
"{",
"ref",
":",
"ref",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// newReference returns a dockerReference for a named reference.
|
[
"newReference",
"returns",
"a",
"dockerReference",
"for",
"a",
"named",
"reference",
"."
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_transport.go#L68-L86
|
test
|
containers/image
|
docker/docker_transport.go
|
tagOrDigest
|
func (ref dockerReference) tagOrDigest() (string, error) {
if ref, ok := ref.ref.(reference.Canonical); ok {
return ref.Digest().String(), nil
}
if ref, ok := ref.ref.(reference.NamedTagged); ok {
return ref.Tag(), nil
}
// This should not happen, NewReference above refuses reference.IsNameOnly values.
return "", errors.Errorf("Internal inconsistency: Reference %s unexpectedly has neither a digest nor a tag", reference.FamiliarString(ref.ref))
}
|
go
|
func (ref dockerReference) tagOrDigest() (string, error) {
if ref, ok := ref.ref.(reference.Canonical); ok {
return ref.Digest().String(), nil
}
if ref, ok := ref.ref.(reference.NamedTagged); ok {
return ref.Tag(), nil
}
// This should not happen, NewReference above refuses reference.IsNameOnly values.
return "", errors.Errorf("Internal inconsistency: Reference %s unexpectedly has neither a digest nor a tag", reference.FamiliarString(ref.ref))
}
|
[
"func",
"(",
"ref",
"dockerReference",
")",
"tagOrDigest",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"ref",
",",
"ok",
":=",
"ref",
".",
"ref",
".",
"(",
"reference",
".",
"Canonical",
")",
";",
"ok",
"{",
"return",
"ref",
".",
"Digest",
"(",
")",
".",
"String",
"(",
")",
",",
"nil",
"\n",
"}",
"\n",
"if",
"ref",
",",
"ok",
":=",
"ref",
".",
"ref",
".",
"(",
"reference",
".",
"NamedTagged",
")",
";",
"ok",
"{",
"return",
"ref",
".",
"Tag",
"(",
")",
",",
"nil",
"\n",
"}",
"\n",
"return",
"\"\"",
",",
"errors",
".",
"Errorf",
"(",
"\"Internal inconsistency: Reference %s unexpectedly has neither a digest nor a tag\"",
",",
"reference",
".",
"FamiliarString",
"(",
"ref",
".",
"ref",
")",
")",
"\n",
"}"
] |
// tagOrDigest returns a tag or digest from the reference.
|
[
"tagOrDigest",
"returns",
"a",
"tag",
"or",
"digest",
"from",
"the",
"reference",
"."
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_transport.go#L159-L168
|
test
|
containers/image
|
copy/copy.go
|
updateEmbeddedDockerReference
|
func (ic *imageCopier) updateEmbeddedDockerReference() error {
if ic.c.dest.IgnoresEmbeddedDockerReference() {
return nil // Destination would prefer us not to update the embedded reference.
}
destRef := ic.c.dest.Reference().DockerReference()
if destRef == nil {
return nil // Destination does not care about Docker references
}
if !ic.src.EmbeddedDockerReferenceConflicts(destRef) {
return nil // No reference embedded in the manifest, or it matches destRef already.
}
if !ic.canModifyManifest {
return errors.Errorf("Copying a schema1 image with an embedded Docker reference to %s (Docker reference %s) would invalidate existing signatures. Explicitly enable signature removal to proceed anyway",
transports.ImageName(ic.c.dest.Reference()), destRef.String())
}
ic.manifestUpdates.EmbeddedDockerReference = destRef
return nil
}
|
go
|
func (ic *imageCopier) updateEmbeddedDockerReference() error {
if ic.c.dest.IgnoresEmbeddedDockerReference() {
return nil // Destination would prefer us not to update the embedded reference.
}
destRef := ic.c.dest.Reference().DockerReference()
if destRef == nil {
return nil // Destination does not care about Docker references
}
if !ic.src.EmbeddedDockerReferenceConflicts(destRef) {
return nil // No reference embedded in the manifest, or it matches destRef already.
}
if !ic.canModifyManifest {
return errors.Errorf("Copying a schema1 image with an embedded Docker reference to %s (Docker reference %s) would invalidate existing signatures. Explicitly enable signature removal to proceed anyway",
transports.ImageName(ic.c.dest.Reference()), destRef.String())
}
ic.manifestUpdates.EmbeddedDockerReference = destRef
return nil
}
|
[
"func",
"(",
"ic",
"*",
"imageCopier",
")",
"updateEmbeddedDockerReference",
"(",
")",
"error",
"{",
"if",
"ic",
".",
"c",
".",
"dest",
".",
"IgnoresEmbeddedDockerReference",
"(",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"destRef",
":=",
"ic",
".",
"c",
".",
"dest",
".",
"Reference",
"(",
")",
".",
"DockerReference",
"(",
")",
"\n",
"if",
"destRef",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"!",
"ic",
".",
"src",
".",
"EmbeddedDockerReferenceConflicts",
"(",
"destRef",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"!",
"ic",
".",
"canModifyManifest",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"Copying a schema1 image with an embedded Docker reference to %s (Docker reference %s) would invalidate existing signatures. Explicitly enable signature removal to proceed anyway\"",
",",
"transports",
".",
"ImageName",
"(",
"ic",
".",
"c",
".",
"dest",
".",
"Reference",
"(",
")",
")",
",",
"destRef",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"ic",
".",
"manifestUpdates",
".",
"EmbeddedDockerReference",
"=",
"destRef",
"\n",
"return",
"nil",
"\n",
"}"
] |
// updateEmbeddedDockerReference handles the Docker reference embedded in Docker schema1 manifests.
|
[
"updateEmbeddedDockerReference",
"handles",
"the",
"Docker",
"reference",
"embedded",
"in",
"Docker",
"schema1",
"manifests",
"."
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/copy/copy.go#L406-L424
|
test
|
containers/image
|
copy/copy.go
|
isTTY
|
func isTTY(w io.Writer) bool {
if f, ok := w.(*os.File); ok {
return terminal.IsTerminal(int(f.Fd()))
}
return false
}
|
go
|
func isTTY(w io.Writer) bool {
if f, ok := w.(*os.File); ok {
return terminal.IsTerminal(int(f.Fd()))
}
return false
}
|
[
"func",
"isTTY",
"(",
"w",
"io",
".",
"Writer",
")",
"bool",
"{",
"if",
"f",
",",
"ok",
":=",
"w",
".",
"(",
"*",
"os",
".",
"File",
")",
";",
"ok",
"{",
"return",
"terminal",
".",
"IsTerminal",
"(",
"int",
"(",
"f",
".",
"Fd",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// isTTY returns true if the io.Writer is a file and a tty.
|
[
"isTTY",
"returns",
"true",
"if",
"the",
"io",
".",
"Writer",
"is",
"a",
"file",
"and",
"a",
"tty",
"."
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/copy/copy.go#L427-L432
|
test
|
containers/image
|
copy/copy.go
|
copyUpdatedConfigAndManifest
|
func (ic *imageCopier) copyUpdatedConfigAndManifest(ctx context.Context) ([]byte, error) {
pendingImage := ic.src
if !reflect.DeepEqual(*ic.manifestUpdates, types.ManifestUpdateOptions{InformationOnly: ic.manifestUpdates.InformationOnly}) {
if !ic.canModifyManifest {
return nil, errors.Errorf("Internal error: copy needs an updated manifest but that was known to be forbidden")
}
if !ic.diffIDsAreNeeded && ic.src.UpdatedImageNeedsLayerDiffIDs(*ic.manifestUpdates) {
// We have set ic.diffIDsAreNeeded based on the preferred MIME type returned by determineManifestConversion.
// So, this can only happen if we are trying to upload using one of the other MIME type candidates.
// Because UpdatedImageNeedsLayerDiffIDs is true only when converting from s1 to s2, this case should only arise
// when ic.c.dest.SupportedManifestMIMETypes() includes both s1 and s2, the upload using s1 failed, and we are now trying s2.
// Supposedly s2-only registries do not exist or are extremely rare, so failing with this error message is good enough for now.
// If handling such registries turns out to be necessary, we could compute ic.diffIDsAreNeeded based on the full list of manifest MIME type candidates.
return nil, errors.Errorf("Can not convert image to %s, preparing DiffIDs for this case is not supported", ic.manifestUpdates.ManifestMIMEType)
}
pi, err := ic.src.UpdatedImage(ctx, *ic.manifestUpdates)
if err != nil {
return nil, errors.Wrap(err, "Error creating an updated image manifest")
}
pendingImage = pi
}
manifest, _, err := pendingImage.Manifest(ctx)
if err != nil {
return nil, errors.Wrap(err, "Error reading manifest")
}
if err := ic.c.copyConfig(ctx, pendingImage); err != nil {
return nil, err
}
ic.c.Printf("Writing manifest to image destination\n")
if err := ic.c.dest.PutManifest(ctx, manifest); err != nil {
return nil, errors.Wrap(err, "Error writing manifest")
}
return manifest, nil
}
|
go
|
func (ic *imageCopier) copyUpdatedConfigAndManifest(ctx context.Context) ([]byte, error) {
pendingImage := ic.src
if !reflect.DeepEqual(*ic.manifestUpdates, types.ManifestUpdateOptions{InformationOnly: ic.manifestUpdates.InformationOnly}) {
if !ic.canModifyManifest {
return nil, errors.Errorf("Internal error: copy needs an updated manifest but that was known to be forbidden")
}
if !ic.diffIDsAreNeeded && ic.src.UpdatedImageNeedsLayerDiffIDs(*ic.manifestUpdates) {
// We have set ic.diffIDsAreNeeded based on the preferred MIME type returned by determineManifestConversion.
// So, this can only happen if we are trying to upload using one of the other MIME type candidates.
// Because UpdatedImageNeedsLayerDiffIDs is true only when converting from s1 to s2, this case should only arise
// when ic.c.dest.SupportedManifestMIMETypes() includes both s1 and s2, the upload using s1 failed, and we are now trying s2.
// Supposedly s2-only registries do not exist or are extremely rare, so failing with this error message is good enough for now.
// If handling such registries turns out to be necessary, we could compute ic.diffIDsAreNeeded based on the full list of manifest MIME type candidates.
return nil, errors.Errorf("Can not convert image to %s, preparing DiffIDs for this case is not supported", ic.manifestUpdates.ManifestMIMEType)
}
pi, err := ic.src.UpdatedImage(ctx, *ic.manifestUpdates)
if err != nil {
return nil, errors.Wrap(err, "Error creating an updated image manifest")
}
pendingImage = pi
}
manifest, _, err := pendingImage.Manifest(ctx)
if err != nil {
return nil, errors.Wrap(err, "Error reading manifest")
}
if err := ic.c.copyConfig(ctx, pendingImage); err != nil {
return nil, err
}
ic.c.Printf("Writing manifest to image destination\n")
if err := ic.c.dest.PutManifest(ctx, manifest); err != nil {
return nil, errors.Wrap(err, "Error writing manifest")
}
return manifest, nil
}
|
[
"func",
"(",
"ic",
"*",
"imageCopier",
")",
"copyUpdatedConfigAndManifest",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"pendingImage",
":=",
"ic",
".",
"src",
"\n",
"if",
"!",
"reflect",
".",
"DeepEqual",
"(",
"*",
"ic",
".",
"manifestUpdates",
",",
"types",
".",
"ManifestUpdateOptions",
"{",
"InformationOnly",
":",
"ic",
".",
"manifestUpdates",
".",
"InformationOnly",
"}",
")",
"{",
"if",
"!",
"ic",
".",
"canModifyManifest",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"Internal error: copy needs an updated manifest but that was known to be forbidden\"",
")",
"\n",
"}",
"\n",
"if",
"!",
"ic",
".",
"diffIDsAreNeeded",
"&&",
"ic",
".",
"src",
".",
"UpdatedImageNeedsLayerDiffIDs",
"(",
"*",
"ic",
".",
"manifestUpdates",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"Errorf",
"(",
"\"Can not convert image to %s, preparing DiffIDs for this case is not supported\"",
",",
"ic",
".",
"manifestUpdates",
".",
"ManifestMIMEType",
")",
"\n",
"}",
"\n",
"pi",
",",
"err",
":=",
"ic",
".",
"src",
".",
"UpdatedImage",
"(",
"ctx",
",",
"*",
"ic",
".",
"manifestUpdates",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Error creating an updated image manifest\"",
")",
"\n",
"}",
"\n",
"pendingImage",
"=",
"pi",
"\n",
"}",
"\n",
"manifest",
",",
"_",
",",
"err",
":=",
"pendingImage",
".",
"Manifest",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Error reading manifest\"",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"ic",
".",
"c",
".",
"copyConfig",
"(",
"ctx",
",",
"pendingImage",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"ic",
".",
"c",
".",
"Printf",
"(",
"\"Writing manifest to image destination\\n\"",
")",
"\n",
"\\n",
"\n",
"if",
"err",
":=",
"ic",
".",
"c",
".",
"dest",
".",
"PutManifest",
"(",
"ctx",
",",
"manifest",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Wrap",
"(",
"err",
",",
"\"Error writing manifest\"",
")",
"\n",
"}",
"\n",
"}"
] |
// copyUpdatedConfigAndManifest updates the image per ic.manifestUpdates, if necessary,
// stores the resulting config and manifest to the destination, and returns the stored manifest.
|
[
"copyUpdatedConfigAndManifest",
"updates",
"the",
"image",
"per",
"ic",
".",
"manifestUpdates",
"if",
"necessary",
"stores",
"the",
"resulting",
"config",
"and",
"manifest",
"to",
"the",
"destination",
"and",
"returns",
"the",
"stored",
"manifest",
"."
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/copy/copy.go#L539-L574
|
test
|
containers/image
|
copy/copy.go
|
createProgressBar
|
func (c *copier) createProgressBar(pool *mpb.Progress, info types.BlobInfo, kind string, onComplete string) *mpb.Bar {
// shortDigestLen is the length of the digest used for blobs.
const shortDigestLen = 12
prefix := fmt.Sprintf("Copying %s %s", kind, info.Digest.Encoded())
// Truncate the prefix (chopping of some part of the digest) to make all progress bars aligned in a column.
maxPrefixLen := len("Copying blob ") + shortDigestLen
if len(prefix) > maxPrefixLen {
prefix = prefix[:maxPrefixLen]
}
bar := pool.AddBar(info.Size,
mpb.BarClearOnComplete(),
mpb.PrependDecorators(
decor.Name(prefix),
),
mpb.AppendDecorators(
decor.OnComplete(decor.CountersKibiByte("%.1f / %.1f"), " "+onComplete),
),
)
if c.progressOutput == ioutil.Discard {
c.Printf("Copying %s %s\n", kind, info.Digest)
}
return bar
}
|
go
|
func (c *copier) createProgressBar(pool *mpb.Progress, info types.BlobInfo, kind string, onComplete string) *mpb.Bar {
// shortDigestLen is the length of the digest used for blobs.
const shortDigestLen = 12
prefix := fmt.Sprintf("Copying %s %s", kind, info.Digest.Encoded())
// Truncate the prefix (chopping of some part of the digest) to make all progress bars aligned in a column.
maxPrefixLen := len("Copying blob ") + shortDigestLen
if len(prefix) > maxPrefixLen {
prefix = prefix[:maxPrefixLen]
}
bar := pool.AddBar(info.Size,
mpb.BarClearOnComplete(),
mpb.PrependDecorators(
decor.Name(prefix),
),
mpb.AppendDecorators(
decor.OnComplete(decor.CountersKibiByte("%.1f / %.1f"), " "+onComplete),
),
)
if c.progressOutput == ioutil.Discard {
c.Printf("Copying %s %s\n", kind, info.Digest)
}
return bar
}
|
[
"func",
"(",
"c",
"*",
"copier",
")",
"createProgressBar",
"(",
"pool",
"*",
"mpb",
".",
"Progress",
",",
"info",
"types",
".",
"BlobInfo",
",",
"kind",
"string",
",",
"onComplete",
"string",
")",
"*",
"mpb",
".",
"Bar",
"{",
"const",
"shortDigestLen",
"=",
"12",
"\n",
"prefix",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"Copying %s %s\"",
",",
"kind",
",",
"info",
".",
"Digest",
".",
"Encoded",
"(",
")",
")",
"\n",
"maxPrefixLen",
":=",
"len",
"(",
"\"Copying blob \"",
")",
"+",
"shortDigestLen",
"\n",
"if",
"len",
"(",
"prefix",
")",
">",
"maxPrefixLen",
"{",
"prefix",
"=",
"prefix",
"[",
":",
"maxPrefixLen",
"]",
"\n",
"}",
"\n",
"bar",
":=",
"pool",
".",
"AddBar",
"(",
"info",
".",
"Size",
",",
"mpb",
".",
"BarClearOnComplete",
"(",
")",
",",
"mpb",
".",
"PrependDecorators",
"(",
"decor",
".",
"Name",
"(",
"prefix",
")",
",",
")",
",",
"mpb",
".",
"AppendDecorators",
"(",
"decor",
".",
"OnComplete",
"(",
"decor",
".",
"CountersKibiByte",
"(",
"\"%.1f / %.1f\"",
")",
",",
"\" \"",
"+",
"onComplete",
")",
",",
")",
",",
")",
"\n",
"if",
"c",
".",
"progressOutput",
"==",
"ioutil",
".",
"Discard",
"{",
"c",
".",
"Printf",
"(",
"\"Copying %s %s\\n\"",
",",
"\\n",
",",
"kind",
")",
"\n",
"}",
"\n",
"info",
".",
"Digest",
"\n",
"}"
] |
// createProgressBar creates a mpb.Bar in pool. Note that if the copier's reportWriter
// is ioutil.Discard, the progress bar's output will be discarded
|
[
"createProgressBar",
"creates",
"a",
"mpb",
".",
"Bar",
"in",
"pool",
".",
"Note",
"that",
"if",
"the",
"copier",
"s",
"reportWriter",
"is",
"ioutil",
".",
"Discard",
"the",
"progress",
"bar",
"s",
"output",
"will",
"be",
"discarded"
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/copy/copy.go#L589-L613
|
test
|
containers/image
|
copy/copy.go
|
copyConfig
|
func (c *copier) copyConfig(ctx context.Context, src types.Image) error {
srcInfo := src.ConfigInfo()
if srcInfo.Digest != "" {
configBlob, err := src.ConfigBlob(ctx)
if err != nil {
return errors.Wrapf(err, "Error reading config blob %s", srcInfo.Digest)
}
destInfo, err := func() (types.BlobInfo, error) { // A scope for defer
progressPool, progressCleanup := c.newProgressPool(ctx)
defer progressCleanup()
bar := c.createProgressBar(progressPool, srcInfo, "config", "done")
destInfo, err := c.copyBlobFromStream(ctx, bytes.NewReader(configBlob), srcInfo, nil, false, true, bar)
if err != nil {
return types.BlobInfo{}, err
}
bar.SetTotal(int64(len(configBlob)), true)
return destInfo, nil
}()
if err != nil {
return nil
}
if destInfo.Digest != srcInfo.Digest {
return errors.Errorf("Internal error: copying uncompressed config blob %s changed digest to %s", srcInfo.Digest, destInfo.Digest)
}
}
return nil
}
|
go
|
func (c *copier) copyConfig(ctx context.Context, src types.Image) error {
srcInfo := src.ConfigInfo()
if srcInfo.Digest != "" {
configBlob, err := src.ConfigBlob(ctx)
if err != nil {
return errors.Wrapf(err, "Error reading config blob %s", srcInfo.Digest)
}
destInfo, err := func() (types.BlobInfo, error) { // A scope for defer
progressPool, progressCleanup := c.newProgressPool(ctx)
defer progressCleanup()
bar := c.createProgressBar(progressPool, srcInfo, "config", "done")
destInfo, err := c.copyBlobFromStream(ctx, bytes.NewReader(configBlob), srcInfo, nil, false, true, bar)
if err != nil {
return types.BlobInfo{}, err
}
bar.SetTotal(int64(len(configBlob)), true)
return destInfo, nil
}()
if err != nil {
return nil
}
if destInfo.Digest != srcInfo.Digest {
return errors.Errorf("Internal error: copying uncompressed config blob %s changed digest to %s", srcInfo.Digest, destInfo.Digest)
}
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"copier",
")",
"copyConfig",
"(",
"ctx",
"context",
".",
"Context",
",",
"src",
"types",
".",
"Image",
")",
"error",
"{",
"srcInfo",
":=",
"src",
".",
"ConfigInfo",
"(",
")",
"\n",
"if",
"srcInfo",
".",
"Digest",
"!=",
"\"\"",
"{",
"configBlob",
",",
"err",
":=",
"src",
".",
"ConfigBlob",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Wrapf",
"(",
"err",
",",
"\"Error reading config blob %s\"",
",",
"srcInfo",
".",
"Digest",
")",
"\n",
"}",
"\n",
"destInfo",
",",
"err",
":=",
"func",
"(",
")",
"(",
"types",
".",
"BlobInfo",
",",
"error",
")",
"{",
"progressPool",
",",
"progressCleanup",
":=",
"c",
".",
"newProgressPool",
"(",
"ctx",
")",
"\n",
"defer",
"progressCleanup",
"(",
")",
"\n",
"bar",
":=",
"c",
".",
"createProgressBar",
"(",
"progressPool",
",",
"srcInfo",
",",
"\"config\"",
",",
"\"done\"",
")",
"\n",
"destInfo",
",",
"err",
":=",
"c",
".",
"copyBlobFromStream",
"(",
"ctx",
",",
"bytes",
".",
"NewReader",
"(",
"configBlob",
")",
",",
"srcInfo",
",",
"nil",
",",
"false",
",",
"true",
",",
"bar",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"types",
".",
"BlobInfo",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"bar",
".",
"SetTotal",
"(",
"int64",
"(",
"len",
"(",
"configBlob",
")",
")",
",",
"true",
")",
"\n",
"return",
"destInfo",
",",
"nil",
"\n",
"}",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"destInfo",
".",
"Digest",
"!=",
"srcInfo",
".",
"Digest",
"{",
"return",
"errors",
".",
"Errorf",
"(",
"\"Internal error: copying uncompressed config blob %s changed digest to %s\"",
",",
"srcInfo",
".",
"Digest",
",",
"destInfo",
".",
"Digest",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// copyConfig copies config.json, if any, from src to dest.
|
[
"copyConfig",
"copies",
"config",
".",
"json",
"if",
"any",
"from",
"src",
"to",
"dest",
"."
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/copy/copy.go#L616-L643
|
test
|
containers/image
|
copy/copy.go
|
diffIDComputationGoroutine
|
func diffIDComputationGoroutine(dest chan<- diffIDResult, layerStream io.ReadCloser, decompressor compression.DecompressorFunc) {
result := diffIDResult{
digest: "",
err: errors.New("Internal error: unexpected panic in diffIDComputationGoroutine"),
}
defer func() { dest <- result }()
defer layerStream.Close() // We do not care to bother the other end of the pipe with other failures; we send them to dest instead.
result.digest, result.err = computeDiffID(layerStream, decompressor)
}
|
go
|
func diffIDComputationGoroutine(dest chan<- diffIDResult, layerStream io.ReadCloser, decompressor compression.DecompressorFunc) {
result := diffIDResult{
digest: "",
err: errors.New("Internal error: unexpected panic in diffIDComputationGoroutine"),
}
defer func() { dest <- result }()
defer layerStream.Close() // We do not care to bother the other end of the pipe with other failures; we send them to dest instead.
result.digest, result.err = computeDiffID(layerStream, decompressor)
}
|
[
"func",
"diffIDComputationGoroutine",
"(",
"dest",
"chan",
"<-",
"diffIDResult",
",",
"layerStream",
"io",
".",
"ReadCloser",
",",
"decompressor",
"compression",
".",
"DecompressorFunc",
")",
"{",
"result",
":=",
"diffIDResult",
"{",
"digest",
":",
"\"\"",
",",
"err",
":",
"errors",
".",
"New",
"(",
"\"Internal error: unexpected panic in diffIDComputationGoroutine\"",
")",
",",
"}",
"\n",
"defer",
"func",
"(",
")",
"{",
"dest",
"<-",
"result",
"}",
"(",
")",
"\n",
"defer",
"layerStream",
".",
"Close",
"(",
")",
"\n",
"result",
".",
"digest",
",",
"result",
".",
"err",
"=",
"computeDiffID",
"(",
"layerStream",
",",
"decompressor",
")",
"\n",
"}"
] |
// diffIDComputationGoroutine reads all input from layerStream, uncompresses using decompressor if necessary, and sends its digest, and status, if any, to dest.
|
[
"diffIDComputationGoroutine",
"reads",
"all",
"input",
"from",
"layerStream",
"uncompresses",
"using",
"decompressor",
"if",
"necessary",
"and",
"sends",
"its",
"digest",
"and",
"status",
"if",
"any",
"to",
"dest",
"."
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/copy/copy.go#L742-L751
|
test
|
containers/image
|
copy/copy.go
|
computeDiffID
|
func computeDiffID(stream io.Reader, decompressor compression.DecompressorFunc) (digest.Digest, error) {
if decompressor != nil {
s, err := decompressor(stream)
if err != nil {
return "", err
}
defer s.Close()
stream = s
}
return digest.Canonical.FromReader(stream)
}
|
go
|
func computeDiffID(stream io.Reader, decompressor compression.DecompressorFunc) (digest.Digest, error) {
if decompressor != nil {
s, err := decompressor(stream)
if err != nil {
return "", err
}
defer s.Close()
stream = s
}
return digest.Canonical.FromReader(stream)
}
|
[
"func",
"computeDiffID",
"(",
"stream",
"io",
".",
"Reader",
",",
"decompressor",
"compression",
".",
"DecompressorFunc",
")",
"(",
"digest",
".",
"Digest",
",",
"error",
")",
"{",
"if",
"decompressor",
"!=",
"nil",
"{",
"s",
",",
"err",
":=",
"decompressor",
"(",
"stream",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"defer",
"s",
".",
"Close",
"(",
")",
"\n",
"stream",
"=",
"s",
"\n",
"}",
"\n",
"return",
"digest",
".",
"Canonical",
".",
"FromReader",
"(",
"stream",
")",
"\n",
"}"
] |
// computeDiffID reads all input from layerStream, uncompresses it using decompressor if necessary, and returns its digest.
|
[
"computeDiffID",
"reads",
"all",
"input",
"from",
"layerStream",
"uncompresses",
"it",
"using",
"decompressor",
"if",
"necessary",
"and",
"returns",
"its",
"digest",
"."
] |
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
|
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/copy/copy.go#L754-L765
|
test
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.