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
containers/image
copy/copy.go
compressGoroutine
func compressGoroutine(dest *io.PipeWriter, src io.Reader) { err := errors.New("Internal error: unexpected panic in compressGoroutine") defer func() { // Note that this is not the same as {defer dest.CloseWithError(err)}; we need err to be evaluated lazily. dest.CloseWithError(err) // CloseWithError(nil) is equivalent to Close() }() zipper := pgzip.NewWriter(dest) defer zipper.Close() _, err = io.Copy(zipper, src) // Sets err to nil, i.e. causes dest.Close() }
go
func compressGoroutine(dest *io.PipeWriter, src io.Reader) { err := errors.New("Internal error: unexpected panic in compressGoroutine") defer func() { // Note that this is not the same as {defer dest.CloseWithError(err)}; we need err to be evaluated lazily. dest.CloseWithError(err) // CloseWithError(nil) is equivalent to Close() }() zipper := pgzip.NewWriter(dest) defer zipper.Close() _, err = io.Copy(zipper, src) // Sets err to nil, i.e. causes dest.Close() }
[ "func", "compressGoroutine", "(", "dest", "*", "io", ".", "PipeWriter", ",", "src", "io", ".", "Reader", ")", "{", "err", ":=", "errors", ".", "New", "(", "\"Internal error: unexpected panic in compressGoroutine\"", ")", "\n", "defer", "func", "(", ")", "{", "dest", ".", "CloseWithError", "(", "err", ")", "\n", "}", "(", ")", "\n", "zipper", ":=", "pgzip", ".", "NewWriter", "(", "dest", ")", "\n", "defer", "zipper", ".", "Close", "(", ")", "\n", "_", ",", "err", "=", "io", ".", "Copy", "(", "zipper", ",", "src", ")", "\n", "}" ]
// compressGoroutine reads all input from src and writes its compressed equivalent to dest.
[ "compressGoroutine", "reads", "all", "input", "from", "src", "and", "writes", "its", "compressed", "equivalent", "to", "dest", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/copy/copy.go#L893-L903
test
containers/image
docker/daemon/client.go
newDockerClient
func newDockerClient(sys *types.SystemContext) (*dockerclient.Client, error) { host := dockerclient.DefaultDockerHost if sys != nil && sys.DockerDaemonHost != "" { host = sys.DockerDaemonHost } // Sadly, unix:// sockets don't work transparently with dockerclient.NewClient. // They work fine with a nil httpClient; with a non-nil httpClient, the transport’s // TLSClientConfig must be nil (or the client will try using HTTPS over the PF_UNIX socket // regardless of the values in the *tls.Config), and we would have to call sockets.ConfigureTransport. // // We don't really want to configure anything for unix:// sockets, so just pass a nil *http.Client. // // Similarly, if we want to communicate over plain HTTP on a TCP socket, we also need to set // TLSClientConfig to nil. This can be achieved by using the form `http://` url, err := dockerclient.ParseHostURL(host) if err != nil { return nil, err } var httpClient *http.Client if url.Scheme != "unix" { if url.Scheme == "http" { httpClient = httpConfig() } else { hc, err := tlsConfig(sys) if err != nil { return nil, err } httpClient = hc } } return dockerclient.NewClient(host, defaultAPIVersion, httpClient, nil) }
go
func newDockerClient(sys *types.SystemContext) (*dockerclient.Client, error) { host := dockerclient.DefaultDockerHost if sys != nil && sys.DockerDaemonHost != "" { host = sys.DockerDaemonHost } // Sadly, unix:// sockets don't work transparently with dockerclient.NewClient. // They work fine with a nil httpClient; with a non-nil httpClient, the transport’s // TLSClientConfig must be nil (or the client will try using HTTPS over the PF_UNIX socket // regardless of the values in the *tls.Config), and we would have to call sockets.ConfigureTransport. // // We don't really want to configure anything for unix:// sockets, so just pass a nil *http.Client. // // Similarly, if we want to communicate over plain HTTP on a TCP socket, we also need to set // TLSClientConfig to nil. This can be achieved by using the form `http://` url, err := dockerclient.ParseHostURL(host) if err != nil { return nil, err } var httpClient *http.Client if url.Scheme != "unix" { if url.Scheme == "http" { httpClient = httpConfig() } else { hc, err := tlsConfig(sys) if err != nil { return nil, err } httpClient = hc } } return dockerclient.NewClient(host, defaultAPIVersion, httpClient, nil) }
[ "func", "newDockerClient", "(", "sys", "*", "types", ".", "SystemContext", ")", "(", "*", "dockerclient", ".", "Client", ",", "error", ")", "{", "host", ":=", "dockerclient", ".", "DefaultDockerHost", "\n", "if", "sys", "!=", "nil", "&&", "sys", ".", "DockerDaemonHost", "!=", "\"\"", "{", "host", "=", "sys", ".", "DockerDaemonHost", "\n", "}", "\n", "url", ",", "err", ":=", "dockerclient", ".", "ParseHostURL", "(", "host", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "var", "httpClient", "*", "http", ".", "Client", "\n", "if", "url", ".", "Scheme", "!=", "\"unix\"", "{", "if", "url", ".", "Scheme", "==", "\"http\"", "{", "httpClient", "=", "httpConfig", "(", ")", "\n", "}", "else", "{", "hc", ",", "err", ":=", "tlsConfig", "(", "sys", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "httpClient", "=", "hc", "\n", "}", "\n", "}", "\n", "return", "dockerclient", ".", "NewClient", "(", "host", ",", "defaultAPIVersion", ",", "httpClient", ",", "nil", ")", "\n", "}" ]
// NewDockerClient initializes a new API client based on the passed SystemContext.
[ "NewDockerClient", "initializes", "a", "new", "API", "client", "based", "on", "the", "passed", "SystemContext", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/daemon/client.go#L18-L51
test
containers/image
signature/policy_config.go
defaultPolicyPath
func defaultPolicyPath(sys *types.SystemContext) string { if sys != nil { if sys.SignaturePolicyPath != "" { return sys.SignaturePolicyPath } if sys.RootForImplicitAbsolutePaths != "" { return filepath.Join(sys.RootForImplicitAbsolutePaths, systemDefaultPolicyPath) } } return systemDefaultPolicyPath }
go
func defaultPolicyPath(sys *types.SystemContext) string { if sys != nil { if sys.SignaturePolicyPath != "" { return sys.SignaturePolicyPath } if sys.RootForImplicitAbsolutePaths != "" { return filepath.Join(sys.RootForImplicitAbsolutePaths, systemDefaultPolicyPath) } } return systemDefaultPolicyPath }
[ "func", "defaultPolicyPath", "(", "sys", "*", "types", ".", "SystemContext", ")", "string", "{", "if", "sys", "!=", "nil", "{", "if", "sys", ".", "SignaturePolicyPath", "!=", "\"\"", "{", "return", "sys", ".", "SignaturePolicyPath", "\n", "}", "\n", "if", "sys", ".", "RootForImplicitAbsolutePaths", "!=", "\"\"", "{", "return", "filepath", ".", "Join", "(", "sys", ".", "RootForImplicitAbsolutePaths", ",", "systemDefaultPolicyPath", ")", "\n", "}", "\n", "}", "\n", "return", "systemDefaultPolicyPath", "\n", "}" ]
// defaultPolicyPath returns a path to the default policy of the system.
[ "defaultPolicyPath", "returns", "a", "path", "to", "the", "default", "policy", "of", "the", "system", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_config.go#L55-L65
test
containers/image
signature/policy_config.go
NewPolicyFromFile
func NewPolicyFromFile(fileName string) (*Policy, error) { contents, err := ioutil.ReadFile(fileName) if err != nil { return nil, err } policy, err := NewPolicyFromBytes(contents) if err != nil { return nil, errors.Wrapf(err, "invalid policy in %q", fileName) } return policy, nil }
go
func NewPolicyFromFile(fileName string) (*Policy, error) { contents, err := ioutil.ReadFile(fileName) if err != nil { return nil, err } policy, err := NewPolicyFromBytes(contents) if err != nil { return nil, errors.Wrapf(err, "invalid policy in %q", fileName) } return policy, nil }
[ "func", "NewPolicyFromFile", "(", "fileName", "string", ")", "(", "*", "Policy", ",", "error", ")", "{", "contents", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "fileName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "policy", ",", "err", ":=", "NewPolicyFromBytes", "(", "contents", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"invalid policy in %q\"", ",", "fileName", ")", "\n", "}", "\n", "return", "policy", ",", "nil", "\n", "}" ]
// NewPolicyFromFile returns a policy configured in the specified file.
[ "NewPolicyFromFile", "returns", "a", "policy", "configured", "in", "the", "specified", "file", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_config.go#L68-L78
test
containers/image
signature/policy_config.go
NewPolicyFromBytes
func NewPolicyFromBytes(data []byte) (*Policy, error) { p := Policy{} if err := json.Unmarshal(data, &p); err != nil { return nil, InvalidPolicyFormatError(err.Error()) } return &p, nil }
go
func NewPolicyFromBytes(data []byte) (*Policy, error) { p := Policy{} if err := json.Unmarshal(data, &p); err != nil { return nil, InvalidPolicyFormatError(err.Error()) } return &p, nil }
[ "func", "NewPolicyFromBytes", "(", "data", "[", "]", "byte", ")", "(", "*", "Policy", ",", "error", ")", "{", "p", ":=", "Policy", "{", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "p", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "InvalidPolicyFormatError", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "&", "p", ",", "nil", "\n", "}" ]
// NewPolicyFromBytes returns a policy parsed from the specified blob. // Use this function instead of calling json.Unmarshal directly.
[ "NewPolicyFromBytes", "returns", "a", "policy", "parsed", "from", "the", "specified", "blob", ".", "Use", "this", "function", "instead", "of", "calling", "json", ".", "Unmarshal", "directly", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_config.go#L82-L88
test
containers/image
signature/policy_config.go
newPolicyRequirementFromJSON
func newPolicyRequirementFromJSON(data []byte) (PolicyRequirement, error) { var typeField prCommon if err := json.Unmarshal(data, &typeField); err != nil { return nil, err } var res PolicyRequirement switch typeField.Type { case prTypeInsecureAcceptAnything: res = &prInsecureAcceptAnything{} case prTypeReject: res = &prReject{} case prTypeSignedBy: res = &prSignedBy{} case prTypeSignedBaseLayer: res = &prSignedBaseLayer{} default: return nil, InvalidPolicyFormatError(fmt.Sprintf("Unknown policy requirement type \"%s\"", typeField.Type)) } if err := json.Unmarshal(data, &res); err != nil { return nil, err } return res, nil }
go
func newPolicyRequirementFromJSON(data []byte) (PolicyRequirement, error) { var typeField prCommon if err := json.Unmarshal(data, &typeField); err != nil { return nil, err } var res PolicyRequirement switch typeField.Type { case prTypeInsecureAcceptAnything: res = &prInsecureAcceptAnything{} case prTypeReject: res = &prReject{} case prTypeSignedBy: res = &prSignedBy{} case prTypeSignedBaseLayer: res = &prSignedBaseLayer{} default: return nil, InvalidPolicyFormatError(fmt.Sprintf("Unknown policy requirement type \"%s\"", typeField.Type)) } if err := json.Unmarshal(data, &res); err != nil { return nil, err } return res, nil }
[ "func", "newPolicyRequirementFromJSON", "(", "data", "[", "]", "byte", ")", "(", "PolicyRequirement", ",", "error", ")", "{", "var", "typeField", "prCommon", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "typeField", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "var", "res", "PolicyRequirement", "\n", "switch", "typeField", ".", "Type", "{", "case", "prTypeInsecureAcceptAnything", ":", "res", "=", "&", "prInsecureAcceptAnything", "{", "}", "\n", "case", "prTypeReject", ":", "res", "=", "&", "prReject", "{", "}", "\n", "case", "prTypeSignedBy", ":", "res", "=", "&", "prSignedBy", "{", "}", "\n", "case", "prTypeSignedBaseLayer", ":", "res", "=", "&", "prSignedBaseLayer", "{", "}", "\n", "default", ":", "return", "nil", ",", "InvalidPolicyFormatError", "(", "fmt", ".", "Sprintf", "(", "\"Unknown policy requirement type \\\"%s\\\"\"", ",", "\\\"", ")", ")", "\n", "}", "\n", "\\\"", "\n", "typeField", ".", "Type", "\n", "}" ]
// newPolicyRequirementFromJSON parses JSON data into a PolicyRequirement implementation.
[ "newPolicyRequirementFromJSON", "parses", "JSON", "data", "into", "a", "PolicyRequirement", "implementation", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_config.go#L221-L243
test
containers/image
signature/policy_config.go
newPRSignedBy
func newPRSignedBy(keyType sbKeyType, keyPath string, keyData []byte, signedIdentity PolicyReferenceMatch) (*prSignedBy, error) { if !keyType.IsValid() { return nil, InvalidPolicyFormatError(fmt.Sprintf("invalid keyType \"%s\"", keyType)) } if len(keyPath) > 0 && len(keyData) > 0 { return nil, InvalidPolicyFormatError("keyType and keyData cannot be used simultaneously") } if signedIdentity == nil { return nil, InvalidPolicyFormatError("signedIdentity not specified") } return &prSignedBy{ prCommon: prCommon{Type: prTypeSignedBy}, KeyType: keyType, KeyPath: keyPath, KeyData: keyData, SignedIdentity: signedIdentity, }, nil }
go
func newPRSignedBy(keyType sbKeyType, keyPath string, keyData []byte, signedIdentity PolicyReferenceMatch) (*prSignedBy, error) { if !keyType.IsValid() { return nil, InvalidPolicyFormatError(fmt.Sprintf("invalid keyType \"%s\"", keyType)) } if len(keyPath) > 0 && len(keyData) > 0 { return nil, InvalidPolicyFormatError("keyType and keyData cannot be used simultaneously") } if signedIdentity == nil { return nil, InvalidPolicyFormatError("signedIdentity not specified") } return &prSignedBy{ prCommon: prCommon{Type: prTypeSignedBy}, KeyType: keyType, KeyPath: keyPath, KeyData: keyData, SignedIdentity: signedIdentity, }, nil }
[ "func", "newPRSignedBy", "(", "keyType", "sbKeyType", ",", "keyPath", "string", ",", "keyData", "[", "]", "byte", ",", "signedIdentity", "PolicyReferenceMatch", ")", "(", "*", "prSignedBy", ",", "error", ")", "{", "if", "!", "keyType", ".", "IsValid", "(", ")", "{", "return", "nil", ",", "InvalidPolicyFormatError", "(", "fmt", ".", "Sprintf", "(", "\"invalid keyType \\\"%s\\\"\"", ",", "\\\"", ")", ")", "\n", "}", "\n", "\\\"", "\n", "keyType", "\n", "if", "len", "(", "keyPath", ")", ">", "0", "&&", "len", "(", "keyData", ")", ">", "0", "{", "return", "nil", ",", "InvalidPolicyFormatError", "(", "\"keyType and keyData cannot be used simultaneously\"", ")", "\n", "}", "\n", "}" ]
// newPRSignedBy returns a new prSignedBy if parameters are valid.
[ "newPRSignedBy", "returns", "a", "new", "prSignedBy", "if", "parameters", "are", "valid", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_config.go#L306-L323
test
containers/image
signature/policy_config.go
newPRSignedByKeyPath
func newPRSignedByKeyPath(keyType sbKeyType, keyPath string, signedIdentity PolicyReferenceMatch) (*prSignedBy, error) { return newPRSignedBy(keyType, keyPath, nil, signedIdentity) }
go
func newPRSignedByKeyPath(keyType sbKeyType, keyPath string, signedIdentity PolicyReferenceMatch) (*prSignedBy, error) { return newPRSignedBy(keyType, keyPath, nil, signedIdentity) }
[ "func", "newPRSignedByKeyPath", "(", "keyType", "sbKeyType", ",", "keyPath", "string", ",", "signedIdentity", "PolicyReferenceMatch", ")", "(", "*", "prSignedBy", ",", "error", ")", "{", "return", "newPRSignedBy", "(", "keyType", ",", "keyPath", ",", "nil", ",", "signedIdentity", ")", "\n", "}" ]
// newPRSignedByKeyPath is NewPRSignedByKeyPath, except it returns the private type.
[ "newPRSignedByKeyPath", "is", "NewPRSignedByKeyPath", "except", "it", "returns", "the", "private", "type", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_config.go#L326-L328
test
containers/image
signature/policy_config.go
NewPRSignedByKeyPath
func NewPRSignedByKeyPath(keyType sbKeyType, keyPath string, signedIdentity PolicyReferenceMatch) (PolicyRequirement, error) { return newPRSignedByKeyPath(keyType, keyPath, signedIdentity) }
go
func NewPRSignedByKeyPath(keyType sbKeyType, keyPath string, signedIdentity PolicyReferenceMatch) (PolicyRequirement, error) { return newPRSignedByKeyPath(keyType, keyPath, signedIdentity) }
[ "func", "NewPRSignedByKeyPath", "(", "keyType", "sbKeyType", ",", "keyPath", "string", ",", "signedIdentity", "PolicyReferenceMatch", ")", "(", "PolicyRequirement", ",", "error", ")", "{", "return", "newPRSignedByKeyPath", "(", "keyType", ",", "keyPath", ",", "signedIdentity", ")", "\n", "}" ]
// NewPRSignedByKeyPath returns a new "signedBy" PolicyRequirement using a KeyPath
[ "NewPRSignedByKeyPath", "returns", "a", "new", "signedBy", "PolicyRequirement", "using", "a", "KeyPath" ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_config.go#L331-L333
test
containers/image
signature/policy_config.go
newPRSignedByKeyData
func newPRSignedByKeyData(keyType sbKeyType, keyData []byte, signedIdentity PolicyReferenceMatch) (*prSignedBy, error) { return newPRSignedBy(keyType, "", keyData, signedIdentity) }
go
func newPRSignedByKeyData(keyType sbKeyType, keyData []byte, signedIdentity PolicyReferenceMatch) (*prSignedBy, error) { return newPRSignedBy(keyType, "", keyData, signedIdentity) }
[ "func", "newPRSignedByKeyData", "(", "keyType", "sbKeyType", ",", "keyData", "[", "]", "byte", ",", "signedIdentity", "PolicyReferenceMatch", ")", "(", "*", "prSignedBy", ",", "error", ")", "{", "return", "newPRSignedBy", "(", "keyType", ",", "\"\"", ",", "keyData", ",", "signedIdentity", ")", "\n", "}" ]
// newPRSignedByKeyData is NewPRSignedByKeyData, except it returns the private type.
[ "newPRSignedByKeyData", "is", "NewPRSignedByKeyData", "except", "it", "returns", "the", "private", "type", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_config.go#L336-L338
test
containers/image
signature/policy_config.go
NewPRSignedByKeyData
func NewPRSignedByKeyData(keyType sbKeyType, keyData []byte, signedIdentity PolicyReferenceMatch) (PolicyRequirement, error) { return newPRSignedByKeyData(keyType, keyData, signedIdentity) }
go
func NewPRSignedByKeyData(keyType sbKeyType, keyData []byte, signedIdentity PolicyReferenceMatch) (PolicyRequirement, error) { return newPRSignedByKeyData(keyType, keyData, signedIdentity) }
[ "func", "NewPRSignedByKeyData", "(", "keyType", "sbKeyType", ",", "keyData", "[", "]", "byte", ",", "signedIdentity", "PolicyReferenceMatch", ")", "(", "PolicyRequirement", ",", "error", ")", "{", "return", "newPRSignedByKeyData", "(", "keyType", ",", "keyData", ",", "signedIdentity", ")", "\n", "}" ]
// NewPRSignedByKeyData returns a new "signedBy" PolicyRequirement using a KeyData
[ "NewPRSignedByKeyData", "returns", "a", "new", "signedBy", "PolicyRequirement", "using", "a", "KeyData" ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_config.go#L341-L343
test
containers/image
signature/policy_config.go
IsValid
func (kt sbKeyType) IsValid() bool { switch kt { case SBKeyTypeGPGKeys, SBKeyTypeSignedByGPGKeys, SBKeyTypeX509Certificates, SBKeyTypeSignedByX509CAs: return true default: return false } }
go
func (kt sbKeyType) IsValid() bool { switch kt { case SBKeyTypeGPGKeys, SBKeyTypeSignedByGPGKeys, SBKeyTypeX509Certificates, SBKeyTypeSignedByX509CAs: return true default: return false } }
[ "func", "(", "kt", "sbKeyType", ")", "IsValid", "(", ")", "bool", "{", "switch", "kt", "{", "case", "SBKeyTypeGPGKeys", ",", "SBKeyTypeSignedByGPGKeys", ",", "SBKeyTypeX509Certificates", ",", "SBKeyTypeSignedByX509CAs", ":", "return", "true", "\n", "default", ":", "return", "false", "\n", "}", "\n", "}" ]
// IsValid returns true iff kt is a recognized value
[ "IsValid", "returns", "true", "iff", "kt", "is", "a", "recognized", "value" ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_config.go#L411-L419
test
containers/image
signature/policy_config.go
newPRSignedBaseLayer
func newPRSignedBaseLayer(baseLayerIdentity PolicyReferenceMatch) (*prSignedBaseLayer, error) { if baseLayerIdentity == nil { return nil, InvalidPolicyFormatError("baseLayerIdentity not specified") } return &prSignedBaseLayer{ prCommon: prCommon{Type: prTypeSignedBaseLayer}, BaseLayerIdentity: baseLayerIdentity, }, nil }
go
func newPRSignedBaseLayer(baseLayerIdentity PolicyReferenceMatch) (*prSignedBaseLayer, error) { if baseLayerIdentity == nil { return nil, InvalidPolicyFormatError("baseLayerIdentity not specified") } return &prSignedBaseLayer{ prCommon: prCommon{Type: prTypeSignedBaseLayer}, BaseLayerIdentity: baseLayerIdentity, }, nil }
[ "func", "newPRSignedBaseLayer", "(", "baseLayerIdentity", "PolicyReferenceMatch", ")", "(", "*", "prSignedBaseLayer", ",", "error", ")", "{", "if", "baseLayerIdentity", "==", "nil", "{", "return", "nil", ",", "InvalidPolicyFormatError", "(", "\"baseLayerIdentity not specified\"", ")", "\n", "}", "\n", "return", "&", "prSignedBaseLayer", "{", "prCommon", ":", "prCommon", "{", "Type", ":", "prTypeSignedBaseLayer", "}", ",", "BaseLayerIdentity", ":", "baseLayerIdentity", ",", "}", ",", "nil", "\n", "}" ]
// newPRSignedBaseLayer is NewPRSignedBaseLayer, except it returns the private type.
[ "newPRSignedBaseLayer", "is", "NewPRSignedBaseLayer", "except", "it", "returns", "the", "private", "type", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_config.go#L439-L447
test
containers/image
signature/policy_config.go
newPolicyReferenceMatchFromJSON
func newPolicyReferenceMatchFromJSON(data []byte) (PolicyReferenceMatch, error) { var typeField prmCommon if err := json.Unmarshal(data, &typeField); err != nil { return nil, err } var res PolicyReferenceMatch switch typeField.Type { case prmTypeMatchExact: res = &prmMatchExact{} case prmTypeMatchRepoDigestOrExact: res = &prmMatchRepoDigestOrExact{} case prmTypeMatchRepository: res = &prmMatchRepository{} case prmTypeExactReference: res = &prmExactReference{} case prmTypeExactRepository: res = &prmExactRepository{} default: return nil, InvalidPolicyFormatError(fmt.Sprintf("Unknown policy reference match type \"%s\"", typeField.Type)) } if err := json.Unmarshal(data, &res); err != nil { return nil, err } return res, nil }
go
func newPolicyReferenceMatchFromJSON(data []byte) (PolicyReferenceMatch, error) { var typeField prmCommon if err := json.Unmarshal(data, &typeField); err != nil { return nil, err } var res PolicyReferenceMatch switch typeField.Type { case prmTypeMatchExact: res = &prmMatchExact{} case prmTypeMatchRepoDigestOrExact: res = &prmMatchRepoDigestOrExact{} case prmTypeMatchRepository: res = &prmMatchRepository{} case prmTypeExactReference: res = &prmExactReference{} case prmTypeExactRepository: res = &prmExactRepository{} default: return nil, InvalidPolicyFormatError(fmt.Sprintf("Unknown policy reference match type \"%s\"", typeField.Type)) } if err := json.Unmarshal(data, &res); err != nil { return nil, err } return res, nil }
[ "func", "newPolicyReferenceMatchFromJSON", "(", "data", "[", "]", "byte", ")", "(", "PolicyReferenceMatch", ",", "error", ")", "{", "var", "typeField", "prmCommon", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "data", ",", "&", "typeField", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "var", "res", "PolicyReferenceMatch", "\n", "switch", "typeField", ".", "Type", "{", "case", "prmTypeMatchExact", ":", "res", "=", "&", "prmMatchExact", "{", "}", "\n", "case", "prmTypeMatchRepoDigestOrExact", ":", "res", "=", "&", "prmMatchRepoDigestOrExact", "{", "}", "\n", "case", "prmTypeMatchRepository", ":", "res", "=", "&", "prmMatchRepository", "{", "}", "\n", "case", "prmTypeExactReference", ":", "res", "=", "&", "prmExactReference", "{", "}", "\n", "case", "prmTypeExactRepository", ":", "res", "=", "&", "prmExactRepository", "{", "}", "\n", "default", ":", "return", "nil", ",", "InvalidPolicyFormatError", "(", "fmt", ".", "Sprintf", "(", "\"Unknown policy reference match type \\\"%s\\\"\"", ",", "\\\"", ")", ")", "\n", "}", "\n", "\\\"", "\n", "typeField", ".", "Type", "\n", "}" ]
// newPolicyReferenceMatchFromJSON parses JSON data into a PolicyReferenceMatch implementation.
[ "newPolicyReferenceMatchFromJSON", "parses", "JSON", "data", "into", "a", "PolicyReferenceMatch", "implementation", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_config.go#L486-L510
test
containers/image
signature/policy_config.go
newPRMExactReference
func newPRMExactReference(dockerReference string) (*prmExactReference, error) { ref, err := reference.ParseNormalizedNamed(dockerReference) if err != nil { return nil, InvalidPolicyFormatError(fmt.Sprintf("Invalid format of dockerReference %s: %s", dockerReference, err.Error())) } if reference.IsNameOnly(ref) { return nil, InvalidPolicyFormatError(fmt.Sprintf("dockerReference %s contains neither a tag nor digest", dockerReference)) } return &prmExactReference{ prmCommon: prmCommon{Type: prmTypeExactReference}, DockerReference: dockerReference, }, nil }
go
func newPRMExactReference(dockerReference string) (*prmExactReference, error) { ref, err := reference.ParseNormalizedNamed(dockerReference) if err != nil { return nil, InvalidPolicyFormatError(fmt.Sprintf("Invalid format of dockerReference %s: %s", dockerReference, err.Error())) } if reference.IsNameOnly(ref) { return nil, InvalidPolicyFormatError(fmt.Sprintf("dockerReference %s contains neither a tag nor digest", dockerReference)) } return &prmExactReference{ prmCommon: prmCommon{Type: prmTypeExactReference}, DockerReference: dockerReference, }, nil }
[ "func", "newPRMExactReference", "(", "dockerReference", "string", ")", "(", "*", "prmExactReference", ",", "error", ")", "{", "ref", ",", "err", ":=", "reference", ".", "ParseNormalizedNamed", "(", "dockerReference", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "InvalidPolicyFormatError", "(", "fmt", ".", "Sprintf", "(", "\"Invalid format of dockerReference %s: %s\"", ",", "dockerReference", ",", "err", ".", "Error", "(", ")", ")", ")", "\n", "}", "\n", "if", "reference", ".", "IsNameOnly", "(", "ref", ")", "{", "return", "nil", ",", "InvalidPolicyFormatError", "(", "fmt", ".", "Sprintf", "(", "\"dockerReference %s contains neither a tag nor digest\"", ",", "dockerReference", ")", ")", "\n", "}", "\n", "return", "&", "prmExactReference", "{", "prmCommon", ":", "prmCommon", "{", "Type", ":", "prmTypeExactReference", "}", ",", "DockerReference", ":", "dockerReference", ",", "}", ",", "nil", "\n", "}" ]
// newPRMExactReference is NewPRMExactReference, except it resturns the private type.
[ "newPRMExactReference", "is", "NewPRMExactReference", "except", "it", "resturns", "the", "private", "type", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_config.go#L603-L615
test
containers/image
signature/policy_config.go
newPRMExactRepository
func newPRMExactRepository(dockerRepository string) (*prmExactRepository, error) { if _, err := reference.ParseNormalizedNamed(dockerRepository); err != nil { return nil, InvalidPolicyFormatError(fmt.Sprintf("Invalid format of dockerRepository %s: %s", dockerRepository, err.Error())) } return &prmExactRepository{ prmCommon: prmCommon{Type: prmTypeExactRepository}, DockerRepository: dockerRepository, }, nil }
go
func newPRMExactRepository(dockerRepository string) (*prmExactRepository, error) { if _, err := reference.ParseNormalizedNamed(dockerRepository); err != nil { return nil, InvalidPolicyFormatError(fmt.Sprintf("Invalid format of dockerRepository %s: %s", dockerRepository, err.Error())) } return &prmExactRepository{ prmCommon: prmCommon{Type: prmTypeExactRepository}, DockerRepository: dockerRepository, }, nil }
[ "func", "newPRMExactRepository", "(", "dockerRepository", "string", ")", "(", "*", "prmExactRepository", ",", "error", ")", "{", "if", "_", ",", "err", ":=", "reference", ".", "ParseNormalizedNamed", "(", "dockerRepository", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "InvalidPolicyFormatError", "(", "fmt", ".", "Sprintf", "(", "\"Invalid format of dockerRepository %s: %s\"", ",", "dockerRepository", ",", "err", ".", "Error", "(", ")", ")", ")", "\n", "}", "\n", "return", "&", "prmExactRepository", "{", "prmCommon", ":", "prmCommon", "{", "Type", ":", "prmTypeExactRepository", "}", ",", "DockerRepository", ":", "dockerRepository", ",", "}", ",", "nil", "\n", "}" ]
// newPRMExactRepository is NewPRMExactRepository, except it resturns the private type.
[ "newPRMExactRepository", "is", "NewPRMExactRepository", "except", "it", "resturns", "the", "private", "type", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_config.go#L649-L657
test
containers/image
storage/storage_image.go
newImageSource
func newImageSource(imageRef storageReference) (*storageImageSource, error) { // First, locate the image. img, err := imageRef.resolveImage() if err != nil { return nil, err } // Build the reader object. image := &storageImageSource{ imageRef: imageRef, image: img, layerPosition: make(map[digest.Digest]int), SignatureSizes: []int{}, } if img.Metadata != "" { if err := json.Unmarshal([]byte(img.Metadata), image); err != nil { return nil, errors.Wrap(err, "error decoding metadata for source image") } } return image, nil }
go
func newImageSource(imageRef storageReference) (*storageImageSource, error) { // First, locate the image. img, err := imageRef.resolveImage() if err != nil { return nil, err } // Build the reader object. image := &storageImageSource{ imageRef: imageRef, image: img, layerPosition: make(map[digest.Digest]int), SignatureSizes: []int{}, } if img.Metadata != "" { if err := json.Unmarshal([]byte(img.Metadata), image); err != nil { return nil, errors.Wrap(err, "error decoding metadata for source image") } } return image, nil }
[ "func", "newImageSource", "(", "imageRef", "storageReference", ")", "(", "*", "storageImageSource", ",", "error", ")", "{", "img", ",", "err", ":=", "imageRef", ".", "resolveImage", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "image", ":=", "&", "storageImageSource", "{", "imageRef", ":", "imageRef", ",", "image", ":", "img", ",", "layerPosition", ":", "make", "(", "map", "[", "digest", ".", "Digest", "]", "int", ")", ",", "SignatureSizes", ":", "[", "]", "int", "{", "}", ",", "}", "\n", "if", "img", ".", "Metadata", "!=", "\"\"", "{", "if", "err", ":=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "img", ".", "Metadata", ")", ",", "image", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"error decoding metadata for source image\"", ")", "\n", "}", "\n", "}", "\n", "return", "image", ",", "nil", "\n", "}" ]
// newImageSource sets up an image for reading.
[ "newImageSource", "sets", "up", "an", "image", "for", "reading", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/storage/storage_image.go#L82-L102
test
containers/image
storage/storage_image.go
getBlobAndLayerID
func (s *storageImageSource) getBlobAndLayerID(info types.BlobInfo) (rc io.ReadCloser, n int64, layerID string, err error) { var layer storage.Layer var diffOptions *storage.DiffOptions // We need a valid digest value. err = info.Digest.Validate() if err != nil { return nil, -1, "", err } // Check if the blob corresponds to a diff that was used to initialize any layers. Our // callers should try to retrieve layers using their uncompressed digests, so no need to // check if they're using one of the compressed digests, which we can't reproduce anyway. layers, err := s.imageRef.transport.store.LayersByUncompressedDigest(info.Digest) // If it's not a layer, then it must be a data item. if len(layers) == 0 { b, err := s.imageRef.transport.store.ImageBigData(s.image.ID, info.Digest.String()) if err != nil { return nil, -1, "", err } r := bytes.NewReader(b) logrus.Debugf("exporting opaque data as blob %q", info.Digest.String()) return ioutil.NopCloser(r), int64(r.Len()), "", nil } // Step through the list of matching layers. Tests may want to verify that if we have multiple layers // which claim to have the same contents, that we actually do have multiple layers, otherwise we could // just go ahead and use the first one every time. s.getBlobMutex.Lock() i := s.layerPosition[info.Digest] s.layerPosition[info.Digest] = i + 1 s.getBlobMutex.Unlock() if len(layers) > 0 { layer = layers[i%len(layers)] } // Force the storage layer to not try to match any compression that was used when the layer was first // handed to it. noCompression := archive.Uncompressed diffOptions = &storage.DiffOptions{ Compression: &noCompression, } if layer.UncompressedSize < 0 { n = -1 } else { n = layer.UncompressedSize } logrus.Debugf("exporting filesystem layer %q without compression for blob %q", layer.ID, info.Digest) rc, err = s.imageRef.transport.store.Diff("", layer.ID, diffOptions) if err != nil { return nil, -1, "", err } return rc, n, layer.ID, err }
go
func (s *storageImageSource) getBlobAndLayerID(info types.BlobInfo) (rc io.ReadCloser, n int64, layerID string, err error) { var layer storage.Layer var diffOptions *storage.DiffOptions // We need a valid digest value. err = info.Digest.Validate() if err != nil { return nil, -1, "", err } // Check if the blob corresponds to a diff that was used to initialize any layers. Our // callers should try to retrieve layers using their uncompressed digests, so no need to // check if they're using one of the compressed digests, which we can't reproduce anyway. layers, err := s.imageRef.transport.store.LayersByUncompressedDigest(info.Digest) // If it's not a layer, then it must be a data item. if len(layers) == 0 { b, err := s.imageRef.transport.store.ImageBigData(s.image.ID, info.Digest.String()) if err != nil { return nil, -1, "", err } r := bytes.NewReader(b) logrus.Debugf("exporting opaque data as blob %q", info.Digest.String()) return ioutil.NopCloser(r), int64(r.Len()), "", nil } // Step through the list of matching layers. Tests may want to verify that if we have multiple layers // which claim to have the same contents, that we actually do have multiple layers, otherwise we could // just go ahead and use the first one every time. s.getBlobMutex.Lock() i := s.layerPosition[info.Digest] s.layerPosition[info.Digest] = i + 1 s.getBlobMutex.Unlock() if len(layers) > 0 { layer = layers[i%len(layers)] } // Force the storage layer to not try to match any compression that was used when the layer was first // handed to it. noCompression := archive.Uncompressed diffOptions = &storage.DiffOptions{ Compression: &noCompression, } if layer.UncompressedSize < 0 { n = -1 } else { n = layer.UncompressedSize } logrus.Debugf("exporting filesystem layer %q without compression for blob %q", layer.ID, info.Digest) rc, err = s.imageRef.transport.store.Diff("", layer.ID, diffOptions) if err != nil { return nil, -1, "", err } return rc, n, layer.ID, err }
[ "func", "(", "s", "*", "storageImageSource", ")", "getBlobAndLayerID", "(", "info", "types", ".", "BlobInfo", ")", "(", "rc", "io", ".", "ReadCloser", ",", "n", "int64", ",", "layerID", "string", ",", "err", "error", ")", "{", "var", "layer", "storage", ".", "Layer", "\n", "var", "diffOptions", "*", "storage", ".", "DiffOptions", "\n", "err", "=", "info", ".", "Digest", ".", "Validate", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "-", "1", ",", "\"\"", ",", "err", "\n", "}", "\n", "layers", ",", "err", ":=", "s", ".", "imageRef", ".", "transport", ".", "store", ".", "LayersByUncompressedDigest", "(", "info", ".", "Digest", ")", "\n", "if", "len", "(", "layers", ")", "==", "0", "{", "b", ",", "err", ":=", "s", ".", "imageRef", ".", "transport", ".", "store", ".", "ImageBigData", "(", "s", ".", "image", ".", "ID", ",", "info", ".", "Digest", ".", "String", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "-", "1", ",", "\"\"", ",", "err", "\n", "}", "\n", "r", ":=", "bytes", ".", "NewReader", "(", "b", ")", "\n", "logrus", ".", "Debugf", "(", "\"exporting opaque data as blob %q\"", ",", "info", ".", "Digest", ".", "String", "(", ")", ")", "\n", "return", "ioutil", ".", "NopCloser", "(", "r", ")", ",", "int64", "(", "r", ".", "Len", "(", ")", ")", ",", "\"\"", ",", "nil", "\n", "}", "\n", "s", ".", "getBlobMutex", ".", "Lock", "(", ")", "\n", "i", ":=", "s", ".", "layerPosition", "[", "info", ".", "Digest", "]", "\n", "s", ".", "layerPosition", "[", "info", ".", "Digest", "]", "=", "i", "+", "1", "\n", "s", ".", "getBlobMutex", ".", "Unlock", "(", ")", "\n", "if", "len", "(", "layers", ")", ">", "0", "{", "layer", "=", "layers", "[", "i", "%", "len", "(", "layers", ")", "]", "\n", "}", "\n", "noCompression", ":=", "archive", ".", "Uncompressed", "\n", "diffOptions", "=", "&", "storage", ".", "DiffOptions", "{", "Compression", ":", "&", "noCompression", ",", "}", "\n", "if", "layer", ".", "UncompressedSize", "<", "0", "{", "n", "=", "-", "1", "\n", "}", "else", "{", "n", "=", "layer", ".", "UncompressedSize", "\n", "}", "\n", "logrus", ".", "Debugf", "(", "\"exporting filesystem layer %q without compression for blob %q\"", ",", "layer", ".", "ID", ",", "info", ".", "Digest", ")", "\n", "rc", ",", "err", "=", "s", ".", "imageRef", ".", "transport", ".", "store", ".", "Diff", "(", "\"\"", ",", "layer", ".", "ID", ",", "diffOptions", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "-", "1", ",", "\"\"", ",", "err", "\n", "}", "\n", "return", "rc", ",", "n", ",", "layer", ".", "ID", ",", "err", "\n", "}" ]
// getBlobAndLayer reads the data blob or filesystem layer which matches the digest and size, if given.
[ "getBlobAndLayer", "reads", "the", "data", "blob", "or", "filesystem", "layer", "which", "matches", "the", "digest", "and", "size", "if", "given", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/storage/storage_image.go#L131-L180
test
containers/image
storage/storage_image.go
computeID
func (s *storageImageDestination) computeID(m manifest.Manifest) string { // Build the diffID list. We need the decompressed sums that we've been calculating to // fill in the DiffIDs. It's expected (but not enforced by us) that the number of // diffIDs corresponds to the number of non-EmptyLayer entries in the history. var diffIDs []digest.Digest switch m := m.(type) { case *manifest.Schema1: // Build a list of the diffIDs we've generated for the non-throwaway FS layers, // in reverse of the order in which they were originally listed. for i, compat := range m.ExtractedV1Compatibility { if compat.ThrowAway { continue } blobSum := m.FSLayers[i].BlobSum diffID, ok := s.blobDiffIDs[blobSum] if !ok { logrus.Infof("error looking up diffID for layer %q", blobSum.String()) return "" } diffIDs = append([]digest.Digest{diffID}, diffIDs...) } case *manifest.Schema2, *manifest.OCI1: // We know the ID calculation for these formats doesn't actually use the diffIDs, // so we don't need to populate the diffID list. default: return "" } id, err := m.ImageID(diffIDs) if err != nil { return "" } return id }
go
func (s *storageImageDestination) computeID(m manifest.Manifest) string { // Build the diffID list. We need the decompressed sums that we've been calculating to // fill in the DiffIDs. It's expected (but not enforced by us) that the number of // diffIDs corresponds to the number of non-EmptyLayer entries in the history. var diffIDs []digest.Digest switch m := m.(type) { case *manifest.Schema1: // Build a list of the diffIDs we've generated for the non-throwaway FS layers, // in reverse of the order in which they were originally listed. for i, compat := range m.ExtractedV1Compatibility { if compat.ThrowAway { continue } blobSum := m.FSLayers[i].BlobSum diffID, ok := s.blobDiffIDs[blobSum] if !ok { logrus.Infof("error looking up diffID for layer %q", blobSum.String()) return "" } diffIDs = append([]digest.Digest{diffID}, diffIDs...) } case *manifest.Schema2, *manifest.OCI1: // We know the ID calculation for these formats doesn't actually use the diffIDs, // so we don't need to populate the diffID list. default: return "" } id, err := m.ImageID(diffIDs) if err != nil { return "" } return id }
[ "func", "(", "s", "*", "storageImageDestination", ")", "computeID", "(", "m", "manifest", ".", "Manifest", ")", "string", "{", "var", "diffIDs", "[", "]", "digest", ".", "Digest", "\n", "switch", "m", ":=", "m", ".", "(", "type", ")", "{", "case", "*", "manifest", ".", "Schema1", ":", "for", "i", ",", "compat", ":=", "range", "m", ".", "ExtractedV1Compatibility", "{", "if", "compat", ".", "ThrowAway", "{", "continue", "\n", "}", "\n", "blobSum", ":=", "m", ".", "FSLayers", "[", "i", "]", ".", "BlobSum", "\n", "diffID", ",", "ok", ":=", "s", ".", "blobDiffIDs", "[", "blobSum", "]", "\n", "if", "!", "ok", "{", "logrus", ".", "Infof", "(", "\"error looking up diffID for layer %q\"", ",", "blobSum", ".", "String", "(", ")", ")", "\n", "return", "\"\"", "\n", "}", "\n", "diffIDs", "=", "append", "(", "[", "]", "digest", ".", "Digest", "{", "diffID", "}", ",", "diffIDs", "...", ")", "\n", "}", "\n", "case", "*", "manifest", ".", "Schema2", ",", "*", "manifest", ".", "OCI1", ":", "default", ":", "return", "\"\"", "\n", "}", "\n", "id", ",", "err", ":=", "m", ".", "ImageID", "(", "diffIDs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", "\n", "}", "\n", "return", "id", "\n", "}" ]
// computeID computes a recommended image ID based on information we have so far. If // the manifest is not of a type that we recognize, we return an empty value, indicating // that since we don't have a recommendation, a random ID should be used if one needs // to be allocated.
[ "computeID", "computes", "a", "recommended", "image", "ID", "based", "on", "information", "we", "have", "so", "far", ".", "If", "the", "manifest", "is", "not", "of", "a", "type", "that", "we", "recognize", "we", "return", "an", "empty", "value", "indicating", "that", "since", "we", "don", "t", "have", "a", "recommendation", "a", "random", "ID", "should", "be", "used", "if", "one", "needs", "to", "be", "allocated", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/storage/storage_image.go#L520-L552
test
containers/image
storage/storage_image.go
PutManifest
func (s *storageImageDestination) PutManifest(ctx context.Context, manifestBlob []byte) error { if s.imageRef.named != nil { if digested, ok := s.imageRef.named.(reference.Digested); ok { matches, err := manifest.MatchesDigest(manifestBlob, digested.Digest()) if err != nil { return err } if !matches { return fmt.Errorf("Manifest does not match expected digest %s", digested.Digest()) } } } s.manifest = make([]byte, len(manifestBlob)) copy(s.manifest, manifestBlob) return nil }
go
func (s *storageImageDestination) PutManifest(ctx context.Context, manifestBlob []byte) error { if s.imageRef.named != nil { if digested, ok := s.imageRef.named.(reference.Digested); ok { matches, err := manifest.MatchesDigest(manifestBlob, digested.Digest()) if err != nil { return err } if !matches { return fmt.Errorf("Manifest does not match expected digest %s", digested.Digest()) } } } s.manifest = make([]byte, len(manifestBlob)) copy(s.manifest, manifestBlob) return nil }
[ "func", "(", "s", "*", "storageImageDestination", ")", "PutManifest", "(", "ctx", "context", ".", "Context", ",", "manifestBlob", "[", "]", "byte", ")", "error", "{", "if", "s", ".", "imageRef", ".", "named", "!=", "nil", "{", "if", "digested", ",", "ok", ":=", "s", ".", "imageRef", ".", "named", ".", "(", "reference", ".", "Digested", ")", ";", "ok", "{", "matches", ",", "err", ":=", "manifest", ".", "MatchesDigest", "(", "manifestBlob", ",", "digested", ".", "Digest", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "!", "matches", "{", "return", "fmt", ".", "Errorf", "(", "\"Manifest does not match expected digest %s\"", ",", "digested", ".", "Digest", "(", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "s", ".", "manifest", "=", "make", "(", "[", "]", "byte", ",", "len", "(", "manifestBlob", ")", ")", "\n", "copy", "(", "s", ".", "manifest", ",", "manifestBlob", ")", "\n", "return", "nil", "\n", "}" ]
// PutManifest writes the manifest to the destination.
[ "PutManifest", "writes", "the", "manifest", "to", "the", "destination", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/storage/storage_image.go#L826-L842
test
containers/image
storage/storage_image.go
PutSignatures
func (s *storageImageDestination) PutSignatures(ctx context.Context, signatures [][]byte) error { sizes := []int{} sigblob := []byte{} for _, sig := range signatures { sizes = append(sizes, len(sig)) newblob := make([]byte, len(sigblob)+len(sig)) copy(newblob, sigblob) copy(newblob[len(sigblob):], sig) sigblob = newblob } s.signatures = sigblob s.SignatureSizes = sizes return nil }
go
func (s *storageImageDestination) PutSignatures(ctx context.Context, signatures [][]byte) error { sizes := []int{} sigblob := []byte{} for _, sig := range signatures { sizes = append(sizes, len(sig)) newblob := make([]byte, len(sigblob)+len(sig)) copy(newblob, sigblob) copy(newblob[len(sigblob):], sig) sigblob = newblob } s.signatures = sigblob s.SignatureSizes = sizes return nil }
[ "func", "(", "s", "*", "storageImageDestination", ")", "PutSignatures", "(", "ctx", "context", ".", "Context", ",", "signatures", "[", "]", "[", "]", "byte", ")", "error", "{", "sizes", ":=", "[", "]", "int", "{", "}", "\n", "sigblob", ":=", "[", "]", "byte", "{", "}", "\n", "for", "_", ",", "sig", ":=", "range", "signatures", "{", "sizes", "=", "append", "(", "sizes", ",", "len", "(", "sig", ")", ")", "\n", "newblob", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "sigblob", ")", "+", "len", "(", "sig", ")", ")", "\n", "copy", "(", "newblob", ",", "sigblob", ")", "\n", "copy", "(", "newblob", "[", "len", "(", "sigblob", ")", ":", "]", ",", "sig", ")", "\n", "sigblob", "=", "newblob", "\n", "}", "\n", "s", ".", "signatures", "=", "sigblob", "\n", "s", ".", "SignatureSizes", "=", "sizes", "\n", "return", "nil", "\n", "}" ]
// PutSignatures records the image's signatures for committing as a single data blob.
[ "PutSignatures", "records", "the", "image", "s", "signatures", "for", "committing", "as", "a", "single", "data", "blob", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/storage/storage_image.go#L869-L882
test
containers/image
storage/storage_image.go
newImage
func newImage(ctx context.Context, sys *types.SystemContext, s storageReference) (types.ImageCloser, error) { src, err := newImageSource(s) if err != nil { return nil, err } img, err := image.FromSource(ctx, sys, src) if err != nil { return nil, err } size, err := src.getSize() if err != nil { return nil, err } return &storageImageCloser{ImageCloser: img, size: size}, nil }
go
func newImage(ctx context.Context, sys *types.SystemContext, s storageReference) (types.ImageCloser, error) { src, err := newImageSource(s) if err != nil { return nil, err } img, err := image.FromSource(ctx, sys, src) if err != nil { return nil, err } size, err := src.getSize() if err != nil { return nil, err } return &storageImageCloser{ImageCloser: img, size: size}, nil }
[ "func", "newImage", "(", "ctx", "context", ".", "Context", ",", "sys", "*", "types", ".", "SystemContext", ",", "s", "storageReference", ")", "(", "types", ".", "ImageCloser", ",", "error", ")", "{", "src", ",", "err", ":=", "newImageSource", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "img", ",", "err", ":=", "image", ".", "FromSource", "(", "ctx", ",", "sys", ",", "src", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "size", ",", "err", ":=", "src", ".", "getSize", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "storageImageCloser", "{", "ImageCloser", ":", "img", ",", "size", ":", "size", "}", ",", "nil", "\n", "}" ]
// newImage creates an image that also knows its size
[ "newImage", "creates", "an", "image", "that", "also", "knows", "its", "size" ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/storage/storage_image.go#L935-L949
test
containers/image
oci/archive/oci_src.go
newImageSource
func newImageSource(ctx context.Context, sys *types.SystemContext, ref ociArchiveReference) (types.ImageSource, error) { tempDirRef, err := createUntarTempDir(ref) if err != nil { return nil, errors.Wrap(err, "error creating temp directory") } unpackedSrc, err := tempDirRef.ociRefExtracted.NewImageSource(ctx, sys) if err != nil { if err := tempDirRef.deleteTempDir(); err != nil { return nil, errors.Wrapf(err, "error deleting temp directory %q", tempDirRef.tempDirectory) } return nil, err } return &ociArchiveImageSource{ref: ref, unpackedSrc: unpackedSrc, tempDirRef: tempDirRef}, nil }
go
func newImageSource(ctx context.Context, sys *types.SystemContext, ref ociArchiveReference) (types.ImageSource, error) { tempDirRef, err := createUntarTempDir(ref) if err != nil { return nil, errors.Wrap(err, "error creating temp directory") } unpackedSrc, err := tempDirRef.ociRefExtracted.NewImageSource(ctx, sys) if err != nil { if err := tempDirRef.deleteTempDir(); err != nil { return nil, errors.Wrapf(err, "error deleting temp directory %q", tempDirRef.tempDirectory) } return nil, err } return &ociArchiveImageSource{ref: ref, unpackedSrc: unpackedSrc, tempDirRef: tempDirRef}, nil }
[ "func", "newImageSource", "(", "ctx", "context", ".", "Context", ",", "sys", "*", "types", ".", "SystemContext", ",", "ref", "ociArchiveReference", ")", "(", "types", ".", "ImageSource", ",", "error", ")", "{", "tempDirRef", ",", "err", ":=", "createUntarTempDir", "(", "ref", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"error creating temp directory\"", ")", "\n", "}", "\n", "unpackedSrc", ",", "err", ":=", "tempDirRef", ".", "ociRefExtracted", ".", "NewImageSource", "(", "ctx", ",", "sys", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", ":=", "tempDirRef", ".", "deleteTempDir", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"error deleting temp directory %q\"", ",", "tempDirRef", ".", "tempDirectory", ")", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "ociArchiveImageSource", "{", "ref", ":", "ref", ",", "unpackedSrc", ":", "unpackedSrc", ",", "tempDirRef", ":", "tempDirRef", "}", ",", "nil", "\n", "}" ]
// newImageSource returns an ImageSource for reading from an existing directory. // newImageSource untars the file and saves it in a temp directory
[ "newImageSource", "returns", "an", "ImageSource", "for", "reading", "from", "an", "existing", "directory", ".", "newImageSource", "untars", "the", "file", "and", "saves", "it", "in", "a", "temp", "directory" ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/archive/oci_src.go#L22-L38
test
containers/image
oci/archive/oci_src.go
LoadManifestDescriptor
func LoadManifestDescriptor(imgRef types.ImageReference) (imgspecv1.Descriptor, error) { ociArchRef, ok := imgRef.(ociArchiveReference) if !ok { return imgspecv1.Descriptor{}, errors.Errorf("error typecasting, need type ociArchiveReference") } tempDirRef, err := createUntarTempDir(ociArchRef) if err != nil { return imgspecv1.Descriptor{}, errors.Wrap(err, "error creating temp directory") } defer tempDirRef.deleteTempDir() descriptor, err := ocilayout.LoadManifestDescriptor(tempDirRef.ociRefExtracted) if err != nil { return imgspecv1.Descriptor{}, errors.Wrap(err, "error loading index") } return descriptor, nil }
go
func LoadManifestDescriptor(imgRef types.ImageReference) (imgspecv1.Descriptor, error) { ociArchRef, ok := imgRef.(ociArchiveReference) if !ok { return imgspecv1.Descriptor{}, errors.Errorf("error typecasting, need type ociArchiveReference") } tempDirRef, err := createUntarTempDir(ociArchRef) if err != nil { return imgspecv1.Descriptor{}, errors.Wrap(err, "error creating temp directory") } defer tempDirRef.deleteTempDir() descriptor, err := ocilayout.LoadManifestDescriptor(tempDirRef.ociRefExtracted) if err != nil { return imgspecv1.Descriptor{}, errors.Wrap(err, "error loading index") } return descriptor, nil }
[ "func", "LoadManifestDescriptor", "(", "imgRef", "types", ".", "ImageReference", ")", "(", "imgspecv1", ".", "Descriptor", ",", "error", ")", "{", "ociArchRef", ",", "ok", ":=", "imgRef", ".", "(", "ociArchiveReference", ")", "\n", "if", "!", "ok", "{", "return", "imgspecv1", ".", "Descriptor", "{", "}", ",", "errors", ".", "Errorf", "(", "\"error typecasting, need type ociArchiveReference\"", ")", "\n", "}", "\n", "tempDirRef", ",", "err", ":=", "createUntarTempDir", "(", "ociArchRef", ")", "\n", "if", "err", "!=", "nil", "{", "return", "imgspecv1", ".", "Descriptor", "{", "}", ",", "errors", ".", "Wrap", "(", "err", ",", "\"error creating temp directory\"", ")", "\n", "}", "\n", "defer", "tempDirRef", ".", "deleteTempDir", "(", ")", "\n", "descriptor", ",", "err", ":=", "ocilayout", ".", "LoadManifestDescriptor", "(", "tempDirRef", ".", "ociRefExtracted", ")", "\n", "if", "err", "!=", "nil", "{", "return", "imgspecv1", ".", "Descriptor", "{", "}", ",", "errors", ".", "Wrap", "(", "err", ",", "\"error loading index\"", ")", "\n", "}", "\n", "return", "descriptor", ",", "nil", "\n", "}" ]
// LoadManifestDescriptor loads the manifest
[ "LoadManifestDescriptor", "loads", "the", "manifest" ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/archive/oci_src.go#L41-L57
test
containers/image
oci/archive/oci_src.go
Close
func (s *ociArchiveImageSource) Close() error { defer s.tempDirRef.deleteTempDir() return s.unpackedSrc.Close() }
go
func (s *ociArchiveImageSource) Close() error { defer s.tempDirRef.deleteTempDir() return s.unpackedSrc.Close() }
[ "func", "(", "s", "*", "ociArchiveImageSource", ")", "Close", "(", ")", "error", "{", "defer", "s", ".", "tempDirRef", ".", "deleteTempDir", "(", ")", "\n", "return", "s", ".", "unpackedSrc", ".", "Close", "(", ")", "\n", "}" ]
// Close removes resources associated with an initialized ImageSource, if any. // Close deletes the temporary directory at dst
[ "Close", "removes", "resources", "associated", "with", "an", "initialized", "ImageSource", "if", "any", ".", "Close", "deletes", "the", "temporary", "directory", "at", "dst" ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/archive/oci_src.go#L66-L69
test
containers/image
copy/manifest.go
append
func (os *orderedSet) append(s string) { if _, ok := os.included[s]; !ok { os.list = append(os.list, s) os.included[s] = struct{}{} } }
go
func (os *orderedSet) append(s string) { if _, ok := os.included[s]; !ok { os.list = append(os.list, s) os.included[s] = struct{}{} } }
[ "func", "(", "os", "*", "orderedSet", ")", "append", "(", "s", "string", ")", "{", "if", "_", ",", "ok", ":=", "os", ".", "included", "[", "s", "]", ";", "!", "ok", "{", "os", ".", "list", "=", "append", "(", "os", ".", "list", ",", "s", ")", "\n", "os", ".", "included", "[", "s", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "}" ]
// append adds s to the end of os, only if it is not included already.
[ "append", "adds", "s", "to", "the", "end", "of", "os", "only", "if", "it", "is", "not", "included", "already", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/copy/manifest.go#L34-L39
test
containers/image
copy/manifest.go
isMultiImage
func isMultiImage(ctx context.Context, img types.UnparsedImage) (bool, error) { _, mt, err := img.Manifest(ctx) if err != nil { return false, err } return manifest.MIMETypeIsMultiImage(mt), nil }
go
func isMultiImage(ctx context.Context, img types.UnparsedImage) (bool, error) { _, mt, err := img.Manifest(ctx) if err != nil { return false, err } return manifest.MIMETypeIsMultiImage(mt), nil }
[ "func", "isMultiImage", "(", "ctx", "context", ".", "Context", ",", "img", "types", ".", "UnparsedImage", ")", "(", "bool", ",", "error", ")", "{", "_", ",", "mt", ",", "err", ":=", "img", ".", "Manifest", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "return", "manifest", ".", "MIMETypeIsMultiImage", "(", "mt", ")", ",", "nil", "\n", "}" ]
// isMultiImage returns true if img is a list of images
[ "isMultiImage", "returns", "true", "if", "img", "is", "a", "list", "of", "images" ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/copy/manifest.go#L115-L121
test
containers/image
pkg/blobinfocache/boltdb/boltdb.go
lockPath
func lockPath(path string) { pl := func() *pathLock { // A scope for defer pathLocksMutex.Lock() defer pathLocksMutex.Unlock() pl, ok := pathLocks[path] if ok { pl.refCount++ } else { pl = &pathLock{refCount: 1, mutex: sync.Mutex{}} pathLocks[path] = pl } return pl }() pl.mutex.Lock() }
go
func lockPath(path string) { pl := func() *pathLock { // A scope for defer pathLocksMutex.Lock() defer pathLocksMutex.Unlock() pl, ok := pathLocks[path] if ok { pl.refCount++ } else { pl = &pathLock{refCount: 1, mutex: sync.Mutex{}} pathLocks[path] = pl } return pl }() pl.mutex.Lock() }
[ "func", "lockPath", "(", "path", "string", ")", "{", "pl", ":=", "func", "(", ")", "*", "pathLock", "{", "pathLocksMutex", ".", "Lock", "(", ")", "\n", "defer", "pathLocksMutex", ".", "Unlock", "(", ")", "\n", "pl", ",", "ok", ":=", "pathLocks", "[", "path", "]", "\n", "if", "ok", "{", "pl", ".", "refCount", "++", "\n", "}", "else", "{", "pl", "=", "&", "pathLock", "{", "refCount", ":", "1", ",", "mutex", ":", "sync", ".", "Mutex", "{", "}", "}", "\n", "pathLocks", "[", "path", "]", "=", "pl", "\n", "}", "\n", "return", "pl", "\n", "}", "(", ")", "\n", "pl", ".", "mutex", ".", "Lock", "(", ")", "\n", "}" ]
// lockPath obtains the pathLock for path. // The caller must call unlockPath eventually.
[ "lockPath", "obtains", "the", "pathLock", "for", "path", ".", "The", "caller", "must", "call", "unlockPath", "eventually", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/blobinfocache/boltdb/boltdb.go#L54-L68
test
containers/image
pkg/blobinfocache/boltdb/boltdb.go
unlockPath
func unlockPath(path string) { pathLocksMutex.Lock() defer pathLocksMutex.Unlock() pl, ok := pathLocks[path] if !ok { // Should this return an error instead? BlobInfoCache ultimately ignores errors… panic(fmt.Sprintf("Internal error: unlocking nonexistent lock for path %s", path)) } pl.mutex.Unlock() pl.refCount-- if pl.refCount == 0 { delete(pathLocks, path) } }
go
func unlockPath(path string) { pathLocksMutex.Lock() defer pathLocksMutex.Unlock() pl, ok := pathLocks[path] if !ok { // Should this return an error instead? BlobInfoCache ultimately ignores errors… panic(fmt.Sprintf("Internal error: unlocking nonexistent lock for path %s", path)) } pl.mutex.Unlock() pl.refCount-- if pl.refCount == 0 { delete(pathLocks, path) } }
[ "func", "unlockPath", "(", "path", "string", ")", "{", "pathLocksMutex", ".", "Lock", "(", ")", "\n", "defer", "pathLocksMutex", ".", "Unlock", "(", ")", "\n", "pl", ",", "ok", ":=", "pathLocks", "[", "path", "]", "\n", "if", "!", "ok", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"Internal error: unlocking nonexistent lock for path %s\"", ",", "path", ")", ")", "\n", "}", "\n", "pl", ".", "mutex", ".", "Unlock", "(", ")", "\n", "pl", ".", "refCount", "--", "\n", "if", "pl", ".", "refCount", "==", "0", "{", "delete", "(", "pathLocks", ",", "path", ")", "\n", "}", "\n", "}" ]
// unlockPath releases the pathLock for path.
[ "unlockPath", "releases", "the", "pathLock", "for", "path", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/blobinfocache/boltdb/boltdb.go#L71-L84
test
containers/image
pkg/blobinfocache/boltdb/boltdb.go
view
func (bdc *cache) view(fn func(tx *bolt.Tx) error) (retErr error) { // bolt.Open(bdc.path, 0600, &bolt.Options{ReadOnly: true}) will, if the file does not exist, // nevertheless create it, but with an O_RDONLY file descriptor, try to initialize it, and fail — while holding // a read lock, blocking any future writes. // Hence this preliminary check, which is RACY: Another process could remove the file // between the Lstat call and opening the database. if _, err := os.Lstat(bdc.path); err != nil && os.IsNotExist(err) { return err } lockPath(bdc.path) defer unlockPath(bdc.path) db, err := bolt.Open(bdc.path, 0600, &bolt.Options{ReadOnly: true}) if err != nil { return err } defer func() { if err := db.Close(); retErr == nil && err != nil { retErr = err } }() return db.View(fn) }
go
func (bdc *cache) view(fn func(tx *bolt.Tx) error) (retErr error) { // bolt.Open(bdc.path, 0600, &bolt.Options{ReadOnly: true}) will, if the file does not exist, // nevertheless create it, but with an O_RDONLY file descriptor, try to initialize it, and fail — while holding // a read lock, blocking any future writes. // Hence this preliminary check, which is RACY: Another process could remove the file // between the Lstat call and opening the database. if _, err := os.Lstat(bdc.path); err != nil && os.IsNotExist(err) { return err } lockPath(bdc.path) defer unlockPath(bdc.path) db, err := bolt.Open(bdc.path, 0600, &bolt.Options{ReadOnly: true}) if err != nil { return err } defer func() { if err := db.Close(); retErr == nil && err != nil { retErr = err } }() return db.View(fn) }
[ "func", "(", "bdc", "*", "cache", ")", "view", "(", "fn", "func", "(", "tx", "*", "bolt", ".", "Tx", ")", "error", ")", "(", "retErr", "error", ")", "{", "if", "_", ",", "err", ":=", "os", ".", "Lstat", "(", "bdc", ".", "path", ")", ";", "err", "!=", "nil", "&&", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "err", "\n", "}", "\n", "lockPath", "(", "bdc", ".", "path", ")", "\n", "defer", "unlockPath", "(", "bdc", ".", "path", ")", "\n", "db", ",", "err", ":=", "bolt", ".", "Open", "(", "bdc", ".", "path", ",", "0600", ",", "&", "bolt", ".", "Options", "{", "ReadOnly", ":", "true", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "func", "(", ")", "{", "if", "err", ":=", "db", ".", "Close", "(", ")", ";", "retErr", "==", "nil", "&&", "err", "!=", "nil", "{", "retErr", "=", "err", "\n", "}", "\n", "}", "(", ")", "\n", "return", "db", ".", "View", "(", "fn", ")", "\n", "}" ]
// view returns runs the specified fn within a read-only transaction on the database.
[ "view", "returns", "runs", "the", "specified", "fn", "within", "a", "read", "-", "only", "transaction", "on", "the", "database", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/blobinfocache/boltdb/boltdb.go#L102-L125
test
containers/image
pkg/blobinfocache/boltdb/boltdb.go
update
func (bdc *cache) update(fn func(tx *bolt.Tx) error) (retErr error) { lockPath(bdc.path) defer unlockPath(bdc.path) db, err := bolt.Open(bdc.path, 0600, nil) if err != nil { return err } defer func() { if err := db.Close(); retErr == nil && err != nil { retErr = err } }() return db.Update(fn) }
go
func (bdc *cache) update(fn func(tx *bolt.Tx) error) (retErr error) { lockPath(bdc.path) defer unlockPath(bdc.path) db, err := bolt.Open(bdc.path, 0600, nil) if err != nil { return err } defer func() { if err := db.Close(); retErr == nil && err != nil { retErr = err } }() return db.Update(fn) }
[ "func", "(", "bdc", "*", "cache", ")", "update", "(", "fn", "func", "(", "tx", "*", "bolt", ".", "Tx", ")", "error", ")", "(", "retErr", "error", ")", "{", "lockPath", "(", "bdc", ".", "path", ")", "\n", "defer", "unlockPath", "(", "bdc", ".", "path", ")", "\n", "db", ",", "err", ":=", "bolt", ".", "Open", "(", "bdc", ".", "path", ",", "0600", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "func", "(", ")", "{", "if", "err", ":=", "db", ".", "Close", "(", ")", ";", "retErr", "==", "nil", "&&", "err", "!=", "nil", "{", "retErr", "=", "err", "\n", "}", "\n", "}", "(", ")", "\n", "return", "db", ".", "Update", "(", "fn", ")", "\n", "}" ]
// update returns runs the specified fn within a read-write transaction on the database.
[ "update", "returns", "runs", "the", "specified", "fn", "within", "a", "read", "-", "write", "transaction", "on", "the", "database", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/blobinfocache/boltdb/boltdb.go#L128-L142
test
containers/image
pkg/blobinfocache/boltdb/boltdb.go
uncompressedDigest
func (bdc *cache) uncompressedDigest(tx *bolt.Tx, anyDigest digest.Digest) digest.Digest { if b := tx.Bucket(uncompressedDigestBucket); b != nil { if uncompressedBytes := b.Get([]byte(anyDigest.String())); uncompressedBytes != nil { d, err := digest.Parse(string(uncompressedBytes)) if err == nil { return d } // FIXME? Log err (but throttle the log volume on repeated accesses)? } } // Presence in digestsByUncompressedBucket implies that anyDigest must already refer to an uncompressed digest. // This way we don't have to waste storage space with trivial (uncompressed, uncompressed) mappings // when we already record a (compressed, uncompressed) pair. if b := tx.Bucket(digestByUncompressedBucket); b != nil { if b = b.Bucket([]byte(anyDigest.String())); b != nil { c := b.Cursor() if k, _ := c.First(); k != nil { // The bucket is non-empty return anyDigest } } } return "" }
go
func (bdc *cache) uncompressedDigest(tx *bolt.Tx, anyDigest digest.Digest) digest.Digest { if b := tx.Bucket(uncompressedDigestBucket); b != nil { if uncompressedBytes := b.Get([]byte(anyDigest.String())); uncompressedBytes != nil { d, err := digest.Parse(string(uncompressedBytes)) if err == nil { return d } // FIXME? Log err (but throttle the log volume on repeated accesses)? } } // Presence in digestsByUncompressedBucket implies that anyDigest must already refer to an uncompressed digest. // This way we don't have to waste storage space with trivial (uncompressed, uncompressed) mappings // when we already record a (compressed, uncompressed) pair. if b := tx.Bucket(digestByUncompressedBucket); b != nil { if b = b.Bucket([]byte(anyDigest.String())); b != nil { c := b.Cursor() if k, _ := c.First(); k != nil { // The bucket is non-empty return anyDigest } } } return "" }
[ "func", "(", "bdc", "*", "cache", ")", "uncompressedDigest", "(", "tx", "*", "bolt", ".", "Tx", ",", "anyDigest", "digest", ".", "Digest", ")", "digest", ".", "Digest", "{", "if", "b", ":=", "tx", ".", "Bucket", "(", "uncompressedDigestBucket", ")", ";", "b", "!=", "nil", "{", "if", "uncompressedBytes", ":=", "b", ".", "Get", "(", "[", "]", "byte", "(", "anyDigest", ".", "String", "(", ")", ")", ")", ";", "uncompressedBytes", "!=", "nil", "{", "d", ",", "err", ":=", "digest", ".", "Parse", "(", "string", "(", "uncompressedBytes", ")", ")", "\n", "if", "err", "==", "nil", "{", "return", "d", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "b", ":=", "tx", ".", "Bucket", "(", "digestByUncompressedBucket", ")", ";", "b", "!=", "nil", "{", "if", "b", "=", "b", ".", "Bucket", "(", "[", "]", "byte", "(", "anyDigest", ".", "String", "(", ")", ")", ")", ";", "b", "!=", "nil", "{", "c", ":=", "b", ".", "Cursor", "(", ")", "\n", "if", "k", ",", "_", ":=", "c", ".", "First", "(", ")", ";", "k", "!=", "nil", "{", "return", "anyDigest", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "\"\"", "\n", "}" ]
// uncompressedDigest implements BlobInfoCache.UncompressedDigest within the provided read-only transaction.
[ "uncompressedDigest", "implements", "BlobInfoCache", ".", "UncompressedDigest", "within", "the", "provided", "read", "-", "only", "transaction", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/blobinfocache/boltdb/boltdb.go#L145-L167
test
containers/image
pkg/blobinfocache/boltdb/boltdb.go
appendReplacementCandidates
func (bdc *cache) appendReplacementCandidates(candidates []prioritize.CandidateWithTime, scopeBucket *bolt.Bucket, digest digest.Digest) []prioritize.CandidateWithTime { b := scopeBucket.Bucket([]byte(digest.String())) if b == nil { return candidates } _ = b.ForEach(func(k, v []byte) error { t := time.Time{} if err := t.UnmarshalBinary(v); err != nil { return err } candidates = append(candidates, prioritize.CandidateWithTime{ Candidate: types.BICReplacementCandidate{ Digest: digest, Location: types.BICLocationReference{Opaque: string(k)}, }, LastSeen: t, }) return nil }) // FIXME? Log error (but throttle the log volume on repeated accesses)? return candidates }
go
func (bdc *cache) appendReplacementCandidates(candidates []prioritize.CandidateWithTime, scopeBucket *bolt.Bucket, digest digest.Digest) []prioritize.CandidateWithTime { b := scopeBucket.Bucket([]byte(digest.String())) if b == nil { return candidates } _ = b.ForEach(func(k, v []byte) error { t := time.Time{} if err := t.UnmarshalBinary(v); err != nil { return err } candidates = append(candidates, prioritize.CandidateWithTime{ Candidate: types.BICReplacementCandidate{ Digest: digest, Location: types.BICLocationReference{Opaque: string(k)}, }, LastSeen: t, }) return nil }) // FIXME? Log error (but throttle the log volume on repeated accesses)? return candidates }
[ "func", "(", "bdc", "*", "cache", ")", "appendReplacementCandidates", "(", "candidates", "[", "]", "prioritize", ".", "CandidateWithTime", ",", "scopeBucket", "*", "bolt", ".", "Bucket", ",", "digest", "digest", ".", "Digest", ")", "[", "]", "prioritize", ".", "CandidateWithTime", "{", "b", ":=", "scopeBucket", ".", "Bucket", "(", "[", "]", "byte", "(", "digest", ".", "String", "(", ")", ")", ")", "\n", "if", "b", "==", "nil", "{", "return", "candidates", "\n", "}", "\n", "_", "=", "b", ".", "ForEach", "(", "func", "(", "k", ",", "v", "[", "]", "byte", ")", "error", "{", "t", ":=", "time", ".", "Time", "{", "}", "\n", "if", "err", ":=", "t", ".", "UnmarshalBinary", "(", "v", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "candidates", "=", "append", "(", "candidates", ",", "prioritize", ".", "CandidateWithTime", "{", "Candidate", ":", "types", ".", "BICReplacementCandidate", "{", "Digest", ":", "digest", ",", "Location", ":", "types", ".", "BICLocationReference", "{", "Opaque", ":", "string", "(", "k", ")", "}", ",", "}", ",", "LastSeen", ":", "t", ",", "}", ")", "\n", "return", "nil", "\n", "}", ")", "\n", "return", "candidates", "\n", "}" ]
// appendReplacementCandiates creates prioritize.CandidateWithTime values for digest in scopeBucket, and returns the result of appending them to candidates.
[ "appendReplacementCandiates", "creates", "prioritize", ".", "CandidateWithTime", "values", "for", "digest", "in", "scopeBucket", "and", "returns", "the", "result", "of", "appending", "them", "to", "candidates", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/blobinfocache/boltdb/boltdb.go#L255-L275
test
containers/image
oci/layout/oci_dest.go
indexExists
func indexExists(ref ociReference) bool { _, err := os.Stat(ref.indexPath()) if err == nil { return true } if os.IsNotExist(err) { return false } return true }
go
func indexExists(ref ociReference) bool { _, err := os.Stat(ref.indexPath()) if err == nil { return true } if os.IsNotExist(err) { return false } return true }
[ "func", "indexExists", "(", "ref", "ociReference", ")", "bool", "{", "_", ",", "err", ":=", "os", ".", "Stat", "(", "ref", ".", "indexPath", "(", ")", ")", "\n", "if", "err", "==", "nil", "{", "return", "true", "\n", "}", "\n", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// indexExists checks whether the index location specified in the OCI reference exists. // The implementation is opinionated, since in case of unexpected errors false is returned
[ "indexExists", "checks", "whether", "the", "index", "location", "specified", "in", "the", "OCI", "reference", "exists", ".", "The", "implementation", "is", "opinionated", "since", "in", "case", "of", "unexpected", "errors", "false", "is", "returned" ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/layout/oci_dest.go#L297-L306
test
containers/image
copy/sign.go
createSignature
func (c *copier) createSignature(manifest []byte, keyIdentity string) ([]byte, error) { mech, err := signature.NewGPGSigningMechanism() if err != nil { return nil, errors.Wrap(err, "Error initializing GPG") } defer mech.Close() if err := mech.SupportsSigning(); err != nil { return nil, errors.Wrap(err, "Signing not supported") } dockerReference := c.dest.Reference().DockerReference() if dockerReference == nil { return nil, errors.Errorf("Cannot determine canonical Docker reference for destination %s", transports.ImageName(c.dest.Reference())) } c.Printf("Signing manifest\n") newSig, err := signature.SignDockerManifest(manifest, dockerReference.String(), mech, keyIdentity) if err != nil { return nil, errors.Wrap(err, "Error creating signature") } return newSig, nil }
go
func (c *copier) createSignature(manifest []byte, keyIdentity string) ([]byte, error) { mech, err := signature.NewGPGSigningMechanism() if err != nil { return nil, errors.Wrap(err, "Error initializing GPG") } defer mech.Close() if err := mech.SupportsSigning(); err != nil { return nil, errors.Wrap(err, "Signing not supported") } dockerReference := c.dest.Reference().DockerReference() if dockerReference == nil { return nil, errors.Errorf("Cannot determine canonical Docker reference for destination %s", transports.ImageName(c.dest.Reference())) } c.Printf("Signing manifest\n") newSig, err := signature.SignDockerManifest(manifest, dockerReference.String(), mech, keyIdentity) if err != nil { return nil, errors.Wrap(err, "Error creating signature") } return newSig, nil }
[ "func", "(", "c", "*", "copier", ")", "createSignature", "(", "manifest", "[", "]", "byte", ",", "keyIdentity", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "mech", ",", "err", ":=", "signature", ".", "NewGPGSigningMechanism", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"Error initializing GPG\"", ")", "\n", "}", "\n", "defer", "mech", ".", "Close", "(", ")", "\n", "if", "err", ":=", "mech", ".", "SupportsSigning", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"Signing not supported\"", ")", "\n", "}", "\n", "dockerReference", ":=", "c", ".", "dest", ".", "Reference", "(", ")", ".", "DockerReference", "(", ")", "\n", "if", "dockerReference", "==", "nil", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"Cannot determine canonical Docker reference for destination %s\"", ",", "transports", ".", "ImageName", "(", "c", ".", "dest", ".", "Reference", "(", ")", ")", ")", "\n", "}", "\n", "c", ".", "Printf", "(", "\"Signing manifest\\n\"", ")", "\n", "\\n", "\n", "newSig", ",", "err", ":=", "signature", ".", "SignDockerManifest", "(", "manifest", ",", "dockerReference", ".", "String", "(", ")", ",", "mech", ",", "keyIdentity", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"Error creating signature\"", ")", "\n", "}", "\n", "}" ]
// createSignature creates a new signature of manifest using keyIdentity.
[ "createSignature", "creates", "a", "new", "signature", "of", "manifest", "using", "keyIdentity", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/copy/sign.go#L10-L31
test
containers/image
oci/layout/oci_transport.go
ParseReference
func ParseReference(reference string) (types.ImageReference, error) { dir, image := internal.SplitPathAndImage(reference) return NewReference(dir, image) }
go
func ParseReference(reference string) (types.ImageReference, error) { dir, image := internal.SplitPathAndImage(reference) return NewReference(dir, image) }
[ "func", "ParseReference", "(", "reference", "string", ")", "(", "types", ".", "ImageReference", ",", "error", ")", "{", "dir", ",", "image", ":=", "internal", ".", "SplitPathAndImage", "(", "reference", ")", "\n", "return", "NewReference", "(", "dir", ",", "image", ")", "\n", "}" ]
// ParseReference converts a string, which should not start with the ImageTransport.Name prefix, into an OCI ImageReference.
[ "ParseReference", "converts", "a", "string", "which", "should", "not", "start", "with", "the", "ImageTransport", ".", "Name", "prefix", "into", "an", "OCI", "ImageReference", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/layout/oci_transport.go#L70-L73
test
containers/image
oci/layout/oci_transport.go
NewReference
func NewReference(dir, image string) (types.ImageReference, error) { resolved, err := explicitfilepath.ResolvePathToFullyExplicit(dir) if err != nil { return nil, err } if err := internal.ValidateOCIPath(dir); err != nil { return nil, err } if err = internal.ValidateImageName(image); err != nil { return nil, err } return ociReference{dir: dir, resolvedDir: resolved, image: image}, nil }
go
func NewReference(dir, image string) (types.ImageReference, error) { resolved, err := explicitfilepath.ResolvePathToFullyExplicit(dir) if err != nil { return nil, err } if err := internal.ValidateOCIPath(dir); err != nil { return nil, err } if err = internal.ValidateImageName(image); err != nil { return nil, err } return ociReference{dir: dir, resolvedDir: resolved, image: image}, nil }
[ "func", "NewReference", "(", "dir", ",", "image", "string", ")", "(", "types", ".", "ImageReference", ",", "error", ")", "{", "resolved", ",", "err", ":=", "explicitfilepath", ".", "ResolvePathToFullyExplicit", "(", "dir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "internal", ".", "ValidateOCIPath", "(", "dir", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", "=", "internal", ".", "ValidateImageName", "(", "image", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "ociReference", "{", "dir", ":", "dir", ",", "resolvedDir", ":", "resolved", ",", "image", ":", "image", "}", ",", "nil", "\n", "}" ]
// NewReference returns an OCI reference for a directory and a image. // // We do not expose an API supplying the resolvedDir; we could, but recomputing it // is generally cheap enough that we prefer being confident about the properties of resolvedDir.
[ "NewReference", "returns", "an", "OCI", "reference", "for", "a", "directory", "and", "a", "image", ".", "We", "do", "not", "expose", "an", "API", "supplying", "the", "resolvedDir", ";", "we", "could", "but", "recomputing", "it", "is", "generally", "cheap", "enough", "that", "we", "prefer", "being", "confident", "about", "the", "properties", "of", "resolvedDir", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/layout/oci_transport.go#L79-L94
test
containers/image
oci/layout/oci_transport.go
getIndex
func (ref ociReference) getIndex() (*imgspecv1.Index, error) { indexJSON, err := os.Open(ref.indexPath()) if err != nil { return nil, err } defer indexJSON.Close() index := &imgspecv1.Index{} if err := json.NewDecoder(indexJSON).Decode(index); err != nil { return nil, err } return index, nil }
go
func (ref ociReference) getIndex() (*imgspecv1.Index, error) { indexJSON, err := os.Open(ref.indexPath()) if err != nil { return nil, err } defer indexJSON.Close() index := &imgspecv1.Index{} if err := json.NewDecoder(indexJSON).Decode(index); err != nil { return nil, err } return index, nil }
[ "func", "(", "ref", "ociReference", ")", "getIndex", "(", ")", "(", "*", "imgspecv1", ".", "Index", ",", "error", ")", "{", "indexJSON", ",", "err", ":=", "os", ".", "Open", "(", "ref", ".", "indexPath", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "indexJSON", ".", "Close", "(", ")", "\n", "index", ":=", "&", "imgspecv1", ".", "Index", "{", "}", "\n", "if", "err", ":=", "json", ".", "NewDecoder", "(", "indexJSON", ")", ".", "Decode", "(", "index", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "index", ",", "nil", "\n", "}" ]
// getIndex returns a pointer to the index references by this ociReference. If an error occurs opening an index nil is returned together // with an error.
[ "getIndex", "returns", "a", "pointer", "to", "the", "index", "references", "by", "this", "ociReference", ".", "If", "an", "error", "occurs", "opening", "an", "index", "nil", "is", "returned", "together", "with", "an", "error", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/layout/oci_transport.go#L166-L178
test
containers/image
oci/layout/oci_transport.go
LoadManifestDescriptor
func LoadManifestDescriptor(imgRef types.ImageReference) (imgspecv1.Descriptor, error) { ociRef, ok := imgRef.(ociReference) if !ok { return imgspecv1.Descriptor{}, errors.Errorf("error typecasting, need type ociRef") } return ociRef.getManifestDescriptor() }
go
func LoadManifestDescriptor(imgRef types.ImageReference) (imgspecv1.Descriptor, error) { ociRef, ok := imgRef.(ociReference) if !ok { return imgspecv1.Descriptor{}, errors.Errorf("error typecasting, need type ociRef") } return ociRef.getManifestDescriptor() }
[ "func", "LoadManifestDescriptor", "(", "imgRef", "types", ".", "ImageReference", ")", "(", "imgspecv1", ".", "Descriptor", ",", "error", ")", "{", "ociRef", ",", "ok", ":=", "imgRef", ".", "(", "ociReference", ")", "\n", "if", "!", "ok", "{", "return", "imgspecv1", ".", "Descriptor", "{", "}", ",", "errors", ".", "Errorf", "(", "\"error typecasting, need type ociRef\"", ")", "\n", "}", "\n", "return", "ociRef", ".", "getManifestDescriptor", "(", ")", "\n", "}" ]
// LoadManifestDescriptor loads the manifest descriptor to be used to retrieve the image name // when pulling an image
[ "LoadManifestDescriptor", "loads", "the", "manifest", "descriptor", "to", "be", "used", "to", "retrieve", "the", "image", "name", "when", "pulling", "an", "image" ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/layout/oci_transport.go#L219-L225
test
containers/image
oci/layout/oci_transport.go
blobPath
func (ref ociReference) blobPath(digest digest.Digest, sharedBlobDir string) (string, error) { if err := digest.Validate(); err != nil { return "", errors.Wrapf(err, "unexpected digest reference %s", digest) } blobDir := filepath.Join(ref.dir, "blobs") if sharedBlobDir != "" { blobDir = sharedBlobDir } return filepath.Join(blobDir, digest.Algorithm().String(), digest.Hex()), nil }
go
func (ref ociReference) blobPath(digest digest.Digest, sharedBlobDir string) (string, error) { if err := digest.Validate(); err != nil { return "", errors.Wrapf(err, "unexpected digest reference %s", digest) } blobDir := filepath.Join(ref.dir, "blobs") if sharedBlobDir != "" { blobDir = sharedBlobDir } return filepath.Join(blobDir, digest.Algorithm().String(), digest.Hex()), nil }
[ "func", "(", "ref", "ociReference", ")", "blobPath", "(", "digest", "digest", ".", "Digest", ",", "sharedBlobDir", "string", ")", "(", "string", ",", "error", ")", "{", "if", "err", ":=", "digest", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "\"\"", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"unexpected digest reference %s\"", ",", "digest", ")", "\n", "}", "\n", "blobDir", ":=", "filepath", ".", "Join", "(", "ref", ".", "dir", ",", "\"blobs\"", ")", "\n", "if", "sharedBlobDir", "!=", "\"\"", "{", "blobDir", "=", "sharedBlobDir", "\n", "}", "\n", "return", "filepath", ".", "Join", "(", "blobDir", ",", "digest", ".", "Algorithm", "(", ")", ".", "String", "(", ")", ",", "digest", ".", "Hex", "(", ")", ")", ",", "nil", "\n", "}" ]
// blobPath returns a path for a blob within a directory using OCI image-layout conventions.
[ "blobPath", "returns", "a", "path", "for", "a", "blob", "within", "a", "directory", "using", "OCI", "image", "-", "layout", "conventions", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/layout/oci_transport.go#L255-L264
test
containers/image
signature/docker.go
SignDockerManifest
func SignDockerManifest(m []byte, dockerReference string, mech SigningMechanism, keyIdentity string) ([]byte, error) { manifestDigest, err := manifest.Digest(m) if err != nil { return nil, err } sig := newUntrustedSignature(manifestDigest, dockerReference) return sig.sign(mech, keyIdentity) }
go
func SignDockerManifest(m []byte, dockerReference string, mech SigningMechanism, keyIdentity string) ([]byte, error) { manifestDigest, err := manifest.Digest(m) if err != nil { return nil, err } sig := newUntrustedSignature(manifestDigest, dockerReference) return sig.sign(mech, keyIdentity) }
[ "func", "SignDockerManifest", "(", "m", "[", "]", "byte", ",", "dockerReference", "string", ",", "mech", "SigningMechanism", ",", "keyIdentity", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "manifestDigest", ",", "err", ":=", "manifest", ".", "Digest", "(", "m", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "sig", ":=", "newUntrustedSignature", "(", "manifestDigest", ",", "dockerReference", ")", "\n", "return", "sig", ".", "sign", "(", "mech", ",", "keyIdentity", ")", "\n", "}" ]
// SignDockerManifest returns a signature for manifest as the specified dockerReference, // using mech and keyIdentity.
[ "SignDockerManifest", "returns", "a", "signature", "for", "manifest", "as", "the", "specified", "dockerReference", "using", "mech", "and", "keyIdentity", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/docker.go#L15-L22
test
containers/image
signature/docker.go
VerifyDockerManifestSignature
func VerifyDockerManifestSignature(unverifiedSignature, unverifiedManifest []byte, expectedDockerReference string, mech SigningMechanism, expectedKeyIdentity string) (*Signature, error) { expectedRef, err := reference.ParseNormalizedNamed(expectedDockerReference) if err != nil { return nil, err } sig, err := verifyAndExtractSignature(mech, unverifiedSignature, signatureAcceptanceRules{ validateKeyIdentity: func(keyIdentity string) error { if keyIdentity != expectedKeyIdentity { return InvalidSignatureError{msg: fmt.Sprintf("Signature by %s does not match expected fingerprint %s", keyIdentity, expectedKeyIdentity)} } return nil }, validateSignedDockerReference: func(signedDockerReference string) error { signedRef, err := reference.ParseNormalizedNamed(signedDockerReference) if err != nil { return InvalidSignatureError{msg: fmt.Sprintf("Invalid docker reference %s in signature", signedDockerReference)} } if signedRef.String() != expectedRef.String() { return InvalidSignatureError{msg: fmt.Sprintf("Docker reference %s does not match %s", signedDockerReference, expectedDockerReference)} } return nil }, validateSignedDockerManifestDigest: func(signedDockerManifestDigest digest.Digest) error { matches, err := manifest.MatchesDigest(unverifiedManifest, signedDockerManifestDigest) if err != nil { return err } if !matches { return InvalidSignatureError{msg: fmt.Sprintf("Signature for docker digest %q does not match", signedDockerManifestDigest)} } return nil }, }) if err != nil { return nil, err } return sig, nil }
go
func VerifyDockerManifestSignature(unverifiedSignature, unverifiedManifest []byte, expectedDockerReference string, mech SigningMechanism, expectedKeyIdentity string) (*Signature, error) { expectedRef, err := reference.ParseNormalizedNamed(expectedDockerReference) if err != nil { return nil, err } sig, err := verifyAndExtractSignature(mech, unverifiedSignature, signatureAcceptanceRules{ validateKeyIdentity: func(keyIdentity string) error { if keyIdentity != expectedKeyIdentity { return InvalidSignatureError{msg: fmt.Sprintf("Signature by %s does not match expected fingerprint %s", keyIdentity, expectedKeyIdentity)} } return nil }, validateSignedDockerReference: func(signedDockerReference string) error { signedRef, err := reference.ParseNormalizedNamed(signedDockerReference) if err != nil { return InvalidSignatureError{msg: fmt.Sprintf("Invalid docker reference %s in signature", signedDockerReference)} } if signedRef.String() != expectedRef.String() { return InvalidSignatureError{msg: fmt.Sprintf("Docker reference %s does not match %s", signedDockerReference, expectedDockerReference)} } return nil }, validateSignedDockerManifestDigest: func(signedDockerManifestDigest digest.Digest) error { matches, err := manifest.MatchesDigest(unverifiedManifest, signedDockerManifestDigest) if err != nil { return err } if !matches { return InvalidSignatureError{msg: fmt.Sprintf("Signature for docker digest %q does not match", signedDockerManifestDigest)} } return nil }, }) if err != nil { return nil, err } return sig, nil }
[ "func", "VerifyDockerManifestSignature", "(", "unverifiedSignature", ",", "unverifiedManifest", "[", "]", "byte", ",", "expectedDockerReference", "string", ",", "mech", "SigningMechanism", ",", "expectedKeyIdentity", "string", ")", "(", "*", "Signature", ",", "error", ")", "{", "expectedRef", ",", "err", ":=", "reference", ".", "ParseNormalizedNamed", "(", "expectedDockerReference", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "sig", ",", "err", ":=", "verifyAndExtractSignature", "(", "mech", ",", "unverifiedSignature", ",", "signatureAcceptanceRules", "{", "validateKeyIdentity", ":", "func", "(", "keyIdentity", "string", ")", "error", "{", "if", "keyIdentity", "!=", "expectedKeyIdentity", "{", "return", "InvalidSignatureError", "{", "msg", ":", "fmt", ".", "Sprintf", "(", "\"Signature by %s does not match expected fingerprint %s\"", ",", "keyIdentity", ",", "expectedKeyIdentity", ")", "}", "\n", "}", "\n", "return", "nil", "\n", "}", ",", "validateSignedDockerReference", ":", "func", "(", "signedDockerReference", "string", ")", "error", "{", "signedRef", ",", "err", ":=", "reference", ".", "ParseNormalizedNamed", "(", "signedDockerReference", ")", "\n", "if", "err", "!=", "nil", "{", "return", "InvalidSignatureError", "{", "msg", ":", "fmt", ".", "Sprintf", "(", "\"Invalid docker reference %s in signature\"", ",", "signedDockerReference", ")", "}", "\n", "}", "\n", "if", "signedRef", ".", "String", "(", ")", "!=", "expectedRef", ".", "String", "(", ")", "{", "return", "InvalidSignatureError", "{", "msg", ":", "fmt", ".", "Sprintf", "(", "\"Docker reference %s does not match %s\"", ",", "signedDockerReference", ",", "expectedDockerReference", ")", "}", "\n", "}", "\n", "return", "nil", "\n", "}", ",", "validateSignedDockerManifestDigest", ":", "func", "(", "signedDockerManifestDigest", "digest", ".", "Digest", ")", "error", "{", "matches", ",", "err", ":=", "manifest", ".", "MatchesDigest", "(", "unverifiedManifest", ",", "signedDockerManifestDigest", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "!", "matches", "{", "return", "InvalidSignatureError", "{", "msg", ":", "fmt", ".", "Sprintf", "(", "\"Signature for docker digest %q does not match\"", ",", "signedDockerManifestDigest", ")", "}", "\n", "}", "\n", "return", "nil", "\n", "}", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "sig", ",", "nil", "\n", "}" ]
// VerifyDockerManifestSignature checks that unverifiedSignature uses expectedKeyIdentity to sign unverifiedManifest as expectedDockerReference, // using mech.
[ "VerifyDockerManifestSignature", "checks", "that", "unverifiedSignature", "uses", "expectedKeyIdentity", "to", "sign", "unverifiedManifest", "as", "expectedDockerReference", "using", "mech", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/docker.go#L26-L65
test
containers/image
openshift/openshift.go
newOpenshiftClient
func newOpenshiftClient(ref openshiftReference) (*openshiftClient, error) { // We have already done this parsing in ParseReference, but thrown away // httpClient. So, parse again. // (We could also rework/split restClientFor to "get base URL" to be done // in ParseReference, and "get httpClient" to be done here. But until/unless // we support non-default clusters, this is good enough.) // Overall, this is modelled on openshift/origin/pkg/cmd/util/clientcmd.New().ClientConfig() and openshift/origin/pkg/client. cmdConfig := defaultClientConfig() logrus.Debugf("cmdConfig: %#v", cmdConfig) restConfig, err := cmdConfig.ClientConfig() if err != nil { return nil, err } // REMOVED: SetOpenShiftDefaults (values are not overridable in config files, so hard-coded these defaults.) logrus.Debugf("restConfig: %#v", restConfig) baseURL, httpClient, err := restClientFor(restConfig) if err != nil { return nil, err } logrus.Debugf("URL: %#v", *baseURL) if httpClient == nil { httpClient = http.DefaultClient } return &openshiftClient{ ref: ref, baseURL: baseURL, httpClient: httpClient, bearerToken: restConfig.BearerToken, username: restConfig.Username, password: restConfig.Password, }, nil }
go
func newOpenshiftClient(ref openshiftReference) (*openshiftClient, error) { // We have already done this parsing in ParseReference, but thrown away // httpClient. So, parse again. // (We could also rework/split restClientFor to "get base URL" to be done // in ParseReference, and "get httpClient" to be done here. But until/unless // we support non-default clusters, this is good enough.) // Overall, this is modelled on openshift/origin/pkg/cmd/util/clientcmd.New().ClientConfig() and openshift/origin/pkg/client. cmdConfig := defaultClientConfig() logrus.Debugf("cmdConfig: %#v", cmdConfig) restConfig, err := cmdConfig.ClientConfig() if err != nil { return nil, err } // REMOVED: SetOpenShiftDefaults (values are not overridable in config files, so hard-coded these defaults.) logrus.Debugf("restConfig: %#v", restConfig) baseURL, httpClient, err := restClientFor(restConfig) if err != nil { return nil, err } logrus.Debugf("URL: %#v", *baseURL) if httpClient == nil { httpClient = http.DefaultClient } return &openshiftClient{ ref: ref, baseURL: baseURL, httpClient: httpClient, bearerToken: restConfig.BearerToken, username: restConfig.Username, password: restConfig.Password, }, nil }
[ "func", "newOpenshiftClient", "(", "ref", "openshiftReference", ")", "(", "*", "openshiftClient", ",", "error", ")", "{", "cmdConfig", ":=", "defaultClientConfig", "(", ")", "\n", "logrus", ".", "Debugf", "(", "\"cmdConfig: %#v\"", ",", "cmdConfig", ")", "\n", "restConfig", ",", "err", ":=", "cmdConfig", ".", "ClientConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "logrus", ".", "Debugf", "(", "\"restConfig: %#v\"", ",", "restConfig", ")", "\n", "baseURL", ",", "httpClient", ",", "err", ":=", "restClientFor", "(", "restConfig", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "logrus", ".", "Debugf", "(", "\"URL: %#v\"", ",", "*", "baseURL", ")", "\n", "if", "httpClient", "==", "nil", "{", "httpClient", "=", "http", ".", "DefaultClient", "\n", "}", "\n", "return", "&", "openshiftClient", "{", "ref", ":", "ref", ",", "baseURL", ":", "baseURL", ",", "httpClient", ":", "httpClient", ",", "bearerToken", ":", "restConfig", ".", "BearerToken", ",", "username", ":", "restConfig", ".", "Username", ",", "password", ":", "restConfig", ".", "Password", ",", "}", ",", "nil", "\n", "}" ]
// newOpenshiftClient creates a new openshiftClient for the specified reference.
[ "newOpenshiftClient", "creates", "a", "new", "openshiftClient", "for", "the", "specified", "reference", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift.go#L37-L71
test
containers/image
openshift/openshift.go
doRequest
func (c *openshiftClient) doRequest(ctx context.Context, method, path string, requestBody []byte) ([]byte, error) { url := *c.baseURL url.Path = path var requestBodyReader io.Reader if requestBody != nil { logrus.Debugf("Will send body: %s", requestBody) requestBodyReader = bytes.NewReader(requestBody) } req, err := http.NewRequest(method, url.String(), requestBodyReader) if err != nil { return nil, err } req = req.WithContext(ctx) if len(c.bearerToken) != 0 { req.Header.Set("Authorization", "Bearer "+c.bearerToken) } else if len(c.username) != 0 { req.SetBasicAuth(c.username, c.password) } req.Header.Set("Accept", "application/json, */*") req.Header.Set("User-Agent", fmt.Sprintf("skopeo/%s", version.Version)) if requestBody != nil { req.Header.Set("Content-Type", "application/json") } logrus.Debugf("%s %s", method, url.String()) res, err := c.httpClient.Do(req) if err != nil { return nil, err } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { return nil, err } logrus.Debugf("Got body: %s", body) // FIXME: Just throwing this useful information away only to try to guess later... logrus.Debugf("Got content-type: %s", res.Header.Get("Content-Type")) var status status statusValid := false if err := json.Unmarshal(body, &status); err == nil && len(status.Status) > 0 { statusValid = true } switch { case res.StatusCode == http.StatusSwitchingProtocols: // FIXME?! No idea why this weird case exists in k8s.io/kubernetes/pkg/client/restclient. if statusValid && status.Status != "Success" { return nil, errors.New(status.Message) } case res.StatusCode >= http.StatusOK && res.StatusCode <= http.StatusPartialContent: // OK. default: if statusValid { return nil, errors.New(status.Message) } return nil, errors.Errorf("HTTP error: status code: %d (%s), body: %s", res.StatusCode, http.StatusText(res.StatusCode), string(body)) } return body, nil }
go
func (c *openshiftClient) doRequest(ctx context.Context, method, path string, requestBody []byte) ([]byte, error) { url := *c.baseURL url.Path = path var requestBodyReader io.Reader if requestBody != nil { logrus.Debugf("Will send body: %s", requestBody) requestBodyReader = bytes.NewReader(requestBody) } req, err := http.NewRequest(method, url.String(), requestBodyReader) if err != nil { return nil, err } req = req.WithContext(ctx) if len(c.bearerToken) != 0 { req.Header.Set("Authorization", "Bearer "+c.bearerToken) } else if len(c.username) != 0 { req.SetBasicAuth(c.username, c.password) } req.Header.Set("Accept", "application/json, */*") req.Header.Set("User-Agent", fmt.Sprintf("skopeo/%s", version.Version)) if requestBody != nil { req.Header.Set("Content-Type", "application/json") } logrus.Debugf("%s %s", method, url.String()) res, err := c.httpClient.Do(req) if err != nil { return nil, err } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { return nil, err } logrus.Debugf("Got body: %s", body) // FIXME: Just throwing this useful information away only to try to guess later... logrus.Debugf("Got content-type: %s", res.Header.Get("Content-Type")) var status status statusValid := false if err := json.Unmarshal(body, &status); err == nil && len(status.Status) > 0 { statusValid = true } switch { case res.StatusCode == http.StatusSwitchingProtocols: // FIXME?! No idea why this weird case exists in k8s.io/kubernetes/pkg/client/restclient. if statusValid && status.Status != "Success" { return nil, errors.New(status.Message) } case res.StatusCode >= http.StatusOK && res.StatusCode <= http.StatusPartialContent: // OK. default: if statusValid { return nil, errors.New(status.Message) } return nil, errors.Errorf("HTTP error: status code: %d (%s), body: %s", res.StatusCode, http.StatusText(res.StatusCode), string(body)) } return body, nil }
[ "func", "(", "c", "*", "openshiftClient", ")", "doRequest", "(", "ctx", "context", ".", "Context", ",", "method", ",", "path", "string", ",", "requestBody", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "url", ":=", "*", "c", ".", "baseURL", "\n", "url", ".", "Path", "=", "path", "\n", "var", "requestBodyReader", "io", ".", "Reader", "\n", "if", "requestBody", "!=", "nil", "{", "logrus", ".", "Debugf", "(", "\"Will send body: %s\"", ",", "requestBody", ")", "\n", "requestBodyReader", "=", "bytes", ".", "NewReader", "(", "requestBody", ")", "\n", "}", "\n", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "method", ",", "url", ".", "String", "(", ")", ",", "requestBodyReader", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "req", "=", "req", ".", "WithContext", "(", "ctx", ")", "\n", "if", "len", "(", "c", ".", "bearerToken", ")", "!=", "0", "{", "req", ".", "Header", ".", "Set", "(", "\"Authorization\"", ",", "\"Bearer \"", "+", "c", ".", "bearerToken", ")", "\n", "}", "else", "if", "len", "(", "c", ".", "username", ")", "!=", "0", "{", "req", ".", "SetBasicAuth", "(", "c", ".", "username", ",", "c", ".", "password", ")", "\n", "}", "\n", "req", ".", "Header", ".", "Set", "(", "\"Accept\"", ",", "\"application/json, */*\"", ")", "\n", "req", ".", "Header", ".", "Set", "(", "\"User-Agent\"", ",", "fmt", ".", "Sprintf", "(", "\"skopeo/%s\"", ",", "version", ".", "Version", ")", ")", "\n", "if", "requestBody", "!=", "nil", "{", "req", ".", "Header", ".", "Set", "(", "\"Content-Type\"", ",", "\"application/json\"", ")", "\n", "}", "\n", "logrus", ".", "Debugf", "(", "\"%s %s\"", ",", "method", ",", "url", ".", "String", "(", ")", ")", "\n", "res", ",", "err", ":=", "c", ".", "httpClient", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "res", ".", "Body", ".", "Close", "(", ")", "\n", "body", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "res", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "logrus", ".", "Debugf", "(", "\"Got body: %s\"", ",", "body", ")", "\n", "logrus", ".", "Debugf", "(", "\"Got content-type: %s\"", ",", "res", ".", "Header", ".", "Get", "(", "\"Content-Type\"", ")", ")", "\n", "var", "status", "status", "\n", "statusValid", ":=", "false", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "body", ",", "&", "status", ")", ";", "err", "==", "nil", "&&", "len", "(", "status", ".", "Status", ")", ">", "0", "{", "statusValid", "=", "true", "\n", "}", "\n", "switch", "{", "case", "res", ".", "StatusCode", "==", "http", ".", "StatusSwitchingProtocols", ":", "if", "statusValid", "&&", "status", ".", "Status", "!=", "\"Success\"", "{", "return", "nil", ",", "errors", ".", "New", "(", "status", ".", "Message", ")", "\n", "}", "\n", "case", "res", ".", "StatusCode", ">=", "http", ".", "StatusOK", "&&", "res", ".", "StatusCode", "<=", "http", ".", "StatusPartialContent", ":", "default", ":", "if", "statusValid", "{", "return", "nil", ",", "errors", ".", "New", "(", "status", ".", "Message", ")", "\n", "}", "\n", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"HTTP error: status code: %d (%s), body: %s\"", ",", "res", ".", "StatusCode", ",", "http", ".", "StatusText", "(", "res", ".", "StatusCode", ")", ",", "string", "(", "body", ")", ")", "\n", "}", "\n", "return", "body", ",", "nil", "\n", "}" ]
// doRequest performs a correctly authenticated request to a specified path, and returns response body or an error object.
[ "doRequest", "performs", "a", "correctly", "authenticated", "request", "to", "a", "specified", "path", "and", "returns", "response", "body", "or", "an", "error", "object", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift.go#L74-L134
test
containers/image
openshift/openshift.go
getImage
func (c *openshiftClient) getImage(ctx context.Context, imageStreamImageName string) (*image, error) { // FIXME: validate components per validation.IsValidPathSegmentName? path := fmt.Sprintf("/oapi/v1/namespaces/%s/imagestreamimages/%s@%s", c.ref.namespace, c.ref.stream, imageStreamImageName) body, err := c.doRequest(ctx, "GET", path, nil) if err != nil { return nil, err } // Note: This does absolutely no kind/version checking or conversions. var isi imageStreamImage if err := json.Unmarshal(body, &isi); err != nil { return nil, err } return &isi.Image, nil }
go
func (c *openshiftClient) getImage(ctx context.Context, imageStreamImageName string) (*image, error) { // FIXME: validate components per validation.IsValidPathSegmentName? path := fmt.Sprintf("/oapi/v1/namespaces/%s/imagestreamimages/%s@%s", c.ref.namespace, c.ref.stream, imageStreamImageName) body, err := c.doRequest(ctx, "GET", path, nil) if err != nil { return nil, err } // Note: This does absolutely no kind/version checking or conversions. var isi imageStreamImage if err := json.Unmarshal(body, &isi); err != nil { return nil, err } return &isi.Image, nil }
[ "func", "(", "c", "*", "openshiftClient", ")", "getImage", "(", "ctx", "context", ".", "Context", ",", "imageStreamImageName", "string", ")", "(", "*", "image", ",", "error", ")", "{", "path", ":=", "fmt", ".", "Sprintf", "(", "\"/oapi/v1/namespaces/%s/imagestreamimages/%s@%s\"", ",", "c", ".", "ref", ".", "namespace", ",", "c", ".", "ref", ".", "stream", ",", "imageStreamImageName", ")", "\n", "body", ",", "err", ":=", "c", ".", "doRequest", "(", "ctx", ",", "\"GET\"", ",", "path", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "var", "isi", "imageStreamImage", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "body", ",", "&", "isi", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "isi", ".", "Image", ",", "nil", "\n", "}" ]
// getImage loads the specified image object.
[ "getImage", "loads", "the", "specified", "image", "object", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift.go#L137-L150
test
containers/image
openshift/openshift.go
convertDockerImageReference
func (c *openshiftClient) convertDockerImageReference(ref string) (string, error) { parts := strings.SplitN(ref, "/", 2) if len(parts) != 2 { return "", errors.Errorf("Invalid format of docker reference %s: missing '/'", ref) } return reference.Domain(c.ref.dockerReference) + "/" + parts[1], nil }
go
func (c *openshiftClient) convertDockerImageReference(ref string) (string, error) { parts := strings.SplitN(ref, "/", 2) if len(parts) != 2 { return "", errors.Errorf("Invalid format of docker reference %s: missing '/'", ref) } return reference.Domain(c.ref.dockerReference) + "/" + parts[1], nil }
[ "func", "(", "c", "*", "openshiftClient", ")", "convertDockerImageReference", "(", "ref", "string", ")", "(", "string", ",", "error", ")", "{", "parts", ":=", "strings", ".", "SplitN", "(", "ref", ",", "\"/\"", ",", "2", ")", "\n", "if", "len", "(", "parts", ")", "!=", "2", "{", "return", "\"\"", ",", "errors", ".", "Errorf", "(", "\"Invalid format of docker reference %s: missing '/'\"", ",", "ref", ")", "\n", "}", "\n", "return", "reference", ".", "Domain", "(", "c", ".", "ref", ".", "dockerReference", ")", "+", "\"/\"", "+", "parts", "[", "1", "]", ",", "nil", "\n", "}" ]
// convertDockerImageReference takes an image API DockerImageReference value and returns a reference we can actually use; // currently OpenShift stores the cluster-internal service IPs here, which are unusable from the outside.
[ "convertDockerImageReference", "takes", "an", "image", "API", "DockerImageReference", "value", "and", "returns", "a", "reference", "we", "can", "actually", "use", ";", "currently", "OpenShift", "stores", "the", "cluster", "-", "internal", "service", "IPs", "here", "which", "are", "unusable", "from", "the", "outside", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift.go#L154-L160
test
containers/image
openshift/openshift.go
ensureImageIsResolved
func (s *openshiftImageSource) ensureImageIsResolved(ctx context.Context) error { if s.docker != nil { return nil } // FIXME: validate components per validation.IsValidPathSegmentName? path := fmt.Sprintf("/oapi/v1/namespaces/%s/imagestreams/%s", s.client.ref.namespace, s.client.ref.stream) body, err := s.client.doRequest(ctx, "GET", path, nil) if err != nil { return err } // Note: This does absolutely no kind/version checking or conversions. var is imageStream if err := json.Unmarshal(body, &is); err != nil { return err } var te *tagEvent for _, tag := range is.Status.Tags { if tag.Tag != s.client.ref.dockerReference.Tag() { continue } if len(tag.Items) > 0 { te = &tag.Items[0] break } } if te == nil { return errors.Errorf("No matching tag found") } logrus.Debugf("tag event %#v", te) dockerRefString, err := s.client.convertDockerImageReference(te.DockerImageReference) if err != nil { return err } logrus.Debugf("Resolved reference %#v", dockerRefString) dockerRef, err := docker.ParseReference("//" + dockerRefString) if err != nil { return err } d, err := dockerRef.NewImageSource(ctx, s.sys) if err != nil { return err } s.docker = d s.imageStreamImageName = te.Image return nil }
go
func (s *openshiftImageSource) ensureImageIsResolved(ctx context.Context) error { if s.docker != nil { return nil } // FIXME: validate components per validation.IsValidPathSegmentName? path := fmt.Sprintf("/oapi/v1/namespaces/%s/imagestreams/%s", s.client.ref.namespace, s.client.ref.stream) body, err := s.client.doRequest(ctx, "GET", path, nil) if err != nil { return err } // Note: This does absolutely no kind/version checking or conversions. var is imageStream if err := json.Unmarshal(body, &is); err != nil { return err } var te *tagEvent for _, tag := range is.Status.Tags { if tag.Tag != s.client.ref.dockerReference.Tag() { continue } if len(tag.Items) > 0 { te = &tag.Items[0] break } } if te == nil { return errors.Errorf("No matching tag found") } logrus.Debugf("tag event %#v", te) dockerRefString, err := s.client.convertDockerImageReference(te.DockerImageReference) if err != nil { return err } logrus.Debugf("Resolved reference %#v", dockerRefString) dockerRef, err := docker.ParseReference("//" + dockerRefString) if err != nil { return err } d, err := dockerRef.NewImageSource(ctx, s.sys) if err != nil { return err } s.docker = d s.imageStreamImageName = te.Image return nil }
[ "func", "(", "s", "*", "openshiftImageSource", ")", "ensureImageIsResolved", "(", "ctx", "context", ".", "Context", ")", "error", "{", "if", "s", ".", "docker", "!=", "nil", "{", "return", "nil", "\n", "}", "\n", "path", ":=", "fmt", ".", "Sprintf", "(", "\"/oapi/v1/namespaces/%s/imagestreams/%s\"", ",", "s", ".", "client", ".", "ref", ".", "namespace", ",", "s", ".", "client", ".", "ref", ".", "stream", ")", "\n", "body", ",", "err", ":=", "s", ".", "client", ".", "doRequest", "(", "ctx", ",", "\"GET\"", ",", "path", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "var", "is", "imageStream", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "body", ",", "&", "is", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "var", "te", "*", "tagEvent", "\n", "for", "_", ",", "tag", ":=", "range", "is", ".", "Status", ".", "Tags", "{", "if", "tag", ".", "Tag", "!=", "s", ".", "client", ".", "ref", ".", "dockerReference", ".", "Tag", "(", ")", "{", "continue", "\n", "}", "\n", "if", "len", "(", "tag", ".", "Items", ")", ">", "0", "{", "te", "=", "&", "tag", ".", "Items", "[", "0", "]", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "te", "==", "nil", "{", "return", "errors", ".", "Errorf", "(", "\"No matching tag found\"", ")", "\n", "}", "\n", "logrus", ".", "Debugf", "(", "\"tag event %#v\"", ",", "te", ")", "\n", "dockerRefString", ",", "err", ":=", "s", ".", "client", ".", "convertDockerImageReference", "(", "te", ".", "DockerImageReference", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "logrus", ".", "Debugf", "(", "\"Resolved reference %#v\"", ",", "dockerRefString", ")", "\n", "dockerRef", ",", "err", ":=", "docker", ".", "ParseReference", "(", "\"//\"", "+", "dockerRefString", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "d", ",", "err", ":=", "dockerRef", ".", "NewImageSource", "(", "ctx", ",", "s", ".", "sys", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "s", ".", "docker", "=", "d", "\n", "s", ".", "imageStreamImageName", "=", "te", ".", "Image", "\n", "return", "nil", "\n", "}" ]
// ensureImageIsResolved sets up s.docker and s.imageStreamImageName
[ "ensureImageIsResolved", "sets", "up", "s", ".", "docker", "and", "s", ".", "imageStreamImageName" ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift.go#L262-L308
test
containers/image
openshift/openshift.go
newImageDestination
func newImageDestination(ctx context.Context, sys *types.SystemContext, ref openshiftReference) (types.ImageDestination, error) { client, err := newOpenshiftClient(ref) if err != nil { return nil, err } // FIXME: Should this always use a digest, not a tag? Uploading to Docker by tag requires the tag _inside_ the manifest to match, // i.e. a single signed image cannot be available under multiple tags. But with types.ImageDestination, we don't know // the manifest digest at this point. dockerRefString := fmt.Sprintf("//%s/%s/%s:%s", reference.Domain(client.ref.dockerReference), client.ref.namespace, client.ref.stream, client.ref.dockerReference.Tag()) dockerRef, err := docker.ParseReference(dockerRefString) if err != nil { return nil, err } docker, err := dockerRef.NewImageDestination(ctx, sys) if err != nil { return nil, err } return &openshiftImageDestination{ client: client, docker: docker, }, nil }
go
func newImageDestination(ctx context.Context, sys *types.SystemContext, ref openshiftReference) (types.ImageDestination, error) { client, err := newOpenshiftClient(ref) if err != nil { return nil, err } // FIXME: Should this always use a digest, not a tag? Uploading to Docker by tag requires the tag _inside_ the manifest to match, // i.e. a single signed image cannot be available under multiple tags. But with types.ImageDestination, we don't know // the manifest digest at this point. dockerRefString := fmt.Sprintf("//%s/%s/%s:%s", reference.Domain(client.ref.dockerReference), client.ref.namespace, client.ref.stream, client.ref.dockerReference.Tag()) dockerRef, err := docker.ParseReference(dockerRefString) if err != nil { return nil, err } docker, err := dockerRef.NewImageDestination(ctx, sys) if err != nil { return nil, err } return &openshiftImageDestination{ client: client, docker: docker, }, nil }
[ "func", "newImageDestination", "(", "ctx", "context", ".", "Context", ",", "sys", "*", "types", ".", "SystemContext", ",", "ref", "openshiftReference", ")", "(", "types", ".", "ImageDestination", ",", "error", ")", "{", "client", ",", "err", ":=", "newOpenshiftClient", "(", "ref", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "dockerRefString", ":=", "fmt", ".", "Sprintf", "(", "\"//%s/%s/%s:%s\"", ",", "reference", ".", "Domain", "(", "client", ".", "ref", ".", "dockerReference", ")", ",", "client", ".", "ref", ".", "namespace", ",", "client", ".", "ref", ".", "stream", ",", "client", ".", "ref", ".", "dockerReference", ".", "Tag", "(", ")", ")", "\n", "dockerRef", ",", "err", ":=", "docker", ".", "ParseReference", "(", "dockerRefString", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "docker", ",", "err", ":=", "dockerRef", ".", "NewImageDestination", "(", "ctx", ",", "sys", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "openshiftImageDestination", "{", "client", ":", "client", ",", "docker", ":", "docker", ",", "}", ",", "nil", "\n", "}" ]
// newImageDestination creates a new ImageDestination for the specified reference.
[ "newImageDestination", "creates", "a", "new", "ImageDestination", "for", "the", "specified", "reference", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/openshift/openshift.go#L318-L341
test
containers/image
signature/signature.go
newUntrustedSignature
func newUntrustedSignature(dockerManifestDigest digest.Digest, dockerReference string) untrustedSignature { // Use intermediate variables for these values so that we can take their addresses. // Golang guarantees that they will have a new address on every execution. creatorID := "atomic " + version.Version timestamp := time.Now().Unix() return untrustedSignature{ UntrustedDockerManifestDigest: dockerManifestDigest, UntrustedDockerReference: dockerReference, UntrustedCreatorID: &creatorID, UntrustedTimestamp: &timestamp, } }
go
func newUntrustedSignature(dockerManifestDigest digest.Digest, dockerReference string) untrustedSignature { // Use intermediate variables for these values so that we can take their addresses. // Golang guarantees that they will have a new address on every execution. creatorID := "atomic " + version.Version timestamp := time.Now().Unix() return untrustedSignature{ UntrustedDockerManifestDigest: dockerManifestDigest, UntrustedDockerReference: dockerReference, UntrustedCreatorID: &creatorID, UntrustedTimestamp: &timestamp, } }
[ "func", "newUntrustedSignature", "(", "dockerManifestDigest", "digest", ".", "Digest", ",", "dockerReference", "string", ")", "untrustedSignature", "{", "creatorID", ":=", "\"atomic \"", "+", "version", ".", "Version", "\n", "timestamp", ":=", "time", ".", "Now", "(", ")", ".", "Unix", "(", ")", "\n", "return", "untrustedSignature", "{", "UntrustedDockerManifestDigest", ":", "dockerManifestDigest", ",", "UntrustedDockerReference", ":", "dockerReference", ",", "UntrustedCreatorID", ":", "&", "creatorID", ",", "UntrustedTimestamp", ":", "&", "timestamp", ",", "}", "\n", "}" ]
// newUntrustedSignature returns an untrustedSignature object with // the specified primary contents and appropriate metadata.
[ "newUntrustedSignature", "returns", "an", "untrustedSignature", "object", "with", "the", "specified", "primary", "contents", "and", "appropriate", "metadata", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/signature.go#L68-L79
test
containers/image
signature/signature.go
MarshalJSON
func (s untrustedSignature) MarshalJSON() ([]byte, error) { if s.UntrustedDockerManifestDigest == "" || s.UntrustedDockerReference == "" { return nil, errors.New("Unexpected empty signature content") } critical := map[string]interface{}{ "type": signatureType, "image": map[string]string{"docker-manifest-digest": s.UntrustedDockerManifestDigest.String()}, "identity": map[string]string{"docker-reference": s.UntrustedDockerReference}, } optional := map[string]interface{}{} if s.UntrustedCreatorID != nil { optional["creator"] = *s.UntrustedCreatorID } if s.UntrustedTimestamp != nil { optional["timestamp"] = *s.UntrustedTimestamp } signature := map[string]interface{}{ "critical": critical, "optional": optional, } return json.Marshal(signature) }
go
func (s untrustedSignature) MarshalJSON() ([]byte, error) { if s.UntrustedDockerManifestDigest == "" || s.UntrustedDockerReference == "" { return nil, errors.New("Unexpected empty signature content") } critical := map[string]interface{}{ "type": signatureType, "image": map[string]string{"docker-manifest-digest": s.UntrustedDockerManifestDigest.String()}, "identity": map[string]string{"docker-reference": s.UntrustedDockerReference}, } optional := map[string]interface{}{} if s.UntrustedCreatorID != nil { optional["creator"] = *s.UntrustedCreatorID } if s.UntrustedTimestamp != nil { optional["timestamp"] = *s.UntrustedTimestamp } signature := map[string]interface{}{ "critical": critical, "optional": optional, } return json.Marshal(signature) }
[ "func", "(", "s", "untrustedSignature", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "s", ".", "UntrustedDockerManifestDigest", "==", "\"\"", "||", "s", ".", "UntrustedDockerReference", "==", "\"\"", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"Unexpected empty signature content\"", ")", "\n", "}", "\n", "critical", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"type\"", ":", "signatureType", ",", "\"image\"", ":", "map", "[", "string", "]", "string", "{", "\"docker-manifest-digest\"", ":", "s", ".", "UntrustedDockerManifestDigest", ".", "String", "(", ")", "}", ",", "\"identity\"", ":", "map", "[", "string", "]", "string", "{", "\"docker-reference\"", ":", "s", ".", "UntrustedDockerReference", "}", ",", "}", "\n", "optional", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "}", "\n", "if", "s", ".", "UntrustedCreatorID", "!=", "nil", "{", "optional", "[", "\"creator\"", "]", "=", "*", "s", ".", "UntrustedCreatorID", "\n", "}", "\n", "if", "s", ".", "UntrustedTimestamp", "!=", "nil", "{", "optional", "[", "\"timestamp\"", "]", "=", "*", "s", ".", "UntrustedTimestamp", "\n", "}", "\n", "signature", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"critical\"", ":", "critical", ",", "\"optional\"", ":", "optional", ",", "}", "\n", "return", "json", ".", "Marshal", "(", "signature", ")", "\n", "}" ]
// MarshalJSON implements the json.Marshaler interface.
[ "MarshalJSON", "implements", "the", "json", ".", "Marshaler", "interface", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/signature.go#L85-L106
test
containers/image
signature/signature.go
UnmarshalJSON
func (s *untrustedSignature) UnmarshalJSON(data []byte) error { err := s.strictUnmarshalJSON(data) if err != nil { if _, ok := err.(jsonFormatError); ok { err = InvalidSignatureError{msg: err.Error()} } } return err }
go
func (s *untrustedSignature) UnmarshalJSON(data []byte) error { err := s.strictUnmarshalJSON(data) if err != nil { if _, ok := err.(jsonFormatError); ok { err = InvalidSignatureError{msg: err.Error()} } } return err }
[ "func", "(", "s", "*", "untrustedSignature", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "err", ":=", "s", ".", "strictUnmarshalJSON", "(", "data", ")", "\n", "if", "err", "!=", "nil", "{", "if", "_", ",", "ok", ":=", "err", ".", "(", "jsonFormatError", ")", ";", "ok", "{", "err", "=", "InvalidSignatureError", "{", "msg", ":", "err", ".", "Error", "(", ")", "}", "\n", "}", "\n", "}", "\n", "return", "err", "\n", "}" ]
// UnmarshalJSON implements the json.Unmarshaler interface
[ "UnmarshalJSON", "implements", "the", "json", ".", "Unmarshaler", "interface" ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/signature.go#L112-L120
test
containers/image
signature/signature.go
verifyAndExtractSignature
func verifyAndExtractSignature(mech SigningMechanism, unverifiedSignature []byte, rules signatureAcceptanceRules) (*Signature, error) { signed, keyIdentity, err := mech.Verify(unverifiedSignature) if err != nil { return nil, err } if err := rules.validateKeyIdentity(keyIdentity); err != nil { return nil, err } var unmatchedSignature untrustedSignature if err := json.Unmarshal(signed, &unmatchedSignature); err != nil { return nil, InvalidSignatureError{msg: err.Error()} } if err := rules.validateSignedDockerManifestDigest(unmatchedSignature.UntrustedDockerManifestDigest); err != nil { return nil, err } if err := rules.validateSignedDockerReference(unmatchedSignature.UntrustedDockerReference); err != nil { return nil, err } // signatureAcceptanceRules have accepted this value. return &Signature{ DockerManifestDigest: unmatchedSignature.UntrustedDockerManifestDigest, DockerReference: unmatchedSignature.UntrustedDockerReference, }, nil }
go
func verifyAndExtractSignature(mech SigningMechanism, unverifiedSignature []byte, rules signatureAcceptanceRules) (*Signature, error) { signed, keyIdentity, err := mech.Verify(unverifiedSignature) if err != nil { return nil, err } if err := rules.validateKeyIdentity(keyIdentity); err != nil { return nil, err } var unmatchedSignature untrustedSignature if err := json.Unmarshal(signed, &unmatchedSignature); err != nil { return nil, InvalidSignatureError{msg: err.Error()} } if err := rules.validateSignedDockerManifestDigest(unmatchedSignature.UntrustedDockerManifestDigest); err != nil { return nil, err } if err := rules.validateSignedDockerReference(unmatchedSignature.UntrustedDockerReference); err != nil { return nil, err } // signatureAcceptanceRules have accepted this value. return &Signature{ DockerManifestDigest: unmatchedSignature.UntrustedDockerManifestDigest, DockerReference: unmatchedSignature.UntrustedDockerReference, }, nil }
[ "func", "verifyAndExtractSignature", "(", "mech", "SigningMechanism", ",", "unverifiedSignature", "[", "]", "byte", ",", "rules", "signatureAcceptanceRules", ")", "(", "*", "Signature", ",", "error", ")", "{", "signed", ",", "keyIdentity", ",", "err", ":=", "mech", ".", "Verify", "(", "unverifiedSignature", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "rules", ".", "validateKeyIdentity", "(", "keyIdentity", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "var", "unmatchedSignature", "untrustedSignature", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "signed", ",", "&", "unmatchedSignature", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "InvalidSignatureError", "{", "msg", ":", "err", ".", "Error", "(", ")", "}", "\n", "}", "\n", "if", "err", ":=", "rules", ".", "validateSignedDockerManifestDigest", "(", "unmatchedSignature", ".", "UntrustedDockerManifestDigest", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "rules", ".", "validateSignedDockerReference", "(", "unmatchedSignature", ".", "UntrustedDockerReference", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "Signature", "{", "DockerManifestDigest", ":", "unmatchedSignature", ".", "UntrustedDockerManifestDigest", ",", "DockerReference", ":", "unmatchedSignature", ".", "UntrustedDockerReference", ",", "}", ",", "nil", "\n", "}" ]
// verifyAndExtractSignature verifies that unverifiedSignature has been signed, and that its principial components // match expected values, both as specified by rules, and returns it
[ "verifyAndExtractSignature", "verifies", "that", "unverifiedSignature", "has", "been", "signed", "and", "that", "its", "principial", "components", "match", "expected", "values", "both", "as", "specified", "by", "rules", "and", "returns", "it" ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/signature.go#L216-L240
test
containers/image
pkg/sysregistriesv2/system_registries_v2.go
RewriteReference
func (e *Endpoint) RewriteReference(ref reference.Named, prefix string) (reference.Named, error) { if ref == nil { return nil, fmt.Errorf("provided reference is nil") } if prefix == "" { return ref, nil } refString := ref.String() if refMatchesPrefix(refString, prefix) { newNamedRef := strings.Replace(refString, prefix, e.Location, 1) newParsedRef, err := reference.ParseNamed(newNamedRef) if newParsedRef != nil { logrus.Debugf("reference rewritten from '%v' to '%v'", refString, newParsedRef.String()) } if err != nil { return nil, errors.Wrapf(err, "error rewriting reference") } return newParsedRef, nil } return nil, fmt.Errorf("invalid prefix '%v' for reference '%v'", prefix, refString) }
go
func (e *Endpoint) RewriteReference(ref reference.Named, prefix string) (reference.Named, error) { if ref == nil { return nil, fmt.Errorf("provided reference is nil") } if prefix == "" { return ref, nil } refString := ref.String() if refMatchesPrefix(refString, prefix) { newNamedRef := strings.Replace(refString, prefix, e.Location, 1) newParsedRef, err := reference.ParseNamed(newNamedRef) if newParsedRef != nil { logrus.Debugf("reference rewritten from '%v' to '%v'", refString, newParsedRef.String()) } if err != nil { return nil, errors.Wrapf(err, "error rewriting reference") } return newParsedRef, nil } return nil, fmt.Errorf("invalid prefix '%v' for reference '%v'", prefix, refString) }
[ "func", "(", "e", "*", "Endpoint", ")", "RewriteReference", "(", "ref", "reference", ".", "Named", ",", "prefix", "string", ")", "(", "reference", ".", "Named", ",", "error", ")", "{", "if", "ref", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"provided reference is nil\"", ")", "\n", "}", "\n", "if", "prefix", "==", "\"\"", "{", "return", "ref", ",", "nil", "\n", "}", "\n", "refString", ":=", "ref", ".", "String", "(", ")", "\n", "if", "refMatchesPrefix", "(", "refString", ",", "prefix", ")", "{", "newNamedRef", ":=", "strings", ".", "Replace", "(", "refString", ",", "prefix", ",", "e", ".", "Location", ",", "1", ")", "\n", "newParsedRef", ",", "err", ":=", "reference", ".", "ParseNamed", "(", "newNamedRef", ")", "\n", "if", "newParsedRef", "!=", "nil", "{", "logrus", ".", "Debugf", "(", "\"reference rewritten from '%v' to '%v'\"", ",", "refString", ",", "newParsedRef", ".", "String", "(", ")", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"error rewriting reference\"", ")", "\n", "}", "\n", "return", "newParsedRef", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"invalid prefix '%v' for reference '%v'\"", ",", "prefix", ",", "refString", ")", "\n", "}" ]
// RewriteReference will substitute the provided reference `prefix` to the // endpoints `location` from the `ref` and creates a new named reference from it. // The function errors if the newly created reference is not parsable.
[ "RewriteReference", "will", "substitute", "the", "provided", "reference", "prefix", "to", "the", "endpoints", "location", "from", "the", "ref", "and", "creates", "a", "new", "named", "reference", "from", "it", ".", "The", "function", "errors", "if", "the", "newly", "created", "reference", "is", "not", "parsable", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/sysregistriesv2/system_registries_v2.go#L41-L62
test
containers/image
pkg/sysregistriesv2/system_registries_v2.go
getV1Registries
func getV1Registries(config *tomlConfig) ([]Registry, error) { regMap := make(map[string]*Registry) // We must preserve the order of config.V1Registries.Search.Registries at least. The order of the // other registries is not really important, but make it deterministic (the same for the same config file) // to minimize behavior inconsistency and not contribute to difficult-to-reproduce situations. registryOrder := []string{} getRegistry := func(location string) (*Registry, error) { // Note: _pointer_ to a long-lived object var err error location, err = parseLocation(location) if err != nil { return nil, err } reg, exists := regMap[location] if !exists { reg = &Registry{ Endpoint: Endpoint{Location: location}, Mirrors: []Endpoint{}, Prefix: location, } regMap[location] = reg registryOrder = append(registryOrder, location) } return reg, nil } // Note: config.V1Registries.Search needs to be processed first to ensure registryOrder is populated in the right order // if one of the search registries is also in one of the other lists. for _, search := range config.V1TOMLConfig.Search.Registries { reg, err := getRegistry(search) if err != nil { return nil, err } reg.Search = true } for _, blocked := range config.V1TOMLConfig.Block.Registries { reg, err := getRegistry(blocked) if err != nil { return nil, err } reg.Blocked = true } for _, insecure := range config.V1TOMLConfig.Insecure.Registries { reg, err := getRegistry(insecure) if err != nil { return nil, err } reg.Insecure = true } registries := []Registry{} for _, location := range registryOrder { reg := regMap[location] registries = append(registries, *reg) } return registries, nil }
go
func getV1Registries(config *tomlConfig) ([]Registry, error) { regMap := make(map[string]*Registry) // We must preserve the order of config.V1Registries.Search.Registries at least. The order of the // other registries is not really important, but make it deterministic (the same for the same config file) // to minimize behavior inconsistency and not contribute to difficult-to-reproduce situations. registryOrder := []string{} getRegistry := func(location string) (*Registry, error) { // Note: _pointer_ to a long-lived object var err error location, err = parseLocation(location) if err != nil { return nil, err } reg, exists := regMap[location] if !exists { reg = &Registry{ Endpoint: Endpoint{Location: location}, Mirrors: []Endpoint{}, Prefix: location, } regMap[location] = reg registryOrder = append(registryOrder, location) } return reg, nil } // Note: config.V1Registries.Search needs to be processed first to ensure registryOrder is populated in the right order // if one of the search registries is also in one of the other lists. for _, search := range config.V1TOMLConfig.Search.Registries { reg, err := getRegistry(search) if err != nil { return nil, err } reg.Search = true } for _, blocked := range config.V1TOMLConfig.Block.Registries { reg, err := getRegistry(blocked) if err != nil { return nil, err } reg.Blocked = true } for _, insecure := range config.V1TOMLConfig.Insecure.Registries { reg, err := getRegistry(insecure) if err != nil { return nil, err } reg.Insecure = true } registries := []Registry{} for _, location := range registryOrder { reg := regMap[location] registries = append(registries, *reg) } return registries, nil }
[ "func", "getV1Registries", "(", "config", "*", "tomlConfig", ")", "(", "[", "]", "Registry", ",", "error", ")", "{", "regMap", ":=", "make", "(", "map", "[", "string", "]", "*", "Registry", ")", "\n", "registryOrder", ":=", "[", "]", "string", "{", "}", "\n", "getRegistry", ":=", "func", "(", "location", "string", ")", "(", "*", "Registry", ",", "error", ")", "{", "var", "err", "error", "\n", "location", ",", "err", "=", "parseLocation", "(", "location", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "reg", ",", "exists", ":=", "regMap", "[", "location", "]", "\n", "if", "!", "exists", "{", "reg", "=", "&", "Registry", "{", "Endpoint", ":", "Endpoint", "{", "Location", ":", "location", "}", ",", "Mirrors", ":", "[", "]", "Endpoint", "{", "}", ",", "Prefix", ":", "location", ",", "}", "\n", "regMap", "[", "location", "]", "=", "reg", "\n", "registryOrder", "=", "append", "(", "registryOrder", ",", "location", ")", "\n", "}", "\n", "return", "reg", ",", "nil", "\n", "}", "\n", "for", "_", ",", "search", ":=", "range", "config", ".", "V1TOMLConfig", ".", "Search", ".", "Registries", "{", "reg", ",", "err", ":=", "getRegistry", "(", "search", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "reg", ".", "Search", "=", "true", "\n", "}", "\n", "for", "_", ",", "blocked", ":=", "range", "config", ".", "V1TOMLConfig", ".", "Block", ".", "Registries", "{", "reg", ",", "err", ":=", "getRegistry", "(", "blocked", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "reg", ".", "Blocked", "=", "true", "\n", "}", "\n", "for", "_", ",", "insecure", ":=", "range", "config", ".", "V1TOMLConfig", ".", "Insecure", ".", "Registries", "{", "reg", ",", "err", ":=", "getRegistry", "(", "insecure", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "reg", ".", "Insecure", "=", "true", "\n", "}", "\n", "registries", ":=", "[", "]", "Registry", "{", "}", "\n", "for", "_", ",", "location", ":=", "range", "registryOrder", "{", "reg", ":=", "regMap", "[", "location", "]", "\n", "registries", "=", "append", "(", "registries", ",", "*", "reg", ")", "\n", "}", "\n", "return", "registries", ",", "nil", "\n", "}" ]
// getV1Registries transforms v1 registries in the config into an array of v2 // registries of type Registry.
[ "getV1Registries", "transforms", "v1", "registries", "in", "the", "config", "into", "an", "array", "of", "v2", "registries", "of", "type", "Registry", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/sysregistriesv2/system_registries_v2.go#L133-L189
test
containers/image
pkg/sysregistriesv2/system_registries_v2.go
getConfigPath
func getConfigPath(ctx *types.SystemContext) string { confPath := systemRegistriesConfPath if ctx != nil { if ctx.SystemRegistriesConfPath != "" { confPath = ctx.SystemRegistriesConfPath } else if ctx.RootForImplicitAbsolutePaths != "" { confPath = filepath.Join(ctx.RootForImplicitAbsolutePaths, systemRegistriesConfPath) } } return confPath }
go
func getConfigPath(ctx *types.SystemContext) string { confPath := systemRegistriesConfPath if ctx != nil { if ctx.SystemRegistriesConfPath != "" { confPath = ctx.SystemRegistriesConfPath } else if ctx.RootForImplicitAbsolutePaths != "" { confPath = filepath.Join(ctx.RootForImplicitAbsolutePaths, systemRegistriesConfPath) } } return confPath }
[ "func", "getConfigPath", "(", "ctx", "*", "types", ".", "SystemContext", ")", "string", "{", "confPath", ":=", "systemRegistriesConfPath", "\n", "if", "ctx", "!=", "nil", "{", "if", "ctx", ".", "SystemRegistriesConfPath", "!=", "\"\"", "{", "confPath", "=", "ctx", ".", "SystemRegistriesConfPath", "\n", "}", "else", "if", "ctx", ".", "RootForImplicitAbsolutePaths", "!=", "\"\"", "{", "confPath", "=", "filepath", ".", "Join", "(", "ctx", ".", "RootForImplicitAbsolutePaths", ",", "systemRegistriesConfPath", ")", "\n", "}", "\n", "}", "\n", "return", "confPath", "\n", "}" ]
// getConfigPath returns the system-registries config path if specified. // Otherwise, systemRegistriesConfPath is returned.
[ "getConfigPath", "returns", "the", "system", "-", "registries", "config", "path", "if", "specified", ".", "Otherwise", "systemRegistriesConfPath", "is", "returned", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/sysregistriesv2/system_registries_v2.go#L253-L263
test
containers/image
pkg/sysregistriesv2/system_registries_v2.go
GetRegistries
func GetRegistries(ctx *types.SystemContext) ([]Registry, error) { configPath := getConfigPath(ctx) configMutex.Lock() defer configMutex.Unlock() // if the config has already been loaded, return the cached registries if registries, inCache := configCache[configPath]; inCache { return registries, nil } // load the config config, err := loadRegistryConf(configPath) if err != nil { // Return an empty []Registry if we use the default config, // which implies that the config path of the SystemContext // isn't set. Note: if ctx.SystemRegistriesConfPath points to // the default config, we will still return an error. if os.IsNotExist(err) && (ctx == nil || ctx.SystemRegistriesConfPath == "") { return []Registry{}, nil } return nil, err } registries := config.Registries // backwards compatibility for v1 configs v1Registries, err := getV1Registries(config) if err != nil { return nil, err } if len(v1Registries) > 0 { if len(registries) > 0 { return nil, &InvalidRegistries{s: "mixing sysregistry v1/v2 is not supported"} } registries = v1Registries } registries, err = postProcessRegistries(registries) if err != nil { return nil, err } // populate the cache configCache[configPath] = registries return registries, err }
go
func GetRegistries(ctx *types.SystemContext) ([]Registry, error) { configPath := getConfigPath(ctx) configMutex.Lock() defer configMutex.Unlock() // if the config has already been loaded, return the cached registries if registries, inCache := configCache[configPath]; inCache { return registries, nil } // load the config config, err := loadRegistryConf(configPath) if err != nil { // Return an empty []Registry if we use the default config, // which implies that the config path of the SystemContext // isn't set. Note: if ctx.SystemRegistriesConfPath points to // the default config, we will still return an error. if os.IsNotExist(err) && (ctx == nil || ctx.SystemRegistriesConfPath == "") { return []Registry{}, nil } return nil, err } registries := config.Registries // backwards compatibility for v1 configs v1Registries, err := getV1Registries(config) if err != nil { return nil, err } if len(v1Registries) > 0 { if len(registries) > 0 { return nil, &InvalidRegistries{s: "mixing sysregistry v1/v2 is not supported"} } registries = v1Registries } registries, err = postProcessRegistries(registries) if err != nil { return nil, err } // populate the cache configCache[configPath] = registries return registries, err }
[ "func", "GetRegistries", "(", "ctx", "*", "types", ".", "SystemContext", ")", "(", "[", "]", "Registry", ",", "error", ")", "{", "configPath", ":=", "getConfigPath", "(", "ctx", ")", "\n", "configMutex", ".", "Lock", "(", ")", "\n", "defer", "configMutex", ".", "Unlock", "(", ")", "\n", "if", "registries", ",", "inCache", ":=", "configCache", "[", "configPath", "]", ";", "inCache", "{", "return", "registries", ",", "nil", "\n", "}", "\n", "config", ",", "err", ":=", "loadRegistryConf", "(", "configPath", ")", "\n", "if", "err", "!=", "nil", "{", "if", "os", ".", "IsNotExist", "(", "err", ")", "&&", "(", "ctx", "==", "nil", "||", "ctx", ".", "SystemRegistriesConfPath", "==", "\"\"", ")", "{", "return", "[", "]", "Registry", "{", "}", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "registries", ":=", "config", ".", "Registries", "\n", "v1Registries", ",", "err", ":=", "getV1Registries", "(", "config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "v1Registries", ")", ">", "0", "{", "if", "len", "(", "registries", ")", ">", "0", "{", "return", "nil", ",", "&", "InvalidRegistries", "{", "s", ":", "\"mixing sysregistry v1/v2 is not supported\"", "}", "\n", "}", "\n", "registries", "=", "v1Registries", "\n", "}", "\n", "registries", ",", "err", "=", "postProcessRegistries", "(", "registries", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "configCache", "[", "configPath", "]", "=", "registries", "\n", "return", "registries", ",", "err", "\n", "}" ]
// GetRegistries loads and returns the registries specified in the config. // Note the parsed content of registry config files is cached. For reloading, // use `InvalidateCache` and re-call `GetRegistries`.
[ "GetRegistries", "loads", "and", "returns", "the", "registries", "specified", "in", "the", "config", ".", "Note", "the", "parsed", "content", "of", "registry", "config", "files", "is", "cached", ".", "For", "reloading", "use", "InvalidateCache", "and", "re", "-", "call", "GetRegistries", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/sysregistriesv2/system_registries_v2.go#L285-L331
test
containers/image
pkg/sysregistriesv2/system_registries_v2.go
readRegistryConf
func readRegistryConf(configPath string) ([]byte, error) { configBytes, err := ioutil.ReadFile(configPath) return configBytes, err }
go
func readRegistryConf(configPath string) ([]byte, error) { configBytes, err := ioutil.ReadFile(configPath) return configBytes, err }
[ "func", "readRegistryConf", "(", "configPath", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "configBytes", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "configPath", ")", "\n", "return", "configBytes", ",", "err", "\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/sysregistriesv2/system_registries_v2.go#L405-L408
test
containers/image
image/sourced.go
Manifest
func (i *sourcedImage) Manifest(ctx context.Context) ([]byte, string, error) { return i.manifestBlob, i.manifestMIMEType, nil }
go
func (i *sourcedImage) Manifest(ctx context.Context) ([]byte, string, error) { return i.manifestBlob, i.manifestMIMEType, nil }
[ "func", "(", "i", "*", "sourcedImage", ")", "Manifest", "(", "ctx", "context", ".", "Context", ")", "(", "[", "]", "byte", ",", "string", ",", "error", ")", "{", "return", "i", ".", "manifestBlob", ",", "i", ".", "manifestMIMEType", ",", "nil", "\n", "}" ]
// Manifest overrides the UnparsedImage.Manifest to always use the fields which we have already fetched.
[ "Manifest", "overrides", "the", "UnparsedImage", ".", "Manifest", "to", "always", "use", "the", "fields", "which", "we", "have", "already", "fetched", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/image/sourced.go#L97-L99
test
containers/image
tarball/tarball_reference.go
ConfigUpdate
func (r *tarballReference) ConfigUpdate(config imgspecv1.Image, annotations map[string]string) error { r.config = config if r.annotations == nil { r.annotations = make(map[string]string) } for k, v := range annotations { r.annotations[k] = v } return nil }
go
func (r *tarballReference) ConfigUpdate(config imgspecv1.Image, annotations map[string]string) error { r.config = config if r.annotations == nil { r.annotations = make(map[string]string) } for k, v := range annotations { r.annotations[k] = v } return nil }
[ "func", "(", "r", "*", "tarballReference", ")", "ConfigUpdate", "(", "config", "imgspecv1", ".", "Image", ",", "annotations", "map", "[", "string", "]", "string", ")", "error", "{", "r", ".", "config", "=", "config", "\n", "if", "r", ".", "annotations", "==", "nil", "{", "r", ".", "annotations", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "}", "\n", "for", "k", ",", "v", ":=", "range", "annotations", "{", "r", ".", "annotations", "[", "k", "]", "=", "v", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ConfigUpdate updates the image's default configuration and adds annotations // which will be visible in source images created using this reference.
[ "ConfigUpdate", "updates", "the", "image", "s", "default", "configuration", "and", "adds", "annotations", "which", "will", "be", "visible", "in", "source", "images", "created", "using", "this", "reference", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/tarball/tarball_reference.go#L34-L43
test
containers/image
signature/policy_reference_match.go
parseImageAndDockerReference
func parseImageAndDockerReference(image types.UnparsedImage, s2 string) (reference.Named, reference.Named, error) { r1 := image.Reference().DockerReference() if r1 == nil { return nil, nil, PolicyRequirementError(fmt.Sprintf("Docker reference match attempted on image %s with no known Docker reference identity", transports.ImageName(image.Reference()))) } r2, err := reference.ParseNormalizedNamed(s2) if err != nil { return nil, nil, err } return r1, r2, nil }
go
func parseImageAndDockerReference(image types.UnparsedImage, s2 string) (reference.Named, reference.Named, error) { r1 := image.Reference().DockerReference() if r1 == nil { return nil, nil, PolicyRequirementError(fmt.Sprintf("Docker reference match attempted on image %s with no known Docker reference identity", transports.ImageName(image.Reference()))) } r2, err := reference.ParseNormalizedNamed(s2) if err != nil { return nil, nil, err } return r1, r2, nil }
[ "func", "parseImageAndDockerReference", "(", "image", "types", ".", "UnparsedImage", ",", "s2", "string", ")", "(", "reference", ".", "Named", ",", "reference", ".", "Named", ",", "error", ")", "{", "r1", ":=", "image", ".", "Reference", "(", ")", ".", "DockerReference", "(", ")", "\n", "if", "r1", "==", "nil", "{", "return", "nil", ",", "nil", ",", "PolicyRequirementError", "(", "fmt", ".", "Sprintf", "(", "\"Docker reference match attempted on image %s with no known Docker reference identity\"", ",", "transports", ".", "ImageName", "(", "image", ".", "Reference", "(", ")", ")", ")", ")", "\n", "}", "\n", "r2", ",", "err", ":=", "reference", ".", "ParseNormalizedNamed", "(", "s2", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "return", "r1", ",", "r2", ",", "nil", "\n", "}" ]
// parseImageAndDockerReference converts an image and a reference string into two parsed entities, failing on any error and handling unidentified images.
[ "parseImageAndDockerReference", "converts", "an", "image", "and", "a", "reference", "string", "into", "two", "parsed", "entities", "failing", "on", "any", "error", "and", "handling", "unidentified", "images", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_reference_match.go#L14-L25
test
containers/image
signature/policy_reference_match.go
parseDockerReferences
func parseDockerReferences(s1, s2 string) (reference.Named, reference.Named, error) { r1, err := reference.ParseNormalizedNamed(s1) if err != nil { return nil, nil, err } r2, err := reference.ParseNormalizedNamed(s2) if err != nil { return nil, nil, err } return r1, r2, nil }
go
func parseDockerReferences(s1, s2 string) (reference.Named, reference.Named, error) { r1, err := reference.ParseNormalizedNamed(s1) if err != nil { return nil, nil, err } r2, err := reference.ParseNormalizedNamed(s2) if err != nil { return nil, nil, err } return r1, r2, nil }
[ "func", "parseDockerReferences", "(", "s1", ",", "s2", "string", ")", "(", "reference", ".", "Named", ",", "reference", ".", "Named", ",", "error", ")", "{", "r1", ",", "err", ":=", "reference", ".", "ParseNormalizedNamed", "(", "s1", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "r2", ",", "err", ":=", "reference", ".", "ParseNormalizedNamed", "(", "s2", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "return", "r1", ",", "r2", ",", "nil", "\n", "}" ]
// parseDockerReferences converts two reference strings into parsed entities, failing on any error
[ "parseDockerReferences", "converts", "two", "reference", "strings", "into", "parsed", "entities", "failing", "on", "any", "error" ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/signature/policy_reference_match.go#L71-L81
test
containers/image
transports/transports.go
ListNames
func ListNames() []string { kt.mu.Lock() defer kt.mu.Unlock() deprecated := map[string]bool{ "atomic": true, } var names []string for _, transport := range kt.transports { if !deprecated[transport.Name()] { names = append(names, transport.Name()) } } sort.Strings(names) return names }
go
func ListNames() []string { kt.mu.Lock() defer kt.mu.Unlock() deprecated := map[string]bool{ "atomic": true, } var names []string for _, transport := range kt.transports { if !deprecated[transport.Name()] { names = append(names, transport.Name()) } } sort.Strings(names) return names }
[ "func", "ListNames", "(", ")", "[", "]", "string", "{", "kt", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "kt", ".", "mu", ".", "Unlock", "(", ")", "\n", "deprecated", ":=", "map", "[", "string", "]", "bool", "{", "\"atomic\"", ":", "true", ",", "}", "\n", "var", "names", "[", "]", "string", "\n", "for", "_", ",", "transport", ":=", "range", "kt", ".", "transports", "{", "if", "!", "deprecated", "[", "transport", ".", "Name", "(", ")", "]", "{", "names", "=", "append", "(", "names", ",", "transport", ".", "Name", "(", ")", ")", "\n", "}", "\n", "}", "\n", "sort", ".", "Strings", "(", "names", ")", "\n", "return", "names", "\n", "}" ]
// ListNames returns a list of non deprecated transport names. // Deprecated transports can be used, but are not presented to users.
[ "ListNames", "returns", "a", "list", "of", "non", "deprecated", "transport", "names", ".", "Deprecated", "transports", "can", "be", "used", "but", "are", "not", "presented", "to", "users", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/transports/transports.go#L76-L90
test
containers/image
ostree/ostree_transport.go
NewReference
func NewReference(image string, repo string) (types.ImageReference, error) { // image is not _really_ in a containers/image/docker/reference format; // as far as the libOSTree ociimage/* namespace is concerned, it is more or // less an arbitrary string with an implied tag. // Parse the image using reference.ParseNormalizedNamed so that we can // check whether the images has a tag specified and we can add ":latest" if needed ostreeImage, err := reference.ParseNormalizedNamed(image) if err != nil { return nil, err } if reference.IsNameOnly(ostreeImage) { image = image + ":latest" } resolved, err := explicitfilepath.ResolvePathToFullyExplicit(repo) if err != nil { // With os.IsNotExist(err), the parent directory of repo is also not existent; // that should ordinarily not happen, but it would be a bit weird to reject // references which do not specify a repo just because the implicit defaultOSTreeRepo // does not exist. if os.IsNotExist(err) && repo == defaultOSTreeRepo { resolved = repo } else { return nil, err } } // This is necessary to prevent directory paths returned by PolicyConfigurationNamespaces // from being ambiguous with values of PolicyConfigurationIdentity. if strings.Contains(resolved, ":") { return nil, errors.Errorf("Invalid OSTree reference %s@%s: path %s contains a colon", image, repo, resolved) } return ostreeReference{ image: image, branchName: encodeOStreeRef(image), repo: resolved, }, nil }
go
func NewReference(image string, repo string) (types.ImageReference, error) { // image is not _really_ in a containers/image/docker/reference format; // as far as the libOSTree ociimage/* namespace is concerned, it is more or // less an arbitrary string with an implied tag. // Parse the image using reference.ParseNormalizedNamed so that we can // check whether the images has a tag specified and we can add ":latest" if needed ostreeImage, err := reference.ParseNormalizedNamed(image) if err != nil { return nil, err } if reference.IsNameOnly(ostreeImage) { image = image + ":latest" } resolved, err := explicitfilepath.ResolvePathToFullyExplicit(repo) if err != nil { // With os.IsNotExist(err), the parent directory of repo is also not existent; // that should ordinarily not happen, but it would be a bit weird to reject // references which do not specify a repo just because the implicit defaultOSTreeRepo // does not exist. if os.IsNotExist(err) && repo == defaultOSTreeRepo { resolved = repo } else { return nil, err } } // This is necessary to prevent directory paths returned by PolicyConfigurationNamespaces // from being ambiguous with values of PolicyConfigurationIdentity. if strings.Contains(resolved, ":") { return nil, errors.Errorf("Invalid OSTree reference %s@%s: path %s contains a colon", image, repo, resolved) } return ostreeReference{ image: image, branchName: encodeOStreeRef(image), repo: resolved, }, nil }
[ "func", "NewReference", "(", "image", "string", ",", "repo", "string", ")", "(", "types", ".", "ImageReference", ",", "error", ")", "{", "ostreeImage", ",", "err", ":=", "reference", ".", "ParseNormalizedNamed", "(", "image", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "reference", ".", "IsNameOnly", "(", "ostreeImage", ")", "{", "image", "=", "image", "+", "\":latest\"", "\n", "}", "\n", "resolved", ",", "err", ":=", "explicitfilepath", ".", "ResolvePathToFullyExplicit", "(", "repo", ")", "\n", "if", "err", "!=", "nil", "{", "if", "os", ".", "IsNotExist", "(", "err", ")", "&&", "repo", "==", "defaultOSTreeRepo", "{", "resolved", "=", "repo", "\n", "}", "else", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "if", "strings", ".", "Contains", "(", "resolved", ",", "\":\"", ")", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"Invalid OSTree reference %s@%s: path %s contains a colon\"", ",", "image", ",", "repo", ",", "resolved", ")", "\n", "}", "\n", "return", "ostreeReference", "{", "image", ":", "image", ",", "branchName", ":", "encodeOStreeRef", "(", "image", ")", ",", "repo", ":", "resolved", ",", "}", ",", "nil", "\n", "}" ]
// NewReference returns an OSTree reference for a specified repo and image.
[ "NewReference", "returns", "an", "OSTree", "reference", "for", "a", "specified", "repo", "and", "image", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/ostree/ostree_transport.go#L89-L127
test
containers/image
ostree/ostree_transport.go
signaturePath
func (ref ostreeReference) signaturePath(index int) string { return filepath.Join("manifest", fmt.Sprintf("signature-%d", index+1)) }
go
func (ref ostreeReference) signaturePath(index int) string { return filepath.Join("manifest", fmt.Sprintf("signature-%d", index+1)) }
[ "func", "(", "ref", "ostreeReference", ")", "signaturePath", "(", "index", "int", ")", "string", "{", "return", "filepath", ".", "Join", "(", "\"manifest\"", ",", "fmt", ".", "Sprintf", "(", "\"signature-%d\"", ",", "index", "+", "1", ")", ")", "\n", "}" ]
// signaturePath returns a path for a signature within a ostree using our conventions.
[ "signaturePath", "returns", "a", "path", "for", "a", "signature", "within", "a", "ostree", "using", "our", "conventions", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/ostree/ostree_transport.go#L250-L252
test
containers/image
oci/internal/oci_util.go
ValidateImageName
func ValidateImageName(image string) error { if len(image) == 0 { return nil } var err error if !refRegexp.MatchString(image) { err = errors.Errorf("Invalid image %s", image) } return err }
go
func ValidateImageName(image string) error { if len(image) == 0 { return nil } var err error if !refRegexp.MatchString(image) { err = errors.Errorf("Invalid image %s", image) } return err }
[ "func", "ValidateImageName", "(", "image", "string", ")", "error", "{", "if", "len", "(", "image", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "var", "err", "error", "\n", "if", "!", "refRegexp", ".", "MatchString", "(", "image", ")", "{", "err", "=", "errors", ".", "Errorf", "(", "\"Invalid image %s\"", ",", "image", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// ValidateImageName returns nil if the image name is empty or matches the open-containers image name specs. // In any other case an error is returned.
[ "ValidateImageName", "returns", "nil", "if", "the", "image", "name", "is", "empty", "or", "matches", "the", "open", "-", "containers", "image", "name", "specs", ".", "In", "any", "other", "case", "an", "error", "is", "returned", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/internal/oci_util.go#L23-L33
test
containers/image
oci/internal/oci_util.go
SplitPathAndImage
func SplitPathAndImage(reference string) (string, string) { if runtime.GOOS == "windows" { return splitPathAndImageWindows(reference) } return splitPathAndImageNonWindows(reference) }
go
func SplitPathAndImage(reference string) (string, string) { if runtime.GOOS == "windows" { return splitPathAndImageWindows(reference) } return splitPathAndImageNonWindows(reference) }
[ "func", "SplitPathAndImage", "(", "reference", "string", ")", "(", "string", ",", "string", ")", "{", "if", "runtime", ".", "GOOS", "==", "\"windows\"", "{", "return", "splitPathAndImageWindows", "(", "reference", ")", "\n", "}", "\n", "return", "splitPathAndImageNonWindows", "(", "reference", ")", "\n", "}" ]
// SplitPathAndImage tries to split the provided OCI reference into the OCI path and image. // Neither path nor image parts are validated at this stage.
[ "SplitPathAndImage", "tries", "to", "split", "the", "provided", "OCI", "reference", "into", "the", "OCI", "path", "and", "image", ".", "Neither", "path", "nor", "image", "parts", "are", "validated", "at", "this", "stage", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/internal/oci_util.go#L37-L42
test
containers/image
oci/internal/oci_util.go
ValidateOCIPath
func ValidateOCIPath(path string) error { if runtime.GOOS == "windows" { // On Windows we must allow for a ':' as part of the path if strings.Count(path, ":") > 1 { return errors.Errorf("Invalid OCI reference: path %s contains more than one colon", path) } } else { if strings.Contains(path, ":") { return errors.Errorf("Invalid OCI reference: path %s contains a colon", path) } } return nil }
go
func ValidateOCIPath(path string) error { if runtime.GOOS == "windows" { // On Windows we must allow for a ':' as part of the path if strings.Count(path, ":") > 1 { return errors.Errorf("Invalid OCI reference: path %s contains more than one colon", path) } } else { if strings.Contains(path, ":") { return errors.Errorf("Invalid OCI reference: path %s contains a colon", path) } } return nil }
[ "func", "ValidateOCIPath", "(", "path", "string", ")", "error", "{", "if", "runtime", ".", "GOOS", "==", "\"windows\"", "{", "if", "strings", ".", "Count", "(", "path", ",", "\":\"", ")", ">", "1", "{", "return", "errors", ".", "Errorf", "(", "\"Invalid OCI reference: path %s contains more than one colon\"", ",", "path", ")", "\n", "}", "\n", "}", "else", "{", "if", "strings", ".", "Contains", "(", "path", ",", "\":\"", ")", "{", "return", "errors", ".", "Errorf", "(", "\"Invalid OCI reference: path %s contains a colon\"", ",", "path", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ValidateOCIPath takes the OCI path and validates it.
[ "ValidateOCIPath", "takes", "the", "OCI", "path", "and", "validates", "it", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/internal/oci_util.go#L71-L83
test
containers/image
oci/internal/oci_util.go
ValidateScope
func ValidateScope(scope string) error { var err error if runtime.GOOS == "windows" { err = validateScopeWindows(scope) } else { err = validateScopeNonWindows(scope) } if err != nil { return err } cleaned := filepath.Clean(scope) if cleaned != scope { return errors.Errorf(`Invalid scope %s: Uses non-canonical path format, perhaps try with path %s`, scope, cleaned) } return nil }
go
func ValidateScope(scope string) error { var err error if runtime.GOOS == "windows" { err = validateScopeWindows(scope) } else { err = validateScopeNonWindows(scope) } if err != nil { return err } cleaned := filepath.Clean(scope) if cleaned != scope { return errors.Errorf(`Invalid scope %s: Uses non-canonical path format, perhaps try with path %s`, scope, cleaned) } return nil }
[ "func", "ValidateScope", "(", "scope", "string", ")", "error", "{", "var", "err", "error", "\n", "if", "runtime", ".", "GOOS", "==", "\"windows\"", "{", "err", "=", "validateScopeWindows", "(", "scope", ")", "\n", "}", "else", "{", "err", "=", "validateScopeNonWindows", "(", "scope", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cleaned", ":=", "filepath", ".", "Clean", "(", "scope", ")", "\n", "if", "cleaned", "!=", "scope", "{", "return", "errors", ".", "Errorf", "(", "`Invalid scope %s: Uses non-canonical path format, perhaps try with path %s`", ",", "scope", ",", "cleaned", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ValidateScope validates a policy configuration scope for an OCI transport.
[ "ValidateScope", "validates", "a", "policy", "configuration", "scope", "for", "an", "OCI", "transport", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/oci/internal/oci_util.go#L86-L103
test
containers/image
manifest/docker_schema2.go
BlobInfoFromSchema2Descriptor
func BlobInfoFromSchema2Descriptor(desc Schema2Descriptor) types.BlobInfo { return types.BlobInfo{ Digest: desc.Digest, Size: desc.Size, URLs: desc.URLs, MediaType: desc.MediaType, } }
go
func BlobInfoFromSchema2Descriptor(desc Schema2Descriptor) types.BlobInfo { return types.BlobInfo{ Digest: desc.Digest, Size: desc.Size, URLs: desc.URLs, MediaType: desc.MediaType, } }
[ "func", "BlobInfoFromSchema2Descriptor", "(", "desc", "Schema2Descriptor", ")", "types", ".", "BlobInfo", "{", "return", "types", ".", "BlobInfo", "{", "Digest", ":", "desc", ".", "Digest", ",", "Size", ":", "desc", ".", "Size", ",", "URLs", ":", "desc", ".", "URLs", ",", "MediaType", ":", "desc", ".", "MediaType", ",", "}", "\n", "}" ]
// BlobInfoFromSchema2Descriptor returns a types.BlobInfo based on the input schema 2 descriptor.
[ "BlobInfoFromSchema2Descriptor", "returns", "a", "types", ".", "BlobInfo", "based", "on", "the", "input", "schema", "2", "descriptor", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/manifest/docker_schema2.go#L22-L29
test
containers/image
manifest/docker_schema2.go
Schema2FromManifest
func Schema2FromManifest(manifest []byte) (*Schema2, error) { s2 := Schema2{} if err := json.Unmarshal(manifest, &s2); err != nil { return nil, err } return &s2, nil }
go
func Schema2FromManifest(manifest []byte) (*Schema2, error) { s2 := Schema2{} if err := json.Unmarshal(manifest, &s2); err != nil { return nil, err } return &s2, nil }
[ "func", "Schema2FromManifest", "(", "manifest", "[", "]", "byte", ")", "(", "*", "Schema2", ",", "error", ")", "{", "s2", ":=", "Schema2", "{", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "manifest", ",", "&", "s2", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "s2", ",", "nil", "\n", "}" ]
// Schema2FromManifest creates a Schema2 manifest instance from a manifest blob.
[ "Schema2FromManifest", "creates", "a", "Schema2", "manifest", "instance", "from", "a", "manifest", "blob", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/manifest/docker_schema2.go#L159-L165
test
containers/image
manifest/docker_schema2.go
Schema2FromComponents
func Schema2FromComponents(config Schema2Descriptor, layers []Schema2Descriptor) *Schema2 { return &Schema2{ SchemaVersion: 2, MediaType: DockerV2Schema2MediaType, ConfigDescriptor: config, LayersDescriptors: layers, } }
go
func Schema2FromComponents(config Schema2Descriptor, layers []Schema2Descriptor) *Schema2 { return &Schema2{ SchemaVersion: 2, MediaType: DockerV2Schema2MediaType, ConfigDescriptor: config, LayersDescriptors: layers, } }
[ "func", "Schema2FromComponents", "(", "config", "Schema2Descriptor", ",", "layers", "[", "]", "Schema2Descriptor", ")", "*", "Schema2", "{", "return", "&", "Schema2", "{", "SchemaVersion", ":", "2", ",", "MediaType", ":", "DockerV2Schema2MediaType", ",", "ConfigDescriptor", ":", "config", ",", "LayersDescriptors", ":", "layers", ",", "}", "\n", "}" ]
// Schema2FromComponents creates an Schema2 manifest instance from the supplied data.
[ "Schema2FromComponents", "creates", "an", "Schema2", "manifest", "instance", "from", "the", "supplied", "data", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/manifest/docker_schema2.go#L168-L175
test
containers/image
pkg/docker/config/config.go
SetAuthentication
func SetAuthentication(sys *types.SystemContext, registry, username, password string) error { return modifyJSON(sys, func(auths *dockerConfigFile) (bool, error) { if ch, exists := auths.CredHelpers[registry]; exists { return false, setAuthToCredHelper(ch, registry, username, password) } creds := base64.StdEncoding.EncodeToString([]byte(username + ":" + password)) newCreds := dockerAuthConfig{Auth: creds} auths.AuthConfigs[registry] = newCreds return true, nil }) }
go
func SetAuthentication(sys *types.SystemContext, registry, username, password string) error { return modifyJSON(sys, func(auths *dockerConfigFile) (bool, error) { if ch, exists := auths.CredHelpers[registry]; exists { return false, setAuthToCredHelper(ch, registry, username, password) } creds := base64.StdEncoding.EncodeToString([]byte(username + ":" + password)) newCreds := dockerAuthConfig{Auth: creds} auths.AuthConfigs[registry] = newCreds return true, nil }) }
[ "func", "SetAuthentication", "(", "sys", "*", "types", ".", "SystemContext", ",", "registry", ",", "username", ",", "password", "string", ")", "error", "{", "return", "modifyJSON", "(", "sys", ",", "func", "(", "auths", "*", "dockerConfigFile", ")", "(", "bool", ",", "error", ")", "{", "if", "ch", ",", "exists", ":=", "auths", ".", "CredHelpers", "[", "registry", "]", ";", "exists", "{", "return", "false", ",", "setAuthToCredHelper", "(", "ch", ",", "registry", ",", "username", ",", "password", ")", "\n", "}", "\n", "creds", ":=", "base64", ".", "StdEncoding", ".", "EncodeToString", "(", "[", "]", "byte", "(", "username", "+", "\":\"", "+", "password", ")", ")", "\n", "newCreds", ":=", "dockerAuthConfig", "{", "Auth", ":", "creds", "}", "\n", "auths", ".", "AuthConfigs", "[", "registry", "]", "=", "newCreds", "\n", "return", "true", ",", "nil", "\n", "}", ")", "\n", "}" ]
// SetAuthentication stores the username and password in the auth.json file
[ "SetAuthentication", "stores", "the", "username", "and", "password", "in", "the", "auth", ".", "json", "file" ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/docker/config/config.go#L41-L52
test
containers/image
pkg/docker/config/config.go
RemoveAuthentication
func RemoveAuthentication(sys *types.SystemContext, registry string) error { return modifyJSON(sys, func(auths *dockerConfigFile) (bool, error) { // First try cred helpers. if ch, exists := auths.CredHelpers[registry]; exists { return false, deleteAuthFromCredHelper(ch, registry) } if _, ok := auths.AuthConfigs[registry]; ok { delete(auths.AuthConfigs, registry) } else if _, ok := auths.AuthConfigs[normalizeRegistry(registry)]; ok { delete(auths.AuthConfigs, normalizeRegistry(registry)) } else { return false, ErrNotLoggedIn } return true, nil }) }
go
func RemoveAuthentication(sys *types.SystemContext, registry string) error { return modifyJSON(sys, func(auths *dockerConfigFile) (bool, error) { // First try cred helpers. if ch, exists := auths.CredHelpers[registry]; exists { return false, deleteAuthFromCredHelper(ch, registry) } if _, ok := auths.AuthConfigs[registry]; ok { delete(auths.AuthConfigs, registry) } else if _, ok := auths.AuthConfigs[normalizeRegistry(registry)]; ok { delete(auths.AuthConfigs, normalizeRegistry(registry)) } else { return false, ErrNotLoggedIn } return true, nil }) }
[ "func", "RemoveAuthentication", "(", "sys", "*", "types", ".", "SystemContext", ",", "registry", "string", ")", "error", "{", "return", "modifyJSON", "(", "sys", ",", "func", "(", "auths", "*", "dockerConfigFile", ")", "(", "bool", ",", "error", ")", "{", "if", "ch", ",", "exists", ":=", "auths", ".", "CredHelpers", "[", "registry", "]", ";", "exists", "{", "return", "false", ",", "deleteAuthFromCredHelper", "(", "ch", ",", "registry", ")", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "auths", ".", "AuthConfigs", "[", "registry", "]", ";", "ok", "{", "delete", "(", "auths", ".", "AuthConfigs", ",", "registry", ")", "\n", "}", "else", "if", "_", ",", "ok", ":=", "auths", ".", "AuthConfigs", "[", "normalizeRegistry", "(", "registry", ")", "]", ";", "ok", "{", "delete", "(", "auths", ".", "AuthConfigs", ",", "normalizeRegistry", "(", "registry", ")", ")", "\n", "}", "else", "{", "return", "false", ",", "ErrNotLoggedIn", "\n", "}", "\n", "return", "true", ",", "nil", "\n", "}", ")", "\n", "}" ]
// RemoveAuthentication deletes the credentials stored in auth.json
[ "RemoveAuthentication", "deletes", "the", "credentials", "stored", "in", "auth", ".", "json" ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/docker/config/config.go#L89-L105
test
containers/image
pkg/docker/config/config.go
RemoveAllAuthentication
func RemoveAllAuthentication(sys *types.SystemContext) error { return modifyJSON(sys, func(auths *dockerConfigFile) (bool, error) { auths.CredHelpers = make(map[string]string) auths.AuthConfigs = make(map[string]dockerAuthConfig) return true, nil }) }
go
func RemoveAllAuthentication(sys *types.SystemContext) error { return modifyJSON(sys, func(auths *dockerConfigFile) (bool, error) { auths.CredHelpers = make(map[string]string) auths.AuthConfigs = make(map[string]dockerAuthConfig) return true, nil }) }
[ "func", "RemoveAllAuthentication", "(", "sys", "*", "types", ".", "SystemContext", ")", "error", "{", "return", "modifyJSON", "(", "sys", ",", "func", "(", "auths", "*", "dockerConfigFile", ")", "(", "bool", ",", "error", ")", "{", "auths", ".", "CredHelpers", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "auths", ".", "AuthConfigs", "=", "make", "(", "map", "[", "string", "]", "dockerAuthConfig", ")", "\n", "return", "true", ",", "nil", "\n", "}", ")", "\n", "}" ]
// RemoveAllAuthentication deletes all the credentials stored in auth.json
[ "RemoveAllAuthentication", "deletes", "all", "the", "credentials", "stored", "in", "auth", ".", "json" ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/docker/config/config.go#L108-L114
test
containers/image
pkg/docker/config/config.go
readJSONFile
func readJSONFile(path string, legacyFormat bool) (dockerConfigFile, error) { var auths dockerConfigFile raw, err := ioutil.ReadFile(path) if err != nil { if os.IsNotExist(err) { auths.AuthConfigs = map[string]dockerAuthConfig{} return auths, nil } return dockerConfigFile{}, err } if legacyFormat { if err = json.Unmarshal(raw, &auths.AuthConfigs); err != nil { return dockerConfigFile{}, errors.Wrapf(err, "error unmarshaling JSON at %q", path) } return auths, nil } if err = json.Unmarshal(raw, &auths); err != nil { return dockerConfigFile{}, errors.Wrapf(err, "error unmarshaling JSON at %q", path) } return auths, nil }
go
func readJSONFile(path string, legacyFormat bool) (dockerConfigFile, error) { var auths dockerConfigFile raw, err := ioutil.ReadFile(path) if err != nil { if os.IsNotExist(err) { auths.AuthConfigs = map[string]dockerAuthConfig{} return auths, nil } return dockerConfigFile{}, err } if legacyFormat { if err = json.Unmarshal(raw, &auths.AuthConfigs); err != nil { return dockerConfigFile{}, errors.Wrapf(err, "error unmarshaling JSON at %q", path) } return auths, nil } if err = json.Unmarshal(raw, &auths); err != nil { return dockerConfigFile{}, errors.Wrapf(err, "error unmarshaling JSON at %q", path) } return auths, nil }
[ "func", "readJSONFile", "(", "path", "string", ",", "legacyFormat", "bool", ")", "(", "dockerConfigFile", ",", "error", ")", "{", "var", "auths", "dockerConfigFile", "\n", "raw", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "auths", ".", "AuthConfigs", "=", "map", "[", "string", "]", "dockerAuthConfig", "{", "}", "\n", "return", "auths", ",", "nil", "\n", "}", "\n", "return", "dockerConfigFile", "{", "}", ",", "err", "\n", "}", "\n", "if", "legacyFormat", "{", "if", "err", "=", "json", ".", "Unmarshal", "(", "raw", ",", "&", "auths", ".", "AuthConfigs", ")", ";", "err", "!=", "nil", "{", "return", "dockerConfigFile", "{", "}", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"error unmarshaling JSON at %q\"", ",", "path", ")", "\n", "}", "\n", "return", "auths", ",", "nil", "\n", "}", "\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "raw", ",", "&", "auths", ")", ";", "err", "!=", "nil", "{", "return", "dockerConfigFile", "{", "}", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"error unmarshaling JSON at %q\"", ",", "path", ")", "\n", "}", "\n", "return", "auths", ",", "nil", "\n", "}" ]
// readJSONFile unmarshals the authentications stored in the auth.json file and returns it // or returns an empty dockerConfigFile data structure if auth.json does not exist // if the file exists and is empty, readJSONFile returns an error
[ "readJSONFile", "unmarshals", "the", "authentications", "stored", "in", "the", "auth", ".", "json", "file", "and", "returns", "it", "or", "returns", "an", "empty", "dockerConfigFile", "data", "structure", "if", "auth", ".", "json", "does", "not", "exist", "if", "the", "file", "exists", "and", "is", "empty", "readJSONFile", "returns", "an", "error" ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/docker/config/config.go#L149-L173
test
containers/image
pkg/docker/config/config.go
modifyJSON
func modifyJSON(sys *types.SystemContext, editor func(auths *dockerConfigFile) (bool, error)) error { path, err := getPathToAuth(sys) if err != nil { return err } dir := filepath.Dir(path) if _, err := os.Stat(dir); os.IsNotExist(err) { if err = os.MkdirAll(dir, 0700); err != nil { return errors.Wrapf(err, "error creating directory %q", dir) } } auths, err := readJSONFile(path, false) if err != nil { return errors.Wrapf(err, "error reading JSON file %q", path) } updated, err := editor(&auths) if err != nil { return errors.Wrapf(err, "error updating %q", path) } if updated { newData, err := json.MarshalIndent(auths, "", "\t") if err != nil { return errors.Wrapf(err, "error marshaling JSON %q", path) } if err = ioutil.WriteFile(path, newData, 0755); err != nil { return errors.Wrapf(err, "error writing to file %q", path) } } return nil }
go
func modifyJSON(sys *types.SystemContext, editor func(auths *dockerConfigFile) (bool, error)) error { path, err := getPathToAuth(sys) if err != nil { return err } dir := filepath.Dir(path) if _, err := os.Stat(dir); os.IsNotExist(err) { if err = os.MkdirAll(dir, 0700); err != nil { return errors.Wrapf(err, "error creating directory %q", dir) } } auths, err := readJSONFile(path, false) if err != nil { return errors.Wrapf(err, "error reading JSON file %q", path) } updated, err := editor(&auths) if err != nil { return errors.Wrapf(err, "error updating %q", path) } if updated { newData, err := json.MarshalIndent(auths, "", "\t") if err != nil { return errors.Wrapf(err, "error marshaling JSON %q", path) } if err = ioutil.WriteFile(path, newData, 0755); err != nil { return errors.Wrapf(err, "error writing to file %q", path) } } return nil }
[ "func", "modifyJSON", "(", "sys", "*", "types", ".", "SystemContext", ",", "editor", "func", "(", "auths", "*", "dockerConfigFile", ")", "(", "bool", ",", "error", ")", ")", "error", "{", "path", ",", "err", ":=", "getPathToAuth", "(", "sys", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "dir", ":=", "filepath", ".", "Dir", "(", "path", ")", "\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "dir", ")", ";", "os", ".", "IsNotExist", "(", "err", ")", "{", "if", "err", "=", "os", ".", "MkdirAll", "(", "dir", ",", "0700", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"error creating directory %q\"", ",", "dir", ")", "\n", "}", "\n", "}", "\n", "auths", ",", "err", ":=", "readJSONFile", "(", "path", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"error reading JSON file %q\"", ",", "path", ")", "\n", "}", "\n", "updated", ",", "err", ":=", "editor", "(", "&", "auths", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"error updating %q\"", ",", "path", ")", "\n", "}", "\n", "if", "updated", "{", "newData", ",", "err", ":=", "json", ".", "MarshalIndent", "(", "auths", ",", "\"\"", ",", "\"\\t\"", ")", "\n", "\\t", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"error marshaling JSON %q\"", ",", "path", ")", "\n", "}", "\n", "}", "\n", "if", "err", "=", "ioutil", ".", "WriteFile", "(", "path", ",", "newData", ",", "0755", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"error writing to file %q\"", ",", "path", ")", "\n", "}", "\n", "}" ]
// modifyJSON writes to auth.json if the dockerConfigFile has been updated
[ "modifyJSON", "writes", "to", "auth", ".", "json", "if", "the", "dockerConfigFile", "has", "been", "updated" ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/docker/config/config.go#L176-L210
test
containers/image
pkg/docker/config/config.go
findAuthentication
func findAuthentication(registry, path string, legacyFormat bool) (string, string, error) { auths, err := readJSONFile(path, legacyFormat) if err != nil { return "", "", errors.Wrapf(err, "error reading JSON file %q", path) } // First try cred helpers. They should always be normalized. if ch, exists := auths.CredHelpers[registry]; exists { return getAuthFromCredHelper(ch, registry) } // I'm feeling lucky if val, exists := auths.AuthConfigs[registry]; exists { return decodeDockerAuth(val.Auth) } // bad luck; let's normalize the entries first registry = normalizeRegistry(registry) normalizedAuths := map[string]dockerAuthConfig{} for k, v := range auths.AuthConfigs { normalizedAuths[normalizeRegistry(k)] = v } if val, exists := normalizedAuths[registry]; exists { return decodeDockerAuth(val.Auth) } return "", "", nil }
go
func findAuthentication(registry, path string, legacyFormat bool) (string, string, error) { auths, err := readJSONFile(path, legacyFormat) if err != nil { return "", "", errors.Wrapf(err, "error reading JSON file %q", path) } // First try cred helpers. They should always be normalized. if ch, exists := auths.CredHelpers[registry]; exists { return getAuthFromCredHelper(ch, registry) } // I'm feeling lucky if val, exists := auths.AuthConfigs[registry]; exists { return decodeDockerAuth(val.Auth) } // bad luck; let's normalize the entries first registry = normalizeRegistry(registry) normalizedAuths := map[string]dockerAuthConfig{} for k, v := range auths.AuthConfigs { normalizedAuths[normalizeRegistry(k)] = v } if val, exists := normalizedAuths[registry]; exists { return decodeDockerAuth(val.Auth) } return "", "", nil }
[ "func", "findAuthentication", "(", "registry", ",", "path", "string", ",", "legacyFormat", "bool", ")", "(", "string", ",", "string", ",", "error", ")", "{", "auths", ",", "err", ":=", "readJSONFile", "(", "path", ",", "legacyFormat", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "\"\"", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"error reading JSON file %q\"", ",", "path", ")", "\n", "}", "\n", "if", "ch", ",", "exists", ":=", "auths", ".", "CredHelpers", "[", "registry", "]", ";", "exists", "{", "return", "getAuthFromCredHelper", "(", "ch", ",", "registry", ")", "\n", "}", "\n", "if", "val", ",", "exists", ":=", "auths", ".", "AuthConfigs", "[", "registry", "]", ";", "exists", "{", "return", "decodeDockerAuth", "(", "val", ".", "Auth", ")", "\n", "}", "\n", "registry", "=", "normalizeRegistry", "(", "registry", ")", "\n", "normalizedAuths", ":=", "map", "[", "string", "]", "dockerAuthConfig", "{", "}", "\n", "for", "k", ",", "v", ":=", "range", "auths", ".", "AuthConfigs", "{", "normalizedAuths", "[", "normalizeRegistry", "(", "k", ")", "]", "=", "v", "\n", "}", "\n", "if", "val", ",", "exists", ":=", "normalizedAuths", "[", "registry", "]", ";", "exists", "{", "return", "decodeDockerAuth", "(", "val", ".", "Auth", ")", "\n", "}", "\n", "return", "\"\"", ",", "\"\"", ",", "nil", "\n", "}" ]
// findAuthentication looks for auth of registry in path
[ "findAuthentication", "looks", "for", "auth", "of", "registry", "in", "path" ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/docker/config/config.go#L240-L266
test
containers/image
docker/tarfile/dest.go
NewDestination
func NewDestination(dest io.Writer, ref reference.NamedTagged) *Destination { repoTags := []reference.NamedTagged{} if ref != nil { repoTags = append(repoTags, ref) } return &Destination{ writer: dest, tar: tar.NewWriter(dest), repoTags: repoTags, blobs: make(map[digest.Digest]types.BlobInfo), } }
go
func NewDestination(dest io.Writer, ref reference.NamedTagged) *Destination { repoTags := []reference.NamedTagged{} if ref != nil { repoTags = append(repoTags, ref) } return &Destination{ writer: dest, tar: tar.NewWriter(dest), repoTags: repoTags, blobs: make(map[digest.Digest]types.BlobInfo), } }
[ "func", "NewDestination", "(", "dest", "io", ".", "Writer", ",", "ref", "reference", ".", "NamedTagged", ")", "*", "Destination", "{", "repoTags", ":=", "[", "]", "reference", ".", "NamedTagged", "{", "}", "\n", "if", "ref", "!=", "nil", "{", "repoTags", "=", "append", "(", "repoTags", ",", "ref", ")", "\n", "}", "\n", "return", "&", "Destination", "{", "writer", ":", "dest", ",", "tar", ":", "tar", ".", "NewWriter", "(", "dest", ")", ",", "repoTags", ":", "repoTags", ",", "blobs", ":", "make", "(", "map", "[", "digest", ".", "Digest", "]", "types", ".", "BlobInfo", ")", ",", "}", "\n", "}" ]
// NewDestination returns a tarfile.Destination for the specified io.Writer.
[ "NewDestination", "returns", "a", "tarfile", ".", "Destination", "for", "the", "specified", "io", ".", "Writer", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/tarfile/dest.go#L35-L46
test
containers/image
docker/tarfile/dest.go
AddRepoTags
func (d *Destination) AddRepoTags(tags []reference.NamedTagged) { d.repoTags = append(d.repoTags, tags...) }
go
func (d *Destination) AddRepoTags(tags []reference.NamedTagged) { d.repoTags = append(d.repoTags, tags...) }
[ "func", "(", "d", "*", "Destination", ")", "AddRepoTags", "(", "tags", "[", "]", "reference", ".", "NamedTagged", ")", "{", "d", ".", "repoTags", "=", "append", "(", "d", ".", "repoTags", ",", "tags", "...", ")", "\n", "}" ]
// AddRepoTags adds the specified tags to the destination's repoTags.
[ "AddRepoTags", "adds", "the", "specified", "tags", "to", "the", "destination", "s", "repoTags", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/tarfile/dest.go#L49-L51
test
containers/image
docker/tarfile/dest.go
writeLegacyLayerMetadata
func (d *Destination) writeLegacyLayerMetadata(layerDescriptors []manifest.Schema2Descriptor) (layerPaths []string, lastLayerID string, err error) { var chainID digest.Digest lastLayerID = "" for i, l := range layerDescriptors { // This chainID value matches the computation in docker/docker/layer.CreateChainID … if chainID == "" { chainID = l.Digest } else { chainID = digest.Canonical.FromString(chainID.String() + " " + l.Digest.String()) } // … but note that this image ID does not match docker/docker/image/v1.CreateID. At least recent // versions allocate new IDs on load, as long as the IDs we use are unique / cannot loop. // // Overall, the goal of computing a digest dependent on the full history is to avoid reusing an image ID // (and possibly creating a loop in the "parent" links) if a layer with the same DiffID appears two or more // times in layersDescriptors. The ChainID values are sufficient for this, the v1.CreateID computation // which also mixes in the full image configuration seems unnecessary, at least as long as we are storing // only a single image per tarball, i.e. all DiffID prefixes are unique (can’t differ only with // configuration). layerID := chainID.Hex() physicalLayerPath := l.Digest.Hex() + ".tar" // The layer itself has been stored into physicalLayerPath in PutManifest. // So, use that path for layerPaths used in the non-legacy manifest layerPaths = append(layerPaths, physicalLayerPath) // ... and create a symlink for the legacy format; if err := d.sendSymlink(filepath.Join(layerID, legacyLayerFileName), filepath.Join("..", physicalLayerPath)); err != nil { return nil, "", errors.Wrap(err, "Error creating layer symbolic link") } b := []byte("1.0") if err := d.sendBytes(filepath.Join(layerID, legacyVersionFileName), b); err != nil { return nil, "", errors.Wrap(err, "Error writing VERSION file") } // The legacy format requires a config file per layer layerConfig := make(map[string]interface{}) layerConfig["id"] = layerID // The root layer doesn't have any parent if lastLayerID != "" { layerConfig["parent"] = lastLayerID } // The root layer configuration file is generated by using subpart of the image configuration if i == len(layerDescriptors)-1 { var config map[string]*json.RawMessage err := json.Unmarshal(d.config, &config) if err != nil { return nil, "", errors.Wrap(err, "Error unmarshaling config") } for _, attr := range [7]string{"architecture", "config", "container", "container_config", "created", "docker_version", "os"} { layerConfig[attr] = config[attr] } } b, err := json.Marshal(layerConfig) if err != nil { return nil, "", errors.Wrap(err, "Error marshaling layer config") } if err := d.sendBytes(filepath.Join(layerID, legacyConfigFileName), b); err != nil { return nil, "", errors.Wrap(err, "Error writing config json file") } lastLayerID = layerID } return layerPaths, lastLayerID, nil }
go
func (d *Destination) writeLegacyLayerMetadata(layerDescriptors []manifest.Schema2Descriptor) (layerPaths []string, lastLayerID string, err error) { var chainID digest.Digest lastLayerID = "" for i, l := range layerDescriptors { // This chainID value matches the computation in docker/docker/layer.CreateChainID … if chainID == "" { chainID = l.Digest } else { chainID = digest.Canonical.FromString(chainID.String() + " " + l.Digest.String()) } // … but note that this image ID does not match docker/docker/image/v1.CreateID. At least recent // versions allocate new IDs on load, as long as the IDs we use are unique / cannot loop. // // Overall, the goal of computing a digest dependent on the full history is to avoid reusing an image ID // (and possibly creating a loop in the "parent" links) if a layer with the same DiffID appears two or more // times in layersDescriptors. The ChainID values are sufficient for this, the v1.CreateID computation // which also mixes in the full image configuration seems unnecessary, at least as long as we are storing // only a single image per tarball, i.e. all DiffID prefixes are unique (can’t differ only with // configuration). layerID := chainID.Hex() physicalLayerPath := l.Digest.Hex() + ".tar" // The layer itself has been stored into physicalLayerPath in PutManifest. // So, use that path for layerPaths used in the non-legacy manifest layerPaths = append(layerPaths, physicalLayerPath) // ... and create a symlink for the legacy format; if err := d.sendSymlink(filepath.Join(layerID, legacyLayerFileName), filepath.Join("..", physicalLayerPath)); err != nil { return nil, "", errors.Wrap(err, "Error creating layer symbolic link") } b := []byte("1.0") if err := d.sendBytes(filepath.Join(layerID, legacyVersionFileName), b); err != nil { return nil, "", errors.Wrap(err, "Error writing VERSION file") } // The legacy format requires a config file per layer layerConfig := make(map[string]interface{}) layerConfig["id"] = layerID // The root layer doesn't have any parent if lastLayerID != "" { layerConfig["parent"] = lastLayerID } // The root layer configuration file is generated by using subpart of the image configuration if i == len(layerDescriptors)-1 { var config map[string]*json.RawMessage err := json.Unmarshal(d.config, &config) if err != nil { return nil, "", errors.Wrap(err, "Error unmarshaling config") } for _, attr := range [7]string{"architecture", "config", "container", "container_config", "created", "docker_version", "os"} { layerConfig[attr] = config[attr] } } b, err := json.Marshal(layerConfig) if err != nil { return nil, "", errors.Wrap(err, "Error marshaling layer config") } if err := d.sendBytes(filepath.Join(layerID, legacyConfigFileName), b); err != nil { return nil, "", errors.Wrap(err, "Error writing config json file") } lastLayerID = layerID } return layerPaths, lastLayerID, nil }
[ "func", "(", "d", "*", "Destination", ")", "writeLegacyLayerMetadata", "(", "layerDescriptors", "[", "]", "manifest", ".", "Schema2Descriptor", ")", "(", "layerPaths", "[", "]", "string", ",", "lastLayerID", "string", ",", "err", "error", ")", "{", "var", "chainID", "digest", ".", "Digest", "\n", "lastLayerID", "=", "\"\"", "\n", "for", "i", ",", "l", ":=", "range", "layerDescriptors", "{", "if", "chainID", "==", "\"\"", "{", "chainID", "=", "l", ".", "Digest", "\n", "}", "else", "{", "chainID", "=", "digest", ".", "Canonical", ".", "FromString", "(", "chainID", ".", "String", "(", ")", "+", "\" \"", "+", "l", ".", "Digest", ".", "String", "(", ")", ")", "\n", "}", "\n", "layerID", ":=", "chainID", ".", "Hex", "(", ")", "\n", "physicalLayerPath", ":=", "l", ".", "Digest", ".", "Hex", "(", ")", "+", "\".tar\"", "\n", "layerPaths", "=", "append", "(", "layerPaths", ",", "physicalLayerPath", ")", "\n", "if", "err", ":=", "d", ".", "sendSymlink", "(", "filepath", ".", "Join", "(", "layerID", ",", "legacyLayerFileName", ")", ",", "filepath", ".", "Join", "(", "\"..\"", ",", "physicalLayerPath", ")", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "\"\"", ",", "errors", ".", "Wrap", "(", "err", ",", "\"Error creating layer symbolic link\"", ")", "\n", "}", "\n", "b", ":=", "[", "]", "byte", "(", "\"1.0\"", ")", "\n", "if", "err", ":=", "d", ".", "sendBytes", "(", "filepath", ".", "Join", "(", "layerID", ",", "legacyVersionFileName", ")", ",", "b", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "\"\"", ",", "errors", ".", "Wrap", "(", "err", ",", "\"Error writing VERSION file\"", ")", "\n", "}", "\n", "layerConfig", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "layerConfig", "[", "\"id\"", "]", "=", "layerID", "\n", "if", "lastLayerID", "!=", "\"\"", "{", "layerConfig", "[", "\"parent\"", "]", "=", "lastLayerID", "\n", "}", "\n", "if", "i", "==", "len", "(", "layerDescriptors", ")", "-", "1", "{", "var", "config", "map", "[", "string", "]", "*", "json", ".", "RawMessage", "\n", "err", ":=", "json", ".", "Unmarshal", "(", "d", ".", "config", ",", "&", "config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"\"", ",", "errors", ".", "Wrap", "(", "err", ",", "\"Error unmarshaling config\"", ")", "\n", "}", "\n", "for", "_", ",", "attr", ":=", "range", "[", "7", "]", "string", "{", "\"architecture\"", ",", "\"config\"", ",", "\"container\"", ",", "\"container_config\"", ",", "\"created\"", ",", "\"docker_version\"", ",", "\"os\"", "}", "{", "layerConfig", "[", "attr", "]", "=", "config", "[", "attr", "]", "\n", "}", "\n", "}", "\n", "b", ",", "err", ":=", "json", ".", "Marshal", "(", "layerConfig", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"\"", ",", "errors", ".", "Wrap", "(", "err", ",", "\"Error marshaling layer config\"", ")", "\n", "}", "\n", "if", "err", ":=", "d", ".", "sendBytes", "(", "filepath", ".", "Join", "(", "layerID", ",", "legacyConfigFileName", ")", ",", "b", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "\"\"", ",", "errors", ".", "Wrap", "(", "err", ",", "\"Error writing config json file\"", ")", "\n", "}", "\n", "lastLayerID", "=", "layerID", "\n", "}", "\n", "return", "layerPaths", ",", "lastLayerID", ",", "nil", "\n", "}" ]
// writeLegacyLayerMetadata writes legacy VERSION and configuration files for all layers
[ "writeLegacyLayerMetadata", "writes", "legacy", "VERSION", "and", "configuration", "files", "for", "all", "layers" ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/tarfile/dest.go#L262-L327
test
containers/image
docker/tarfile/dest.go
sendSymlink
func (d *Destination) sendSymlink(path string, target string) error { hdr, err := tar.FileInfoHeader(&tarFI{path: path, size: 0, isSymlink: true}, target) if err != nil { return nil } logrus.Debugf("Sending as tar link %s -> %s", path, target) return d.tar.WriteHeader(hdr) }
go
func (d *Destination) sendSymlink(path string, target string) error { hdr, err := tar.FileInfoHeader(&tarFI{path: path, size: 0, isSymlink: true}, target) if err != nil { return nil } logrus.Debugf("Sending as tar link %s -> %s", path, target) return d.tar.WriteHeader(hdr) }
[ "func", "(", "d", "*", "Destination", ")", "sendSymlink", "(", "path", "string", ",", "target", "string", ")", "error", "{", "hdr", ",", "err", ":=", "tar", ".", "FileInfoHeader", "(", "&", "tarFI", "{", "path", ":", "path", ",", "size", ":", "0", ",", "isSymlink", ":", "true", "}", ",", "target", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n", "logrus", ".", "Debugf", "(", "\"Sending as tar link %s -> %s\"", ",", "path", ",", "target", ")", "\n", "return", "d", ".", "tar", ".", "WriteHeader", "(", "hdr", ")", "\n", "}" ]
// sendSymlink sends a symlink into the tar stream.
[ "sendSymlink", "sends", "a", "symlink", "into", "the", "tar", "stream", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/tarfile/dest.go#L358-L365
test
containers/image
docker/tarfile/dest.go
sendBytes
func (d *Destination) sendBytes(path string, b []byte) error { return d.sendFile(path, int64(len(b)), bytes.NewReader(b)) }
go
func (d *Destination) sendBytes(path string, b []byte) error { return d.sendFile(path, int64(len(b)), bytes.NewReader(b)) }
[ "func", "(", "d", "*", "Destination", ")", "sendBytes", "(", "path", "string", ",", "b", "[", "]", "byte", ")", "error", "{", "return", "d", ".", "sendFile", "(", "path", ",", "int64", "(", "len", "(", "b", ")", ")", ",", "bytes", ".", "NewReader", "(", "b", ")", ")", "\n", "}" ]
// sendBytes sends a path into the tar stream.
[ "sendBytes", "sends", "a", "path", "into", "the", "tar", "stream", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/tarfile/dest.go#L368-L370
test
containers/image
docker/tarfile/dest.go
sendFile
func (d *Destination) sendFile(path string, expectedSize int64, stream io.Reader) error { hdr, err := tar.FileInfoHeader(&tarFI{path: path, size: expectedSize}, "") if err != nil { return nil } logrus.Debugf("Sending as tar file %s", path) if err := d.tar.WriteHeader(hdr); err != nil { return err } // TODO: This can take quite some time, and should ideally be cancellable using a context.Context. size, err := io.Copy(d.tar, stream) if err != nil { return err } if size != expectedSize { return errors.Errorf("Size mismatch when copying %s, expected %d, got %d", path, expectedSize, size) } return nil }
go
func (d *Destination) sendFile(path string, expectedSize int64, stream io.Reader) error { hdr, err := tar.FileInfoHeader(&tarFI{path: path, size: expectedSize}, "") if err != nil { return nil } logrus.Debugf("Sending as tar file %s", path) if err := d.tar.WriteHeader(hdr); err != nil { return err } // TODO: This can take quite some time, and should ideally be cancellable using a context.Context. size, err := io.Copy(d.tar, stream) if err != nil { return err } if size != expectedSize { return errors.Errorf("Size mismatch when copying %s, expected %d, got %d", path, expectedSize, size) } return nil }
[ "func", "(", "d", "*", "Destination", ")", "sendFile", "(", "path", "string", ",", "expectedSize", "int64", ",", "stream", "io", ".", "Reader", ")", "error", "{", "hdr", ",", "err", ":=", "tar", ".", "FileInfoHeader", "(", "&", "tarFI", "{", "path", ":", "path", ",", "size", ":", "expectedSize", "}", ",", "\"\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n", "logrus", ".", "Debugf", "(", "\"Sending as tar file %s\"", ",", "path", ")", "\n", "if", "err", ":=", "d", ".", "tar", ".", "WriteHeader", "(", "hdr", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "size", ",", "err", ":=", "io", ".", "Copy", "(", "d", ".", "tar", ",", "stream", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "size", "!=", "expectedSize", "{", "return", "errors", ".", "Errorf", "(", "\"Size mismatch when copying %s, expected %d, got %d\"", ",", "path", ",", "expectedSize", ",", "size", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// sendFile sends a file into the tar stream.
[ "sendFile", "sends", "a", "file", "into", "the", "tar", "stream", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/tarfile/dest.go#L373-L391
test
containers/image
docker/tarfile/dest.go
Commit
func (d *Destination) Commit(ctx context.Context) error { return d.tar.Close() }
go
func (d *Destination) Commit(ctx context.Context) error { return d.tar.Close() }
[ "func", "(", "d", "*", "Destination", ")", "Commit", "(", "ctx", "context", ".", "Context", ")", "error", "{", "return", "d", ".", "tar", ".", "Close", "(", ")", "\n", "}" ]
// Commit finishes writing data to the underlying io.Writer. // It is the caller's responsibility to close it, if necessary.
[ "Commit", "finishes", "writing", "data", "to", "the", "underlying", "io", ".", "Writer", ".", "It", "is", "the", "caller", "s", "responsibility", "to", "close", "it", "if", "necessary", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/tarfile/dest.go#L405-L407
test
containers/image
storage/storage_reference.go
imageMatchesRepo
func imageMatchesRepo(image *storage.Image, ref reference.Named) bool { repo := ref.Name() for _, name := range image.Names { if named, err := reference.ParseNormalizedNamed(name); err == nil { if named.Name() == repo { return true } } } return false }
go
func imageMatchesRepo(image *storage.Image, ref reference.Named) bool { repo := ref.Name() for _, name := range image.Names { if named, err := reference.ParseNormalizedNamed(name); err == nil { if named.Name() == repo { return true } } } return false }
[ "func", "imageMatchesRepo", "(", "image", "*", "storage", ".", "Image", ",", "ref", "reference", ".", "Named", ")", "bool", "{", "repo", ":=", "ref", ".", "Name", "(", ")", "\n", "for", "_", ",", "name", ":=", "range", "image", ".", "Names", "{", "if", "named", ",", "err", ":=", "reference", ".", "ParseNormalizedNamed", "(", "name", ")", ";", "err", "==", "nil", "{", "if", "named", ".", "Name", "(", ")", "==", "repo", "{", "return", "true", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// imageMatchesRepo returns true iff image.Names contains an element with the same repo as ref
[ "imageMatchesRepo", "returns", "true", "iff", "image", ".", "Names", "contains", "an", "element", "with", "the", "same", "repo", "as", "ref" ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/storage/storage_reference.go#L42-L52
test
containers/image
storage/storage_reference.go
resolveImage
func (s *storageReference) resolveImage() (*storage.Image, error) { var loadedImage *storage.Image if s.id == "" && s.named != nil { // Look for an image that has the expanded reference name as an explicit Name value. image, err := s.transport.store.Image(s.named.String()) if image != nil && err == nil { loadedImage = image s.id = image.ID } } if s.id == "" && s.named != nil { if digested, ok := s.named.(reference.Digested); ok { // Look for an image with the specified digest that has the same name, // though possibly with a different tag or digest, as a Name value, so // that the canonical reference can be implicitly resolved to the image. images, err := s.transport.store.ImagesByDigest(digested.Digest()) if err == nil && len(images) > 0 { for _, image := range images { if imageMatchesRepo(image, s.named) { loadedImage = image s.id = image.ID break } } } } } if s.id == "" { logrus.Debugf("reference %q does not resolve to an image ID", s.StringWithinTransport()) return nil, errors.Wrapf(ErrNoSuchImage, "reference %q does not resolve to an image ID", s.StringWithinTransport()) } if loadedImage == nil { img, err := s.transport.store.Image(s.id) if err != nil { return nil, errors.Wrapf(err, "error reading image %q", s.id) } loadedImage = img } if s.named != nil { if !imageMatchesRepo(loadedImage, s.named) { logrus.Errorf("no image matching reference %q found", s.StringWithinTransport()) return nil, ErrNoSuchImage } } // Default to having the image digest that we hand back match the most recently // added manifest... if digest, ok := loadedImage.BigDataDigests[storage.ImageDigestBigDataKey]; ok { loadedImage.Digest = digest } // ... unless the named reference says otherwise, and it matches one of the digests // in the image. For those cases, set the Digest field to that value, for the // sake of older consumers that don't know there's a whole list in there now. if s.named != nil { if digested, ok := s.named.(reference.Digested); ok { for _, digest := range loadedImage.Digests { if digest == digested.Digest() { loadedImage.Digest = digest break } } } } return loadedImage, nil }
go
func (s *storageReference) resolveImage() (*storage.Image, error) { var loadedImage *storage.Image if s.id == "" && s.named != nil { // Look for an image that has the expanded reference name as an explicit Name value. image, err := s.transport.store.Image(s.named.String()) if image != nil && err == nil { loadedImage = image s.id = image.ID } } if s.id == "" && s.named != nil { if digested, ok := s.named.(reference.Digested); ok { // Look for an image with the specified digest that has the same name, // though possibly with a different tag or digest, as a Name value, so // that the canonical reference can be implicitly resolved to the image. images, err := s.transport.store.ImagesByDigest(digested.Digest()) if err == nil && len(images) > 0 { for _, image := range images { if imageMatchesRepo(image, s.named) { loadedImage = image s.id = image.ID break } } } } } if s.id == "" { logrus.Debugf("reference %q does not resolve to an image ID", s.StringWithinTransport()) return nil, errors.Wrapf(ErrNoSuchImage, "reference %q does not resolve to an image ID", s.StringWithinTransport()) } if loadedImage == nil { img, err := s.transport.store.Image(s.id) if err != nil { return nil, errors.Wrapf(err, "error reading image %q", s.id) } loadedImage = img } if s.named != nil { if !imageMatchesRepo(loadedImage, s.named) { logrus.Errorf("no image matching reference %q found", s.StringWithinTransport()) return nil, ErrNoSuchImage } } // Default to having the image digest that we hand back match the most recently // added manifest... if digest, ok := loadedImage.BigDataDigests[storage.ImageDigestBigDataKey]; ok { loadedImage.Digest = digest } // ... unless the named reference says otherwise, and it matches one of the digests // in the image. For those cases, set the Digest field to that value, for the // sake of older consumers that don't know there's a whole list in there now. if s.named != nil { if digested, ok := s.named.(reference.Digested); ok { for _, digest := range loadedImage.Digests { if digest == digested.Digest() { loadedImage.Digest = digest break } } } } return loadedImage, nil }
[ "func", "(", "s", "*", "storageReference", ")", "resolveImage", "(", ")", "(", "*", "storage", ".", "Image", ",", "error", ")", "{", "var", "loadedImage", "*", "storage", ".", "Image", "\n", "if", "s", ".", "id", "==", "\"\"", "&&", "s", ".", "named", "!=", "nil", "{", "image", ",", "err", ":=", "s", ".", "transport", ".", "store", ".", "Image", "(", "s", ".", "named", ".", "String", "(", ")", ")", "\n", "if", "image", "!=", "nil", "&&", "err", "==", "nil", "{", "loadedImage", "=", "image", "\n", "s", ".", "id", "=", "image", ".", "ID", "\n", "}", "\n", "}", "\n", "if", "s", ".", "id", "==", "\"\"", "&&", "s", ".", "named", "!=", "nil", "{", "if", "digested", ",", "ok", ":=", "s", ".", "named", ".", "(", "reference", ".", "Digested", ")", ";", "ok", "{", "images", ",", "err", ":=", "s", ".", "transport", ".", "store", ".", "ImagesByDigest", "(", "digested", ".", "Digest", "(", ")", ")", "\n", "if", "err", "==", "nil", "&&", "len", "(", "images", ")", ">", "0", "{", "for", "_", ",", "image", ":=", "range", "images", "{", "if", "imageMatchesRepo", "(", "image", ",", "s", ".", "named", ")", "{", "loadedImage", "=", "image", "\n", "s", ".", "id", "=", "image", ".", "ID", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "s", ".", "id", "==", "\"\"", "{", "logrus", ".", "Debugf", "(", "\"reference %q does not resolve to an image ID\"", ",", "s", ".", "StringWithinTransport", "(", ")", ")", "\n", "return", "nil", ",", "errors", ".", "Wrapf", "(", "ErrNoSuchImage", ",", "\"reference %q does not resolve to an image ID\"", ",", "s", ".", "StringWithinTransport", "(", ")", ")", "\n", "}", "\n", "if", "loadedImage", "==", "nil", "{", "img", ",", "err", ":=", "s", ".", "transport", ".", "store", ".", "Image", "(", "s", ".", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"error reading image %q\"", ",", "s", ".", "id", ")", "\n", "}", "\n", "loadedImage", "=", "img", "\n", "}", "\n", "if", "s", ".", "named", "!=", "nil", "{", "if", "!", "imageMatchesRepo", "(", "loadedImage", ",", "s", ".", "named", ")", "{", "logrus", ".", "Errorf", "(", "\"no image matching reference %q found\"", ",", "s", ".", "StringWithinTransport", "(", ")", ")", "\n", "return", "nil", ",", "ErrNoSuchImage", "\n", "}", "\n", "}", "\n", "if", "digest", ",", "ok", ":=", "loadedImage", ".", "BigDataDigests", "[", "storage", ".", "ImageDigestBigDataKey", "]", ";", "ok", "{", "loadedImage", ".", "Digest", "=", "digest", "\n", "}", "\n", "if", "s", ".", "named", "!=", "nil", "{", "if", "digested", ",", "ok", ":=", "s", ".", "named", ".", "(", "reference", ".", "Digested", ")", ";", "ok", "{", "for", "_", ",", "digest", ":=", "range", "loadedImage", ".", "Digests", "{", "if", "digest", "==", "digested", ".", "Digest", "(", ")", "{", "loadedImage", ".", "Digest", "=", "digest", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "loadedImage", ",", "nil", "\n", "}" ]
// Resolve the reference's name to an image ID in the store, if there's already // one present with the same name or ID, and return the image.
[ "Resolve", "the", "reference", "s", "name", "to", "an", "image", "ID", "in", "the", "store", "if", "there", "s", "already", "one", "present", "with", "the", "same", "name", "or", "ID", "and", "return", "the", "image", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/storage/storage_reference.go#L56-L119
test
containers/image
storage/storage_reference.go
Transport
func (s storageReference) Transport() types.ImageTransport { return &storageTransport{ store: s.transport.store, defaultUIDMap: s.transport.defaultUIDMap, defaultGIDMap: s.transport.defaultGIDMap, } }
go
func (s storageReference) Transport() types.ImageTransport { return &storageTransport{ store: s.transport.store, defaultUIDMap: s.transport.defaultUIDMap, defaultGIDMap: s.transport.defaultGIDMap, } }
[ "func", "(", "s", "storageReference", ")", "Transport", "(", ")", "types", ".", "ImageTransport", "{", "return", "&", "storageTransport", "{", "store", ":", "s", ".", "transport", ".", "store", ",", "defaultUIDMap", ":", "s", ".", "transport", ".", "defaultUIDMap", ",", "defaultGIDMap", ":", "s", ".", "transport", ".", "defaultGIDMap", ",", "}", "\n", "}" ]
// Return a Transport object that defaults to using the same store that we used // to build this reference object.
[ "Return", "a", "Transport", "object", "that", "defaults", "to", "using", "the", "same", "store", "that", "we", "used", "to", "build", "this", "reference", "object", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/storage/storage_reference.go#L123-L129
test
containers/image
storage/storage_reference.go
StringWithinTransport
func (s storageReference) StringWithinTransport() string { optionsList := "" options := s.transport.store.GraphOptions() if len(options) > 0 { optionsList = ":" + strings.Join(options, ",") } res := "[" + s.transport.store.GraphDriverName() + "@" + s.transport.store.GraphRoot() + "+" + s.transport.store.RunRoot() + optionsList + "]" if s.named != nil { res = res + s.named.String() } if s.id != "" { res = res + "@" + s.id } return res }
go
func (s storageReference) StringWithinTransport() string { optionsList := "" options := s.transport.store.GraphOptions() if len(options) > 0 { optionsList = ":" + strings.Join(options, ",") } res := "[" + s.transport.store.GraphDriverName() + "@" + s.transport.store.GraphRoot() + "+" + s.transport.store.RunRoot() + optionsList + "]" if s.named != nil { res = res + s.named.String() } if s.id != "" { res = res + "@" + s.id } return res }
[ "func", "(", "s", "storageReference", ")", "StringWithinTransport", "(", ")", "string", "{", "optionsList", ":=", "\"\"", "\n", "options", ":=", "s", ".", "transport", ".", "store", ".", "GraphOptions", "(", ")", "\n", "if", "len", "(", "options", ")", ">", "0", "{", "optionsList", "=", "\":\"", "+", "strings", ".", "Join", "(", "options", ",", "\",\"", ")", "\n", "}", "\n", "res", ":=", "\"[\"", "+", "s", ".", "transport", ".", "store", ".", "GraphDriverName", "(", ")", "+", "\"@\"", "+", "s", ".", "transport", ".", "store", ".", "GraphRoot", "(", ")", "+", "\"+\"", "+", "s", ".", "transport", ".", "store", ".", "RunRoot", "(", ")", "+", "optionsList", "+", "\"]\"", "\n", "if", "s", ".", "named", "!=", "nil", "{", "res", "=", "res", "+", "s", ".", "named", ".", "String", "(", ")", "\n", "}", "\n", "if", "s", ".", "id", "!=", "\"\"", "{", "res", "=", "res", "+", "\"@\"", "+", "s", ".", "id", "\n", "}", "\n", "return", "res", "\n", "}" ]
// Return a name with a tag, prefixed with the graph root and driver name, to // disambiguate between images which may be present in multiple stores and // share only their names.
[ "Return", "a", "name", "with", "a", "tag", "prefixed", "with", "the", "graph", "root", "and", "driver", "name", "to", "disambiguate", "between", "images", "which", "may", "be", "present", "in", "multiple", "stores", "and", "share", "only", "their", "names", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/storage/storage_reference.go#L139-L153
test
containers/image
storage/storage_reference.go
PolicyConfigurationNamespaces
func (s storageReference) PolicyConfigurationNamespaces() []string { storeSpec := "[" + s.transport.store.GraphDriverName() + "@" + s.transport.store.GraphRoot() + "]" driverlessStoreSpec := "[" + s.transport.store.GraphRoot() + "]" namespaces := []string{} if s.named != nil { if s.id != "" { // The reference without the ID is also a valid namespace. namespaces = append(namespaces, storeSpec+s.named.String()) } tagged, isTagged := s.named.(reference.Tagged) _, isDigested := s.named.(reference.Digested) if isTagged && isDigested { // s.named is "name:tag@digest"; add a "name:tag" parent namespace. namespaces = append(namespaces, storeSpec+s.named.Name()+":"+tagged.Tag()) } components := strings.Split(s.named.Name(), "/") for len(components) > 0 { namespaces = append(namespaces, storeSpec+strings.Join(components, "/")) components = components[:len(components)-1] } } namespaces = append(namespaces, storeSpec) namespaces = append(namespaces, driverlessStoreSpec) return namespaces }
go
func (s storageReference) PolicyConfigurationNamespaces() []string { storeSpec := "[" + s.transport.store.GraphDriverName() + "@" + s.transport.store.GraphRoot() + "]" driverlessStoreSpec := "[" + s.transport.store.GraphRoot() + "]" namespaces := []string{} if s.named != nil { if s.id != "" { // The reference without the ID is also a valid namespace. namespaces = append(namespaces, storeSpec+s.named.String()) } tagged, isTagged := s.named.(reference.Tagged) _, isDigested := s.named.(reference.Digested) if isTagged && isDigested { // s.named is "name:tag@digest"; add a "name:tag" parent namespace. namespaces = append(namespaces, storeSpec+s.named.Name()+":"+tagged.Tag()) } components := strings.Split(s.named.Name(), "/") for len(components) > 0 { namespaces = append(namespaces, storeSpec+strings.Join(components, "/")) components = components[:len(components)-1] } } namespaces = append(namespaces, storeSpec) namespaces = append(namespaces, driverlessStoreSpec) return namespaces }
[ "func", "(", "s", "storageReference", ")", "PolicyConfigurationNamespaces", "(", ")", "[", "]", "string", "{", "storeSpec", ":=", "\"[\"", "+", "s", ".", "transport", ".", "store", ".", "GraphDriverName", "(", ")", "+", "\"@\"", "+", "s", ".", "transport", ".", "store", ".", "GraphRoot", "(", ")", "+", "\"]\"", "\n", "driverlessStoreSpec", ":=", "\"[\"", "+", "s", ".", "transport", ".", "store", ".", "GraphRoot", "(", ")", "+", "\"]\"", "\n", "namespaces", ":=", "[", "]", "string", "{", "}", "\n", "if", "s", ".", "named", "!=", "nil", "{", "if", "s", ".", "id", "!=", "\"\"", "{", "namespaces", "=", "append", "(", "namespaces", ",", "storeSpec", "+", "s", ".", "named", ".", "String", "(", ")", ")", "\n", "}", "\n", "tagged", ",", "isTagged", ":=", "s", ".", "named", ".", "(", "reference", ".", "Tagged", ")", "\n", "_", ",", "isDigested", ":=", "s", ".", "named", ".", "(", "reference", ".", "Digested", ")", "\n", "if", "isTagged", "&&", "isDigested", "{", "namespaces", "=", "append", "(", "namespaces", ",", "storeSpec", "+", "s", ".", "named", ".", "Name", "(", ")", "+", "\":\"", "+", "tagged", ".", "Tag", "(", ")", ")", "\n", "}", "\n", "components", ":=", "strings", ".", "Split", "(", "s", ".", "named", ".", "Name", "(", ")", ",", "\"/\"", ")", "\n", "for", "len", "(", "components", ")", ">", "0", "{", "namespaces", "=", "append", "(", "namespaces", ",", "storeSpec", "+", "strings", ".", "Join", "(", "components", ",", "\"/\"", ")", ")", "\n", "components", "=", "components", "[", ":", "len", "(", "components", ")", "-", "1", "]", "\n", "}", "\n", "}", "\n", "namespaces", "=", "append", "(", "namespaces", ",", "storeSpec", ")", "\n", "namespaces", "=", "append", "(", "namespaces", ",", "driverlessStoreSpec", ")", "\n", "return", "namespaces", "\n", "}" ]
// Also accept policy that's tied to the combination of the graph root and // driver name, to apply to all images stored in the Store, and to just the // graph root, in case we're using multiple drivers in the same directory for // some reason.
[ "Also", "accept", "policy", "that", "s", "tied", "to", "the", "combination", "of", "the", "graph", "root", "and", "driver", "name", "to", "apply", "to", "all", "images", "stored", "in", "the", "Store", "and", "to", "just", "the", "graph", "root", "in", "case", "we", "re", "using", "multiple", "drivers", "in", "the", "same", "directory", "for", "some", "reason", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/storage/storage_reference.go#L170-L193
test
containers/image
pkg/compression/compression.go
GzipDecompressor
func GzipDecompressor(r io.Reader) (io.ReadCloser, error) { return pgzip.NewReader(r) }
go
func GzipDecompressor(r io.Reader) (io.ReadCloser, error) { return pgzip.NewReader(r) }
[ "func", "GzipDecompressor", "(", "r", "io", ".", "Reader", ")", "(", "io", ".", "ReadCloser", ",", "error", ")", "{", "return", "pgzip", ".", "NewReader", "(", "r", ")", "\n", "}" ]
// GzipDecompressor is a DecompressorFunc for the gzip compression algorithm.
[ "GzipDecompressor", "is", "a", "DecompressorFunc", "for", "the", "gzip", "compression", "algorithm", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/compression/compression.go#L20-L22
test
containers/image
pkg/compression/compression.go
Bzip2Decompressor
func Bzip2Decompressor(r io.Reader) (io.ReadCloser, error) { return ioutil.NopCloser(bzip2.NewReader(r)), nil }
go
func Bzip2Decompressor(r io.Reader) (io.ReadCloser, error) { return ioutil.NopCloser(bzip2.NewReader(r)), nil }
[ "func", "Bzip2Decompressor", "(", "r", "io", ".", "Reader", ")", "(", "io", ".", "ReadCloser", ",", "error", ")", "{", "return", "ioutil", ".", "NopCloser", "(", "bzip2", ".", "NewReader", "(", "r", ")", ")", ",", "nil", "\n", "}" ]
// Bzip2Decompressor is a DecompressorFunc for the bzip2 compression algorithm.
[ "Bzip2Decompressor", "is", "a", "DecompressorFunc", "for", "the", "bzip2", "compression", "algorithm", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/compression/compression.go#L25-L27
test
containers/image
pkg/compression/compression.go
XzDecompressor
func XzDecompressor(r io.Reader) (io.ReadCloser, error) { r, err := xz.NewReader(r) if err != nil { return nil, err } return ioutil.NopCloser(r), nil }
go
func XzDecompressor(r io.Reader) (io.ReadCloser, error) { r, err := xz.NewReader(r) if err != nil { return nil, err } return ioutil.NopCloser(r), nil }
[ "func", "XzDecompressor", "(", "r", "io", ".", "Reader", ")", "(", "io", ".", "ReadCloser", ",", "error", ")", "{", "r", ",", "err", ":=", "xz", ".", "NewReader", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "ioutil", ".", "NopCloser", "(", "r", ")", ",", "nil", "\n", "}" ]
// XzDecompressor is a DecompressorFunc for the xz compression algorithm.
[ "XzDecompressor", "is", "a", "DecompressorFunc", "for", "the", "xz", "compression", "algorithm", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/compression/compression.go#L30-L36
test
containers/image
pkg/compression/compression.go
DetectCompression
func DetectCompression(input io.Reader) (DecompressorFunc, io.Reader, error) { buffer := [8]byte{} n, err := io.ReadAtLeast(input, buffer[:], len(buffer)) if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF { // This is a “real” error. We could just ignore it this time, process the data we have, and hope that the source will report the same error again. // Instead, fail immediately with the original error cause instead of a possibly secondary/misleading error returned later. return nil, nil, err } var decompressor DecompressorFunc for name, algo := range compressionAlgos { if bytes.HasPrefix(buffer[:n], algo.prefix) { logrus.Debugf("Detected compression format %s", name) decompressor = algo.decompressor break } } if decompressor == nil { logrus.Debugf("No compression detected") } return decompressor, io.MultiReader(bytes.NewReader(buffer[:n]), input), nil }
go
func DetectCompression(input io.Reader) (DecompressorFunc, io.Reader, error) { buffer := [8]byte{} n, err := io.ReadAtLeast(input, buffer[:], len(buffer)) if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF { // This is a “real” error. We could just ignore it this time, process the data we have, and hope that the source will report the same error again. // Instead, fail immediately with the original error cause instead of a possibly secondary/misleading error returned later. return nil, nil, err } var decompressor DecompressorFunc for name, algo := range compressionAlgos { if bytes.HasPrefix(buffer[:n], algo.prefix) { logrus.Debugf("Detected compression format %s", name) decompressor = algo.decompressor break } } if decompressor == nil { logrus.Debugf("No compression detected") } return decompressor, io.MultiReader(bytes.NewReader(buffer[:n]), input), nil }
[ "func", "DetectCompression", "(", "input", "io", ".", "Reader", ")", "(", "DecompressorFunc", ",", "io", ".", "Reader", ",", "error", ")", "{", "buffer", ":=", "[", "8", "]", "byte", "{", "}", "\n", "n", ",", "err", ":=", "io", ".", "ReadAtLeast", "(", "input", ",", "buffer", "[", ":", "]", ",", "len", "(", "buffer", ")", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "io", ".", "EOF", "&&", "err", "!=", "io", ".", "ErrUnexpectedEOF", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "var", "decompressor", "DecompressorFunc", "\n", "for", "name", ",", "algo", ":=", "range", "compressionAlgos", "{", "if", "bytes", ".", "HasPrefix", "(", "buffer", "[", ":", "n", "]", ",", "algo", ".", "prefix", ")", "{", "logrus", ".", "Debugf", "(", "\"Detected compression format %s\"", ",", "name", ")", "\n", "decompressor", "=", "algo", ".", "decompressor", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "decompressor", "==", "nil", "{", "logrus", ".", "Debugf", "(", "\"No compression detected\"", ")", "\n", "}", "\n", "return", "decompressor", ",", "io", ".", "MultiReader", "(", "bytes", ".", "NewReader", "(", "buffer", "[", ":", "n", "]", ")", ",", "input", ")", ",", "nil", "\n", "}" ]
// DetectCompression returns a DecompressorFunc if the input is recognized as a compressed format, nil otherwise. // Because it consumes the start of input, other consumers must use the returned io.Reader instead to also read from the beginning.
[ "DetectCompression", "returns", "a", "DecompressorFunc", "if", "the", "input", "is", "recognized", "as", "a", "compressed", "format", "nil", "otherwise", ".", "Because", "it", "consumes", "the", "start", "of", "input", "other", "consumers", "must", "use", "the", "returned", "io", ".", "Reader", "instead", "to", "also", "read", "from", "the", "beginning", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/pkg/compression/compression.go#L50-L73
test
containers/image
docker/docker_image_dest.go
newImageDestination
func newImageDestination(sys *types.SystemContext, ref dockerReference) (types.ImageDestination, error) { c, err := newDockerClientFromRef(sys, ref, true, "pull,push") if err != nil { return nil, err } return &dockerImageDestination{ ref: ref, c: c, }, nil }
go
func newImageDestination(sys *types.SystemContext, ref dockerReference) (types.ImageDestination, error) { c, err := newDockerClientFromRef(sys, ref, true, "pull,push") if err != nil { return nil, err } return &dockerImageDestination{ ref: ref, c: c, }, nil }
[ "func", "newImageDestination", "(", "sys", "*", "types", ".", "SystemContext", ",", "ref", "dockerReference", ")", "(", "types", ".", "ImageDestination", ",", "error", ")", "{", "c", ",", "err", ":=", "newDockerClientFromRef", "(", "sys", ",", "ref", ",", "true", ",", "\"pull,push\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "dockerImageDestination", "{", "ref", ":", "ref", ",", "c", ":", "c", ",", "}", ",", "nil", "\n", "}" ]
// newImageDestination creates a new ImageDestination for the specified image reference.
[ "newImageDestination", "creates", "a", "new", "ImageDestination", "for", "the", "specified", "image", "reference", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_image_dest.go#L38-L47
test
containers/image
docker/docker_image_dest.go
mountBlob
func (d *dockerImageDestination) mountBlob(ctx context.Context, srcRepo reference.Named, srcDigest digest.Digest, extraScope *authScope) error { u := url.URL{ Path: fmt.Sprintf(blobUploadPath, reference.Path(d.ref.ref)), RawQuery: url.Values{ "mount": {srcDigest.String()}, "from": {reference.Path(srcRepo)}, }.Encode(), } mountPath := u.String() logrus.Debugf("Trying to mount %s", mountPath) res, err := d.c.makeRequest(ctx, "POST", mountPath, nil, nil, v2Auth, extraScope) if err != nil { return err } defer res.Body.Close() switch res.StatusCode { case http.StatusCreated: logrus.Debugf("... mount OK") return nil case http.StatusAccepted: // Oops, the mount was ignored - either the registry does not support that yet, or the blob does not exist; the registry has started an ordinary upload process. // Abort, and let the ultimate caller do an upload when its ready, instead. // NOTE: This does not really work in docker/distribution servers, which incorrectly require the "delete" action in the token's scope, and is thus entirely untested. uploadLocation, err := res.Location() if err != nil { return errors.Wrap(err, "Error determining upload URL after a mount attempt") } logrus.Debugf("... started an upload instead of mounting, trying to cancel at %s", uploadLocation.String()) res2, err := d.c.makeRequestToResolvedURL(ctx, "DELETE", uploadLocation.String(), nil, nil, -1, v2Auth, extraScope) if err != nil { logrus.Debugf("Error trying to cancel an inadvertent upload: %s", err) } else { defer res2.Body.Close() if res2.StatusCode != http.StatusNoContent { logrus.Debugf("Error trying to cancel an inadvertent upload, status %s", http.StatusText(res.StatusCode)) } } // Anyway, if canceling the upload fails, ignore it and return the more important error: return fmt.Errorf("Mounting %s from %s to %s started an upload instead", srcDigest, srcRepo.Name(), d.ref.ref.Name()) default: logrus.Debugf("Error mounting, response %#v", *res) return errors.Wrapf(client.HandleErrorResponse(res), "Error mounting %s from %s to %s", srcDigest, srcRepo.Name(), d.ref.ref.Name()) } }
go
func (d *dockerImageDestination) mountBlob(ctx context.Context, srcRepo reference.Named, srcDigest digest.Digest, extraScope *authScope) error { u := url.URL{ Path: fmt.Sprintf(blobUploadPath, reference.Path(d.ref.ref)), RawQuery: url.Values{ "mount": {srcDigest.String()}, "from": {reference.Path(srcRepo)}, }.Encode(), } mountPath := u.String() logrus.Debugf("Trying to mount %s", mountPath) res, err := d.c.makeRequest(ctx, "POST", mountPath, nil, nil, v2Auth, extraScope) if err != nil { return err } defer res.Body.Close() switch res.StatusCode { case http.StatusCreated: logrus.Debugf("... mount OK") return nil case http.StatusAccepted: // Oops, the mount was ignored - either the registry does not support that yet, or the blob does not exist; the registry has started an ordinary upload process. // Abort, and let the ultimate caller do an upload when its ready, instead. // NOTE: This does not really work in docker/distribution servers, which incorrectly require the "delete" action in the token's scope, and is thus entirely untested. uploadLocation, err := res.Location() if err != nil { return errors.Wrap(err, "Error determining upload URL after a mount attempt") } logrus.Debugf("... started an upload instead of mounting, trying to cancel at %s", uploadLocation.String()) res2, err := d.c.makeRequestToResolvedURL(ctx, "DELETE", uploadLocation.String(), nil, nil, -1, v2Auth, extraScope) if err != nil { logrus.Debugf("Error trying to cancel an inadvertent upload: %s", err) } else { defer res2.Body.Close() if res2.StatusCode != http.StatusNoContent { logrus.Debugf("Error trying to cancel an inadvertent upload, status %s", http.StatusText(res.StatusCode)) } } // Anyway, if canceling the upload fails, ignore it and return the more important error: return fmt.Errorf("Mounting %s from %s to %s started an upload instead", srcDigest, srcRepo.Name(), d.ref.ref.Name()) default: logrus.Debugf("Error mounting, response %#v", *res) return errors.Wrapf(client.HandleErrorResponse(res), "Error mounting %s from %s to %s", srcDigest, srcRepo.Name(), d.ref.ref.Name()) } }
[ "func", "(", "d", "*", "dockerImageDestination", ")", "mountBlob", "(", "ctx", "context", ".", "Context", ",", "srcRepo", "reference", ".", "Named", ",", "srcDigest", "digest", ".", "Digest", ",", "extraScope", "*", "authScope", ")", "error", "{", "u", ":=", "url", ".", "URL", "{", "Path", ":", "fmt", ".", "Sprintf", "(", "blobUploadPath", ",", "reference", ".", "Path", "(", "d", ".", "ref", ".", "ref", ")", ")", ",", "RawQuery", ":", "url", ".", "Values", "{", "\"mount\"", ":", "{", "srcDigest", ".", "String", "(", ")", "}", ",", "\"from\"", ":", "{", "reference", ".", "Path", "(", "srcRepo", ")", "}", ",", "}", ".", "Encode", "(", ")", ",", "}", "\n", "mountPath", ":=", "u", ".", "String", "(", ")", "\n", "logrus", ".", "Debugf", "(", "\"Trying to mount %s\"", ",", "mountPath", ")", "\n", "res", ",", "err", ":=", "d", ".", "c", ".", "makeRequest", "(", "ctx", ",", "\"POST\"", ",", "mountPath", ",", "nil", ",", "nil", ",", "v2Auth", ",", "extraScope", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "res", ".", "Body", ".", "Close", "(", ")", "\n", "switch", "res", ".", "StatusCode", "{", "case", "http", ".", "StatusCreated", ":", "logrus", ".", "Debugf", "(", "\"... mount OK\"", ")", "\n", "return", "nil", "\n", "case", "http", ".", "StatusAccepted", ":", "uploadLocation", ",", "err", ":=", "res", ".", "Location", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"Error determining upload URL after a mount attempt\"", ")", "\n", "}", "\n", "logrus", ".", "Debugf", "(", "\"... started an upload instead of mounting, trying to cancel at %s\"", ",", "uploadLocation", ".", "String", "(", ")", ")", "\n", "res2", ",", "err", ":=", "d", ".", "c", ".", "makeRequestToResolvedURL", "(", "ctx", ",", "\"DELETE\"", ",", "uploadLocation", ".", "String", "(", ")", ",", "nil", ",", "nil", ",", "-", "1", ",", "v2Auth", ",", "extraScope", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "Debugf", "(", "\"Error trying to cancel an inadvertent upload: %s\"", ",", "err", ")", "\n", "}", "else", "{", "defer", "res2", ".", "Body", ".", "Close", "(", ")", "\n", "if", "res2", ".", "StatusCode", "!=", "http", ".", "StatusNoContent", "{", "logrus", ".", "Debugf", "(", "\"Error trying to cancel an inadvertent upload, status %s\"", ",", "http", ".", "StatusText", "(", "res", ".", "StatusCode", ")", ")", "\n", "}", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"Mounting %s from %s to %s started an upload instead\"", ",", "srcDigest", ",", "srcRepo", ".", "Name", "(", ")", ",", "d", ".", "ref", ".", "ref", ".", "Name", "(", ")", ")", "\n", "default", ":", "logrus", ".", "Debugf", "(", "\"Error mounting, response %#v\"", ",", "*", "res", ")", "\n", "return", "errors", ".", "Wrapf", "(", "client", ".", "HandleErrorResponse", "(", "res", ")", ",", "\"Error mounting %s from %s to %s\"", ",", "srcDigest", ",", "srcRepo", ".", "Name", "(", ")", ",", "d", ".", "ref", ".", "ref", ".", "Name", "(", ")", ")", "\n", "}", "\n", "}" ]
// mountBlob tries to mount blob srcDigest from srcRepo to the current destination.
[ "mountBlob", "tries", "to", "mount", "blob", "srcDigest", "from", "srcRepo", "to", "the", "current", "destination", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/docker_image_dest.go#L222-L265
test
containers/image
docker/cache.go
bicTransportScope
func bicTransportScope(ref dockerReference) types.BICTransportScope { // Blobs can be reused across the whole registry. return types.BICTransportScope{Opaque: reference.Domain(ref.ref)} }
go
func bicTransportScope(ref dockerReference) types.BICTransportScope { // Blobs can be reused across the whole registry. return types.BICTransportScope{Opaque: reference.Domain(ref.ref)} }
[ "func", "bicTransportScope", "(", "ref", "dockerReference", ")", "types", ".", "BICTransportScope", "{", "return", "types", ".", "BICTransportScope", "{", "Opaque", ":", "reference", ".", "Domain", "(", "ref", ".", "ref", ")", "}", "\n", "}" ]
// bicTransportScope returns a BICTransportScope appropriate for ref.
[ "bicTransportScope", "returns", "a", "BICTransportScope", "appropriate", "for", "ref", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/cache.go#L9-L12
test
containers/image
docker/cache.go
newBICLocationReference
func newBICLocationReference(ref dockerReference) types.BICLocationReference { // Blobs are scoped to repositories (the tag/digest are not necessary to reuse a blob). return types.BICLocationReference{Opaque: ref.ref.Name()} }
go
func newBICLocationReference(ref dockerReference) types.BICLocationReference { // Blobs are scoped to repositories (the tag/digest are not necessary to reuse a blob). return types.BICLocationReference{Opaque: ref.ref.Name()} }
[ "func", "newBICLocationReference", "(", "ref", "dockerReference", ")", "types", ".", "BICLocationReference", "{", "return", "types", ".", "BICLocationReference", "{", "Opaque", ":", "ref", ".", "ref", ".", "Name", "(", ")", "}", "\n", "}" ]
// newBICLocationReference returns a BICLocationReference appropriate for ref.
[ "newBICLocationReference", "returns", "a", "BICLocationReference", "appropriate", "for", "ref", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/cache.go#L15-L18
test
containers/image
docker/cache.go
parseBICLocationReference
func parseBICLocationReference(lr types.BICLocationReference) (reference.Named, error) { return reference.ParseNormalizedNamed(lr.Opaque) }
go
func parseBICLocationReference(lr types.BICLocationReference) (reference.Named, error) { return reference.ParseNormalizedNamed(lr.Opaque) }
[ "func", "parseBICLocationReference", "(", "lr", "types", ".", "BICLocationReference", ")", "(", "reference", ".", "Named", ",", "error", ")", "{", "return", "reference", ".", "ParseNormalizedNamed", "(", "lr", ".", "Opaque", ")", "\n", "}" ]
// parseBICLocationReference returns a repository for encoded lr.
[ "parseBICLocationReference", "returns", "a", "repository", "for", "encoded", "lr", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/cache.go#L21-L23
test
containers/image
docker/tarfile/src.go
NewSourceFromStream
func NewSourceFromStream(inputStream io.Reader) (*Source, error) { // FIXME: use SystemContext here. // Save inputStream to a temporary file tarCopyFile, err := ioutil.TempFile(tmpdir.TemporaryDirectoryForBigFiles(), "docker-tar") if err != nil { return nil, errors.Wrap(err, "error creating temporary file") } defer tarCopyFile.Close() succeeded := false defer func() { if !succeeded { os.Remove(tarCopyFile.Name()) } }() // In order to be compatible with docker-load, we need to support // auto-decompression (it's also a nice quality-of-life thing to avoid // giving users really confusing "invalid tar header" errors). uncompressedStream, _, err := compression.AutoDecompress(inputStream) if err != nil { return nil, errors.Wrap(err, "Error auto-decompressing input") } defer uncompressedStream.Close() // Copy the plain archive to the temporary file. // // TODO: This can take quite some time, and should ideally be cancellable // using a context.Context. if _, err := io.Copy(tarCopyFile, uncompressedStream); err != nil { return nil, errors.Wrapf(err, "error copying contents to temporary file %q", tarCopyFile.Name()) } succeeded = true return &Source{ tarPath: tarCopyFile.Name(), removeTarPathOnClose: true, }, nil }
go
func NewSourceFromStream(inputStream io.Reader) (*Source, error) { // FIXME: use SystemContext here. // Save inputStream to a temporary file tarCopyFile, err := ioutil.TempFile(tmpdir.TemporaryDirectoryForBigFiles(), "docker-tar") if err != nil { return nil, errors.Wrap(err, "error creating temporary file") } defer tarCopyFile.Close() succeeded := false defer func() { if !succeeded { os.Remove(tarCopyFile.Name()) } }() // In order to be compatible with docker-load, we need to support // auto-decompression (it's also a nice quality-of-life thing to avoid // giving users really confusing "invalid tar header" errors). uncompressedStream, _, err := compression.AutoDecompress(inputStream) if err != nil { return nil, errors.Wrap(err, "Error auto-decompressing input") } defer uncompressedStream.Close() // Copy the plain archive to the temporary file. // // TODO: This can take quite some time, and should ideally be cancellable // using a context.Context. if _, err := io.Copy(tarCopyFile, uncompressedStream); err != nil { return nil, errors.Wrapf(err, "error copying contents to temporary file %q", tarCopyFile.Name()) } succeeded = true return &Source{ tarPath: tarCopyFile.Name(), removeTarPathOnClose: true, }, nil }
[ "func", "NewSourceFromStream", "(", "inputStream", "io", ".", "Reader", ")", "(", "*", "Source", ",", "error", ")", "{", "tarCopyFile", ",", "err", ":=", "ioutil", ".", "TempFile", "(", "tmpdir", ".", "TemporaryDirectoryForBigFiles", "(", ")", ",", "\"docker-tar\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"error creating temporary file\"", ")", "\n", "}", "\n", "defer", "tarCopyFile", ".", "Close", "(", ")", "\n", "succeeded", ":=", "false", "\n", "defer", "func", "(", ")", "{", "if", "!", "succeeded", "{", "os", ".", "Remove", "(", "tarCopyFile", ".", "Name", "(", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n", "uncompressedStream", ",", "_", ",", "err", ":=", "compression", ".", "AutoDecompress", "(", "inputStream", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"Error auto-decompressing input\"", ")", "\n", "}", "\n", "defer", "uncompressedStream", ".", "Close", "(", ")", "\n", "if", "_", ",", "err", ":=", "io", ".", "Copy", "(", "tarCopyFile", ",", "uncompressedStream", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"error copying contents to temporary file %q\"", ",", "tarCopyFile", ".", "Name", "(", ")", ")", "\n", "}", "\n", "succeeded", "=", "true", "\n", "return", "&", "Source", "{", "tarPath", ":", "tarCopyFile", ".", "Name", "(", ")", ",", "removeTarPathOnClose", ":", "true", ",", "}", ",", "nil", "\n", "}" ]
// NewSourceFromStream returns a tarfile.Source for the specified inputStream, // which can be either compressed or uncompressed. The caller can close the // inputStream immediately after NewSourceFromFile returns.
[ "NewSourceFromStream", "returns", "a", "tarfile", ".", "Source", "for", "the", "specified", "inputStream", "which", "can", "be", "either", "compressed", "or", "uncompressed", ".", "The", "caller", "can", "close", "the", "inputStream", "immediately", "after", "NewSourceFromFile", "returns", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/tarfile/src.go#L74-L112
test
containers/image
docker/tarfile/src.go
readTarComponent
func (s *Source) readTarComponent(path string) ([]byte, error) { file, err := s.openTarComponent(path) if err != nil { return nil, errors.Wrapf(err, "Error loading tar component %s", path) } defer file.Close() bytes, err := ioutil.ReadAll(file) if err != nil { return nil, err } return bytes, nil }
go
func (s *Source) readTarComponent(path string) ([]byte, error) { file, err := s.openTarComponent(path) if err != nil { return nil, errors.Wrapf(err, "Error loading tar component %s", path) } defer file.Close() bytes, err := ioutil.ReadAll(file) if err != nil { return nil, err } return bytes, nil }
[ "func", "(", "s", "*", "Source", ")", "readTarComponent", "(", "path", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "file", ",", "err", ":=", "s", ".", "openTarComponent", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"Error loading tar component %s\"", ",", "path", ")", "\n", "}", "\n", "defer", "file", ".", "Close", "(", ")", "\n", "bytes", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "file", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "bytes", ",", "nil", "\n", "}" ]
// readTarComponent returns full contents of componentPath.
[ "readTarComponent", "returns", "full", "contents", "of", "componentPath", "." ]
da9ab3561ad2031aeb5e036b7cf2755d4e246fec
https://github.com/containers/image/blob/da9ab3561ad2031aeb5e036b7cf2755d4e246fec/docker/tarfile/src.go#L190-L201
test