repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
openshift/source-to-image
pkg/util/interrupt/interrupt.go
close
func (h *Handler) close() { h.once.Do(func() { for _, fn := range h.notify { fn() } }) }
go
func (h *Handler) close() { h.once.Do(func() { for _, fn := range h.notify { fn() } }) }
[ "func", "(", "h", "*", "Handler", ")", "close", "(", ")", "{", "h", ".", "once", ".", "Do", "(", "func", "(", ")", "{", "for", "_", ",", "fn", ":=", "range", "h", ".", "notify", "{", "fn", "(", ")", "\n", "}", "\n", "}", ")", "\n", "}" ]
// close calls the notify functions, used when no signal was caught and the Run // method returned.
[ "close", "calls", "the", "notify", "functions", "used", "when", "no", "signal", "was", "caught", "and", "the", "Run", "method", "returned", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/util/interrupt/interrupt.go#L83-L89
train
openshift/source-to-image
pkg/util/interrupt/interrupt.go
signal
func (h *Handler) signal(s os.Signal) { h.once.Do(func() { for _, fn := range h.notify { fn() } if h.final == nil { os.Exit(2) } h.final(s) }) }
go
func (h *Handler) signal(s os.Signal) { h.once.Do(func() { for _, fn := range h.notify { fn() } if h.final == nil { os.Exit(2) } h.final(s) }) }
[ "func", "(", "h", "*", "Handler", ")", "signal", "(", "s", "os", ".", "Signal", ")", "{", "h", ".", "once", ".", "Do", "(", "func", "(", ")", "{", "for", "_", ",", "fn", ":=", "range", "h", ".", "notify", "{", "fn", "(", ")", "\n", "}", "\n", "if", "h", ".", "final", "==", "nil", "{", "os", ".", "Exit", "(", "2", ")", "\n", "}", "\n", "h", ".", "final", "(", "s", ")", "\n", "}", ")", "\n", "}" ]
// signal calls the notify functions and final, used when a signal was caught // while the Run method was running. If final is nil, os.Exit will be called as // a default.
[ "signal", "calls", "the", "notify", "functions", "and", "final", "used", "when", "a", "signal", "was", "caught", "while", "the", "Run", "method", "was", "running", ".", "If", "final", "is", "nil", "os", ".", "Exit", "will", "be", "called", "as", "a", "default", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/util/interrupt/interrupt.go#L94-L104
train
openshift/source-to-image
pkg/scm/downloaders/empty/noop.go
Download
func (n *Noop) Download(config *api.Config) (*git.SourceInfo, error) { glog.V(1).Info("No source location defined (the assemble script is responsible for obtaining the source)") return &git.SourceInfo{}, nil }
go
func (n *Noop) Download(config *api.Config) (*git.SourceInfo, error) { glog.V(1).Info("No source location defined (the assemble script is responsible for obtaining the source)") return &git.SourceInfo{}, nil }
[ "func", "(", "n", "*", "Noop", ")", "Download", "(", "config", "*", "api", ".", "Config", ")", "(", "*", "git", ".", "SourceInfo", ",", "error", ")", "{", "glog", ".", "V", "(", "1", ")", ".", "Info", "(", "\"", "\"", ")", "\n\n", "return", "&", "git", ".", "SourceInfo", "{", "}", ",", "nil", "\n", "}" ]
// Download is a no-op downloader so that Noop satisfies build.Downloader
[ "Download", "is", "a", "no", "-", "op", "downloader", "so", "that", "Noop", "satisfies", "build", ".", "Downloader" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/scm/downloaders/empty/noop.go#L17-L21
train
openshift/source-to-image
pkg/util/cmd/cmd.go
RunWithOptions
func (c *runner) RunWithOptions(opts CommandOpts, name string, arg ...string) error { cmd := exec.Command(name, arg...) if opts.Stdout != nil { cmd.Stdout = opts.Stdout } if opts.Stderr != nil { cmd.Stderr = opts.Stderr } if opts.Dir != "" { cmd.Dir = opts.Dir } if len(opts.EnvAppend) > 0 { cmd.Env = os.Environ() cmd.Env = append(cmd.Env, opts.EnvAppend...) } return cmd.Run() }
go
func (c *runner) RunWithOptions(opts CommandOpts, name string, arg ...string) error { cmd := exec.Command(name, arg...) if opts.Stdout != nil { cmd.Stdout = opts.Stdout } if opts.Stderr != nil { cmd.Stderr = opts.Stderr } if opts.Dir != "" { cmd.Dir = opts.Dir } if len(opts.EnvAppend) > 0 { cmd.Env = os.Environ() cmd.Env = append(cmd.Env, opts.EnvAppend...) } return cmd.Run() }
[ "func", "(", "c", "*", "runner", ")", "RunWithOptions", "(", "opts", "CommandOpts", ",", "name", "string", ",", "arg", "...", "string", ")", "error", "{", "cmd", ":=", "exec", ".", "Command", "(", "name", ",", "arg", "...", ")", "\n", "if", "opts", ".", "Stdout", "!=", "nil", "{", "cmd", ".", "Stdout", "=", "opts", ".", "Stdout", "\n", "}", "\n", "if", "opts", ".", "Stderr", "!=", "nil", "{", "cmd", ".", "Stderr", "=", "opts", ".", "Stderr", "\n", "}", "\n", "if", "opts", ".", "Dir", "!=", "\"", "\"", "{", "cmd", ".", "Dir", "=", "opts", ".", "Dir", "\n", "}", "\n", "if", "len", "(", "opts", ".", "EnvAppend", ")", ">", "0", "{", "cmd", ".", "Env", "=", "os", ".", "Environ", "(", ")", "\n", "cmd", ".", "Env", "=", "append", "(", "cmd", ".", "Env", ",", "opts", ".", "EnvAppend", "...", ")", "\n", "}", "\n", "return", "cmd", ".", "Run", "(", ")", "\n", "}" ]
// RunWithOptions runs a command with the provided options
[ "RunWithOptions", "runs", "a", "command", "with", "the", "provided", "options" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/util/cmd/cmd.go#L37-L53
train
openshift/source-to-image
pkg/util/cmd/cmd.go
Run
func (c *runner) Run(name string, arg ...string) error { return c.RunWithOptions(CommandOpts{}, name, arg...) }
go
func (c *runner) Run(name string, arg ...string) error { return c.RunWithOptions(CommandOpts{}, name, arg...) }
[ "func", "(", "c", "*", "runner", ")", "Run", "(", "name", "string", ",", "arg", "...", "string", ")", "error", "{", "return", "c", ".", "RunWithOptions", "(", "CommandOpts", "{", "}", ",", "name", ",", "arg", "...", ")", "\n", "}" ]
// Run executes a command with default options
[ "Run", "executes", "a", "command", "with", "default", "options" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/util/cmd/cmd.go#L56-L58
train
openshift/source-to-image
pkg/util/cmd/cmd.go
StartWithStdoutPipe
func (c *runner) StartWithStdoutPipe(opts CommandOpts, name string, arg ...string) (io.ReadCloser, error) { c.cmd = exec.Command(name, arg...) if opts.Stderr != nil { c.cmd.Stderr = opts.Stderr } if opts.Dir != "" { c.cmd.Dir = opts.Dir } if len(opts.EnvAppend) > 0 { c.cmd.Env = os.Environ() c.cmd.Env = append(c.cmd.Env, opts.EnvAppend...) } r, err := c.cmd.StdoutPipe() if err != nil { return nil, err } return r, c.cmd.Start() }
go
func (c *runner) StartWithStdoutPipe(opts CommandOpts, name string, arg ...string) (io.ReadCloser, error) { c.cmd = exec.Command(name, arg...) if opts.Stderr != nil { c.cmd.Stderr = opts.Stderr } if opts.Dir != "" { c.cmd.Dir = opts.Dir } if len(opts.EnvAppend) > 0 { c.cmd.Env = os.Environ() c.cmd.Env = append(c.cmd.Env, opts.EnvAppend...) } r, err := c.cmd.StdoutPipe() if err != nil { return nil, err } return r, c.cmd.Start() }
[ "func", "(", "c", "*", "runner", ")", "StartWithStdoutPipe", "(", "opts", "CommandOpts", ",", "name", "string", ",", "arg", "...", "string", ")", "(", "io", ".", "ReadCloser", ",", "error", ")", "{", "c", ".", "cmd", "=", "exec", ".", "Command", "(", "name", ",", "arg", "...", ")", "\n", "if", "opts", ".", "Stderr", "!=", "nil", "{", "c", ".", "cmd", ".", "Stderr", "=", "opts", ".", "Stderr", "\n", "}", "\n", "if", "opts", ".", "Dir", "!=", "\"", "\"", "{", "c", ".", "cmd", ".", "Dir", "=", "opts", ".", "Dir", "\n", "}", "\n", "if", "len", "(", "opts", ".", "EnvAppend", ")", ">", "0", "{", "c", ".", "cmd", ".", "Env", "=", "os", ".", "Environ", "(", ")", "\n", "c", ".", "cmd", ".", "Env", "=", "append", "(", "c", ".", "cmd", ".", "Env", ",", "opts", ".", "EnvAppend", "...", ")", "\n", "}", "\n", "r", ",", "err", ":=", "c", ".", "cmd", ".", "StdoutPipe", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "r", ",", "c", ".", "cmd", ".", "Start", "(", ")", "\n", "}" ]
// StartWithStdoutPipe executes a command returning a ReadCloser connected to // the command's stdout.
[ "StartWithStdoutPipe", "executes", "a", "command", "returning", "a", "ReadCloser", "connected", "to", "the", "command", "s", "stdout", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/util/cmd/cmd.go#L62-L79
train
openshift/source-to-image
pkg/build/config.go
GenerateConfigFromLabels
func GenerateConfigFromLabels(config *api.Config, metadata *docker.PullResult) error { if config == nil { return errors.New("config must be provided to GenerateConfigFromLabels") } if metadata == nil { return errors.New("image metadata must be provided to GenerateConfigFromLabels") } labels := metadata.Image.Config.Labels if builderVersion, ok := labels[constants.BuilderVersionLabel]; ok { config.BuilderImageVersion = builderVersion config.BuilderBaseImageVersion = labels[constants.BuilderBaseVersionLabel] } config.ScriptsURL = labels[constants.ScriptsURLLabel] if len(config.ScriptsURL) == 0 { // FIXME: Backward compatibility config.ScriptsURL = labels[constants.DeprecatedScriptsURLLabel] } config.Description = labels[constants.KubernetesDescriptionLabel] config.DisplayName = labels[constants.KubernetesDisplayNameLabel] if builder, ok := labels[constants.BuildImageLabel]; ok { config.BuilderImage = builder } else { return fmt.Errorf("required label %q not found in image", constants.BuildImageLabel) } if repo, ok := labels[constants.BuildSourceLocationLabel]; ok { source, err := git.Parse(repo) if err != nil { return fmt.Errorf("couldn't parse label %q value %s: %v", constants.BuildSourceLocationLabel, repo, err) } config.Source = source } else { return fmt.Errorf("required label %q not found in image", constants.BuildSourceLocationLabel) } config.ContextDir = labels[constants.BuildSourceContextDirLabel] config.Source.URL.Fragment = labels[constants.BuildCommitRefLabel] return nil }
go
func GenerateConfigFromLabels(config *api.Config, metadata *docker.PullResult) error { if config == nil { return errors.New("config must be provided to GenerateConfigFromLabels") } if metadata == nil { return errors.New("image metadata must be provided to GenerateConfigFromLabels") } labels := metadata.Image.Config.Labels if builderVersion, ok := labels[constants.BuilderVersionLabel]; ok { config.BuilderImageVersion = builderVersion config.BuilderBaseImageVersion = labels[constants.BuilderBaseVersionLabel] } config.ScriptsURL = labels[constants.ScriptsURLLabel] if len(config.ScriptsURL) == 0 { // FIXME: Backward compatibility config.ScriptsURL = labels[constants.DeprecatedScriptsURLLabel] } config.Description = labels[constants.KubernetesDescriptionLabel] config.DisplayName = labels[constants.KubernetesDisplayNameLabel] if builder, ok := labels[constants.BuildImageLabel]; ok { config.BuilderImage = builder } else { return fmt.Errorf("required label %q not found in image", constants.BuildImageLabel) } if repo, ok := labels[constants.BuildSourceLocationLabel]; ok { source, err := git.Parse(repo) if err != nil { return fmt.Errorf("couldn't parse label %q value %s: %v", constants.BuildSourceLocationLabel, repo, err) } config.Source = source } else { return fmt.Errorf("required label %q not found in image", constants.BuildSourceLocationLabel) } config.ContextDir = labels[constants.BuildSourceContextDirLabel] config.Source.URL.Fragment = labels[constants.BuildCommitRefLabel] return nil }
[ "func", "GenerateConfigFromLabels", "(", "config", "*", "api", ".", "Config", ",", "metadata", "*", "docker", ".", "PullResult", ")", "error", "{", "if", "config", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "metadata", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "labels", ":=", "metadata", ".", "Image", ".", "Config", ".", "Labels", "\n\n", "if", "builderVersion", ",", "ok", ":=", "labels", "[", "constants", ".", "BuilderVersionLabel", "]", ";", "ok", "{", "config", ".", "BuilderImageVersion", "=", "builderVersion", "\n", "config", ".", "BuilderBaseImageVersion", "=", "labels", "[", "constants", ".", "BuilderBaseVersionLabel", "]", "\n", "}", "\n\n", "config", ".", "ScriptsURL", "=", "labels", "[", "constants", ".", "ScriptsURLLabel", "]", "\n", "if", "len", "(", "config", ".", "ScriptsURL", ")", "==", "0", "{", "// FIXME: Backward compatibility", "config", ".", "ScriptsURL", "=", "labels", "[", "constants", ".", "DeprecatedScriptsURLLabel", "]", "\n", "}", "\n\n", "config", ".", "Description", "=", "labels", "[", "constants", ".", "KubernetesDescriptionLabel", "]", "\n", "config", ".", "DisplayName", "=", "labels", "[", "constants", ".", "KubernetesDisplayNameLabel", "]", "\n\n", "if", "builder", ",", "ok", ":=", "labels", "[", "constants", ".", "BuildImageLabel", "]", ";", "ok", "{", "config", ".", "BuilderImage", "=", "builder", "\n", "}", "else", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "constants", ".", "BuildImageLabel", ")", "\n", "}", "\n\n", "if", "repo", ",", "ok", ":=", "labels", "[", "constants", ".", "BuildSourceLocationLabel", "]", ";", "ok", "{", "source", ",", "err", ":=", "git", ".", "Parse", "(", "repo", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "constants", ".", "BuildSourceLocationLabel", ",", "repo", ",", "err", ")", "\n", "}", "\n", "config", ".", "Source", "=", "source", "\n", "}", "else", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "constants", ".", "BuildSourceLocationLabel", ")", "\n", "}", "\n\n", "config", ".", "ContextDir", "=", "labels", "[", "constants", ".", "BuildSourceContextDirLabel", "]", "\n", "config", ".", "Source", ".", "URL", ".", "Fragment", "=", "labels", "[", "constants", ".", "BuildCommitRefLabel", "]", "\n\n", "return", "nil", "\n", "}" ]
// GenerateConfigFromLabels generates the S2I Config struct from the Docker // image labels.
[ "GenerateConfigFromLabels", "generates", "the", "S2I", "Config", "struct", "from", "the", "Docker", "image", "labels", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/build/config.go#L15-L59
train
openshift/source-to-image
pkg/scripts/environment.go
ConvertEnvironmentList
func ConvertEnvironmentList(env api.EnvironmentList) (result []string) { for _, e := range env { result = append(result, fmt.Sprintf("%s=%s", e.Name, e.Value)) } return }
go
func ConvertEnvironmentList(env api.EnvironmentList) (result []string) { for _, e := range env { result = append(result, fmt.Sprintf("%s=%s", e.Name, e.Value)) } return }
[ "func", "ConvertEnvironmentList", "(", "env", "api", ".", "EnvironmentList", ")", "(", "result", "[", "]", "string", ")", "{", "for", "_", ",", "e", ":=", "range", "env", "{", "result", "=", "append", "(", "result", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "e", ".", "Name", ",", "e", ".", "Value", ")", ")", "\n", "}", "\n", "return", "\n", "}" ]
// ConvertEnvironmentList converts the EnvironmentList to "key=val" strings.
[ "ConvertEnvironmentList", "converts", "the", "EnvironmentList", "to", "key", "=", "val", "strings", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/scripts/environment.go#L46-L51
train
openshift/source-to-image
pkg/scripts/environment.go
ConvertEnvironmentToDocker
func ConvertEnvironmentToDocker(env api.EnvironmentList) (result string) { for i, e := range env { if i == 0 { result += fmt.Sprintf("ENV %s=\"%s\"", e.Name, e.Value) } else { result += fmt.Sprintf(" \\\n %s=\"%s\"", e.Name, e.Value) } } result += "\n" return }
go
func ConvertEnvironmentToDocker(env api.EnvironmentList) (result string) { for i, e := range env { if i == 0 { result += fmt.Sprintf("ENV %s=\"%s\"", e.Name, e.Value) } else { result += fmt.Sprintf(" \\\n %s=\"%s\"", e.Name, e.Value) } } result += "\n" return }
[ "func", "ConvertEnvironmentToDocker", "(", "env", "api", ".", "EnvironmentList", ")", "(", "result", "string", ")", "{", "for", "i", ",", "e", ":=", "range", "env", "{", "if", "i", "==", "0", "{", "result", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\\"", "\\\"", "\"", ",", "e", ".", "Name", ",", "e", ".", "Value", ")", "\n", "}", "else", "{", "result", "+=", "fmt", ".", "Sprintf", "(", "\"", "\\\\", "\\n", "\\\"", "\\\"", "\"", ",", "e", ".", "Name", ",", "e", ".", "Value", ")", "\n", "}", "\n", "}", "\n", "result", "+=", "\"", "\\n", "\"", "\n", "return", "\n", "}" ]
// ConvertEnvironmentToDocker converts the EnvironmentList into Dockerfile format.
[ "ConvertEnvironmentToDocker", "converts", "the", "EnvironmentList", "into", "Dockerfile", "format", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/scripts/environment.go#L54-L64
train
openshift/source-to-image
pkg/api/validation/validation.go
ValidateConfig
func ValidateConfig(config *api.Config) []Error { allErrs := []Error{} if len(config.BuilderImage) == 0 { allErrs = append(allErrs, NewFieldRequired("builderImage")) } switch config.BuilderPullPolicy { case api.PullNever, api.PullAlways, api.PullIfNotPresent: default: allErrs = append(allErrs, NewFieldInvalidValue("builderPullPolicy")) } if config.DockerConfig == nil || len(config.DockerConfig.Endpoint) == 0 { allErrs = append(allErrs, NewFieldRequired("dockerConfig.endpoint")) } if config.DockerNetworkMode != "" && !validateDockerNetworkMode(config.DockerNetworkMode) { allErrs = append(allErrs, NewFieldInvalidValue("dockerNetworkMode")) } if config.Labels != nil { for k := range config.Labels { if len(k) == 0 { allErrs = append(allErrs, NewFieldInvalidValue("labels")) } } } if config.Tag != "" { if err := validateDockerReference(config.Tag); err != nil { allErrs = append(allErrs, NewFieldInvalidValueWithReason("tag", err.Error())) } } return allErrs }
go
func ValidateConfig(config *api.Config) []Error { allErrs := []Error{} if len(config.BuilderImage) == 0 { allErrs = append(allErrs, NewFieldRequired("builderImage")) } switch config.BuilderPullPolicy { case api.PullNever, api.PullAlways, api.PullIfNotPresent: default: allErrs = append(allErrs, NewFieldInvalidValue("builderPullPolicy")) } if config.DockerConfig == nil || len(config.DockerConfig.Endpoint) == 0 { allErrs = append(allErrs, NewFieldRequired("dockerConfig.endpoint")) } if config.DockerNetworkMode != "" && !validateDockerNetworkMode(config.DockerNetworkMode) { allErrs = append(allErrs, NewFieldInvalidValue("dockerNetworkMode")) } if config.Labels != nil { for k := range config.Labels { if len(k) == 0 { allErrs = append(allErrs, NewFieldInvalidValue("labels")) } } } if config.Tag != "" { if err := validateDockerReference(config.Tag); err != nil { allErrs = append(allErrs, NewFieldInvalidValueWithReason("tag", err.Error())) } } return allErrs }
[ "func", "ValidateConfig", "(", "config", "*", "api", ".", "Config", ")", "[", "]", "Error", "{", "allErrs", ":=", "[", "]", "Error", "{", "}", "\n", "if", "len", "(", "config", ".", "BuilderImage", ")", "==", "0", "{", "allErrs", "=", "append", "(", "allErrs", ",", "NewFieldRequired", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "switch", "config", ".", "BuilderPullPolicy", "{", "case", "api", ".", "PullNever", ",", "api", ".", "PullAlways", ",", "api", ".", "PullIfNotPresent", ":", "default", ":", "allErrs", "=", "append", "(", "allErrs", ",", "NewFieldInvalidValue", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "if", "config", ".", "DockerConfig", "==", "nil", "||", "len", "(", "config", ".", "DockerConfig", ".", "Endpoint", ")", "==", "0", "{", "allErrs", "=", "append", "(", "allErrs", ",", "NewFieldRequired", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "if", "config", ".", "DockerNetworkMode", "!=", "\"", "\"", "&&", "!", "validateDockerNetworkMode", "(", "config", ".", "DockerNetworkMode", ")", "{", "allErrs", "=", "append", "(", "allErrs", ",", "NewFieldInvalidValue", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "if", "config", ".", "Labels", "!=", "nil", "{", "for", "k", ":=", "range", "config", ".", "Labels", "{", "if", "len", "(", "k", ")", "==", "0", "{", "allErrs", "=", "append", "(", "allErrs", ",", "NewFieldInvalidValue", "(", "\"", "\"", ")", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "config", ".", "Tag", "!=", "\"", "\"", "{", "if", "err", ":=", "validateDockerReference", "(", "config", ".", "Tag", ")", ";", "err", "!=", "nil", "{", "allErrs", "=", "append", "(", "allErrs", ",", "NewFieldInvalidValueWithReason", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", ")", "\n", "}", "\n", "}", "\n", "return", "allErrs", "\n", "}" ]
// ValidateConfig returns a list of error from validation.
[ "ValidateConfig", "returns", "a", "list", "of", "error", "from", "validation", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/api/validation/validation.go#L13-L42
train
openshift/source-to-image
pkg/api/validation/validation.go
NewFieldInvalidValueWithReason
func NewFieldInvalidValueWithReason(field, reason string) Error { return Error{Type: ErrorInvalidValue, Field: field, Reason: reason} }
go
func NewFieldInvalidValueWithReason(field, reason string) Error { return Error{Type: ErrorInvalidValue, Field: field, Reason: reason} }
[ "func", "NewFieldInvalidValueWithReason", "(", "field", ",", "reason", "string", ")", "Error", "{", "return", "Error", "{", "Type", ":", "ErrorInvalidValue", ",", "Field", ":", "field", ",", "Reason", ":", "reason", "}", "\n", "}" ]
// NewFieldInvalidValueWithReason returns a ValidationError indicating "invalid value" and a reason for the error
[ "NewFieldInvalidValueWithReason", "returns", "a", "ValidationError", "indicating", "invalid", "value", "and", "a", "reason", "for", "the", "error" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/api/validation/validation.go#L76-L78
train
openshift/source-to-image
pkg/cmd/cli/cmd/completion.go
NewCmdCompletion
func NewCmdCompletion(root *cobra.Command) *cobra.Command { shells := []string{} for s := range completionShells { shells = append(shells, s) } return &cobra.Command{ Use: "completion SHELL", Short: "Generate completion for the s2i command (bash or zsh)", Long: "Generate completion for the s2i command into standard output (bash or zsh)", Run: func(cmd *cobra.Command, args []string) { // TODO: The version of cobra we vendor takes a // *bytes.Buffer, while newer versions take an // io.Writer. The code below could be simplified to a // single line `root.GenBashCompletion(os.Stdout)` when // we update cobra. var out bytes.Buffer err := RunCompletion(&out, cmd, root, args) if err != nil { s2ierr.CheckError(err) } else { fmt.Print(out.String()) } }, ValidArgs: shells, } }
go
func NewCmdCompletion(root *cobra.Command) *cobra.Command { shells := []string{} for s := range completionShells { shells = append(shells, s) } return &cobra.Command{ Use: "completion SHELL", Short: "Generate completion for the s2i command (bash or zsh)", Long: "Generate completion for the s2i command into standard output (bash or zsh)", Run: func(cmd *cobra.Command, args []string) { // TODO: The version of cobra we vendor takes a // *bytes.Buffer, while newer versions take an // io.Writer. The code below could be simplified to a // single line `root.GenBashCompletion(os.Stdout)` when // we update cobra. var out bytes.Buffer err := RunCompletion(&out, cmd, root, args) if err != nil { s2ierr.CheckError(err) } else { fmt.Print(out.String()) } }, ValidArgs: shells, } }
[ "func", "NewCmdCompletion", "(", "root", "*", "cobra", ".", "Command", ")", "*", "cobra", ".", "Command", "{", "shells", ":=", "[", "]", "string", "{", "}", "\n", "for", "s", ":=", "range", "completionShells", "{", "shells", "=", "append", "(", "shells", ",", "s", ")", "\n", "}", "\n\n", "return", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "Long", ":", "\"", "\"", ",", "Run", ":", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "// TODO: The version of cobra we vendor takes a", "// *bytes.Buffer, while newer versions take an", "// io.Writer. The code below could be simplified to a", "// single line `root.GenBashCompletion(os.Stdout)` when", "// we update cobra.", "var", "out", "bytes", ".", "Buffer", "\n", "err", ":=", "RunCompletion", "(", "&", "out", ",", "cmd", ",", "root", ",", "args", ")", "\n", "if", "err", "!=", "nil", "{", "s2ierr", ".", "CheckError", "(", "err", ")", "\n", "}", "else", "{", "fmt", ".", "Print", "(", "out", ".", "String", "(", ")", ")", "\n", "}", "\n", "}", ",", "ValidArgs", ":", "shells", ",", "}", "\n", "}" ]
// NewCmdCompletion implements the S2I cli completion command.
[ "NewCmdCompletion", "implements", "the", "S2I", "cli", "completion", "command", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/cmd/cli/cmd/completion.go#L21-L47
train
openshift/source-to-image
pkg/errors/errors.go
NewInspectImageError
func NewInspectImageError(name string, err error) error { return Error{ Message: fmt.Sprintf("unable to get metadata for %s", name), Details: err, ErrorCode: InspectImageError, Suggestion: "check image name", } }
go
func NewInspectImageError(name string, err error) error { return Error{ Message: fmt.Sprintf("unable to get metadata for %s", name), Details: err, ErrorCode: InspectImageError, Suggestion: "check image name", } }
[ "func", "NewInspectImageError", "(", "name", "string", ",", "err", "error", ")", "error", "{", "return", "Error", "{", "Message", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "name", ")", ",", "Details", ":", "err", ",", "ErrorCode", ":", "InspectImageError", ",", "Suggestion", ":", "\"", "\"", ",", "}", "\n", "}" ]
// NewInspectImageError returns a new error which indicates there was a problem // inspecting the image
[ "NewInspectImageError", "returns", "a", "new", "error", "which", "indicates", "there", "was", "a", "problem", "inspecting", "the", "image" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/errors/errors.go#L61-L68
train
openshift/source-to-image
pkg/errors/errors.go
NewPullImageError
func NewPullImageError(name string, err error) error { return Error{ Message: fmt.Sprintf("unable to get %s", name), Details: err, ErrorCode: PullImageError, Suggestion: fmt.Sprintf("check image name, or if using a local image set the builder image pull policy to %q", "never"), } }
go
func NewPullImageError(name string, err error) error { return Error{ Message: fmt.Sprintf("unable to get %s", name), Details: err, ErrorCode: PullImageError, Suggestion: fmt.Sprintf("check image name, or if using a local image set the builder image pull policy to %q", "never"), } }
[ "func", "NewPullImageError", "(", "name", "string", ",", "err", "error", ")", "error", "{", "return", "Error", "{", "Message", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "name", ")", ",", "Details", ":", "err", ",", "ErrorCode", ":", "PullImageError", ",", "Suggestion", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "\"", "\"", ")", ",", "}", "\n", "}" ]
// NewPullImageError returns a new error which indicates there was a problem // pulling the image
[ "NewPullImageError", "returns", "a", "new", "error", "which", "indicates", "there", "was", "a", "problem", "pulling", "the", "image" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/errors/errors.go#L72-L79
train
openshift/source-to-image
pkg/errors/errors.go
NewSaveArtifactsError
func NewSaveArtifactsError(name, output string, err error) error { return Error{ Message: fmt.Sprintf("saving artifacts for %s failed:\n%s", name, output), Details: err, ErrorCode: SaveArtifactsError, Suggestion: "check the save-artifacts script for errors", } }
go
func NewSaveArtifactsError(name, output string, err error) error { return Error{ Message: fmt.Sprintf("saving artifacts for %s failed:\n%s", name, output), Details: err, ErrorCode: SaveArtifactsError, Suggestion: "check the save-artifacts script for errors", } }
[ "func", "NewSaveArtifactsError", "(", "name", ",", "output", "string", ",", "err", "error", ")", "error", "{", "return", "Error", "{", "Message", ":", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "name", ",", "output", ")", ",", "Details", ":", "err", ",", "ErrorCode", ":", "SaveArtifactsError", ",", "Suggestion", ":", "\"", "\"", ",", "}", "\n", "}" ]
// NewSaveArtifactsError returns a new error which indicates there was a problem // calling save-artifacts script
[ "NewSaveArtifactsError", "returns", "a", "new", "error", "which", "indicates", "there", "was", "a", "problem", "calling", "save", "-", "artifacts", "script" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/errors/errors.go#L83-L90
train
openshift/source-to-image
pkg/errors/errors.go
NewAssembleError
func NewAssembleError(name, output string, err error) error { return Error{ Message: fmt.Sprintf("assemble for %s failed:\n%s", name, output), Details: err, ErrorCode: AssembleError, Suggestion: "check the assemble script output for errors", } }
go
func NewAssembleError(name, output string, err error) error { return Error{ Message: fmt.Sprintf("assemble for %s failed:\n%s", name, output), Details: err, ErrorCode: AssembleError, Suggestion: "check the assemble script output for errors", } }
[ "func", "NewAssembleError", "(", "name", ",", "output", "string", ",", "err", "error", ")", "error", "{", "return", "Error", "{", "Message", ":", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "name", ",", "output", ")", ",", "Details", ":", "err", ",", "ErrorCode", ":", "AssembleError", ",", "Suggestion", ":", "\"", "\"", ",", "}", "\n", "}" ]
// NewAssembleError returns a new error which indicates there was a problem // running assemble script
[ "NewAssembleError", "returns", "a", "new", "error", "which", "indicates", "there", "was", "a", "problem", "running", "assemble", "script" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/errors/errors.go#L94-L101
train
openshift/source-to-image
pkg/errors/errors.go
NewWorkDirError
func NewWorkDirError(dir string, err error) error { return Error{ Message: fmt.Sprintf("creating temporary directory %s failed", dir), Details: err, ErrorCode: WorkdirError, Suggestion: "check if you have access to your system's temporary directory", } }
go
func NewWorkDirError(dir string, err error) error { return Error{ Message: fmt.Sprintf("creating temporary directory %s failed", dir), Details: err, ErrorCode: WorkdirError, Suggestion: "check if you have access to your system's temporary directory", } }
[ "func", "NewWorkDirError", "(", "dir", "string", ",", "err", "error", ")", "error", "{", "return", "Error", "{", "Message", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "dir", ")", ",", "Details", ":", "err", ",", "ErrorCode", ":", "WorkdirError", ",", "Suggestion", ":", "\"", "\"", ",", "}", "\n", "}" ]
// NewWorkDirError returns a new error which indicates there was a problem // when creating working directory
[ "NewWorkDirError", "returns", "a", "new", "error", "which", "indicates", "there", "was", "a", "problem", "when", "creating", "working", "directory" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/errors/errors.go#L105-L112
train
openshift/source-to-image
pkg/errors/errors.go
NewBuildError
func NewBuildError(name string, err error) error { return Error{ Message: fmt.Sprintf("building %s failed", name), Details: err, ErrorCode: BuildError, Suggestion: "check the build output for errors", } }
go
func NewBuildError(name string, err error) error { return Error{ Message: fmt.Sprintf("building %s failed", name), Details: err, ErrorCode: BuildError, Suggestion: "check the build output for errors", } }
[ "func", "NewBuildError", "(", "name", "string", ",", "err", "error", ")", "error", "{", "return", "Error", "{", "Message", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "name", ")", ",", "Details", ":", "err", ",", "ErrorCode", ":", "BuildError", ",", "Suggestion", ":", "\"", "\"", ",", "}", "\n", "}" ]
// NewBuildError returns a new error which indicates there was a problem // building the image
[ "NewBuildError", "returns", "a", "new", "error", "which", "indicates", "there", "was", "a", "problem", "building", "the", "image" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/errors/errors.go#L116-L123
train
openshift/source-to-image
pkg/errors/errors.go
NewTarTimeoutError
func NewTarTimeoutError() error { return Error{ Message: fmt.Sprintf("timeout waiting for tar stream"), Details: nil, ErrorCode: TarTimeoutError, Suggestion: "check the Source-To-Image scripts if it accepts tar stream for assemble and sends for save-artifacts", } }
go
func NewTarTimeoutError() error { return Error{ Message: fmt.Sprintf("timeout waiting for tar stream"), Details: nil, ErrorCode: TarTimeoutError, Suggestion: "check the Source-To-Image scripts if it accepts tar stream for assemble and sends for save-artifacts", } }
[ "func", "NewTarTimeoutError", "(", ")", "error", "{", "return", "Error", "{", "Message", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ")", ",", "Details", ":", "nil", ",", "ErrorCode", ":", "TarTimeoutError", ",", "Suggestion", ":", "\"", "\"", ",", "}", "\n", "}" ]
// NewTarTimeoutError returns a new error which indicates there was a problem // when sending or receiving tar stream
[ "NewTarTimeoutError", "returns", "a", "new", "error", "which", "indicates", "there", "was", "a", "problem", "when", "sending", "or", "receiving", "tar", "stream" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/errors/errors.go#L138-L145
train
openshift/source-to-image
pkg/errors/errors.go
NewDownloadError
func NewDownloadError(url string, code int) error { return Error{ Message: fmt.Sprintf("failed to retrieve %s, response code %d", url, code), Details: nil, ErrorCode: DownloadError, Suggestion: "check the availability of the address", } }
go
func NewDownloadError(url string, code int) error { return Error{ Message: fmt.Sprintf("failed to retrieve %s, response code %d", url, code), Details: nil, ErrorCode: DownloadError, Suggestion: "check the availability of the address", } }
[ "func", "NewDownloadError", "(", "url", "string", ",", "code", "int", ")", "error", "{", "return", "Error", "{", "Message", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "url", ",", "code", ")", ",", "Details", ":", "nil", ",", "ErrorCode", ":", "DownloadError", ",", "Suggestion", ":", "\"", "\"", ",", "}", "\n", "}" ]
// NewDownloadError returns a new error which indicates there was a problem // when downloading a file
[ "NewDownloadError", "returns", "a", "new", "error", "which", "indicates", "there", "was", "a", "problem", "when", "downloading", "a", "file" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/errors/errors.go#L149-L156
train
openshift/source-to-image
pkg/errors/errors.go
NewScriptsInsideImageError
func NewScriptsInsideImageError(url string) error { return Error{ Message: fmt.Sprintf("scripts inside the image: %s", url), Details: nil, ErrorCode: ScriptsInsideImageError, Suggestion: "", } }
go
func NewScriptsInsideImageError(url string) error { return Error{ Message: fmt.Sprintf("scripts inside the image: %s", url), Details: nil, ErrorCode: ScriptsInsideImageError, Suggestion: "", } }
[ "func", "NewScriptsInsideImageError", "(", "url", "string", ")", "error", "{", "return", "Error", "{", "Message", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "url", ")", ",", "Details", ":", "nil", ",", "ErrorCode", ":", "ScriptsInsideImageError", ",", "Suggestion", ":", "\"", "\"", ",", "}", "\n", "}" ]
// NewScriptsInsideImageError returns a new error which informs of scripts // being placed inside the image
[ "NewScriptsInsideImageError", "returns", "a", "new", "error", "which", "informs", "of", "scripts", "being", "placed", "inside", "the", "image" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/errors/errors.go#L160-L167
train
openshift/source-to-image
pkg/errors/errors.go
NewInstallError
func NewInstallError(script string) error { return Error{ Message: fmt.Sprintf("failed to install %v", script), Details: nil, ErrorCode: InstallError, Suggestion: fmt.Sprintf("set the scripts URL parameter with the location of the S2I scripts, or check if the image has the %q label set", constants.ScriptsURLLabel), } }
go
func NewInstallError(script string) error { return Error{ Message: fmt.Sprintf("failed to install %v", script), Details: nil, ErrorCode: InstallError, Suggestion: fmt.Sprintf("set the scripts URL parameter with the location of the S2I scripts, or check if the image has the %q label set", constants.ScriptsURLLabel), } }
[ "func", "NewInstallError", "(", "script", "string", ")", "error", "{", "return", "Error", "{", "Message", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "script", ")", ",", "Details", ":", "nil", ",", "ErrorCode", ":", "InstallError", ",", "Suggestion", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "constants", ".", "ScriptsURLLabel", ")", ",", "}", "\n", "}" ]
// NewInstallError returns a new error which indicates there was a problem // when downloading a script
[ "NewInstallError", "returns", "a", "new", "error", "which", "indicates", "there", "was", "a", "problem", "when", "downloading", "a", "script" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/errors/errors.go#L171-L178
train
openshift/source-to-image
pkg/errors/errors.go
NewInstallRequiredError
func NewInstallRequiredError(scripts []string, label string) error { return Error{ Message: fmt.Sprintf("failed to install %v", scripts), Details: nil, ErrorCode: InstallErrorRequired, Suggestion: fmt.Sprintf("set the scripts URL parameter with the location of the S2I scripts, or check if the image has the %q label set", constants.ScriptsURLLabel), } }
go
func NewInstallRequiredError(scripts []string, label string) error { return Error{ Message: fmt.Sprintf("failed to install %v", scripts), Details: nil, ErrorCode: InstallErrorRequired, Suggestion: fmt.Sprintf("set the scripts URL parameter with the location of the S2I scripts, or check if the image has the %q label set", constants.ScriptsURLLabel), } }
[ "func", "NewInstallRequiredError", "(", "scripts", "[", "]", "string", ",", "label", "string", ")", "error", "{", "return", "Error", "{", "Message", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "scripts", ")", ",", "Details", ":", "nil", ",", "ErrorCode", ":", "InstallErrorRequired", ",", "Suggestion", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "constants", ".", "ScriptsURLLabel", ")", ",", "}", "\n", "}" ]
// NewInstallRequiredError returns a new error which indicates there was a problem // when downloading a required script
[ "NewInstallRequiredError", "returns", "a", "new", "error", "which", "indicates", "there", "was", "a", "problem", "when", "downloading", "a", "required", "script" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/errors/errors.go#L182-L189
train
openshift/source-to-image
pkg/errors/errors.go
NewURLHandlerError
func NewURLHandlerError(url string) error { return Error{ Message: fmt.Sprintf("no URL handler for %s", url), Details: nil, ErrorCode: URLHandlerError, Suggestion: "check the URL", } }
go
func NewURLHandlerError(url string) error { return Error{ Message: fmt.Sprintf("no URL handler for %s", url), Details: nil, ErrorCode: URLHandlerError, Suggestion: "check the URL", } }
[ "func", "NewURLHandlerError", "(", "url", "string", ")", "error", "{", "return", "Error", "{", "Message", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "url", ")", ",", "Details", ":", "nil", ",", "ErrorCode", ":", "URLHandlerError", ",", "Suggestion", ":", "\"", "\"", ",", "}", "\n", "}" ]
// NewURLHandlerError returns a new error which indicates there was a problem // when trying to read scripts URL
[ "NewURLHandlerError", "returns", "a", "new", "error", "which", "indicates", "there", "was", "a", "problem", "when", "trying", "to", "read", "scripts", "URL" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/errors/errors.go#L193-L200
train
openshift/source-to-image
pkg/errors/errors.go
NewContainerError
func NewContainerError(name string, code int, output string) error { return ContainerError{ Message: fmt.Sprintf("non-zero (%d) exit code from %s", code, name), Output: output, ErrorCode: STIContainerError, Suggestion: "check the container logs for more information on the failure", ExitCode: code, } }
go
func NewContainerError(name string, code int, output string) error { return ContainerError{ Message: fmt.Sprintf("non-zero (%d) exit code from %s", code, name), Output: output, ErrorCode: STIContainerError, Suggestion: "check the container logs for more information on the failure", ExitCode: code, } }
[ "func", "NewContainerError", "(", "name", "string", ",", "code", "int", ",", "output", "string", ")", "error", "{", "return", "ContainerError", "{", "Message", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "code", ",", "name", ")", ",", "Output", ":", "output", ",", "ErrorCode", ":", "STIContainerError", ",", "Suggestion", ":", "\"", "\"", ",", "ExitCode", ":", "code", ",", "}", "\n", "}" ]
// NewContainerError return a new error which indicates there was a problem // invoking command inside container
[ "NewContainerError", "return", "a", "new", "error", "which", "indicates", "there", "was", "a", "problem", "invoking", "command", "inside", "container" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/errors/errors.go#L204-L212
train
openshift/source-to-image
pkg/errors/errors.go
NewSourcePathError
func NewSourcePathError(path string) error { return Error{ Message: fmt.Sprintf("Local filesystem source path does not exist: %s", path), Details: nil, ErrorCode: SourcePathError, Suggestion: "check the source code path on the local filesystem", } }
go
func NewSourcePathError(path string) error { return Error{ Message: fmt.Sprintf("Local filesystem source path does not exist: %s", path), Details: nil, ErrorCode: SourcePathError, Suggestion: "check the source code path on the local filesystem", } }
[ "func", "NewSourcePathError", "(", "path", "string", ")", "error", "{", "return", "Error", "{", "Message", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "path", ")", ",", "Details", ":", "nil", ",", "ErrorCode", ":", "SourcePathError", ",", "Suggestion", ":", "\"", "\"", ",", "}", "\n", "}" ]
// NewSourcePathError returns a new error which indicates there was a problem // when accessing the source code from the local filesystem
[ "NewSourcePathError", "returns", "a", "new", "error", "which", "indicates", "there", "was", "a", "problem", "when", "accessing", "the", "source", "code", "from", "the", "local", "filesystem" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/errors/errors.go#L216-L223
train
openshift/source-to-image
pkg/errors/errors.go
NewUserNotAllowedError
func NewUserNotAllowedError(image string, onbuild bool) error { var msg string if onbuild { msg = fmt.Sprintf("image %q includes at least one ONBUILD instruction that sets the user to a user that is not allowed", image) } else { msg = fmt.Sprintf("image %q must specify a user that is numeric and within the range of allowed users", image) } return Error{ Message: msg, ErrorCode: UserNotAllowedError, Suggestion: fmt.Sprintf("modify image %q to use a numeric user within the allowed range, or build without the allowed UIDs paremeter set", image), } }
go
func NewUserNotAllowedError(image string, onbuild bool) error { var msg string if onbuild { msg = fmt.Sprintf("image %q includes at least one ONBUILD instruction that sets the user to a user that is not allowed", image) } else { msg = fmt.Sprintf("image %q must specify a user that is numeric and within the range of allowed users", image) } return Error{ Message: msg, ErrorCode: UserNotAllowedError, Suggestion: fmt.Sprintf("modify image %q to use a numeric user within the allowed range, or build without the allowed UIDs paremeter set", image), } }
[ "func", "NewUserNotAllowedError", "(", "image", "string", ",", "onbuild", "bool", ")", "error", "{", "var", "msg", "string", "\n", "if", "onbuild", "{", "msg", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "image", ")", "\n", "}", "else", "{", "msg", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "image", ")", "\n", "}", "\n", "return", "Error", "{", "Message", ":", "msg", ",", "ErrorCode", ":", "UserNotAllowedError", ",", "Suggestion", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "image", ")", ",", "}", "\n", "}" ]
// NewUserNotAllowedError returns a new error that indicates that the build // could not run because the image uses a user outside of the range of allowed users
[ "NewUserNotAllowedError", "returns", "a", "new", "error", "that", "indicates", "that", "the", "build", "could", "not", "run", "because", "the", "image", "uses", "a", "user", "outside", "of", "the", "range", "of", "allowed", "users" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/errors/errors.go#L227-L239
train
openshift/source-to-image
pkg/errors/errors.go
NewAssembleUserNotAllowedError
func NewAssembleUserNotAllowedError(image string, usesConfig bool) error { var msg, suggestion string if usesConfig { msg = "assemble user must be numeric and within the range of allowed users" suggestion = "build without the allowed UIDs or assemble user configurations set" } else { msg = fmt.Sprintf("image %q includes the %q label whose value is not within the allowed range", image, constants.AssembleUserLabel) suggestion = fmt.Sprintf("modify the %q label in image %q to use a numeric user within the allowed range, or build without the allowed UIDs configuration set", constants.AssembleUserLabel, image) } return Error{ Message: msg, ErrorCode: UserNotAllowedError, Suggestion: suggestion, } }
go
func NewAssembleUserNotAllowedError(image string, usesConfig bool) error { var msg, suggestion string if usesConfig { msg = "assemble user must be numeric and within the range of allowed users" suggestion = "build without the allowed UIDs or assemble user configurations set" } else { msg = fmt.Sprintf("image %q includes the %q label whose value is not within the allowed range", image, constants.AssembleUserLabel) suggestion = fmt.Sprintf("modify the %q label in image %q to use a numeric user within the allowed range, or build without the allowed UIDs configuration set", constants.AssembleUserLabel, image) } return Error{ Message: msg, ErrorCode: UserNotAllowedError, Suggestion: suggestion, } }
[ "func", "NewAssembleUserNotAllowedError", "(", "image", "string", ",", "usesConfig", "bool", ")", "error", "{", "var", "msg", ",", "suggestion", "string", "\n", "if", "usesConfig", "{", "msg", "=", "\"", "\"", "\n", "suggestion", "=", "\"", "\"", "\n", "}", "else", "{", "msg", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "image", ",", "constants", ".", "AssembleUserLabel", ")", "\n", "suggestion", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "constants", ".", "AssembleUserLabel", ",", "image", ")", "\n", "}", "\n", "return", "Error", "{", "Message", ":", "msg", ",", "ErrorCode", ":", "UserNotAllowedError", ",", "Suggestion", ":", "suggestion", ",", "}", "\n", "}" ]
// NewAssembleUserNotAllowedError returns a new error that indicates that the build // could not run because the build or image uses an assemble user outside of the range // of allowed users.
[ "NewAssembleUserNotAllowedError", "returns", "a", "new", "error", "that", "indicates", "that", "the", "build", "could", "not", "run", "because", "the", "build", "or", "image", "uses", "an", "assemble", "user", "outside", "of", "the", "range", "of", "allowed", "users", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/errors/errors.go#L244-L258
train
openshift/source-to-image
pkg/errors/errors.go
CheckError
func CheckError(err error) { if err == nil { return } if e, ok := err.(Error); ok { glog.Errorf("An error occurred: %v", e) glog.Errorf("Suggested solution: %v", e.Suggestion) if e.Details != nil { glog.V(1).Infof("Details: %v", e.Details) } glog.Error("If the problem persists consult the docs at https://github.com/openshift/source-to-image/tree/master/docs. " + "Eventually reach us on freenode #openshift or file an issue at https://github.com/openshift/source-to-image/issues " + "providing us with a log from your build using log output level 3.") os.Exit(e.ErrorCode) } else { glog.Errorf("An error occurred: %v", err) os.Exit(1) } }
go
func CheckError(err error) { if err == nil { return } if e, ok := err.(Error); ok { glog.Errorf("An error occurred: %v", e) glog.Errorf("Suggested solution: %v", e.Suggestion) if e.Details != nil { glog.V(1).Infof("Details: %v", e.Details) } glog.Error("If the problem persists consult the docs at https://github.com/openshift/source-to-image/tree/master/docs. " + "Eventually reach us on freenode #openshift or file an issue at https://github.com/openshift/source-to-image/issues " + "providing us with a log from your build using log output level 3.") os.Exit(e.ErrorCode) } else { glog.Errorf("An error occurred: %v", err) os.Exit(1) } }
[ "func", "CheckError", "(", "err", "error", ")", "{", "if", "err", "==", "nil", "{", "return", "\n", "}", "\n\n", "if", "e", ",", "ok", ":=", "err", ".", "(", "Error", ")", ";", "ok", "{", "glog", ".", "Errorf", "(", "\"", "\"", ",", "e", ")", "\n", "glog", ".", "Errorf", "(", "\"", "\"", ",", "e", ".", "Suggestion", ")", "\n", "if", "e", ".", "Details", "!=", "nil", "{", "glog", ".", "V", "(", "1", ")", ".", "Infof", "(", "\"", "\"", ",", "e", ".", "Details", ")", "\n", "}", "\n", "glog", ".", "Error", "(", "\"", "\"", "+", "\"", "\"", "+", "\"", "\"", ")", "\n", "os", ".", "Exit", "(", "e", ".", "ErrorCode", ")", "\n", "}", "else", "{", "glog", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}", "\n", "}" ]
// CheckError checks input error. // 1. if the input error is nil, the function does nothing but return. // 2. if the input error is a kind of Error which is thrown during S2I execution, // the function handle it with Suggestion and Details. // 3. if the input error is a kind of system Error which is unknown, the function exit with 1.
[ "CheckError", "checks", "input", "error", ".", "1", ".", "if", "the", "input", "error", "is", "nil", "the", "function", "does", "nothing", "but", "return", ".", "2", ".", "if", "the", "input", "error", "is", "a", "kind", "of", "Error", "which", "is", "thrown", "during", "S2I", "execution", "the", "function", "handle", "it", "with", "Suggestion", "and", "Details", ".", "3", ".", "if", "the", "input", "error", "is", "a", "kind", "of", "system", "Error", "which", "is", "unknown", "the", "function", "exit", "with", "1", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/errors/errors.go#L280-L299
train
openshift/source-to-image
pkg/version/version.go
String
func (info Info) String() string { version := info.GitVersion if version == "" { version = "unknown" } return version }
go
func (info Info) String() string { version := info.GitVersion if version == "" { version = "unknown" } return version }
[ "func", "(", "info", "Info", ")", "String", "(", ")", "string", "{", "version", ":=", "info", ".", "GitVersion", "\n", "if", "version", "==", "\"", "\"", "{", "version", "=", "\"", "\"", "\n", "}", "\n", "return", "version", "\n", "}" ]
// String returns info as a human-friendly version string.
[ "String", "returns", "info", "as", "a", "human", "-", "friendly", "version", "string", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/version/version.go#L36-L42
train
openshift/source-to-image
pkg/scripts/download.go
NewDownloader
func NewDownloader(proxyConfig *api.ProxyConfig) Downloader { httpReader := NewHTTPURLReader(proxyConfig) return &downloader{ schemeReaders: map[string]schemeReader{ "http": httpReader, "https": httpReader, "file": &FileURLReader{}, "image": &ImageReader{}, }, } }
go
func NewDownloader(proxyConfig *api.ProxyConfig) Downloader { httpReader := NewHTTPURLReader(proxyConfig) return &downloader{ schemeReaders: map[string]schemeReader{ "http": httpReader, "https": httpReader, "file": &FileURLReader{}, "image": &ImageReader{}, }, } }
[ "func", "NewDownloader", "(", "proxyConfig", "*", "api", ".", "ProxyConfig", ")", "Downloader", "{", "httpReader", ":=", "NewHTTPURLReader", "(", "proxyConfig", ")", "\n", "return", "&", "downloader", "{", "schemeReaders", ":", "map", "[", "string", "]", "schemeReader", "{", "\"", "\"", ":", "httpReader", ",", "\"", "\"", ":", "httpReader", ",", "\"", "\"", ":", "&", "FileURLReader", "{", "}", ",", "\"", "\"", ":", "&", "ImageReader", "{", "}", ",", "}", ",", "}", "\n", "}" ]
// NewDownloader creates an instance of the default Downloader implementation
[ "NewDownloader", "creates", "an", "instance", "of", "the", "default", "Downloader", "implementation" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/scripts/download.go#L34-L44
train
openshift/source-to-image
pkg/scripts/download.go
NewHTTPURLReader
func NewHTTPURLReader(proxyConfig *api.ProxyConfig) *HTTPURLReader { getFunc := http.Get if proxyConfig != nil { transportMapMutex.Lock() transport, ok := transportMap[*proxyConfig] if !ok { transport = &http.Transport{ Proxy: func(req *http.Request) (*url.URL, error) { if proxyConfig.HTTPSProxy != nil && req.URL.Scheme == "https" { return proxyConfig.HTTPSProxy, nil } return proxyConfig.HTTPProxy, nil }, } transportMap[*proxyConfig] = transport } transportMapMutex.Unlock() client := &http.Client{ Transport: transport, } getFunc = client.Get } return &HTTPURLReader{Get: getFunc} }
go
func NewHTTPURLReader(proxyConfig *api.ProxyConfig) *HTTPURLReader { getFunc := http.Get if proxyConfig != nil { transportMapMutex.Lock() transport, ok := transportMap[*proxyConfig] if !ok { transport = &http.Transport{ Proxy: func(req *http.Request) (*url.URL, error) { if proxyConfig.HTTPSProxy != nil && req.URL.Scheme == "https" { return proxyConfig.HTTPSProxy, nil } return proxyConfig.HTTPProxy, nil }, } transportMap[*proxyConfig] = transport } transportMapMutex.Unlock() client := &http.Client{ Transport: transport, } getFunc = client.Get } return &HTTPURLReader{Get: getFunc} }
[ "func", "NewHTTPURLReader", "(", "proxyConfig", "*", "api", ".", "ProxyConfig", ")", "*", "HTTPURLReader", "{", "getFunc", ":=", "http", ".", "Get", "\n", "if", "proxyConfig", "!=", "nil", "{", "transportMapMutex", ".", "Lock", "(", ")", "\n", "transport", ",", "ok", ":=", "transportMap", "[", "*", "proxyConfig", "]", "\n", "if", "!", "ok", "{", "transport", "=", "&", "http", ".", "Transport", "{", "Proxy", ":", "func", "(", "req", "*", "http", ".", "Request", ")", "(", "*", "url", ".", "URL", ",", "error", ")", "{", "if", "proxyConfig", ".", "HTTPSProxy", "!=", "nil", "&&", "req", ".", "URL", ".", "Scheme", "==", "\"", "\"", "{", "return", "proxyConfig", ".", "HTTPSProxy", ",", "nil", "\n", "}", "\n", "return", "proxyConfig", ".", "HTTPProxy", ",", "nil", "\n", "}", ",", "}", "\n", "transportMap", "[", "*", "proxyConfig", "]", "=", "transport", "\n", "}", "\n", "transportMapMutex", ".", "Unlock", "(", ")", "\n", "client", ":=", "&", "http", ".", "Client", "{", "Transport", ":", "transport", ",", "}", "\n", "getFunc", "=", "client", ".", "Get", "\n", "}", "\n", "return", "&", "HTTPURLReader", "{", "Get", ":", "getFunc", "}", "\n", "}" ]
// NewHTTPURLReader returns a new HTTPURLReader.
[ "NewHTTPURLReader", "returns", "a", "new", "HTTPURLReader", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/scripts/download.go#L95-L118
train
openshift/source-to-image
pkg/scripts/download.go
Read
func (*FileURLReader) Read(url *url.URL) (io.ReadCloser, error) { // for some reason url.Host may contain information about the ./ or ../ when // specifying relative path, thus using that value as well return os.Open(filepath.Join(url.Host, url.Path)) }
go
func (*FileURLReader) Read(url *url.URL) (io.ReadCloser, error) { // for some reason url.Host may contain information about the ./ or ../ when // specifying relative path, thus using that value as well return os.Open(filepath.Join(url.Host, url.Path)) }
[ "func", "(", "*", "FileURLReader", ")", "Read", "(", "url", "*", "url", ".", "URL", ")", "(", "io", ".", "ReadCloser", ",", "error", ")", "{", "// for some reason url.Host may contain information about the ./ or ../ when", "// specifying relative path, thus using that value as well", "return", "os", ".", "Open", "(", "filepath", ".", "Join", "(", "url", ".", "Host", ",", "url", ".", "Path", ")", ")", "\n", "}" ]
// Read produces an io.Reader from a file URL
[ "Read", "produces", "an", "io", ".", "Reader", "from", "a", "file", "URL" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/scripts/download.go#L139-L143
train
openshift/source-to-image
pkg/scripts/download.go
Read
func (*ImageReader) Read(url *url.URL) (io.ReadCloser, error) { return nil, s2ierr.NewScriptsInsideImageError(url.String()) }
go
func (*ImageReader) Read(url *url.URL) (io.ReadCloser, error) { return nil, s2ierr.NewScriptsInsideImageError(url.String()) }
[ "func", "(", "*", "ImageReader", ")", "Read", "(", "url", "*", "url", ".", "URL", ")", "(", "io", ".", "ReadCloser", ",", "error", ")", "{", "return", "nil", ",", "s2ierr", ".", "NewScriptsInsideImageError", "(", "url", ".", "String", "(", ")", ")", "\n", "}" ]
// Read throws Not implemented error
[ "Read", "throws", "Not", "implemented", "error" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/scripts/download.go#L149-L151
train
openshift/source-to-image
pkg/build/strategies/dockerfile/dockerfile.go
New
func New(config *api.Config, fs fs.FileSystem) (*Dockerfile, error) { return &Dockerfile{ fs: fs, // where we will get the assemble/run scripts from on the host machine, // if any are provided. uploadScriptsDir: constants.UploadScripts, uploadSrcDir: constants.Source, result: &api.Result{}, ignorer: &ignore.DockerIgnorer{}, }, nil }
go
func New(config *api.Config, fs fs.FileSystem) (*Dockerfile, error) { return &Dockerfile{ fs: fs, // where we will get the assemble/run scripts from on the host machine, // if any are provided. uploadScriptsDir: constants.UploadScripts, uploadSrcDir: constants.Source, result: &api.Result{}, ignorer: &ignore.DockerIgnorer{}, }, nil }
[ "func", "New", "(", "config", "*", "api", ".", "Config", ",", "fs", "fs", ".", "FileSystem", ")", "(", "*", "Dockerfile", ",", "error", ")", "{", "return", "&", "Dockerfile", "{", "fs", ":", "fs", ",", "// where we will get the assemble/run scripts from on the host machine,", "// if any are provided.", "uploadScriptsDir", ":", "constants", ".", "UploadScripts", ",", "uploadSrcDir", ":", "constants", ".", "Source", ",", "result", ":", "&", "api", ".", "Result", "{", "}", ",", "ignorer", ":", "&", "ignore", ".", "DockerIgnorer", "{", "}", ",", "}", ",", "nil", "\n", "}" ]
// New creates a Dockerfile builder.
[ "New", "creates", "a", "Dockerfile", "builder", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/build/strategies/dockerfile/dockerfile.go#L58-L68
train
openshift/source-to-image
pkg/build/strategies/dockerfile/dockerfile.go
Build
func (builder *Dockerfile) Build(config *api.Config) (*api.Result, error) { // Handle defaulting of the configuration that is unique to the dockerfile strategy if strings.HasSuffix(config.AsDockerfile, string(os.PathSeparator)) { config.AsDockerfile = config.AsDockerfile + "Dockerfile" } if len(config.AssembleUser) == 0 { config.AssembleUser = "1001" } if !user.IsUserAllowed(config.AssembleUser, &config.AllowedUIDs) { builder.setFailureReason(utilstatus.ReasonAssembleUserForbidden, utilstatus.ReasonMessageAssembleUserForbidden) return builder.result, s2ierr.NewUserNotAllowedError(config.AssembleUser, false) } dir, _ := filepath.Split(config.AsDockerfile) if len(dir) == 0 { dir = "." } config.PreserveWorkingDir = true config.WorkingDir = dir if config.BuilderImage == "" { builder.setFailureReason(utilstatus.ReasonGenericS2IBuildFailed, utilstatus.ReasonMessageGenericS2iBuildFailed) return builder.result, errors.New("builder image name cannot be empty") } if err := builder.Prepare(config); err != nil { return builder.result, err } if err := builder.CreateDockerfile(config); err != nil { builder.setFailureReason(utilstatus.ReasonDockerfileCreateFailed, utilstatus.ReasonMessageDockerfileCreateFailed) return builder.result, err } builder.result.Success = true return builder.result, nil }
go
func (builder *Dockerfile) Build(config *api.Config) (*api.Result, error) { // Handle defaulting of the configuration that is unique to the dockerfile strategy if strings.HasSuffix(config.AsDockerfile, string(os.PathSeparator)) { config.AsDockerfile = config.AsDockerfile + "Dockerfile" } if len(config.AssembleUser) == 0 { config.AssembleUser = "1001" } if !user.IsUserAllowed(config.AssembleUser, &config.AllowedUIDs) { builder.setFailureReason(utilstatus.ReasonAssembleUserForbidden, utilstatus.ReasonMessageAssembleUserForbidden) return builder.result, s2ierr.NewUserNotAllowedError(config.AssembleUser, false) } dir, _ := filepath.Split(config.AsDockerfile) if len(dir) == 0 { dir = "." } config.PreserveWorkingDir = true config.WorkingDir = dir if config.BuilderImage == "" { builder.setFailureReason(utilstatus.ReasonGenericS2IBuildFailed, utilstatus.ReasonMessageGenericS2iBuildFailed) return builder.result, errors.New("builder image name cannot be empty") } if err := builder.Prepare(config); err != nil { return builder.result, err } if err := builder.CreateDockerfile(config); err != nil { builder.setFailureReason(utilstatus.ReasonDockerfileCreateFailed, utilstatus.ReasonMessageDockerfileCreateFailed) return builder.result, err } builder.result.Success = true return builder.result, nil }
[ "func", "(", "builder", "*", "Dockerfile", ")", "Build", "(", "config", "*", "api", ".", "Config", ")", "(", "*", "api", ".", "Result", ",", "error", ")", "{", "// Handle defaulting of the configuration that is unique to the dockerfile strategy", "if", "strings", ".", "HasSuffix", "(", "config", ".", "AsDockerfile", ",", "string", "(", "os", ".", "PathSeparator", ")", ")", "{", "config", ".", "AsDockerfile", "=", "config", ".", "AsDockerfile", "+", "\"", "\"", "\n", "}", "\n", "if", "len", "(", "config", ".", "AssembleUser", ")", "==", "0", "{", "config", ".", "AssembleUser", "=", "\"", "\"", "\n", "}", "\n", "if", "!", "user", ".", "IsUserAllowed", "(", "config", ".", "AssembleUser", ",", "&", "config", ".", "AllowedUIDs", ")", "{", "builder", ".", "setFailureReason", "(", "utilstatus", ".", "ReasonAssembleUserForbidden", ",", "utilstatus", ".", "ReasonMessageAssembleUserForbidden", ")", "\n", "return", "builder", ".", "result", ",", "s2ierr", ".", "NewUserNotAllowedError", "(", "config", ".", "AssembleUser", ",", "false", ")", "\n", "}", "\n\n", "dir", ",", "_", ":=", "filepath", ".", "Split", "(", "config", ".", "AsDockerfile", ")", "\n", "if", "len", "(", "dir", ")", "==", "0", "{", "dir", "=", "\"", "\"", "\n", "}", "\n", "config", ".", "PreserveWorkingDir", "=", "true", "\n", "config", ".", "WorkingDir", "=", "dir", "\n\n", "if", "config", ".", "BuilderImage", "==", "\"", "\"", "{", "builder", ".", "setFailureReason", "(", "utilstatus", ".", "ReasonGenericS2IBuildFailed", ",", "utilstatus", ".", "ReasonMessageGenericS2iBuildFailed", ")", "\n", "return", "builder", ".", "result", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "err", ":=", "builder", ".", "Prepare", "(", "config", ")", ";", "err", "!=", "nil", "{", "return", "builder", ".", "result", ",", "err", "\n", "}", "\n\n", "if", "err", ":=", "builder", ".", "CreateDockerfile", "(", "config", ")", ";", "err", "!=", "nil", "{", "builder", ".", "setFailureReason", "(", "utilstatus", ".", "ReasonDockerfileCreateFailed", ",", "utilstatus", ".", "ReasonMessageDockerfileCreateFailed", ")", "\n", "return", "builder", ".", "result", ",", "err", "\n", "}", "\n\n", "builder", ".", "result", ".", "Success", "=", "true", "\n\n", "return", "builder", ".", "result", ",", "nil", "\n", "}" ]
// Build produces a Dockerfile that when run with the correct filesystem // context, will produce the application image.
[ "Build", "produces", "a", "Dockerfile", "that", "when", "run", "with", "the", "correct", "filesystem", "context", "will", "produce", "the", "application", "image", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/build/strategies/dockerfile/dockerfile.go#L72-L110
train
openshift/source-to-image
pkg/build/strategies/dockerfile/dockerfile.go
installScripts
func (builder *Dockerfile) installScripts(scriptsURL string, config *api.Config) []api.InstallResult { scriptInstaller := scripts.NewInstaller( "", scriptsURL, config.ScriptDownloadProxyConfig, nil, api.AuthConfig{}, builder.fs, ) // all scripts are optional, we trust the image contains scripts if we don't find them // in the source repo. return scriptInstaller.InstallOptional(append(scripts.RequiredScripts, scripts.OptionalScripts...), config.WorkingDir) }
go
func (builder *Dockerfile) installScripts(scriptsURL string, config *api.Config) []api.InstallResult { scriptInstaller := scripts.NewInstaller( "", scriptsURL, config.ScriptDownloadProxyConfig, nil, api.AuthConfig{}, builder.fs, ) // all scripts are optional, we trust the image contains scripts if we don't find them // in the source repo. return scriptInstaller.InstallOptional(append(scripts.RequiredScripts, scripts.OptionalScripts...), config.WorkingDir) }
[ "func", "(", "builder", "*", "Dockerfile", ")", "installScripts", "(", "scriptsURL", "string", ",", "config", "*", "api", ".", "Config", ")", "[", "]", "api", ".", "InstallResult", "{", "scriptInstaller", ":=", "scripts", ".", "NewInstaller", "(", "\"", "\"", ",", "scriptsURL", ",", "config", ".", "ScriptDownloadProxyConfig", ",", "nil", ",", "api", ".", "AuthConfig", "{", "}", ",", "builder", ".", "fs", ",", ")", "\n\n", "// all scripts are optional, we trust the image contains scripts if we don't find them", "// in the source repo.", "return", "scriptInstaller", ".", "InstallOptional", "(", "append", "(", "scripts", ".", "RequiredScripts", ",", "scripts", ".", "OptionalScripts", "...", ")", ",", "config", ".", "WorkingDir", ")", "\n", "}" ]
// installScripts installs scripts at the provided URL to the Dockerfile context
[ "installScripts", "installs", "scripts", "at", "the", "provided", "URL", "to", "the", "Dockerfile", "context" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/build/strategies/dockerfile/dockerfile.go#L384-L397
train
openshift/source-to-image
pkg/build/strategies/dockerfile/dockerfile.go
setFailureReason
func (builder *Dockerfile) setFailureReason(reason api.StepFailureReason, message api.StepFailureMessage) { builder.result.BuildInfo.FailureReason = utilstatus.NewFailureReason(reason, message) }
go
func (builder *Dockerfile) setFailureReason(reason api.StepFailureReason, message api.StepFailureMessage) { builder.result.BuildInfo.FailureReason = utilstatus.NewFailureReason(reason, message) }
[ "func", "(", "builder", "*", "Dockerfile", ")", "setFailureReason", "(", "reason", "api", ".", "StepFailureReason", ",", "message", "api", ".", "StepFailureMessage", ")", "{", "builder", ".", "result", ".", "BuildInfo", ".", "FailureReason", "=", "utilstatus", ".", "NewFailureReason", "(", "reason", ",", "message", ")", "\n", "}" ]
// setFailureReason sets the builder's failure reason with the given reason and message.
[ "setFailureReason", "sets", "the", "builder", "s", "failure", "reason", "with", "the", "given", "reason", "and", "message", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/build/strategies/dockerfile/dockerfile.go#L400-L402
train
openshift/source-to-image
pkg/build/strategies/dockerfile/dockerfile.go
getImageScriptsDir
func getImageScriptsDir(config *api.Config) (string, bool) { if strings.HasPrefix(config.ScriptsURL, "image://") { return strings.TrimPrefix(config.ScriptsURL, "image://"), true } if strings.HasPrefix(config.ImageScriptsURL, "image://") { return strings.TrimPrefix(config.ImageScriptsURL, "image://"), false } return defaultScriptsDir, false }
go
func getImageScriptsDir(config *api.Config) (string, bool) { if strings.HasPrefix(config.ScriptsURL, "image://") { return strings.TrimPrefix(config.ScriptsURL, "image://"), true } if strings.HasPrefix(config.ImageScriptsURL, "image://") { return strings.TrimPrefix(config.ImageScriptsURL, "image://"), false } return defaultScriptsDir, false }
[ "func", "getImageScriptsDir", "(", "config", "*", "api", ".", "Config", ")", "(", "string", ",", "bool", ")", "{", "if", "strings", ".", "HasPrefix", "(", "config", ".", "ScriptsURL", ",", "\"", "\"", ")", "{", "return", "strings", ".", "TrimPrefix", "(", "config", ".", "ScriptsURL", ",", "\"", "\"", ")", ",", "true", "\n", "}", "\n", "if", "strings", ".", "HasPrefix", "(", "config", ".", "ImageScriptsURL", ",", "\"", "\"", ")", "{", "return", "strings", ".", "TrimPrefix", "(", "config", ".", "ImageScriptsURL", ",", "\"", "\"", ")", ",", "false", "\n", "}", "\n", "return", "defaultScriptsDir", ",", "false", "\n", "}" ]
// getImageScriptsDir returns the directory containing the builder image scripts and a bool // indicating that the directory is expected to contain all s2i scripts
[ "getImageScriptsDir", "returns", "the", "directory", "containing", "the", "builder", "image", "scripts", "and", "a", "bool", "indicating", "that", "the", "directory", "is", "expected", "to", "contain", "all", "s2i", "scripts" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/build/strategies/dockerfile/dockerfile.go#L415-L423
train
openshift/source-to-image
pkg/build/strategies/dockerfile/dockerfile.go
scanScripts
func scanScripts(name string) map[string]bool { scriptsMap := make(map[string]bool) items, err := ioutil.ReadDir(name) if os.IsNotExist(err) { glog.Warningf("Unable to access directory %q: %v", name, err) } if err != nil || len(items) == 0 { return scriptsMap } assembleProvided := false runProvided := false saveArtifactsProvided := false for _, f := range items { glog.V(2).Infof("found override script file %s", f.Name()) if f.Name() == constants.Run { runProvided = true scriptsMap[constants.Run] = true } else if f.Name() == constants.Assemble { assembleProvided = true scriptsMap[constants.Assemble] = true } else if f.Name() == constants.SaveArtifacts { saveArtifactsProvided = true scriptsMap[constants.SaveArtifacts] = true } if runProvided && assembleProvided && saveArtifactsProvided { break } } return scriptsMap }
go
func scanScripts(name string) map[string]bool { scriptsMap := make(map[string]bool) items, err := ioutil.ReadDir(name) if os.IsNotExist(err) { glog.Warningf("Unable to access directory %q: %v", name, err) } if err != nil || len(items) == 0 { return scriptsMap } assembleProvided := false runProvided := false saveArtifactsProvided := false for _, f := range items { glog.V(2).Infof("found override script file %s", f.Name()) if f.Name() == constants.Run { runProvided = true scriptsMap[constants.Run] = true } else if f.Name() == constants.Assemble { assembleProvided = true scriptsMap[constants.Assemble] = true } else if f.Name() == constants.SaveArtifacts { saveArtifactsProvided = true scriptsMap[constants.SaveArtifacts] = true } if runProvided && assembleProvided && saveArtifactsProvided { break } } return scriptsMap }
[ "func", "scanScripts", "(", "name", "string", ")", "map", "[", "string", "]", "bool", "{", "scriptsMap", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "items", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "name", ")", "\n", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "glog", ".", "Warningf", "(", "\"", "\"", ",", "name", ",", "err", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "||", "len", "(", "items", ")", "==", "0", "{", "return", "scriptsMap", "\n", "}", "\n\n", "assembleProvided", ":=", "false", "\n", "runProvided", ":=", "false", "\n", "saveArtifactsProvided", ":=", "false", "\n", "for", "_", ",", "f", ":=", "range", "items", "{", "glog", ".", "V", "(", "2", ")", ".", "Infof", "(", "\"", "\"", ",", "f", ".", "Name", "(", ")", ")", "\n", "if", "f", ".", "Name", "(", ")", "==", "constants", ".", "Run", "{", "runProvided", "=", "true", "\n", "scriptsMap", "[", "constants", ".", "Run", "]", "=", "true", "\n", "}", "else", "if", "f", ".", "Name", "(", ")", "==", "constants", ".", "Assemble", "{", "assembleProvided", "=", "true", "\n", "scriptsMap", "[", "constants", ".", "Assemble", "]", "=", "true", "\n", "}", "else", "if", "f", ".", "Name", "(", ")", "==", "constants", ".", "SaveArtifacts", "{", "saveArtifactsProvided", "=", "true", "\n", "scriptsMap", "[", "constants", ".", "SaveArtifacts", "]", "=", "true", "\n", "}", "\n", "if", "runProvided", "&&", "assembleProvided", "&&", "saveArtifactsProvided", "{", "break", "\n", "}", "\n", "}", "\n", "return", "scriptsMap", "\n", "}" ]
// scanScripts returns a map of provided s2i scripts
[ "scanScripts", "returns", "a", "map", "of", "provided", "s2i", "scripts" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/build/strategies/dockerfile/dockerfile.go#L426-L456
train
openshift/source-to-image
pkg/util/labels.go
GenerateOutputImageLabels
func GenerateOutputImageLabels(info *git.SourceInfo, config *api.Config) map[string]string { labels := map[string]string{} namespace := constants.DefaultNamespace if len(config.LabelNamespace) > 0 { namespace = config.LabelNamespace } labels = GenerateLabelsFromConfig(labels, config, namespace) labels = GenerateLabelsFromSourceInfo(labels, info, namespace) return labels }
go
func GenerateOutputImageLabels(info *git.SourceInfo, config *api.Config) map[string]string { labels := map[string]string{} namespace := constants.DefaultNamespace if len(config.LabelNamespace) > 0 { namespace = config.LabelNamespace } labels = GenerateLabelsFromConfig(labels, config, namespace) labels = GenerateLabelsFromSourceInfo(labels, info, namespace) return labels }
[ "func", "GenerateOutputImageLabels", "(", "info", "*", "git", ".", "SourceInfo", ",", "config", "*", "api", ".", "Config", ")", "map", "[", "string", "]", "string", "{", "labels", ":=", "map", "[", "string", "]", "string", "{", "}", "\n", "namespace", ":=", "constants", ".", "DefaultNamespace", "\n", "if", "len", "(", "config", ".", "LabelNamespace", ")", ">", "0", "{", "namespace", "=", "config", ".", "LabelNamespace", "\n", "}", "\n\n", "labels", "=", "GenerateLabelsFromConfig", "(", "labels", ",", "config", ",", "namespace", ")", "\n", "labels", "=", "GenerateLabelsFromSourceInfo", "(", "labels", ",", "info", ",", "namespace", ")", "\n", "return", "labels", "\n", "}" ]
// GenerateOutputImageLabels generate the labels based on the s2i Config // and source repository informations.
[ "GenerateOutputImageLabels", "generate", "the", "labels", "based", "on", "the", "s2i", "Config", "and", "source", "repository", "informations", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/util/labels.go#L13-L23
train
openshift/source-to-image
pkg/util/labels.go
GenerateLabelsFromConfig
func GenerateLabelsFromConfig(labels map[string]string, config *api.Config, namespace string) map[string]string { if len(config.Description) > 0 { labels[constants.KubernetesDescriptionLabel] = config.Description } if len(config.DisplayName) > 0 { labels[constants.KubernetesDisplayNameLabel] = config.DisplayName } else if len(config.Tag) > 0 { labels[constants.KubernetesDisplayNameLabel] = config.Tag } addBuildLabel(labels, "image", config.BuilderImage, namespace) return labels }
go
func GenerateLabelsFromConfig(labels map[string]string, config *api.Config, namespace string) map[string]string { if len(config.Description) > 0 { labels[constants.KubernetesDescriptionLabel] = config.Description } if len(config.DisplayName) > 0 { labels[constants.KubernetesDisplayNameLabel] = config.DisplayName } else if len(config.Tag) > 0 { labels[constants.KubernetesDisplayNameLabel] = config.Tag } addBuildLabel(labels, "image", config.BuilderImage, namespace) return labels }
[ "func", "GenerateLabelsFromConfig", "(", "labels", "map", "[", "string", "]", "string", ",", "config", "*", "api", ".", "Config", ",", "namespace", "string", ")", "map", "[", "string", "]", "string", "{", "if", "len", "(", "config", ".", "Description", ")", ">", "0", "{", "labels", "[", "constants", ".", "KubernetesDescriptionLabel", "]", "=", "config", ".", "Description", "\n", "}", "\n\n", "if", "len", "(", "config", ".", "DisplayName", ")", ">", "0", "{", "labels", "[", "constants", ".", "KubernetesDisplayNameLabel", "]", "=", "config", ".", "DisplayName", "\n", "}", "else", "if", "len", "(", "config", ".", "Tag", ")", ">", "0", "{", "labels", "[", "constants", ".", "KubernetesDisplayNameLabel", "]", "=", "config", ".", "Tag", "\n", "}", "\n\n", "addBuildLabel", "(", "labels", ",", "\"", "\"", ",", "config", ".", "BuilderImage", ",", "namespace", ")", "\n", "return", "labels", "\n", "}" ]
// GenerateLabelsFromConfig generate the labels based on build s2i Config
[ "GenerateLabelsFromConfig", "generate", "the", "labels", "based", "on", "build", "s2i", "Config" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/util/labels.go#L26-L39
train
openshift/source-to-image
pkg/util/labels.go
GenerateLabelsFromSourceInfo
func GenerateLabelsFromSourceInfo(labels map[string]string, info *git.SourceInfo, namespace string) map[string]string { if info == nil { glog.V(3).Info("Unable to fetch source information, the output image labels will not be set") return labels } if len(info.AuthorName) > 0 { author := fmt.Sprintf("%s <%s>", info.AuthorName, info.AuthorEmail) addBuildLabel(labels, "commit.author", author, namespace) } addBuildLabel(labels, "commit.date", info.Date, namespace) addBuildLabel(labels, "commit.id", info.CommitID, namespace) addBuildLabel(labels, "commit.ref", info.Ref, namespace) addBuildLabel(labels, "commit.message", info.Message, namespace) addBuildLabel(labels, "source-location", info.Location, namespace) addBuildLabel(labels, "source-context-dir", info.ContextDir, namespace) return labels }
go
func GenerateLabelsFromSourceInfo(labels map[string]string, info *git.SourceInfo, namespace string) map[string]string { if info == nil { glog.V(3).Info("Unable to fetch source information, the output image labels will not be set") return labels } if len(info.AuthorName) > 0 { author := fmt.Sprintf("%s <%s>", info.AuthorName, info.AuthorEmail) addBuildLabel(labels, "commit.author", author, namespace) } addBuildLabel(labels, "commit.date", info.Date, namespace) addBuildLabel(labels, "commit.id", info.CommitID, namespace) addBuildLabel(labels, "commit.ref", info.Ref, namespace) addBuildLabel(labels, "commit.message", info.Message, namespace) addBuildLabel(labels, "source-location", info.Location, namespace) addBuildLabel(labels, "source-context-dir", info.ContextDir, namespace) return labels }
[ "func", "GenerateLabelsFromSourceInfo", "(", "labels", "map", "[", "string", "]", "string", ",", "info", "*", "git", ".", "SourceInfo", ",", "namespace", "string", ")", "map", "[", "string", "]", "string", "{", "if", "info", "==", "nil", "{", "glog", ".", "V", "(", "3", ")", ".", "Info", "(", "\"", "\"", ")", "\n", "return", "labels", "\n", "}", "\n\n", "if", "len", "(", "info", ".", "AuthorName", ")", ">", "0", "{", "author", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "info", ".", "AuthorName", ",", "info", ".", "AuthorEmail", ")", "\n", "addBuildLabel", "(", "labels", ",", "\"", "\"", ",", "author", ",", "namespace", ")", "\n", "}", "\n\n", "addBuildLabel", "(", "labels", ",", "\"", "\"", ",", "info", ".", "Date", ",", "namespace", ")", "\n", "addBuildLabel", "(", "labels", ",", "\"", "\"", ",", "info", ".", "CommitID", ",", "namespace", ")", "\n", "addBuildLabel", "(", "labels", ",", "\"", "\"", ",", "info", ".", "Ref", ",", "namespace", ")", "\n", "addBuildLabel", "(", "labels", ",", "\"", "\"", ",", "info", ".", "Message", ",", "namespace", ")", "\n", "addBuildLabel", "(", "labels", ",", "\"", "\"", ",", "info", ".", "Location", ",", "namespace", ")", "\n", "addBuildLabel", "(", "labels", ",", "\"", "\"", ",", "info", ".", "ContextDir", ",", "namespace", ")", "\n", "return", "labels", "\n", "}" ]
// GenerateLabelsFromSourceInfo generate the labels based on the source repository // informations.
[ "GenerateLabelsFromSourceInfo", "generate", "the", "labels", "based", "on", "the", "source", "repository", "informations", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/util/labels.go#L43-L61
train
openshift/source-to-image
pkg/tar/tar.go
WriteHeader
func (a ChmodAdapter) WriteHeader(hdr *tar.Header) error { if hdr.FileInfo().Mode()&os.ModeSymlink == 0 { newMode := hdr.Mode &^ 0777 if hdr.FileInfo().IsDir() { newMode |= a.NewDirMode } else if hdr.FileInfo().Mode()&0010 != 0 { // S_IXUSR newMode |= a.NewExecFileMode } else { newMode |= a.NewFileMode } hdr.Mode = newMode } return a.Writer.WriteHeader(hdr) }
go
func (a ChmodAdapter) WriteHeader(hdr *tar.Header) error { if hdr.FileInfo().Mode()&os.ModeSymlink == 0 { newMode := hdr.Mode &^ 0777 if hdr.FileInfo().IsDir() { newMode |= a.NewDirMode } else if hdr.FileInfo().Mode()&0010 != 0 { // S_IXUSR newMode |= a.NewExecFileMode } else { newMode |= a.NewFileMode } hdr.Mode = newMode } return a.Writer.WriteHeader(hdr) }
[ "func", "(", "a", "ChmodAdapter", ")", "WriteHeader", "(", "hdr", "*", "tar", ".", "Header", ")", "error", "{", "if", "hdr", ".", "FileInfo", "(", ")", ".", "Mode", "(", ")", "&", "os", ".", "ModeSymlink", "==", "0", "{", "newMode", ":=", "hdr", ".", "Mode", "&^", "0777", "\n", "if", "hdr", ".", "FileInfo", "(", ")", ".", "IsDir", "(", ")", "{", "newMode", "|=", "a", ".", "NewDirMode", "\n", "}", "else", "if", "hdr", ".", "FileInfo", "(", ")", ".", "Mode", "(", ")", "&", "0010", "!=", "0", "{", "// S_IXUSR", "newMode", "|=", "a", ".", "NewExecFileMode", "\n", "}", "else", "{", "newMode", "|=", "a", ".", "NewFileMode", "\n", "}", "\n", "hdr", ".", "Mode", "=", "newMode", "\n", "}", "\n", "return", "a", ".", "Writer", ".", "WriteHeader", "(", "hdr", ")", "\n", "}" ]
// WriteHeader changes the mode of files and directories inline as a tarfile is // being written
[ "WriteHeader", "changes", "the", "mode", "of", "files", "and", "directories", "inline", "as", "a", "tarfile", "is", "being", "written" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/tar/tar.go#L100-L113
train
openshift/source-to-image
pkg/tar/tar.go
WriteHeader
func (a RenameAdapter) WriteHeader(hdr *tar.Header) error { if hdr.Name == a.Old { hdr.Name = a.New } else if strings.HasPrefix(hdr.Name, a.Old+"/") { hdr.Name = a.New + hdr.Name[len(a.Old):] } return a.Writer.WriteHeader(hdr) }
go
func (a RenameAdapter) WriteHeader(hdr *tar.Header) error { if hdr.Name == a.Old { hdr.Name = a.New } else if strings.HasPrefix(hdr.Name, a.Old+"/") { hdr.Name = a.New + hdr.Name[len(a.Old):] } return a.Writer.WriteHeader(hdr) }
[ "func", "(", "a", "RenameAdapter", ")", "WriteHeader", "(", "hdr", "*", "tar", ".", "Header", ")", "error", "{", "if", "hdr", ".", "Name", "==", "a", ".", "Old", "{", "hdr", ".", "Name", "=", "a", ".", "New", "\n", "}", "else", "if", "strings", ".", "HasPrefix", "(", "hdr", ".", "Name", ",", "a", ".", "Old", "+", "\"", "\"", ")", "{", "hdr", ".", "Name", "=", "a", ".", "New", "+", "hdr", ".", "Name", "[", "len", "(", "a", ".", "Old", ")", ":", "]", "\n", "}", "\n\n", "return", "a", ".", "Writer", ".", "WriteHeader", "(", "hdr", ")", "\n", "}" ]
// WriteHeader renames files and directories inline as a tarfile is being // written
[ "WriteHeader", "renames", "files", "and", "directories", "inline", "as", "a", "tarfile", "is", "being", "written" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/tar/tar.go#L125-L133
train
openshift/source-to-image
pkg/tar/tar.go
New
func New(fs fs.FileSystem) Tar { return &stiTar{ FileSystem: fs, exclude: DefaultExclusionPattern, timeout: defaultTimeout, } }
go
func New(fs fs.FileSystem) Tar { return &stiTar{ FileSystem: fs, exclude: DefaultExclusionPattern, timeout: defaultTimeout, } }
[ "func", "New", "(", "fs", "fs", ".", "FileSystem", ")", "Tar", "{", "return", "&", "stiTar", "{", "FileSystem", ":", "fs", ",", "exclude", ":", "DefaultExclusionPattern", ",", "timeout", ":", "defaultTimeout", ",", "}", "\n", "}" ]
// New creates a new Tar
[ "New", "creates", "a", "new", "Tar" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/tar/tar.go#L136-L142
train
openshift/source-to-image
pkg/tar/tar.go
NewWithTimeout
func NewWithTimeout(fs fs.FileSystem, timeout time.Duration) Tar { return &stiTar{ FileSystem: fs, exclude: DefaultExclusionPattern, timeout: timeout, } }
go
func NewWithTimeout(fs fs.FileSystem, timeout time.Duration) Tar { return &stiTar{ FileSystem: fs, exclude: DefaultExclusionPattern, timeout: timeout, } }
[ "func", "NewWithTimeout", "(", "fs", "fs", ".", "FileSystem", ",", "timeout", "time", ".", "Duration", ")", "Tar", "{", "return", "&", "stiTar", "{", "FileSystem", ":", "fs", ",", "exclude", ":", "DefaultExclusionPattern", ",", "timeout", ":", "timeout", ",", "}", "\n", "}" ]
// NewWithTimeout creates a new Tar with the provided timeout extracting files.
[ "NewWithTimeout", "creates", "a", "new", "Tar", "with", "the", "provided", "timeout", "extracting", "files", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/tar/tar.go#L145-L151
train
openshift/source-to-image
pkg/tar/tar.go
NewParanoid
func NewParanoid(fs fs.FileSystem) Tar { return &stiTar{ FileSystem: fs, exclude: DefaultExclusionPattern, timeout: defaultTimeout, disallowOverwrite: true, disallowOutsidePaths: true, disallowSpecialFiles: true, } }
go
func NewParanoid(fs fs.FileSystem) Tar { return &stiTar{ FileSystem: fs, exclude: DefaultExclusionPattern, timeout: defaultTimeout, disallowOverwrite: true, disallowOutsidePaths: true, disallowSpecialFiles: true, } }
[ "func", "NewParanoid", "(", "fs", "fs", ".", "FileSystem", ")", "Tar", "{", "return", "&", "stiTar", "{", "FileSystem", ":", "fs", ",", "exclude", ":", "DefaultExclusionPattern", ",", "timeout", ":", "defaultTimeout", ",", "disallowOverwrite", ":", "true", ",", "disallowOutsidePaths", ":", "true", ",", "disallowSpecialFiles", ":", "true", ",", "}", "\n", "}" ]
// NewParanoid creates a new Tar that has restrictions // on what it can do while extracting files.
[ "NewParanoid", "creates", "a", "new", "Tar", "that", "has", "restrictions", "on", "what", "it", "can", "do", "while", "extracting", "files", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/tar/tar.go#L155-L164
train
openshift/source-to-image
pkg/tar/tar.go
NewParanoidWithTimeout
func NewParanoidWithTimeout(fs fs.FileSystem, timeout time.Duration) Tar { return &stiTar{ FileSystem: fs, exclude: DefaultExclusionPattern, timeout: timeout, disallowOverwrite: true, disallowOutsidePaths: true, disallowSpecialFiles: true, } }
go
func NewParanoidWithTimeout(fs fs.FileSystem, timeout time.Duration) Tar { return &stiTar{ FileSystem: fs, exclude: DefaultExclusionPattern, timeout: timeout, disallowOverwrite: true, disallowOutsidePaths: true, disallowSpecialFiles: true, } }
[ "func", "NewParanoidWithTimeout", "(", "fs", "fs", ".", "FileSystem", ",", "timeout", "time", ".", "Duration", ")", "Tar", "{", "return", "&", "stiTar", "{", "FileSystem", ":", "fs", ",", "exclude", ":", "DefaultExclusionPattern", ",", "timeout", ":", "timeout", ",", "disallowOverwrite", ":", "true", ",", "disallowOutsidePaths", ":", "true", ",", "disallowSpecialFiles", ":", "true", ",", "}", "\n", "}" ]
// NewParanoidWithTimeout creates a new Tar with the provided timeout extracting files. // It has restrictions on what it can do while extracting files.
[ "NewParanoidWithTimeout", "creates", "a", "new", "Tar", "with", "the", "provided", "timeout", "extracting", "files", ".", "It", "has", "restrictions", "on", "what", "it", "can", "do", "while", "extracting", "files", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/tar/tar.go#L168-L177
train
openshift/source-to-image
pkg/tar/tar.go
CreateTarFile
func (t *stiTar) CreateTarFile(base, dir string) (string, error) { tarFile, err := ioutil.TempFile(base, "tar") defer tarFile.Close() if err != nil { return "", err } if err = t.CreateTarStream(dir, false, tarFile); err != nil { return "", err } return tarFile.Name(), nil }
go
func (t *stiTar) CreateTarFile(base, dir string) (string, error) { tarFile, err := ioutil.TempFile(base, "tar") defer tarFile.Close() if err != nil { return "", err } if err = t.CreateTarStream(dir, false, tarFile); err != nil { return "", err } return tarFile.Name(), nil }
[ "func", "(", "t", "*", "stiTar", ")", "CreateTarFile", "(", "base", ",", "dir", "string", ")", "(", "string", ",", "error", ")", "{", "tarFile", ",", "err", ":=", "ioutil", ".", "TempFile", "(", "base", ",", "\"", "\"", ")", "\n", "defer", "tarFile", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "if", "err", "=", "t", ".", "CreateTarStream", "(", "dir", ",", "false", ",", "tarFile", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "tarFile", ".", "Name", "(", ")", ",", "nil", "\n", "}" ]
// CreateTarFile creates a tar file from the given directory // while excluding files that match the given exclusion pattern // It returns the name of the created file
[ "CreateTarFile", "creates", "a", "tar", "file", "from", "the", "given", "directory", "while", "excluding", "files", "that", "match", "the", "given", "exclusion", "pattern", "It", "returns", "the", "name", "of", "the", "created", "file" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/tar/tar.go#L200-L210
train
openshift/source-to-image
pkg/tar/tar.go
CreateTarStream
func (t *stiTar) CreateTarStream(dir string, includeDirInPath bool, writer io.Writer) error { tarWriter := tar.NewWriter(writer) defer tarWriter.Close() return t.CreateTarStreamToTarWriter(dir, includeDirInPath, tarWriter, nil) }
go
func (t *stiTar) CreateTarStream(dir string, includeDirInPath bool, writer io.Writer) error { tarWriter := tar.NewWriter(writer) defer tarWriter.Close() return t.CreateTarStreamToTarWriter(dir, includeDirInPath, tarWriter, nil) }
[ "func", "(", "t", "*", "stiTar", ")", "CreateTarStream", "(", "dir", "string", ",", "includeDirInPath", "bool", ",", "writer", "io", ".", "Writer", ")", "error", "{", "tarWriter", ":=", "tar", ".", "NewWriter", "(", "writer", ")", "\n", "defer", "tarWriter", ".", "Close", "(", ")", "\n\n", "return", "t", ".", "CreateTarStreamToTarWriter", "(", "dir", ",", "includeDirInPath", ",", "tarWriter", ",", "nil", ")", "\n", "}" ]
// CreateTarStream calls CreateTarStreamToTarWriter with a nil logger
[ "CreateTarStream", "calls", "CreateTarStreamToTarWriter", "with", "a", "nil", "logger" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/tar/tar.go#L217-L222
train
openshift/source-to-image
pkg/tar/tar.go
CreateTarStreamReader
func (t *stiTar) CreateTarStreamReader(dir string, includeDirInPath bool) io.ReadCloser { r, w := io.Pipe() go func() { w.CloseWithError(t.CreateTarStream(dir, includeDirInPath, w)) }() return r }
go
func (t *stiTar) CreateTarStreamReader(dir string, includeDirInPath bool) io.ReadCloser { r, w := io.Pipe() go func() { w.CloseWithError(t.CreateTarStream(dir, includeDirInPath, w)) }() return r }
[ "func", "(", "t", "*", "stiTar", ")", "CreateTarStreamReader", "(", "dir", "string", ",", "includeDirInPath", "bool", ")", "io", ".", "ReadCloser", "{", "r", ",", "w", ":=", "io", ".", "Pipe", "(", ")", "\n", "go", "func", "(", ")", "{", "w", ".", "CloseWithError", "(", "t", ".", "CreateTarStream", "(", "dir", ",", "includeDirInPath", ",", "w", ")", ")", "\n", "}", "(", ")", "\n", "return", "r", "\n", "}" ]
// CreateTarStreamReader returns an io.ReadCloser from which a tar stream can be // read. The tar stream is created using CreateTarStream.
[ "CreateTarStreamReader", "returns", "an", "io", ".", "ReadCloser", "from", "which", "a", "tar", "stream", "can", "be", "read", ".", "The", "tar", "stream", "is", "created", "using", "CreateTarStream", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/tar/tar.go#L226-L232
train
openshift/source-to-image
pkg/tar/tar.go
CreateTarStreamToTarWriter
func (t *stiTar) CreateTarStreamToTarWriter(dir string, includeDirInPath bool, tarWriter Writer, logger io.Writer) error { dir = filepath.Clean(dir) // remove relative paths and extraneous slashes glog.V(5).Infof("Adding %q to tar ...", dir) err := t.Walk(dir, func(path string, info os.FileInfo, err error) error { if err != nil { return err } // on Windows, directory symlinks report as a directory and as a symlink. // They should be treated as symlinks. if !t.shouldExclude(path) { // if file is a link just writing header info is enough if info.Mode()&os.ModeSymlink != 0 { if dir == path { return nil } if err = t.writeTarHeader(tarWriter, dir, path, info, includeDirInPath, logger); err != nil { glog.Errorf("Error writing header for %q: %v", info.Name(), err) } // on Windows, filepath.Walk recurses into directory symlinks when it // shouldn't. https://github.com/golang/go/issues/17540 if err == nil && info.Mode()&os.ModeDir != 0 { return filepath.SkipDir } return err } if info.IsDir() { if dir == path { return nil } if err = t.writeTarHeader(tarWriter, dir, path, info, includeDirInPath, logger); err != nil { glog.Errorf("Error writing header for %q: %v", info.Name(), err) } return err } // regular files are copied into tar, if accessible file, err := os.Open(path) if err != nil { glog.Errorf("Ignoring file %s: %v", path, err) return nil } defer file.Close() if err = t.writeTarHeader(tarWriter, dir, path, info, includeDirInPath, logger); err != nil { glog.Errorf("Error writing header for %q: %v", info.Name(), err) return err } if _, err = io.Copy(tarWriter, file); err != nil { glog.Errorf("Error copying file %q to tar: %v", path, err) return err } } return nil }) if err != nil { glog.Errorf("Error writing tar: %v", err) return err } return nil }
go
func (t *stiTar) CreateTarStreamToTarWriter(dir string, includeDirInPath bool, tarWriter Writer, logger io.Writer) error { dir = filepath.Clean(dir) // remove relative paths and extraneous slashes glog.V(5).Infof("Adding %q to tar ...", dir) err := t.Walk(dir, func(path string, info os.FileInfo, err error) error { if err != nil { return err } // on Windows, directory symlinks report as a directory and as a symlink. // They should be treated as symlinks. if !t.shouldExclude(path) { // if file is a link just writing header info is enough if info.Mode()&os.ModeSymlink != 0 { if dir == path { return nil } if err = t.writeTarHeader(tarWriter, dir, path, info, includeDirInPath, logger); err != nil { glog.Errorf("Error writing header for %q: %v", info.Name(), err) } // on Windows, filepath.Walk recurses into directory symlinks when it // shouldn't. https://github.com/golang/go/issues/17540 if err == nil && info.Mode()&os.ModeDir != 0 { return filepath.SkipDir } return err } if info.IsDir() { if dir == path { return nil } if err = t.writeTarHeader(tarWriter, dir, path, info, includeDirInPath, logger); err != nil { glog.Errorf("Error writing header for %q: %v", info.Name(), err) } return err } // regular files are copied into tar, if accessible file, err := os.Open(path) if err != nil { glog.Errorf("Ignoring file %s: %v", path, err) return nil } defer file.Close() if err = t.writeTarHeader(tarWriter, dir, path, info, includeDirInPath, logger); err != nil { glog.Errorf("Error writing header for %q: %v", info.Name(), err) return err } if _, err = io.Copy(tarWriter, file); err != nil { glog.Errorf("Error copying file %q to tar: %v", path, err) return err } } return nil }) if err != nil { glog.Errorf("Error writing tar: %v", err) return err } return nil }
[ "func", "(", "t", "*", "stiTar", ")", "CreateTarStreamToTarWriter", "(", "dir", "string", ",", "includeDirInPath", "bool", ",", "tarWriter", "Writer", ",", "logger", "io", ".", "Writer", ")", "error", "{", "dir", "=", "filepath", ".", "Clean", "(", "dir", ")", "// remove relative paths and extraneous slashes", "\n", "glog", ".", "V", "(", "5", ")", ".", "Infof", "(", "\"", "\"", ",", "dir", ")", "\n", "err", ":=", "t", ".", "Walk", "(", "dir", ",", "func", "(", "path", "string", ",", "info", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// on Windows, directory symlinks report as a directory and as a symlink.", "// They should be treated as symlinks.", "if", "!", "t", ".", "shouldExclude", "(", "path", ")", "{", "// if file is a link just writing header info is enough", "if", "info", ".", "Mode", "(", ")", "&", "os", ".", "ModeSymlink", "!=", "0", "{", "if", "dir", "==", "path", "{", "return", "nil", "\n", "}", "\n", "if", "err", "=", "t", ".", "writeTarHeader", "(", "tarWriter", ",", "dir", ",", "path", ",", "info", ",", "includeDirInPath", ",", "logger", ")", ";", "err", "!=", "nil", "{", "glog", ".", "Errorf", "(", "\"", "\"", ",", "info", ".", "Name", "(", ")", ",", "err", ")", "\n", "}", "\n", "// on Windows, filepath.Walk recurses into directory symlinks when it", "// shouldn't. https://github.com/golang/go/issues/17540", "if", "err", "==", "nil", "&&", "info", ".", "Mode", "(", ")", "&", "os", ".", "ModeDir", "!=", "0", "{", "return", "filepath", ".", "SkipDir", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "if", "info", ".", "IsDir", "(", ")", "{", "if", "dir", "==", "path", "{", "return", "nil", "\n", "}", "\n", "if", "err", "=", "t", ".", "writeTarHeader", "(", "tarWriter", ",", "dir", ",", "path", ",", "info", ",", "includeDirInPath", ",", "logger", ")", ";", "err", "!=", "nil", "{", "glog", ".", "Errorf", "(", "\"", "\"", ",", "info", ".", "Name", "(", ")", ",", "err", ")", "\n", "}", "\n", "return", "err", "\n", "}", "\n\n", "// regular files are copied into tar, if accessible", "file", ",", "err", ":=", "os", ".", "Open", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "glog", ".", "Errorf", "(", "\"", "\"", ",", "path", ",", "err", ")", "\n", "return", "nil", "\n", "}", "\n", "defer", "file", ".", "Close", "(", ")", "\n", "if", "err", "=", "t", ".", "writeTarHeader", "(", "tarWriter", ",", "dir", ",", "path", ",", "info", ",", "includeDirInPath", ",", "logger", ")", ";", "err", "!=", "nil", "{", "glog", ".", "Errorf", "(", "\"", "\"", ",", "info", ".", "Name", "(", ")", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n", "if", "_", ",", "err", "=", "io", ".", "Copy", "(", "tarWriter", ",", "file", ")", ";", "err", "!=", "nil", "{", "glog", ".", "Errorf", "(", "\"", "\"", ",", "path", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n\n", "if", "err", "!=", "nil", "{", "glog", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// CreateTarStreamToTarWriter creates a tar stream on the given writer from // the given directory while excluding files that match the given // exclusion pattern.
[ "CreateTarStreamToTarWriter", "creates", "a", "tar", "stream", "on", "the", "given", "writer", "from", "the", "given", "directory", "while", "excluding", "files", "that", "match", "the", "given", "exclusion", "pattern", "." ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/tar/tar.go#L237-L297
train
openshift/source-to-image
pkg/tar/tar.go
writeTarHeader
func (t *stiTar) writeTarHeader(tarWriter Writer, dir string, path string, info os.FileInfo, includeDirInPath bool, logger io.Writer) error { var ( link string err error ) if info.Mode()&os.ModeSymlink != 0 { link, err = os.Readlink(path) if err != nil { return err } } header, err := tar.FileInfoHeader(info, link) if err != nil { return err } // on Windows, tar.FileInfoHeader incorrectly interprets directory symlinks // as directories. https://github.com/golang/go/issues/17541 if info.Mode()&os.ModeSymlink != 0 && info.Mode()&os.ModeDir != 0 { header.Typeflag = tar.TypeSymlink header.Mode &^= 040000 // c_ISDIR header.Mode |= 0120000 // c_ISLNK header.Linkname = link } prefix := dir if includeDirInPath { prefix = filepath.Dir(prefix) } fileName := path if prefix != "." { fileName = path[1+len(prefix):] } header.Name = filepath.ToSlash(fileName) header.Linkname = filepath.ToSlash(header.Linkname) // Force the header format to PAX to support UTF-8 filenames // and use the same format throughout the entire tar file. header.Format = tar.FormatPAX logFile(logger, header.Name) glog.V(5).Infof("Adding to tar: %s as %s", path, header.Name) return tarWriter.WriteHeader(header) }
go
func (t *stiTar) writeTarHeader(tarWriter Writer, dir string, path string, info os.FileInfo, includeDirInPath bool, logger io.Writer) error { var ( link string err error ) if info.Mode()&os.ModeSymlink != 0 { link, err = os.Readlink(path) if err != nil { return err } } header, err := tar.FileInfoHeader(info, link) if err != nil { return err } // on Windows, tar.FileInfoHeader incorrectly interprets directory symlinks // as directories. https://github.com/golang/go/issues/17541 if info.Mode()&os.ModeSymlink != 0 && info.Mode()&os.ModeDir != 0 { header.Typeflag = tar.TypeSymlink header.Mode &^= 040000 // c_ISDIR header.Mode |= 0120000 // c_ISLNK header.Linkname = link } prefix := dir if includeDirInPath { prefix = filepath.Dir(prefix) } fileName := path if prefix != "." { fileName = path[1+len(prefix):] } header.Name = filepath.ToSlash(fileName) header.Linkname = filepath.ToSlash(header.Linkname) // Force the header format to PAX to support UTF-8 filenames // and use the same format throughout the entire tar file. header.Format = tar.FormatPAX logFile(logger, header.Name) glog.V(5).Infof("Adding to tar: %s as %s", path, header.Name) return tarWriter.WriteHeader(header) }
[ "func", "(", "t", "*", "stiTar", ")", "writeTarHeader", "(", "tarWriter", "Writer", ",", "dir", "string", ",", "path", "string", ",", "info", "os", ".", "FileInfo", ",", "includeDirInPath", "bool", ",", "logger", "io", ".", "Writer", ")", "error", "{", "var", "(", "link", "string", "\n", "err", "error", "\n", ")", "\n", "if", "info", ".", "Mode", "(", ")", "&", "os", ".", "ModeSymlink", "!=", "0", "{", "link", ",", "err", "=", "os", ".", "Readlink", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "header", ",", "err", ":=", "tar", ".", "FileInfoHeader", "(", "info", ",", "link", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// on Windows, tar.FileInfoHeader incorrectly interprets directory symlinks", "// as directories. https://github.com/golang/go/issues/17541", "if", "info", ".", "Mode", "(", ")", "&", "os", ".", "ModeSymlink", "!=", "0", "&&", "info", ".", "Mode", "(", ")", "&", "os", ".", "ModeDir", "!=", "0", "{", "header", ".", "Typeflag", "=", "tar", ".", "TypeSymlink", "\n", "header", ".", "Mode", "&^=", "040000", "// c_ISDIR", "\n", "header", ".", "Mode", "|=", "0120000", "// c_ISLNK", "\n", "header", ".", "Linkname", "=", "link", "\n", "}", "\n", "prefix", ":=", "dir", "\n", "if", "includeDirInPath", "{", "prefix", "=", "filepath", ".", "Dir", "(", "prefix", ")", "\n", "}", "\n", "fileName", ":=", "path", "\n", "if", "prefix", "!=", "\"", "\"", "{", "fileName", "=", "path", "[", "1", "+", "len", "(", "prefix", ")", ":", "]", "\n", "}", "\n", "header", ".", "Name", "=", "filepath", ".", "ToSlash", "(", "fileName", ")", "\n", "header", ".", "Linkname", "=", "filepath", ".", "ToSlash", "(", "header", ".", "Linkname", ")", "\n", "// Force the header format to PAX to support UTF-8 filenames", "// and use the same format throughout the entire tar file.", "header", ".", "Format", "=", "tar", ".", "FormatPAX", "\n", "logFile", "(", "logger", ",", "header", ".", "Name", ")", "\n", "glog", ".", "V", "(", "5", ")", ".", "Infof", "(", "\"", "\"", ",", "path", ",", "header", ".", "Name", ")", "\n", "return", "tarWriter", ".", "WriteHeader", "(", "header", ")", "\n", "}" ]
// writeTarHeader writes tar header for given file, returns error if operation fails
[ "writeTarHeader", "writes", "tar", "header", "for", "given", "file", "returns", "error", "if", "operation", "fails" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/tar/tar.go#L300-L339
train
openshift/source-to-image
pkg/tar/tar.go
ExtractTarStream
func (t *stiTar) ExtractTarStream(dir string, reader io.Reader) error { tarReader := tar.NewReader(reader) return t.ExtractTarStreamFromTarReader(dir, tarReader, nil) }
go
func (t *stiTar) ExtractTarStream(dir string, reader io.Reader) error { tarReader := tar.NewReader(reader) return t.ExtractTarStreamFromTarReader(dir, tarReader, nil) }
[ "func", "(", "t", "*", "stiTar", ")", "ExtractTarStream", "(", "dir", "string", ",", "reader", "io", ".", "Reader", ")", "error", "{", "tarReader", ":=", "tar", ".", "NewReader", "(", "reader", ")", "\n", "return", "t", ".", "ExtractTarStreamFromTarReader", "(", "dir", ",", "tarReader", ",", "nil", ")", "\n", "}" ]
// ExtractTarStream calls ExtractTarStreamFromTarReader with a default reader and nil logger
[ "ExtractTarStream", "calls", "ExtractTarStreamFromTarReader", "with", "a", "default", "reader", "and", "nil", "logger" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/tar/tar.go#L342-L345
train
openshift/source-to-image
pkg/tar/tar.go
ExtractTarStreamWithLogging
func (t *stiTar) ExtractTarStreamWithLogging(dir string, reader io.Reader, logger io.Writer) error { tarReader := tar.NewReader(reader) return t.ExtractTarStreamFromTarReader(dir, tarReader, logger) }
go
func (t *stiTar) ExtractTarStreamWithLogging(dir string, reader io.Reader, logger io.Writer) error { tarReader := tar.NewReader(reader) return t.ExtractTarStreamFromTarReader(dir, tarReader, logger) }
[ "func", "(", "t", "*", "stiTar", ")", "ExtractTarStreamWithLogging", "(", "dir", "string", ",", "reader", "io", ".", "Reader", ",", "logger", "io", ".", "Writer", ")", "error", "{", "tarReader", ":=", "tar", ".", "NewReader", "(", "reader", ")", "\n", "return", "t", ".", "ExtractTarStreamFromTarReader", "(", "dir", ",", "tarReader", ",", "logger", ")", "\n", "}" ]
// ExtractTarStreamWithLogging calls ExtractTarStreamFromTarReader with a default reader
[ "ExtractTarStreamWithLogging", "calls", "ExtractTarStreamFromTarReader", "with", "a", "default", "reader" ]
2ba8a349386aff03c26729096b0225a691355fe9
https://github.com/openshift/source-to-image/blob/2ba8a349386aff03c26729096b0225a691355fe9/pkg/tar/tar.go#L348-L351
train
boltdb/bolt
bolt_linux.go
fdatasync
func fdatasync(db *DB) error { return syscall.Fdatasync(int(db.file.Fd())) }
go
func fdatasync(db *DB) error { return syscall.Fdatasync(int(db.file.Fd())) }
[ "func", "fdatasync", "(", "db", "*", "DB", ")", "error", "{", "return", "syscall", ".", "Fdatasync", "(", "int", "(", "db", ".", "file", ".", "Fd", "(", ")", ")", ")", "\n", "}" ]
// fdatasync flushes written data to a file descriptor.
[ "fdatasync", "flushes", "written", "data", "to", "a", "file", "descriptor", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/bolt_linux.go#L8-L10
train
boltdb/bolt
freelist.go
newFreelist
func newFreelist() *freelist { return &freelist{ pending: make(map[txid][]pgid), cache: make(map[pgid]bool), } }
go
func newFreelist() *freelist { return &freelist{ pending: make(map[txid][]pgid), cache: make(map[pgid]bool), } }
[ "func", "newFreelist", "(", ")", "*", "freelist", "{", "return", "&", "freelist", "{", "pending", ":", "make", "(", "map", "[", "txid", "]", "[", "]", "pgid", ")", ",", "cache", ":", "make", "(", "map", "[", "pgid", "]", "bool", ")", ",", "}", "\n", "}" ]
// newFreelist returns an empty, initialized freelist.
[ "newFreelist", "returns", "an", "empty", "initialized", "freelist", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/freelist.go#L18-L23
train
boltdb/bolt
freelist.go
size
func (f *freelist) size() int { n := f.count() if n >= 0xFFFF { // The first element will be used to store the count. See freelist.write. n++ } return pageHeaderSize + (int(unsafe.Sizeof(pgid(0))) * n) }
go
func (f *freelist) size() int { n := f.count() if n >= 0xFFFF { // The first element will be used to store the count. See freelist.write. n++ } return pageHeaderSize + (int(unsafe.Sizeof(pgid(0))) * n) }
[ "func", "(", "f", "*", "freelist", ")", "size", "(", ")", "int", "{", "n", ":=", "f", ".", "count", "(", ")", "\n", "if", "n", ">=", "0xFFFF", "{", "// The first element will be used to store the count. See freelist.write.", "n", "++", "\n", "}", "\n", "return", "pageHeaderSize", "+", "(", "int", "(", "unsafe", ".", "Sizeof", "(", "pgid", "(", "0", ")", ")", ")", "*", "n", ")", "\n", "}" ]
// size returns the size of the page after serialization.
[ "size", "returns", "the", "size", "of", "the", "page", "after", "serialization", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/freelist.go#L26-L33
train
boltdb/bolt
freelist.go
pending_count
func (f *freelist) pending_count() int { var count int for _, list := range f.pending { count += len(list) } return count }
go
func (f *freelist) pending_count() int { var count int for _, list := range f.pending { count += len(list) } return count }
[ "func", "(", "f", "*", "freelist", ")", "pending_count", "(", ")", "int", "{", "var", "count", "int", "\n", "for", "_", ",", "list", ":=", "range", "f", ".", "pending", "{", "count", "+=", "len", "(", "list", ")", "\n", "}", "\n", "return", "count", "\n", "}" ]
// pending_count returns count of pending pages
[ "pending_count", "returns", "count", "of", "pending", "pages" ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/freelist.go#L46-L52
train
boltdb/bolt
freelist.go
copyall
func (f *freelist) copyall(dst []pgid) { m := make(pgids, 0, f.pending_count()) for _, list := range f.pending { m = append(m, list...) } sort.Sort(m) mergepgids(dst, f.ids, m) }
go
func (f *freelist) copyall(dst []pgid) { m := make(pgids, 0, f.pending_count()) for _, list := range f.pending { m = append(m, list...) } sort.Sort(m) mergepgids(dst, f.ids, m) }
[ "func", "(", "f", "*", "freelist", ")", "copyall", "(", "dst", "[", "]", "pgid", ")", "{", "m", ":=", "make", "(", "pgids", ",", "0", ",", "f", ".", "pending_count", "(", ")", ")", "\n", "for", "_", ",", "list", ":=", "range", "f", ".", "pending", "{", "m", "=", "append", "(", "m", ",", "list", "...", ")", "\n", "}", "\n", "sort", ".", "Sort", "(", "m", ")", "\n", "mergepgids", "(", "dst", ",", "f", ".", "ids", ",", "m", ")", "\n", "}" ]
// copyall copies into dst a list of all free ids and all pending ids in one sorted list. // f.count returns the minimum length required for dst.
[ "copyall", "copies", "into", "dst", "a", "list", "of", "all", "free", "ids", "and", "all", "pending", "ids", "in", "one", "sorted", "list", ".", "f", ".", "count", "returns", "the", "minimum", "length", "required", "for", "dst", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/freelist.go#L56-L63
train
boltdb/bolt
freelist.go
allocate
func (f *freelist) allocate(n int) pgid { if len(f.ids) == 0 { return 0 } var initial, previd pgid for i, id := range f.ids { if id <= 1 { panic(fmt.Sprintf("invalid page allocation: %d", id)) } // Reset initial page if this is not contiguous. if previd == 0 || id-previd != 1 { initial = id } // If we found a contiguous block then remove it and return it. if (id-initial)+1 == pgid(n) { // If we're allocating off the beginning then take the fast path // and just adjust the existing slice. This will use extra memory // temporarily but the append() in free() will realloc the slice // as is necessary. if (i + 1) == n { f.ids = f.ids[i+1:] } else { copy(f.ids[i-n+1:], f.ids[i+1:]) f.ids = f.ids[:len(f.ids)-n] } // Remove from the free cache. for i := pgid(0); i < pgid(n); i++ { delete(f.cache, initial+i) } return initial } previd = id } return 0 }
go
func (f *freelist) allocate(n int) pgid { if len(f.ids) == 0 { return 0 } var initial, previd pgid for i, id := range f.ids { if id <= 1 { panic(fmt.Sprintf("invalid page allocation: %d", id)) } // Reset initial page if this is not contiguous. if previd == 0 || id-previd != 1 { initial = id } // If we found a contiguous block then remove it and return it. if (id-initial)+1 == pgid(n) { // If we're allocating off the beginning then take the fast path // and just adjust the existing slice. This will use extra memory // temporarily but the append() in free() will realloc the slice // as is necessary. if (i + 1) == n { f.ids = f.ids[i+1:] } else { copy(f.ids[i-n+1:], f.ids[i+1:]) f.ids = f.ids[:len(f.ids)-n] } // Remove from the free cache. for i := pgid(0); i < pgid(n); i++ { delete(f.cache, initial+i) } return initial } previd = id } return 0 }
[ "func", "(", "f", "*", "freelist", ")", "allocate", "(", "n", "int", ")", "pgid", "{", "if", "len", "(", "f", ".", "ids", ")", "==", "0", "{", "return", "0", "\n", "}", "\n\n", "var", "initial", ",", "previd", "pgid", "\n", "for", "i", ",", "id", ":=", "range", "f", ".", "ids", "{", "if", "id", "<=", "1", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "id", ")", ")", "\n", "}", "\n\n", "// Reset initial page if this is not contiguous.", "if", "previd", "==", "0", "||", "id", "-", "previd", "!=", "1", "{", "initial", "=", "id", "\n", "}", "\n\n", "// If we found a contiguous block then remove it and return it.", "if", "(", "id", "-", "initial", ")", "+", "1", "==", "pgid", "(", "n", ")", "{", "// If we're allocating off the beginning then take the fast path", "// and just adjust the existing slice. This will use extra memory", "// temporarily but the append() in free() will realloc the slice", "// as is necessary.", "if", "(", "i", "+", "1", ")", "==", "n", "{", "f", ".", "ids", "=", "f", ".", "ids", "[", "i", "+", "1", ":", "]", "\n", "}", "else", "{", "copy", "(", "f", ".", "ids", "[", "i", "-", "n", "+", "1", ":", "]", ",", "f", ".", "ids", "[", "i", "+", "1", ":", "]", ")", "\n", "f", ".", "ids", "=", "f", ".", "ids", "[", ":", "len", "(", "f", ".", "ids", ")", "-", "n", "]", "\n", "}", "\n\n", "// Remove from the free cache.", "for", "i", ":=", "pgid", "(", "0", ")", ";", "i", "<", "pgid", "(", "n", ")", ";", "i", "++", "{", "delete", "(", "f", ".", "cache", ",", "initial", "+", "i", ")", "\n", "}", "\n\n", "return", "initial", "\n", "}", "\n\n", "previd", "=", "id", "\n", "}", "\n", "return", "0", "\n", "}" ]
// allocate returns the starting page id of a contiguous list of pages of a given size. // If a contiguous block cannot be found then 0 is returned.
[ "allocate", "returns", "the", "starting", "page", "id", "of", "a", "contiguous", "list", "of", "pages", "of", "a", "given", "size", ".", "If", "a", "contiguous", "block", "cannot", "be", "found", "then", "0", "is", "returned", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/freelist.go#L67-L107
train
boltdb/bolt
freelist.go
free
func (f *freelist) free(txid txid, p *page) { if p.id <= 1 { panic(fmt.Sprintf("cannot free page 0 or 1: %d", p.id)) } // Free page and all its overflow pages. var ids = f.pending[txid] for id := p.id; id <= p.id+pgid(p.overflow); id++ { // Verify that page is not already free. if f.cache[id] { panic(fmt.Sprintf("page %d already freed", id)) } // Add to the freelist and cache. ids = append(ids, id) f.cache[id] = true } f.pending[txid] = ids }
go
func (f *freelist) free(txid txid, p *page) { if p.id <= 1 { panic(fmt.Sprintf("cannot free page 0 or 1: %d", p.id)) } // Free page and all its overflow pages. var ids = f.pending[txid] for id := p.id; id <= p.id+pgid(p.overflow); id++ { // Verify that page is not already free. if f.cache[id] { panic(fmt.Sprintf("page %d already freed", id)) } // Add to the freelist and cache. ids = append(ids, id) f.cache[id] = true } f.pending[txid] = ids }
[ "func", "(", "f", "*", "freelist", ")", "free", "(", "txid", "txid", ",", "p", "*", "page", ")", "{", "if", "p", ".", "id", "<=", "1", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "p", ".", "id", ")", ")", "\n", "}", "\n\n", "// Free page and all its overflow pages.", "var", "ids", "=", "f", ".", "pending", "[", "txid", "]", "\n", "for", "id", ":=", "p", ".", "id", ";", "id", "<=", "p", ".", "id", "+", "pgid", "(", "p", ".", "overflow", ")", ";", "id", "++", "{", "// Verify that page is not already free.", "if", "f", ".", "cache", "[", "id", "]", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "id", ")", ")", "\n", "}", "\n\n", "// Add to the freelist and cache.", "ids", "=", "append", "(", "ids", ",", "id", ")", "\n", "f", ".", "cache", "[", "id", "]", "=", "true", "\n", "}", "\n", "f", ".", "pending", "[", "txid", "]", "=", "ids", "\n", "}" ]
// free releases a page and its overflow for a given transaction id. // If the page is already free then a panic will occur.
[ "free", "releases", "a", "page", "and", "its", "overflow", "for", "a", "given", "transaction", "id", ".", "If", "the", "page", "is", "already", "free", "then", "a", "panic", "will", "occur", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/freelist.go#L111-L129
train
boltdb/bolt
freelist.go
rollback
func (f *freelist) rollback(txid txid) { // Remove page ids from cache. for _, id := range f.pending[txid] { delete(f.cache, id) } // Remove pages from pending list. delete(f.pending, txid) }
go
func (f *freelist) rollback(txid txid) { // Remove page ids from cache. for _, id := range f.pending[txid] { delete(f.cache, id) } // Remove pages from pending list. delete(f.pending, txid) }
[ "func", "(", "f", "*", "freelist", ")", "rollback", "(", "txid", "txid", ")", "{", "// Remove page ids from cache.", "for", "_", ",", "id", ":=", "range", "f", ".", "pending", "[", "txid", "]", "{", "delete", "(", "f", ".", "cache", ",", "id", ")", "\n", "}", "\n\n", "// Remove pages from pending list.", "delete", "(", "f", ".", "pending", ",", "txid", ")", "\n", "}" ]
// rollback removes the pages from a given pending tx.
[ "rollback", "removes", "the", "pages", "from", "a", "given", "pending", "tx", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/freelist.go#L147-L155
train
boltdb/bolt
freelist.go
read
func (f *freelist) read(p *page) { // If the page.count is at the max uint16 value (64k) then it's considered // an overflow and the size of the freelist is stored as the first element. idx, count := 0, int(p.count) if count == 0xFFFF { idx = 1 count = int(((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[0]) } // Copy the list of page ids from the freelist. if count == 0 { f.ids = nil } else { ids := ((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[idx:count] f.ids = make([]pgid, len(ids)) copy(f.ids, ids) // Make sure they're sorted. sort.Sort(pgids(f.ids)) } // Rebuild the page cache. f.reindex() }
go
func (f *freelist) read(p *page) { // If the page.count is at the max uint16 value (64k) then it's considered // an overflow and the size of the freelist is stored as the first element. idx, count := 0, int(p.count) if count == 0xFFFF { idx = 1 count = int(((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[0]) } // Copy the list of page ids from the freelist. if count == 0 { f.ids = nil } else { ids := ((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[idx:count] f.ids = make([]pgid, len(ids)) copy(f.ids, ids) // Make sure they're sorted. sort.Sort(pgids(f.ids)) } // Rebuild the page cache. f.reindex() }
[ "func", "(", "f", "*", "freelist", ")", "read", "(", "p", "*", "page", ")", "{", "// If the page.count is at the max uint16 value (64k) then it's considered", "// an overflow and the size of the freelist is stored as the first element.", "idx", ",", "count", ":=", "0", ",", "int", "(", "p", ".", "count", ")", "\n", "if", "count", "==", "0xFFFF", "{", "idx", "=", "1", "\n", "count", "=", "int", "(", "(", "(", "*", "[", "maxAllocSize", "]", "pgid", ")", "(", "unsafe", ".", "Pointer", "(", "&", "p", ".", "ptr", ")", ")", ")", "[", "0", "]", ")", "\n", "}", "\n\n", "// Copy the list of page ids from the freelist.", "if", "count", "==", "0", "{", "f", ".", "ids", "=", "nil", "\n", "}", "else", "{", "ids", ":=", "(", "(", "*", "[", "maxAllocSize", "]", "pgid", ")", "(", "unsafe", ".", "Pointer", "(", "&", "p", ".", "ptr", ")", ")", ")", "[", "idx", ":", "count", "]", "\n", "f", ".", "ids", "=", "make", "(", "[", "]", "pgid", ",", "len", "(", "ids", ")", ")", "\n", "copy", "(", "f", ".", "ids", ",", "ids", ")", "\n\n", "// Make sure they're sorted.", "sort", ".", "Sort", "(", "pgids", "(", "f", ".", "ids", ")", ")", "\n", "}", "\n\n", "// Rebuild the page cache.", "f", ".", "reindex", "(", ")", "\n", "}" ]
// read initializes the freelist from a freelist page.
[ "read", "initializes", "the", "freelist", "from", "a", "freelist", "page", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/freelist.go#L163-L186
train
boltdb/bolt
freelist.go
write
func (f *freelist) write(p *page) error { // Combine the old free pgids and pgids waiting on an open transaction. // Update the header flag. p.flags |= freelistPageFlag // The page.count can only hold up to 64k elements so if we overflow that // number then we handle it by putting the size in the first element. lenids := f.count() if lenids == 0 { p.count = uint16(lenids) } else if lenids < 0xFFFF { p.count = uint16(lenids) f.copyall(((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[:]) } else { p.count = 0xFFFF ((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[0] = pgid(lenids) f.copyall(((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[1:]) } return nil }
go
func (f *freelist) write(p *page) error { // Combine the old free pgids and pgids waiting on an open transaction. // Update the header flag. p.flags |= freelistPageFlag // The page.count can only hold up to 64k elements so if we overflow that // number then we handle it by putting the size in the first element. lenids := f.count() if lenids == 0 { p.count = uint16(lenids) } else if lenids < 0xFFFF { p.count = uint16(lenids) f.copyall(((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[:]) } else { p.count = 0xFFFF ((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[0] = pgid(lenids) f.copyall(((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[1:]) } return nil }
[ "func", "(", "f", "*", "freelist", ")", "write", "(", "p", "*", "page", ")", "error", "{", "// Combine the old free pgids and pgids waiting on an open transaction.", "// Update the header flag.", "p", ".", "flags", "|=", "freelistPageFlag", "\n\n", "// The page.count can only hold up to 64k elements so if we overflow that", "// number then we handle it by putting the size in the first element.", "lenids", ":=", "f", ".", "count", "(", ")", "\n", "if", "lenids", "==", "0", "{", "p", ".", "count", "=", "uint16", "(", "lenids", ")", "\n", "}", "else", "if", "lenids", "<", "0xFFFF", "{", "p", ".", "count", "=", "uint16", "(", "lenids", ")", "\n", "f", ".", "copyall", "(", "(", "(", "*", "[", "maxAllocSize", "]", "pgid", ")", "(", "unsafe", ".", "Pointer", "(", "&", "p", ".", "ptr", ")", ")", ")", "[", ":", "]", ")", "\n", "}", "else", "{", "p", ".", "count", "=", "0xFFFF", "\n", "(", "(", "*", "[", "maxAllocSize", "]", "pgid", ")", "(", "unsafe", ".", "Pointer", "(", "&", "p", ".", "ptr", ")", ")", ")", "[", "0", "]", "=", "pgid", "(", "lenids", ")", "\n", "f", ".", "copyall", "(", "(", "(", "*", "[", "maxAllocSize", "]", "pgid", ")", "(", "unsafe", ".", "Pointer", "(", "&", "p", ".", "ptr", ")", ")", ")", "[", "1", ":", "]", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// write writes the page ids onto a freelist page. All free and pending ids are // saved to disk since in the event of a program crash, all pending ids will // become free.
[ "write", "writes", "the", "page", "ids", "onto", "a", "freelist", "page", ".", "All", "free", "and", "pending", "ids", "are", "saved", "to", "disk", "since", "in", "the", "event", "of", "a", "program", "crash", "all", "pending", "ids", "will", "become", "free", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/freelist.go#L191-L212
train
boltdb/bolt
freelist.go
reload
func (f *freelist) reload(p *page) { f.read(p) // Build a cache of only pending pages. pcache := make(map[pgid]bool) for _, pendingIDs := range f.pending { for _, pendingID := range pendingIDs { pcache[pendingID] = true } } // Check each page in the freelist and build a new available freelist // with any pages not in the pending lists. var a []pgid for _, id := range f.ids { if !pcache[id] { a = append(a, id) } } f.ids = a // Once the available list is rebuilt then rebuild the free cache so that // it includes the available and pending free pages. f.reindex() }
go
func (f *freelist) reload(p *page) { f.read(p) // Build a cache of only pending pages. pcache := make(map[pgid]bool) for _, pendingIDs := range f.pending { for _, pendingID := range pendingIDs { pcache[pendingID] = true } } // Check each page in the freelist and build a new available freelist // with any pages not in the pending lists. var a []pgid for _, id := range f.ids { if !pcache[id] { a = append(a, id) } } f.ids = a // Once the available list is rebuilt then rebuild the free cache so that // it includes the available and pending free pages. f.reindex() }
[ "func", "(", "f", "*", "freelist", ")", "reload", "(", "p", "*", "page", ")", "{", "f", ".", "read", "(", "p", ")", "\n\n", "// Build a cache of only pending pages.", "pcache", ":=", "make", "(", "map", "[", "pgid", "]", "bool", ")", "\n", "for", "_", ",", "pendingIDs", ":=", "range", "f", ".", "pending", "{", "for", "_", ",", "pendingID", ":=", "range", "pendingIDs", "{", "pcache", "[", "pendingID", "]", "=", "true", "\n", "}", "\n", "}", "\n\n", "// Check each page in the freelist and build a new available freelist", "// with any pages not in the pending lists.", "var", "a", "[", "]", "pgid", "\n", "for", "_", ",", "id", ":=", "range", "f", ".", "ids", "{", "if", "!", "pcache", "[", "id", "]", "{", "a", "=", "append", "(", "a", ",", "id", ")", "\n", "}", "\n", "}", "\n", "f", ".", "ids", "=", "a", "\n\n", "// Once the available list is rebuilt then rebuild the free cache so that", "// it includes the available and pending free pages.", "f", ".", "reindex", "(", ")", "\n", "}" ]
// reload reads the freelist from a page and filters out pending items.
[ "reload", "reads", "the", "freelist", "from", "a", "page", "and", "filters", "out", "pending", "items", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/freelist.go#L215-L239
train
boltdb/bolt
freelist.go
reindex
func (f *freelist) reindex() { f.cache = make(map[pgid]bool, len(f.ids)) for _, id := range f.ids { f.cache[id] = true } for _, pendingIDs := range f.pending { for _, pendingID := range pendingIDs { f.cache[pendingID] = true } } }
go
func (f *freelist) reindex() { f.cache = make(map[pgid]bool, len(f.ids)) for _, id := range f.ids { f.cache[id] = true } for _, pendingIDs := range f.pending { for _, pendingID := range pendingIDs { f.cache[pendingID] = true } } }
[ "func", "(", "f", "*", "freelist", ")", "reindex", "(", ")", "{", "f", ".", "cache", "=", "make", "(", "map", "[", "pgid", "]", "bool", ",", "len", "(", "f", ".", "ids", ")", ")", "\n", "for", "_", ",", "id", ":=", "range", "f", ".", "ids", "{", "f", ".", "cache", "[", "id", "]", "=", "true", "\n", "}", "\n", "for", "_", ",", "pendingIDs", ":=", "range", "f", ".", "pending", "{", "for", "_", ",", "pendingID", ":=", "range", "pendingIDs", "{", "f", ".", "cache", "[", "pendingID", "]", "=", "true", "\n", "}", "\n", "}", "\n", "}" ]
// reindex rebuilds the free cache based on available and pending free lists.
[ "reindex", "rebuilds", "the", "free", "cache", "based", "on", "available", "and", "pending", "free", "lists", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/freelist.go#L242-L252
train
boltdb/bolt
db.go
Open
func Open(path string, mode os.FileMode, options *Options) (*DB, error) { var db = &DB{opened: true} // Set default options if no options are provided. if options == nil { options = DefaultOptions } db.NoGrowSync = options.NoGrowSync db.MmapFlags = options.MmapFlags // Set default values for later DB operations. db.MaxBatchSize = DefaultMaxBatchSize db.MaxBatchDelay = DefaultMaxBatchDelay db.AllocSize = DefaultAllocSize flag := os.O_RDWR if options.ReadOnly { flag = os.O_RDONLY db.readOnly = true } // Open data file and separate sync handler for metadata writes. db.path = path var err error if db.file, err = os.OpenFile(db.path, flag|os.O_CREATE, mode); err != nil { _ = db.close() return nil, err } // Lock file so that other processes using Bolt in read-write mode cannot // use the database at the same time. This would cause corruption since // the two processes would write meta pages and free pages separately. // The database file is locked exclusively (only one process can grab the lock) // if !options.ReadOnly. // The database file is locked using the shared lock (more than one process may // hold a lock at the same time) otherwise (options.ReadOnly is set). if err := flock(db, mode, !db.readOnly, options.Timeout); err != nil { _ = db.close() return nil, err } // Default values for test hooks db.ops.writeAt = db.file.WriteAt // Initialize the database if it doesn't exist. if info, err := db.file.Stat(); err != nil { return nil, err } else if info.Size() == 0 { // Initialize new files with meta pages. if err := db.init(); err != nil { return nil, err } } else { // Read the first meta page to determine the page size. var buf [0x1000]byte if _, err := db.file.ReadAt(buf[:], 0); err == nil { m := db.pageInBuffer(buf[:], 0).meta() if err := m.validate(); err != nil { // If we can't read the page size, we can assume it's the same // as the OS -- since that's how the page size was chosen in the // first place. // // If the first page is invalid and this OS uses a different // page size than what the database was created with then we // are out of luck and cannot access the database. db.pageSize = os.Getpagesize() } else { db.pageSize = int(m.pageSize) } } } // Initialize page pool. db.pagePool = sync.Pool{ New: func() interface{} { return make([]byte, db.pageSize) }, } // Memory map the data file. if err := db.mmap(options.InitialMmapSize); err != nil { _ = db.close() return nil, err } // Read in the freelist. db.freelist = newFreelist() db.freelist.read(db.page(db.meta().freelist)) // Mark the database as opened and return. return db, nil }
go
func Open(path string, mode os.FileMode, options *Options) (*DB, error) { var db = &DB{opened: true} // Set default options if no options are provided. if options == nil { options = DefaultOptions } db.NoGrowSync = options.NoGrowSync db.MmapFlags = options.MmapFlags // Set default values for later DB operations. db.MaxBatchSize = DefaultMaxBatchSize db.MaxBatchDelay = DefaultMaxBatchDelay db.AllocSize = DefaultAllocSize flag := os.O_RDWR if options.ReadOnly { flag = os.O_RDONLY db.readOnly = true } // Open data file and separate sync handler for metadata writes. db.path = path var err error if db.file, err = os.OpenFile(db.path, flag|os.O_CREATE, mode); err != nil { _ = db.close() return nil, err } // Lock file so that other processes using Bolt in read-write mode cannot // use the database at the same time. This would cause corruption since // the two processes would write meta pages and free pages separately. // The database file is locked exclusively (only one process can grab the lock) // if !options.ReadOnly. // The database file is locked using the shared lock (more than one process may // hold a lock at the same time) otherwise (options.ReadOnly is set). if err := flock(db, mode, !db.readOnly, options.Timeout); err != nil { _ = db.close() return nil, err } // Default values for test hooks db.ops.writeAt = db.file.WriteAt // Initialize the database if it doesn't exist. if info, err := db.file.Stat(); err != nil { return nil, err } else if info.Size() == 0 { // Initialize new files with meta pages. if err := db.init(); err != nil { return nil, err } } else { // Read the first meta page to determine the page size. var buf [0x1000]byte if _, err := db.file.ReadAt(buf[:], 0); err == nil { m := db.pageInBuffer(buf[:], 0).meta() if err := m.validate(); err != nil { // If we can't read the page size, we can assume it's the same // as the OS -- since that's how the page size was chosen in the // first place. // // If the first page is invalid and this OS uses a different // page size than what the database was created with then we // are out of luck and cannot access the database. db.pageSize = os.Getpagesize() } else { db.pageSize = int(m.pageSize) } } } // Initialize page pool. db.pagePool = sync.Pool{ New: func() interface{} { return make([]byte, db.pageSize) }, } // Memory map the data file. if err := db.mmap(options.InitialMmapSize); err != nil { _ = db.close() return nil, err } // Read in the freelist. db.freelist = newFreelist() db.freelist.read(db.page(db.meta().freelist)) // Mark the database as opened and return. return db, nil }
[ "func", "Open", "(", "path", "string", ",", "mode", "os", ".", "FileMode", ",", "options", "*", "Options", ")", "(", "*", "DB", ",", "error", ")", "{", "var", "db", "=", "&", "DB", "{", "opened", ":", "true", "}", "\n\n", "// Set default options if no options are provided.", "if", "options", "==", "nil", "{", "options", "=", "DefaultOptions", "\n", "}", "\n", "db", ".", "NoGrowSync", "=", "options", ".", "NoGrowSync", "\n", "db", ".", "MmapFlags", "=", "options", ".", "MmapFlags", "\n\n", "// Set default values for later DB operations.", "db", ".", "MaxBatchSize", "=", "DefaultMaxBatchSize", "\n", "db", ".", "MaxBatchDelay", "=", "DefaultMaxBatchDelay", "\n", "db", ".", "AllocSize", "=", "DefaultAllocSize", "\n\n", "flag", ":=", "os", ".", "O_RDWR", "\n", "if", "options", ".", "ReadOnly", "{", "flag", "=", "os", ".", "O_RDONLY", "\n", "db", ".", "readOnly", "=", "true", "\n", "}", "\n\n", "// Open data file and separate sync handler for metadata writes.", "db", ".", "path", "=", "path", "\n", "var", "err", "error", "\n", "if", "db", ".", "file", ",", "err", "=", "os", ".", "OpenFile", "(", "db", ".", "path", ",", "flag", "|", "os", ".", "O_CREATE", ",", "mode", ")", ";", "err", "!=", "nil", "{", "_", "=", "db", ".", "close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Lock file so that other processes using Bolt in read-write mode cannot", "// use the database at the same time. This would cause corruption since", "// the two processes would write meta pages and free pages separately.", "// The database file is locked exclusively (only one process can grab the lock)", "// if !options.ReadOnly.", "// The database file is locked using the shared lock (more than one process may", "// hold a lock at the same time) otherwise (options.ReadOnly is set).", "if", "err", ":=", "flock", "(", "db", ",", "mode", ",", "!", "db", ".", "readOnly", ",", "options", ".", "Timeout", ")", ";", "err", "!=", "nil", "{", "_", "=", "db", ".", "close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Default values for test hooks", "db", ".", "ops", ".", "writeAt", "=", "db", ".", "file", ".", "WriteAt", "\n\n", "// Initialize the database if it doesn't exist.", "if", "info", ",", "err", ":=", "db", ".", "file", ".", "Stat", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "else", "if", "info", ".", "Size", "(", ")", "==", "0", "{", "// Initialize new files with meta pages.", "if", "err", ":=", "db", ".", "init", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "else", "{", "// Read the first meta page to determine the page size.", "var", "buf", "[", "0x1000", "]", "byte", "\n", "if", "_", ",", "err", ":=", "db", ".", "file", ".", "ReadAt", "(", "buf", "[", ":", "]", ",", "0", ")", ";", "err", "==", "nil", "{", "m", ":=", "db", ".", "pageInBuffer", "(", "buf", "[", ":", "]", ",", "0", ")", ".", "meta", "(", ")", "\n", "if", "err", ":=", "m", ".", "validate", "(", ")", ";", "err", "!=", "nil", "{", "// If we can't read the page size, we can assume it's the same", "// as the OS -- since that's how the page size was chosen in the", "// first place.", "//", "// If the first page is invalid and this OS uses a different", "// page size than what the database was created with then we", "// are out of luck and cannot access the database.", "db", ".", "pageSize", "=", "os", ".", "Getpagesize", "(", ")", "\n", "}", "else", "{", "db", ".", "pageSize", "=", "int", "(", "m", ".", "pageSize", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Initialize page pool.", "db", ".", "pagePool", "=", "sync", ".", "Pool", "{", "New", ":", "func", "(", ")", "interface", "{", "}", "{", "return", "make", "(", "[", "]", "byte", ",", "db", ".", "pageSize", ")", "\n", "}", ",", "}", "\n\n", "// Memory map the data file.", "if", "err", ":=", "db", ".", "mmap", "(", "options", ".", "InitialMmapSize", ")", ";", "err", "!=", "nil", "{", "_", "=", "db", ".", "close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Read in the freelist.", "db", ".", "freelist", "=", "newFreelist", "(", ")", "\n", "db", ".", "freelist", ".", "read", "(", "db", ".", "page", "(", "db", ".", "meta", "(", ")", ".", "freelist", ")", ")", "\n\n", "// Mark the database as opened and return.", "return", "db", ",", "nil", "\n", "}" ]
// Open creates and opens a database at the given path. // If the file does not exist then it will be created automatically. // Passing in nil options will cause Bolt to open the database with the default options.
[ "Open", "creates", "and", "opens", "a", "database", "at", "the", "given", "path", ".", "If", "the", "file", "does", "not", "exist", "then", "it", "will", "be", "created", "automatically", ".", "Passing", "in", "nil", "options", "will", "cause", "Bolt", "to", "open", "the", "database", "with", "the", "default", "options", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/db.go#L150-L241
train
boltdb/bolt
db.go
mmap
func (db *DB) mmap(minsz int) error { db.mmaplock.Lock() defer db.mmaplock.Unlock() info, err := db.file.Stat() if err != nil { return fmt.Errorf("mmap stat error: %s", err) } else if int(info.Size()) < db.pageSize*2 { return fmt.Errorf("file size too small") } // Ensure the size is at least the minimum size. var size = int(info.Size()) if size < minsz { size = minsz } size, err = db.mmapSize(size) if err != nil { return err } // Dereference all mmap references before unmapping. if db.rwtx != nil { db.rwtx.root.dereference() } // Unmap existing data before continuing. if err := db.munmap(); err != nil { return err } // Memory-map the data file as a byte slice. if err := mmap(db, size); err != nil { return err } // Save references to the meta pages. db.meta0 = db.page(0).meta() db.meta1 = db.page(1).meta() // Validate the meta pages. We only return an error if both meta pages fail // validation, since meta0 failing validation means that it wasn't saved // properly -- but we can recover using meta1. And vice-versa. err0 := db.meta0.validate() err1 := db.meta1.validate() if err0 != nil && err1 != nil { return err0 } return nil }
go
func (db *DB) mmap(minsz int) error { db.mmaplock.Lock() defer db.mmaplock.Unlock() info, err := db.file.Stat() if err != nil { return fmt.Errorf("mmap stat error: %s", err) } else if int(info.Size()) < db.pageSize*2 { return fmt.Errorf("file size too small") } // Ensure the size is at least the minimum size. var size = int(info.Size()) if size < minsz { size = minsz } size, err = db.mmapSize(size) if err != nil { return err } // Dereference all mmap references before unmapping. if db.rwtx != nil { db.rwtx.root.dereference() } // Unmap existing data before continuing. if err := db.munmap(); err != nil { return err } // Memory-map the data file as a byte slice. if err := mmap(db, size); err != nil { return err } // Save references to the meta pages. db.meta0 = db.page(0).meta() db.meta1 = db.page(1).meta() // Validate the meta pages. We only return an error if both meta pages fail // validation, since meta0 failing validation means that it wasn't saved // properly -- but we can recover using meta1. And vice-versa. err0 := db.meta0.validate() err1 := db.meta1.validate() if err0 != nil && err1 != nil { return err0 } return nil }
[ "func", "(", "db", "*", "DB", ")", "mmap", "(", "minsz", "int", ")", "error", "{", "db", ".", "mmaplock", ".", "Lock", "(", ")", "\n", "defer", "db", ".", "mmaplock", ".", "Unlock", "(", ")", "\n\n", "info", ",", "err", ":=", "db", ".", "file", ".", "Stat", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "else", "if", "int", "(", "info", ".", "Size", "(", ")", ")", "<", "db", ".", "pageSize", "*", "2", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Ensure the size is at least the minimum size.", "var", "size", "=", "int", "(", "info", ".", "Size", "(", ")", ")", "\n", "if", "size", "<", "minsz", "{", "size", "=", "minsz", "\n", "}", "\n", "size", ",", "err", "=", "db", ".", "mmapSize", "(", "size", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Dereference all mmap references before unmapping.", "if", "db", ".", "rwtx", "!=", "nil", "{", "db", ".", "rwtx", ".", "root", ".", "dereference", "(", ")", "\n", "}", "\n\n", "// Unmap existing data before continuing.", "if", "err", ":=", "db", ".", "munmap", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Memory-map the data file as a byte slice.", "if", "err", ":=", "mmap", "(", "db", ",", "size", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Save references to the meta pages.", "db", ".", "meta0", "=", "db", ".", "page", "(", "0", ")", ".", "meta", "(", ")", "\n", "db", ".", "meta1", "=", "db", ".", "page", "(", "1", ")", ".", "meta", "(", ")", "\n\n", "// Validate the meta pages. We only return an error if both meta pages fail", "// validation, since meta0 failing validation means that it wasn't saved", "// properly -- but we can recover using meta1. And vice-versa.", "err0", ":=", "db", ".", "meta0", ".", "validate", "(", ")", "\n", "err1", ":=", "db", ".", "meta1", ".", "validate", "(", ")", "\n", "if", "err0", "!=", "nil", "&&", "err1", "!=", "nil", "{", "return", "err0", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// mmap opens the underlying memory-mapped file and initializes the meta references. // minsz is the minimum size that the new mmap can be.
[ "mmap", "opens", "the", "underlying", "memory", "-", "mapped", "file", "and", "initializes", "the", "meta", "references", ".", "minsz", "is", "the", "minimum", "size", "that", "the", "new", "mmap", "can", "be", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/db.go#L245-L295
train
boltdb/bolt
db.go
munmap
func (db *DB) munmap() error { if err := munmap(db); err != nil { return fmt.Errorf("unmap error: " + err.Error()) } return nil }
go
func (db *DB) munmap() error { if err := munmap(db); err != nil { return fmt.Errorf("unmap error: " + err.Error()) } return nil }
[ "func", "(", "db", "*", "DB", ")", "munmap", "(", ")", "error", "{", "if", "err", ":=", "munmap", "(", "db", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// munmap unmaps the data file from memory.
[ "munmap", "unmaps", "the", "data", "file", "from", "memory", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/db.go#L298-L303
train
boltdb/bolt
db.go
mmapSize
func (db *DB) mmapSize(size int) (int, error) { // Double the size from 32KB until 1GB. for i := uint(15); i <= 30; i++ { if size <= 1<<i { return 1 << i, nil } } // Verify the requested size is not above the maximum allowed. if size > maxMapSize { return 0, fmt.Errorf("mmap too large") } // If larger than 1GB then grow by 1GB at a time. sz := int64(size) if remainder := sz % int64(maxMmapStep); remainder > 0 { sz += int64(maxMmapStep) - remainder } // Ensure that the mmap size is a multiple of the page size. // This should always be true since we're incrementing in MBs. pageSize := int64(db.pageSize) if (sz % pageSize) != 0 { sz = ((sz / pageSize) + 1) * pageSize } // If we've exceeded the max size then only grow up to the max size. if sz > maxMapSize { sz = maxMapSize } return int(sz), nil }
go
func (db *DB) mmapSize(size int) (int, error) { // Double the size from 32KB until 1GB. for i := uint(15); i <= 30; i++ { if size <= 1<<i { return 1 << i, nil } } // Verify the requested size is not above the maximum allowed. if size > maxMapSize { return 0, fmt.Errorf("mmap too large") } // If larger than 1GB then grow by 1GB at a time. sz := int64(size) if remainder := sz % int64(maxMmapStep); remainder > 0 { sz += int64(maxMmapStep) - remainder } // Ensure that the mmap size is a multiple of the page size. // This should always be true since we're incrementing in MBs. pageSize := int64(db.pageSize) if (sz % pageSize) != 0 { sz = ((sz / pageSize) + 1) * pageSize } // If we've exceeded the max size then only grow up to the max size. if sz > maxMapSize { sz = maxMapSize } return int(sz), nil }
[ "func", "(", "db", "*", "DB", ")", "mmapSize", "(", "size", "int", ")", "(", "int", ",", "error", ")", "{", "// Double the size from 32KB until 1GB.", "for", "i", ":=", "uint", "(", "15", ")", ";", "i", "<=", "30", ";", "i", "++", "{", "if", "size", "<=", "1", "<<", "i", "{", "return", "1", "<<", "i", ",", "nil", "\n", "}", "\n", "}", "\n\n", "// Verify the requested size is not above the maximum allowed.", "if", "size", ">", "maxMapSize", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// If larger than 1GB then grow by 1GB at a time.", "sz", ":=", "int64", "(", "size", ")", "\n", "if", "remainder", ":=", "sz", "%", "int64", "(", "maxMmapStep", ")", ";", "remainder", ">", "0", "{", "sz", "+=", "int64", "(", "maxMmapStep", ")", "-", "remainder", "\n", "}", "\n\n", "// Ensure that the mmap size is a multiple of the page size.", "// This should always be true since we're incrementing in MBs.", "pageSize", ":=", "int64", "(", "db", ".", "pageSize", ")", "\n", "if", "(", "sz", "%", "pageSize", ")", "!=", "0", "{", "sz", "=", "(", "(", "sz", "/", "pageSize", ")", "+", "1", ")", "*", "pageSize", "\n", "}", "\n\n", "// If we've exceeded the max size then only grow up to the max size.", "if", "sz", ">", "maxMapSize", "{", "sz", "=", "maxMapSize", "\n", "}", "\n\n", "return", "int", "(", "sz", ")", ",", "nil", "\n", "}" ]
// mmapSize determines the appropriate size for the mmap given the current size // of the database. The minimum size is 32KB and doubles until it reaches 1GB. // Returns an error if the new mmap size is greater than the max allowed.
[ "mmapSize", "determines", "the", "appropriate", "size", "for", "the", "mmap", "given", "the", "current", "size", "of", "the", "database", ".", "The", "minimum", "size", "is", "32KB", "and", "doubles", "until", "it", "reaches", "1GB", ".", "Returns", "an", "error", "if", "the", "new", "mmap", "size", "is", "greater", "than", "the", "max", "allowed", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/db.go#L308-L340
train
boltdb/bolt
db.go
init
func (db *DB) init() error { // Set the page size to the OS page size. db.pageSize = os.Getpagesize() // Create two meta pages on a buffer. buf := make([]byte, db.pageSize*4) for i := 0; i < 2; i++ { p := db.pageInBuffer(buf[:], pgid(i)) p.id = pgid(i) p.flags = metaPageFlag // Initialize the meta page. m := p.meta() m.magic = magic m.version = version m.pageSize = uint32(db.pageSize) m.freelist = 2 m.root = bucket{root: 3} m.pgid = 4 m.txid = txid(i) m.checksum = m.sum64() } // Write an empty freelist at page 3. p := db.pageInBuffer(buf[:], pgid(2)) p.id = pgid(2) p.flags = freelistPageFlag p.count = 0 // Write an empty leaf page at page 4. p = db.pageInBuffer(buf[:], pgid(3)) p.id = pgid(3) p.flags = leafPageFlag p.count = 0 // Write the buffer to our data file. if _, err := db.ops.writeAt(buf, 0); err != nil { return err } if err := fdatasync(db); err != nil { return err } return nil }
go
func (db *DB) init() error { // Set the page size to the OS page size. db.pageSize = os.Getpagesize() // Create two meta pages on a buffer. buf := make([]byte, db.pageSize*4) for i := 0; i < 2; i++ { p := db.pageInBuffer(buf[:], pgid(i)) p.id = pgid(i) p.flags = metaPageFlag // Initialize the meta page. m := p.meta() m.magic = magic m.version = version m.pageSize = uint32(db.pageSize) m.freelist = 2 m.root = bucket{root: 3} m.pgid = 4 m.txid = txid(i) m.checksum = m.sum64() } // Write an empty freelist at page 3. p := db.pageInBuffer(buf[:], pgid(2)) p.id = pgid(2) p.flags = freelistPageFlag p.count = 0 // Write an empty leaf page at page 4. p = db.pageInBuffer(buf[:], pgid(3)) p.id = pgid(3) p.flags = leafPageFlag p.count = 0 // Write the buffer to our data file. if _, err := db.ops.writeAt(buf, 0); err != nil { return err } if err := fdatasync(db); err != nil { return err } return nil }
[ "func", "(", "db", "*", "DB", ")", "init", "(", ")", "error", "{", "// Set the page size to the OS page size.", "db", ".", "pageSize", "=", "os", ".", "Getpagesize", "(", ")", "\n\n", "// Create two meta pages on a buffer.", "buf", ":=", "make", "(", "[", "]", "byte", ",", "db", ".", "pageSize", "*", "4", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "2", ";", "i", "++", "{", "p", ":=", "db", ".", "pageInBuffer", "(", "buf", "[", ":", "]", ",", "pgid", "(", "i", ")", ")", "\n", "p", ".", "id", "=", "pgid", "(", "i", ")", "\n", "p", ".", "flags", "=", "metaPageFlag", "\n\n", "// Initialize the meta page.", "m", ":=", "p", ".", "meta", "(", ")", "\n", "m", ".", "magic", "=", "magic", "\n", "m", ".", "version", "=", "version", "\n", "m", ".", "pageSize", "=", "uint32", "(", "db", ".", "pageSize", ")", "\n", "m", ".", "freelist", "=", "2", "\n", "m", ".", "root", "=", "bucket", "{", "root", ":", "3", "}", "\n", "m", ".", "pgid", "=", "4", "\n", "m", ".", "txid", "=", "txid", "(", "i", ")", "\n", "m", ".", "checksum", "=", "m", ".", "sum64", "(", ")", "\n", "}", "\n\n", "// Write an empty freelist at page 3.", "p", ":=", "db", ".", "pageInBuffer", "(", "buf", "[", ":", "]", ",", "pgid", "(", "2", ")", ")", "\n", "p", ".", "id", "=", "pgid", "(", "2", ")", "\n", "p", ".", "flags", "=", "freelistPageFlag", "\n", "p", ".", "count", "=", "0", "\n\n", "// Write an empty leaf page at page 4.", "p", "=", "db", ".", "pageInBuffer", "(", "buf", "[", ":", "]", ",", "pgid", "(", "3", ")", ")", "\n", "p", ".", "id", "=", "pgid", "(", "3", ")", "\n", "p", ".", "flags", "=", "leafPageFlag", "\n", "p", ".", "count", "=", "0", "\n\n", "// Write the buffer to our data file.", "if", "_", ",", "err", ":=", "db", ".", "ops", ".", "writeAt", "(", "buf", ",", "0", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "fdatasync", "(", "db", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// init creates a new database file and initializes its meta pages.
[ "init", "creates", "a", "new", "database", "file", "and", "initializes", "its", "meta", "pages", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/db.go#L343-L387
train
boltdb/bolt
db.go
removeTx
func (db *DB) removeTx(tx *Tx) { // Release the read lock on the mmap. db.mmaplock.RUnlock() // Use the meta lock to restrict access to the DB object. db.metalock.Lock() // Remove the transaction. for i, t := range db.txs { if t == tx { last := len(db.txs) - 1 db.txs[i] = db.txs[last] db.txs[last] = nil db.txs = db.txs[:last] break } } n := len(db.txs) // Unlock the meta pages. db.metalock.Unlock() // Merge statistics. db.statlock.Lock() db.stats.OpenTxN = n db.stats.TxStats.add(&tx.stats) db.statlock.Unlock() }
go
func (db *DB) removeTx(tx *Tx) { // Release the read lock on the mmap. db.mmaplock.RUnlock() // Use the meta lock to restrict access to the DB object. db.metalock.Lock() // Remove the transaction. for i, t := range db.txs { if t == tx { last := len(db.txs) - 1 db.txs[i] = db.txs[last] db.txs[last] = nil db.txs = db.txs[:last] break } } n := len(db.txs) // Unlock the meta pages. db.metalock.Unlock() // Merge statistics. db.statlock.Lock() db.stats.OpenTxN = n db.stats.TxStats.add(&tx.stats) db.statlock.Unlock() }
[ "func", "(", "db", "*", "DB", ")", "removeTx", "(", "tx", "*", "Tx", ")", "{", "// Release the read lock on the mmap.", "db", ".", "mmaplock", ".", "RUnlock", "(", ")", "\n\n", "// Use the meta lock to restrict access to the DB object.", "db", ".", "metalock", ".", "Lock", "(", ")", "\n\n", "// Remove the transaction.", "for", "i", ",", "t", ":=", "range", "db", ".", "txs", "{", "if", "t", "==", "tx", "{", "last", ":=", "len", "(", "db", ".", "txs", ")", "-", "1", "\n", "db", ".", "txs", "[", "i", "]", "=", "db", ".", "txs", "[", "last", "]", "\n", "db", ".", "txs", "[", "last", "]", "=", "nil", "\n", "db", ".", "txs", "=", "db", ".", "txs", "[", ":", "last", "]", "\n", "break", "\n", "}", "\n", "}", "\n", "n", ":=", "len", "(", "db", ".", "txs", ")", "\n\n", "// Unlock the meta pages.", "db", ".", "metalock", ".", "Unlock", "(", ")", "\n\n", "// Merge statistics.", "db", ".", "statlock", ".", "Lock", "(", ")", "\n", "db", ".", "stats", ".", "OpenTxN", "=", "n", "\n", "db", ".", "stats", ".", "TxStats", ".", "add", "(", "&", "tx", ".", "stats", ")", "\n", "db", ".", "statlock", ".", "Unlock", "(", ")", "\n", "}" ]
// removeTx removes a transaction from the database.
[ "removeTx", "removes", "a", "transaction", "from", "the", "database", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/db.go#L545-L572
train
boltdb/bolt
db.go
run
func (b *batch) run() { b.db.batchMu.Lock() b.timer.Stop() // Make sure no new work is added to this batch, but don't break // other batches. if b.db.batch == b { b.db.batch = nil } b.db.batchMu.Unlock() retry: for len(b.calls) > 0 { var failIdx = -1 err := b.db.Update(func(tx *Tx) error { for i, c := range b.calls { if err := safelyCall(c.fn, tx); err != nil { failIdx = i return err } } return nil }) if failIdx >= 0 { // take the failing transaction out of the batch. it's // safe to shorten b.calls here because db.batch no longer // points to us, and we hold the mutex anyway. c := b.calls[failIdx] b.calls[failIdx], b.calls = b.calls[len(b.calls)-1], b.calls[:len(b.calls)-1] // tell the submitter re-run it solo, continue with the rest of the batch c.err <- trySolo continue retry } // pass success, or bolt internal errors, to all callers for _, c := range b.calls { c.err <- err } break retry } }
go
func (b *batch) run() { b.db.batchMu.Lock() b.timer.Stop() // Make sure no new work is added to this batch, but don't break // other batches. if b.db.batch == b { b.db.batch = nil } b.db.batchMu.Unlock() retry: for len(b.calls) > 0 { var failIdx = -1 err := b.db.Update(func(tx *Tx) error { for i, c := range b.calls { if err := safelyCall(c.fn, tx); err != nil { failIdx = i return err } } return nil }) if failIdx >= 0 { // take the failing transaction out of the batch. it's // safe to shorten b.calls here because db.batch no longer // points to us, and we hold the mutex anyway. c := b.calls[failIdx] b.calls[failIdx], b.calls = b.calls[len(b.calls)-1], b.calls[:len(b.calls)-1] // tell the submitter re-run it solo, continue with the rest of the batch c.err <- trySolo continue retry } // pass success, or bolt internal errors, to all callers for _, c := range b.calls { c.err <- err } break retry } }
[ "func", "(", "b", "*", "batch", ")", "run", "(", ")", "{", "b", ".", "db", ".", "batchMu", ".", "Lock", "(", ")", "\n", "b", ".", "timer", ".", "Stop", "(", ")", "\n", "// Make sure no new work is added to this batch, but don't break", "// other batches.", "if", "b", ".", "db", ".", "batch", "==", "b", "{", "b", ".", "db", ".", "batch", "=", "nil", "\n", "}", "\n", "b", ".", "db", ".", "batchMu", ".", "Unlock", "(", ")", "\n\n", "retry", ":", "for", "len", "(", "b", ".", "calls", ")", ">", "0", "{", "var", "failIdx", "=", "-", "1", "\n", "err", ":=", "b", ".", "db", ".", "Update", "(", "func", "(", "tx", "*", "Tx", ")", "error", "{", "for", "i", ",", "c", ":=", "range", "b", ".", "calls", "{", "if", "err", ":=", "safelyCall", "(", "c", ".", "fn", ",", "tx", ")", ";", "err", "!=", "nil", "{", "failIdx", "=", "i", "\n", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n\n", "if", "failIdx", ">=", "0", "{", "// take the failing transaction out of the batch. it's", "// safe to shorten b.calls here because db.batch no longer", "// points to us, and we hold the mutex anyway.", "c", ":=", "b", ".", "calls", "[", "failIdx", "]", "\n", "b", ".", "calls", "[", "failIdx", "]", ",", "b", ".", "calls", "=", "b", ".", "calls", "[", "len", "(", "b", ".", "calls", ")", "-", "1", "]", ",", "b", ".", "calls", "[", ":", "len", "(", "b", ".", "calls", ")", "-", "1", "]", "\n", "// tell the submitter re-run it solo, continue with the rest of the batch", "c", ".", "err", "<-", "trySolo", "\n", "continue", "retry", "\n", "}", "\n\n", "// pass success, or bolt internal errors, to all callers", "for", "_", ",", "c", ":=", "range", "b", ".", "calls", "{", "c", ".", "err", "<-", "err", "\n", "}", "\n", "break", "retry", "\n", "}", "\n", "}" ]
// run performs the transactions in the batch and communicates results // back to DB.Batch.
[ "run", "performs", "the", "transactions", "in", "the", "batch", "and", "communicates", "results", "back", "to", "DB", ".", "Batch", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/db.go#L704-L744
train
boltdb/bolt
db.go
Stats
func (db *DB) Stats() Stats { db.statlock.RLock() defer db.statlock.RUnlock() return db.stats }
go
func (db *DB) Stats() Stats { db.statlock.RLock() defer db.statlock.RUnlock() return db.stats }
[ "func", "(", "db", "*", "DB", ")", "Stats", "(", ")", "Stats", "{", "db", ".", "statlock", ".", "RLock", "(", ")", "\n", "defer", "db", ".", "statlock", ".", "RUnlock", "(", ")", "\n", "return", "db", ".", "stats", "\n", "}" ]
// Stats retrieves ongoing performance stats for the database. // This is only updated when a transaction closes.
[ "Stats", "retrieves", "ongoing", "performance", "stats", "for", "the", "database", ".", "This", "is", "only", "updated", "when", "a", "transaction", "closes", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/db.go#L779-L783
train
boltdb/bolt
db.go
Info
func (db *DB) Info() *Info { return &Info{uintptr(unsafe.Pointer(&db.data[0])), db.pageSize} }
go
func (db *DB) Info() *Info { return &Info{uintptr(unsafe.Pointer(&db.data[0])), db.pageSize} }
[ "func", "(", "db", "*", "DB", ")", "Info", "(", ")", "*", "Info", "{", "return", "&", "Info", "{", "uintptr", "(", "unsafe", ".", "Pointer", "(", "&", "db", ".", "data", "[", "0", "]", ")", ")", ",", "db", ".", "pageSize", "}", "\n", "}" ]
// This is for internal access to the raw data bytes from the C cursor, use // carefully, or not at all.
[ "This", "is", "for", "internal", "access", "to", "the", "raw", "data", "bytes", "from", "the", "C", "cursor", "use", "carefully", "or", "not", "at", "all", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/db.go#L787-L789
train
boltdb/bolt
db.go
page
func (db *DB) page(id pgid) *page { pos := id * pgid(db.pageSize) return (*page)(unsafe.Pointer(&db.data[pos])) }
go
func (db *DB) page(id pgid) *page { pos := id * pgid(db.pageSize) return (*page)(unsafe.Pointer(&db.data[pos])) }
[ "func", "(", "db", "*", "DB", ")", "page", "(", "id", "pgid", ")", "*", "page", "{", "pos", ":=", "id", "*", "pgid", "(", "db", ".", "pageSize", ")", "\n", "return", "(", "*", "page", ")", "(", "unsafe", ".", "Pointer", "(", "&", "db", ".", "data", "[", "pos", "]", ")", ")", "\n", "}" ]
// page retrieves a page reference from the mmap based on the current page size.
[ "page", "retrieves", "a", "page", "reference", "from", "the", "mmap", "based", "on", "the", "current", "page", "size", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/db.go#L792-L795
train
boltdb/bolt
db.go
pageInBuffer
func (db *DB) pageInBuffer(b []byte, id pgid) *page { return (*page)(unsafe.Pointer(&b[id*pgid(db.pageSize)])) }
go
func (db *DB) pageInBuffer(b []byte, id pgid) *page { return (*page)(unsafe.Pointer(&b[id*pgid(db.pageSize)])) }
[ "func", "(", "db", "*", "DB", ")", "pageInBuffer", "(", "b", "[", "]", "byte", ",", "id", "pgid", ")", "*", "page", "{", "return", "(", "*", "page", ")", "(", "unsafe", ".", "Pointer", "(", "&", "b", "[", "id", "*", "pgid", "(", "db", ".", "pageSize", ")", "]", ")", ")", "\n", "}" ]
// pageInBuffer retrieves a page reference from a given byte array based on the current page size.
[ "pageInBuffer", "retrieves", "a", "page", "reference", "from", "a", "given", "byte", "array", "based", "on", "the", "current", "page", "size", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/db.go#L798-L800
train
boltdb/bolt
db.go
meta
func (db *DB) meta() *meta { // We have to return the meta with the highest txid which doesn't fail // validation. Otherwise, we can cause errors when in fact the database is // in a consistent state. metaA is the one with the higher txid. metaA := db.meta0 metaB := db.meta1 if db.meta1.txid > db.meta0.txid { metaA = db.meta1 metaB = db.meta0 } // Use higher meta page if valid. Otherwise fallback to previous, if valid. if err := metaA.validate(); err == nil { return metaA } else if err := metaB.validate(); err == nil { return metaB } // This should never be reached, because both meta1 and meta0 were validated // on mmap() and we do fsync() on every write. panic("bolt.DB.meta(): invalid meta pages") }
go
func (db *DB) meta() *meta { // We have to return the meta with the highest txid which doesn't fail // validation. Otherwise, we can cause errors when in fact the database is // in a consistent state. metaA is the one with the higher txid. metaA := db.meta0 metaB := db.meta1 if db.meta1.txid > db.meta0.txid { metaA = db.meta1 metaB = db.meta0 } // Use higher meta page if valid. Otherwise fallback to previous, if valid. if err := metaA.validate(); err == nil { return metaA } else if err := metaB.validate(); err == nil { return metaB } // This should never be reached, because both meta1 and meta0 were validated // on mmap() and we do fsync() on every write. panic("bolt.DB.meta(): invalid meta pages") }
[ "func", "(", "db", "*", "DB", ")", "meta", "(", ")", "*", "meta", "{", "// We have to return the meta with the highest txid which doesn't fail", "// validation. Otherwise, we can cause errors when in fact the database is", "// in a consistent state. metaA is the one with the higher txid.", "metaA", ":=", "db", ".", "meta0", "\n", "metaB", ":=", "db", ".", "meta1", "\n", "if", "db", ".", "meta1", ".", "txid", ">", "db", ".", "meta0", ".", "txid", "{", "metaA", "=", "db", ".", "meta1", "\n", "metaB", "=", "db", ".", "meta0", "\n", "}", "\n\n", "// Use higher meta page if valid. Otherwise fallback to previous, if valid.", "if", "err", ":=", "metaA", ".", "validate", "(", ")", ";", "err", "==", "nil", "{", "return", "metaA", "\n", "}", "else", "if", "err", ":=", "metaB", ".", "validate", "(", ")", ";", "err", "==", "nil", "{", "return", "metaB", "\n", "}", "\n\n", "// This should never be reached, because both meta1 and meta0 were validated", "// on mmap() and we do fsync() on every write.", "panic", "(", "\"", "\"", ")", "\n", "}" ]
// meta retrieves the current meta page reference.
[ "meta", "retrieves", "the", "current", "meta", "page", "reference", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/db.go#L803-L824
train
boltdb/bolt
db.go
grow
func (db *DB) grow(sz int) error { // Ignore if the new size is less than available file size. if sz <= db.filesz { return nil } // If the data is smaller than the alloc size then only allocate what's needed. // Once it goes over the allocation size then allocate in chunks. if db.datasz < db.AllocSize { sz = db.datasz } else { sz += db.AllocSize } // Truncate and fsync to ensure file size metadata is flushed. // https://github.com/boltdb/bolt/issues/284 if !db.NoGrowSync && !db.readOnly { if runtime.GOOS != "windows" { if err := db.file.Truncate(int64(sz)); err != nil { return fmt.Errorf("file resize error: %s", err) } } if err := db.file.Sync(); err != nil { return fmt.Errorf("file sync error: %s", err) } } db.filesz = sz return nil }
go
func (db *DB) grow(sz int) error { // Ignore if the new size is less than available file size. if sz <= db.filesz { return nil } // If the data is smaller than the alloc size then only allocate what's needed. // Once it goes over the allocation size then allocate in chunks. if db.datasz < db.AllocSize { sz = db.datasz } else { sz += db.AllocSize } // Truncate and fsync to ensure file size metadata is flushed. // https://github.com/boltdb/bolt/issues/284 if !db.NoGrowSync && !db.readOnly { if runtime.GOOS != "windows" { if err := db.file.Truncate(int64(sz)); err != nil { return fmt.Errorf("file resize error: %s", err) } } if err := db.file.Sync(); err != nil { return fmt.Errorf("file sync error: %s", err) } } db.filesz = sz return nil }
[ "func", "(", "db", "*", "DB", ")", "grow", "(", "sz", "int", ")", "error", "{", "// Ignore if the new size is less than available file size.", "if", "sz", "<=", "db", ".", "filesz", "{", "return", "nil", "\n", "}", "\n\n", "// If the data is smaller than the alloc size then only allocate what's needed.", "// Once it goes over the allocation size then allocate in chunks.", "if", "db", ".", "datasz", "<", "db", ".", "AllocSize", "{", "sz", "=", "db", ".", "datasz", "\n", "}", "else", "{", "sz", "+=", "db", ".", "AllocSize", "\n", "}", "\n\n", "// Truncate and fsync to ensure file size metadata is flushed.", "// https://github.com/boltdb/bolt/issues/284", "if", "!", "db", ".", "NoGrowSync", "&&", "!", "db", ".", "readOnly", "{", "if", "runtime", ".", "GOOS", "!=", "\"", "\"", "{", "if", "err", ":=", "db", ".", "file", ".", "Truncate", "(", "int64", "(", "sz", ")", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "db", ".", "file", ".", "Sync", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "db", ".", "filesz", "=", "sz", "\n", "return", "nil", "\n", "}" ]
// grow grows the size of the database to the given sz.
[ "grow", "grows", "the", "size", "of", "the", "database", "to", "the", "given", "sz", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/db.go#L859-L888
train
boltdb/bolt
db.go
Sub
func (s *Stats) Sub(other *Stats) Stats { if other == nil { return *s } var diff Stats diff.FreePageN = s.FreePageN diff.PendingPageN = s.PendingPageN diff.FreeAlloc = s.FreeAlloc diff.FreelistInuse = s.FreelistInuse diff.TxN = s.TxN - other.TxN diff.TxStats = s.TxStats.Sub(&other.TxStats) return diff }
go
func (s *Stats) Sub(other *Stats) Stats { if other == nil { return *s } var diff Stats diff.FreePageN = s.FreePageN diff.PendingPageN = s.PendingPageN diff.FreeAlloc = s.FreeAlloc diff.FreelistInuse = s.FreelistInuse diff.TxN = s.TxN - other.TxN diff.TxStats = s.TxStats.Sub(&other.TxStats) return diff }
[ "func", "(", "s", "*", "Stats", ")", "Sub", "(", "other", "*", "Stats", ")", "Stats", "{", "if", "other", "==", "nil", "{", "return", "*", "s", "\n", "}", "\n", "var", "diff", "Stats", "\n", "diff", ".", "FreePageN", "=", "s", ".", "FreePageN", "\n", "diff", ".", "PendingPageN", "=", "s", ".", "PendingPageN", "\n", "diff", ".", "FreeAlloc", "=", "s", ".", "FreeAlloc", "\n", "diff", ".", "FreelistInuse", "=", "s", ".", "FreelistInuse", "\n", "diff", ".", "TxN", "=", "s", ".", "TxN", "-", "other", ".", "TxN", "\n", "diff", ".", "TxStats", "=", "s", ".", "TxStats", ".", "Sub", "(", "&", "other", ".", "TxStats", ")", "\n", "return", "diff", "\n", "}" ]
// Sub calculates and returns the difference between two sets of database stats. // This is useful when obtaining stats at two different points and time and // you need the performance counters that occurred within that time span.
[ "Sub", "calculates", "and", "returns", "the", "difference", "between", "two", "sets", "of", "database", "stats", ".", "This", "is", "useful", "when", "obtaining", "stats", "at", "two", "different", "points", "and", "time", "and", "you", "need", "the", "performance", "counters", "that", "occurred", "within", "that", "time", "span", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/db.go#L947-L959
train
boltdb/bolt
db.go
validate
func (m *meta) validate() error { if m.magic != magic { return ErrInvalid } else if m.version != version { return ErrVersionMismatch } else if m.checksum != 0 && m.checksum != m.sum64() { return ErrChecksum } return nil }
go
func (m *meta) validate() error { if m.magic != magic { return ErrInvalid } else if m.version != version { return ErrVersionMismatch } else if m.checksum != 0 && m.checksum != m.sum64() { return ErrChecksum } return nil }
[ "func", "(", "m", "*", "meta", ")", "validate", "(", ")", "error", "{", "if", "m", ".", "magic", "!=", "magic", "{", "return", "ErrInvalid", "\n", "}", "else", "if", "m", ".", "version", "!=", "version", "{", "return", "ErrVersionMismatch", "\n", "}", "else", "if", "m", ".", "checksum", "!=", "0", "&&", "m", ".", "checksum", "!=", "m", ".", "sum64", "(", ")", "{", "return", "ErrChecksum", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// validate checks the marker bytes and version of the meta page to ensure it matches this binary.
[ "validate", "checks", "the", "marker", "bytes", "and", "version", "of", "the", "meta", "page", "to", "ensure", "it", "matches", "this", "binary", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/db.go#L983-L992
train
boltdb/bolt
db.go
write
func (m *meta) write(p *page) { if m.root.root >= m.pgid { panic(fmt.Sprintf("root bucket pgid (%d) above high water mark (%d)", m.root.root, m.pgid)) } else if m.freelist >= m.pgid { panic(fmt.Sprintf("freelist pgid (%d) above high water mark (%d)", m.freelist, m.pgid)) } // Page id is either going to be 0 or 1 which we can determine by the transaction ID. p.id = pgid(m.txid % 2) p.flags |= metaPageFlag // Calculate the checksum. m.checksum = m.sum64() m.copy(p.meta()) }
go
func (m *meta) write(p *page) { if m.root.root >= m.pgid { panic(fmt.Sprintf("root bucket pgid (%d) above high water mark (%d)", m.root.root, m.pgid)) } else if m.freelist >= m.pgid { panic(fmt.Sprintf("freelist pgid (%d) above high water mark (%d)", m.freelist, m.pgid)) } // Page id is either going to be 0 or 1 which we can determine by the transaction ID. p.id = pgid(m.txid % 2) p.flags |= metaPageFlag // Calculate the checksum. m.checksum = m.sum64() m.copy(p.meta()) }
[ "func", "(", "m", "*", "meta", ")", "write", "(", "p", "*", "page", ")", "{", "if", "m", ".", "root", ".", "root", ">=", "m", ".", "pgid", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "m", ".", "root", ".", "root", ",", "m", ".", "pgid", ")", ")", "\n", "}", "else", "if", "m", ".", "freelist", ">=", "m", ".", "pgid", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "m", ".", "freelist", ",", "m", ".", "pgid", ")", ")", "\n", "}", "\n\n", "// Page id is either going to be 0 or 1 which we can determine by the transaction ID.", "p", ".", "id", "=", "pgid", "(", "m", ".", "txid", "%", "2", ")", "\n", "p", ".", "flags", "|=", "metaPageFlag", "\n\n", "// Calculate the checksum.", "m", ".", "checksum", "=", "m", ".", "sum64", "(", ")", "\n\n", "m", ".", "copy", "(", "p", ".", "meta", "(", ")", ")", "\n", "}" ]
// write writes the meta onto a page.
[ "write", "writes", "the", "meta", "onto", "a", "page", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/db.go#L1000-L1015
train
boltdb/bolt
db.go
sum64
func (m *meta) sum64() uint64 { var h = fnv.New64a() _, _ = h.Write((*[unsafe.Offsetof(meta{}.checksum)]byte)(unsafe.Pointer(m))[:]) return h.Sum64() }
go
func (m *meta) sum64() uint64 { var h = fnv.New64a() _, _ = h.Write((*[unsafe.Offsetof(meta{}.checksum)]byte)(unsafe.Pointer(m))[:]) return h.Sum64() }
[ "func", "(", "m", "*", "meta", ")", "sum64", "(", ")", "uint64", "{", "var", "h", "=", "fnv", ".", "New64a", "(", ")", "\n", "_", ",", "_", "=", "h", ".", "Write", "(", "(", "*", "[", "unsafe", ".", "Offsetof", "(", "meta", "{", "}", ".", "checksum", ")", "]", "byte", ")", "(", "unsafe", ".", "Pointer", "(", "m", ")", ")", "[", ":", "]", ")", "\n", "return", "h", ".", "Sum64", "(", ")", "\n", "}" ]
// generates the checksum for the meta.
[ "generates", "the", "checksum", "for", "the", "meta", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/db.go#L1018-L1022
train
boltdb/bolt
tx.go
init
func (tx *Tx) init(db *DB) { tx.db = db tx.pages = nil // Copy the meta page since it can be changed by the writer. tx.meta = &meta{} db.meta().copy(tx.meta) // Copy over the root bucket. tx.root = newBucket(tx) tx.root.bucket = &bucket{} *tx.root.bucket = tx.meta.root // Increment the transaction id and add a page cache for writable transactions. if tx.writable { tx.pages = make(map[pgid]*page) tx.meta.txid += txid(1) } }
go
func (tx *Tx) init(db *DB) { tx.db = db tx.pages = nil // Copy the meta page since it can be changed by the writer. tx.meta = &meta{} db.meta().copy(tx.meta) // Copy over the root bucket. tx.root = newBucket(tx) tx.root.bucket = &bucket{} *tx.root.bucket = tx.meta.root // Increment the transaction id and add a page cache for writable transactions. if tx.writable { tx.pages = make(map[pgid]*page) tx.meta.txid += txid(1) } }
[ "func", "(", "tx", "*", "Tx", ")", "init", "(", "db", "*", "DB", ")", "{", "tx", ".", "db", "=", "db", "\n", "tx", ".", "pages", "=", "nil", "\n\n", "// Copy the meta page since it can be changed by the writer.", "tx", ".", "meta", "=", "&", "meta", "{", "}", "\n", "db", ".", "meta", "(", ")", ".", "copy", "(", "tx", ".", "meta", ")", "\n\n", "// Copy over the root bucket.", "tx", ".", "root", "=", "newBucket", "(", "tx", ")", "\n", "tx", ".", "root", ".", "bucket", "=", "&", "bucket", "{", "}", "\n", "*", "tx", ".", "root", ".", "bucket", "=", "tx", ".", "meta", ".", "root", "\n\n", "// Increment the transaction id and add a page cache for writable transactions.", "if", "tx", ".", "writable", "{", "tx", ".", "pages", "=", "make", "(", "map", "[", "pgid", "]", "*", "page", ")", "\n", "tx", ".", "meta", ".", "txid", "+=", "txid", "(", "1", ")", "\n", "}", "\n", "}" ]
// init initializes the transaction.
[ "init", "initializes", "the", "transaction", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/tx.go#L44-L62
train
boltdb/bolt
tx.go
Size
func (tx *Tx) Size() int64 { return int64(tx.meta.pgid) * int64(tx.db.pageSize) }
go
func (tx *Tx) Size() int64 { return int64(tx.meta.pgid) * int64(tx.db.pageSize) }
[ "func", "(", "tx", "*", "Tx", ")", "Size", "(", ")", "int64", "{", "return", "int64", "(", "tx", ".", "meta", ".", "pgid", ")", "*", "int64", "(", "tx", ".", "db", ".", "pageSize", ")", "\n", "}" ]
// Size returns current database size in bytes as seen by this transaction.
[ "Size", "returns", "current", "database", "size", "in", "bytes", "as", "seen", "by", "this", "transaction", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/tx.go#L75-L77
train
boltdb/bolt
tx.go
Bucket
func (tx *Tx) Bucket(name []byte) *Bucket { return tx.root.Bucket(name) }
go
func (tx *Tx) Bucket(name []byte) *Bucket { return tx.root.Bucket(name) }
[ "func", "(", "tx", "*", "Tx", ")", "Bucket", "(", "name", "[", "]", "byte", ")", "*", "Bucket", "{", "return", "tx", ".", "root", ".", "Bucket", "(", "name", ")", "\n", "}" ]
// Bucket retrieves a bucket by name. // Returns nil if the bucket does not exist. // The bucket instance is only valid for the lifetime of the transaction.
[ "Bucket", "retrieves", "a", "bucket", "by", "name", ".", "Returns", "nil", "if", "the", "bucket", "does", "not", "exist", ".", "The", "bucket", "instance", "is", "only", "valid", "for", "the", "lifetime", "of", "the", "transaction", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/tx.go#L100-L102
train
boltdb/bolt
tx.go
CreateBucket
func (tx *Tx) CreateBucket(name []byte) (*Bucket, error) { return tx.root.CreateBucket(name) }
go
func (tx *Tx) CreateBucket(name []byte) (*Bucket, error) { return tx.root.CreateBucket(name) }
[ "func", "(", "tx", "*", "Tx", ")", "CreateBucket", "(", "name", "[", "]", "byte", ")", "(", "*", "Bucket", ",", "error", ")", "{", "return", "tx", ".", "root", ".", "CreateBucket", "(", "name", ")", "\n", "}" ]
// CreateBucket creates a new bucket. // Returns an error if the bucket already exists, if the bucket name is blank, or if the bucket name is too long. // The bucket instance is only valid for the lifetime of the transaction.
[ "CreateBucket", "creates", "a", "new", "bucket", ".", "Returns", "an", "error", "if", "the", "bucket", "already", "exists", "if", "the", "bucket", "name", "is", "blank", "or", "if", "the", "bucket", "name", "is", "too", "long", ".", "The", "bucket", "instance", "is", "only", "valid", "for", "the", "lifetime", "of", "the", "transaction", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/tx.go#L107-L109
train
boltdb/bolt
tx.go
CreateBucketIfNotExists
func (tx *Tx) CreateBucketIfNotExists(name []byte) (*Bucket, error) { return tx.root.CreateBucketIfNotExists(name) }
go
func (tx *Tx) CreateBucketIfNotExists(name []byte) (*Bucket, error) { return tx.root.CreateBucketIfNotExists(name) }
[ "func", "(", "tx", "*", "Tx", ")", "CreateBucketIfNotExists", "(", "name", "[", "]", "byte", ")", "(", "*", "Bucket", ",", "error", ")", "{", "return", "tx", ".", "root", ".", "CreateBucketIfNotExists", "(", "name", ")", "\n", "}" ]
// CreateBucketIfNotExists creates a new bucket if it doesn't already exist. // Returns an error if the bucket name is blank, or if the bucket name is too long. // The bucket instance is only valid for the lifetime of the transaction.
[ "CreateBucketIfNotExists", "creates", "a", "new", "bucket", "if", "it", "doesn", "t", "already", "exist", ".", "Returns", "an", "error", "if", "the", "bucket", "name", "is", "blank", "or", "if", "the", "bucket", "name", "is", "too", "long", ".", "The", "bucket", "instance", "is", "only", "valid", "for", "the", "lifetime", "of", "the", "transaction", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/tx.go#L114-L116
train
boltdb/bolt
tx.go
DeleteBucket
func (tx *Tx) DeleteBucket(name []byte) error { return tx.root.DeleteBucket(name) }
go
func (tx *Tx) DeleteBucket(name []byte) error { return tx.root.DeleteBucket(name) }
[ "func", "(", "tx", "*", "Tx", ")", "DeleteBucket", "(", "name", "[", "]", "byte", ")", "error", "{", "return", "tx", ".", "root", ".", "DeleteBucket", "(", "name", ")", "\n", "}" ]
// DeleteBucket deletes a bucket. // Returns an error if the bucket cannot be found or if the key represents a non-bucket value.
[ "DeleteBucket", "deletes", "a", "bucket", ".", "Returns", "an", "error", "if", "the", "bucket", "cannot", "be", "found", "or", "if", "the", "key", "represents", "a", "non", "-", "bucket", "value", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/tx.go#L120-L122
train
boltdb/bolt
tx.go
ForEach
func (tx *Tx) ForEach(fn func(name []byte, b *Bucket) error) error { return tx.root.ForEach(func(k, v []byte) error { if err := fn(k, tx.root.Bucket(k)); err != nil { return err } return nil }) }
go
func (tx *Tx) ForEach(fn func(name []byte, b *Bucket) error) error { return tx.root.ForEach(func(k, v []byte) error { if err := fn(k, tx.root.Bucket(k)); err != nil { return err } return nil }) }
[ "func", "(", "tx", "*", "Tx", ")", "ForEach", "(", "fn", "func", "(", "name", "[", "]", "byte", ",", "b", "*", "Bucket", ")", "error", ")", "error", "{", "return", "tx", ".", "root", ".", "ForEach", "(", "func", "(", "k", ",", "v", "[", "]", "byte", ")", "error", "{", "if", "err", ":=", "fn", "(", "k", ",", "tx", ".", "root", ".", "Bucket", "(", "k", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "}" ]
// ForEach executes a function for each bucket in the root. // If the provided function returns an error then the iteration is stopped and // the error is returned to the caller.
[ "ForEach", "executes", "a", "function", "for", "each", "bucket", "in", "the", "root", ".", "If", "the", "provided", "function", "returns", "an", "error", "then", "the", "iteration", "is", "stopped", "and", "the", "error", "is", "returned", "to", "the", "caller", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/tx.go#L127-L134
train
boltdb/bolt
tx.go
OnCommit
func (tx *Tx) OnCommit(fn func()) { tx.commitHandlers = append(tx.commitHandlers, fn) }
go
func (tx *Tx) OnCommit(fn func()) { tx.commitHandlers = append(tx.commitHandlers, fn) }
[ "func", "(", "tx", "*", "Tx", ")", "OnCommit", "(", "fn", "func", "(", ")", ")", "{", "tx", ".", "commitHandlers", "=", "append", "(", "tx", ".", "commitHandlers", ",", "fn", ")", "\n", "}" ]
// OnCommit adds a handler function to be executed after the transaction successfully commits.
[ "OnCommit", "adds", "a", "handler", "function", "to", "be", "executed", "after", "the", "transaction", "successfully", "commits", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/tx.go#L137-L139
train
boltdb/bolt
tx.go
Commit
func (tx *Tx) Commit() error { _assert(!tx.managed, "managed tx commit not allowed") if tx.db == nil { return ErrTxClosed } else if !tx.writable { return ErrTxNotWritable } // TODO(benbjohnson): Use vectorized I/O to write out dirty pages. // Rebalance nodes which have had deletions. var startTime = time.Now() tx.root.rebalance() if tx.stats.Rebalance > 0 { tx.stats.RebalanceTime += time.Since(startTime) } // spill data onto dirty pages. startTime = time.Now() if err := tx.root.spill(); err != nil { tx.rollback() return err } tx.stats.SpillTime += time.Since(startTime) // Free the old root bucket. tx.meta.root.root = tx.root.root opgid := tx.meta.pgid // Free the freelist and allocate new pages for it. This will overestimate // the size of the freelist but not underestimate the size (which would be bad). tx.db.freelist.free(tx.meta.txid, tx.db.page(tx.meta.freelist)) p, err := tx.allocate((tx.db.freelist.size() / tx.db.pageSize) + 1) if err != nil { tx.rollback() return err } if err := tx.db.freelist.write(p); err != nil { tx.rollback() return err } tx.meta.freelist = p.id // If the high water mark has moved up then attempt to grow the database. if tx.meta.pgid > opgid { if err := tx.db.grow(int(tx.meta.pgid+1) * tx.db.pageSize); err != nil { tx.rollback() return err } } // Write dirty pages to disk. startTime = time.Now() if err := tx.write(); err != nil { tx.rollback() return err } // If strict mode is enabled then perform a consistency check. // Only the first consistency error is reported in the panic. if tx.db.StrictMode { ch := tx.Check() var errs []string for { err, ok := <-ch if !ok { break } errs = append(errs, err.Error()) } if len(errs) > 0 { panic("check fail: " + strings.Join(errs, "\n")) } } // Write meta to disk. if err := tx.writeMeta(); err != nil { tx.rollback() return err } tx.stats.WriteTime += time.Since(startTime) // Finalize the transaction. tx.close() // Execute commit handlers now that the locks have been removed. for _, fn := range tx.commitHandlers { fn() } return nil }
go
func (tx *Tx) Commit() error { _assert(!tx.managed, "managed tx commit not allowed") if tx.db == nil { return ErrTxClosed } else if !tx.writable { return ErrTxNotWritable } // TODO(benbjohnson): Use vectorized I/O to write out dirty pages. // Rebalance nodes which have had deletions. var startTime = time.Now() tx.root.rebalance() if tx.stats.Rebalance > 0 { tx.stats.RebalanceTime += time.Since(startTime) } // spill data onto dirty pages. startTime = time.Now() if err := tx.root.spill(); err != nil { tx.rollback() return err } tx.stats.SpillTime += time.Since(startTime) // Free the old root bucket. tx.meta.root.root = tx.root.root opgid := tx.meta.pgid // Free the freelist and allocate new pages for it. This will overestimate // the size of the freelist but not underestimate the size (which would be bad). tx.db.freelist.free(tx.meta.txid, tx.db.page(tx.meta.freelist)) p, err := tx.allocate((tx.db.freelist.size() / tx.db.pageSize) + 1) if err != nil { tx.rollback() return err } if err := tx.db.freelist.write(p); err != nil { tx.rollback() return err } tx.meta.freelist = p.id // If the high water mark has moved up then attempt to grow the database. if tx.meta.pgid > opgid { if err := tx.db.grow(int(tx.meta.pgid+1) * tx.db.pageSize); err != nil { tx.rollback() return err } } // Write dirty pages to disk. startTime = time.Now() if err := tx.write(); err != nil { tx.rollback() return err } // If strict mode is enabled then perform a consistency check. // Only the first consistency error is reported in the panic. if tx.db.StrictMode { ch := tx.Check() var errs []string for { err, ok := <-ch if !ok { break } errs = append(errs, err.Error()) } if len(errs) > 0 { panic("check fail: " + strings.Join(errs, "\n")) } } // Write meta to disk. if err := tx.writeMeta(); err != nil { tx.rollback() return err } tx.stats.WriteTime += time.Since(startTime) // Finalize the transaction. tx.close() // Execute commit handlers now that the locks have been removed. for _, fn := range tx.commitHandlers { fn() } return nil }
[ "func", "(", "tx", "*", "Tx", ")", "Commit", "(", ")", "error", "{", "_assert", "(", "!", "tx", ".", "managed", ",", "\"", "\"", ")", "\n", "if", "tx", ".", "db", "==", "nil", "{", "return", "ErrTxClosed", "\n", "}", "else", "if", "!", "tx", ".", "writable", "{", "return", "ErrTxNotWritable", "\n", "}", "\n\n", "// TODO(benbjohnson): Use vectorized I/O to write out dirty pages.", "// Rebalance nodes which have had deletions.", "var", "startTime", "=", "time", ".", "Now", "(", ")", "\n", "tx", ".", "root", ".", "rebalance", "(", ")", "\n", "if", "tx", ".", "stats", ".", "Rebalance", ">", "0", "{", "tx", ".", "stats", ".", "RebalanceTime", "+=", "time", ".", "Since", "(", "startTime", ")", "\n", "}", "\n\n", "// spill data onto dirty pages.", "startTime", "=", "time", ".", "Now", "(", ")", "\n", "if", "err", ":=", "tx", ".", "root", ".", "spill", "(", ")", ";", "err", "!=", "nil", "{", "tx", ".", "rollback", "(", ")", "\n", "return", "err", "\n", "}", "\n", "tx", ".", "stats", ".", "SpillTime", "+=", "time", ".", "Since", "(", "startTime", ")", "\n\n", "// Free the old root bucket.", "tx", ".", "meta", ".", "root", ".", "root", "=", "tx", ".", "root", ".", "root", "\n\n", "opgid", ":=", "tx", ".", "meta", ".", "pgid", "\n\n", "// Free the freelist and allocate new pages for it. This will overestimate", "// the size of the freelist but not underestimate the size (which would be bad).", "tx", ".", "db", ".", "freelist", ".", "free", "(", "tx", ".", "meta", ".", "txid", ",", "tx", ".", "db", ".", "page", "(", "tx", ".", "meta", ".", "freelist", ")", ")", "\n", "p", ",", "err", ":=", "tx", ".", "allocate", "(", "(", "tx", ".", "db", ".", "freelist", ".", "size", "(", ")", "/", "tx", ".", "db", ".", "pageSize", ")", "+", "1", ")", "\n", "if", "err", "!=", "nil", "{", "tx", ".", "rollback", "(", ")", "\n", "return", "err", "\n", "}", "\n", "if", "err", ":=", "tx", ".", "db", ".", "freelist", ".", "write", "(", "p", ")", ";", "err", "!=", "nil", "{", "tx", ".", "rollback", "(", ")", "\n", "return", "err", "\n", "}", "\n", "tx", ".", "meta", ".", "freelist", "=", "p", ".", "id", "\n\n", "// If the high water mark has moved up then attempt to grow the database.", "if", "tx", ".", "meta", ".", "pgid", ">", "opgid", "{", "if", "err", ":=", "tx", ".", "db", ".", "grow", "(", "int", "(", "tx", ".", "meta", ".", "pgid", "+", "1", ")", "*", "tx", ".", "db", ".", "pageSize", ")", ";", "err", "!=", "nil", "{", "tx", ".", "rollback", "(", ")", "\n", "return", "err", "\n", "}", "\n", "}", "\n\n", "// Write dirty pages to disk.", "startTime", "=", "time", ".", "Now", "(", ")", "\n", "if", "err", ":=", "tx", ".", "write", "(", ")", ";", "err", "!=", "nil", "{", "tx", ".", "rollback", "(", ")", "\n", "return", "err", "\n", "}", "\n\n", "// If strict mode is enabled then perform a consistency check.", "// Only the first consistency error is reported in the panic.", "if", "tx", ".", "db", ".", "StrictMode", "{", "ch", ":=", "tx", ".", "Check", "(", ")", "\n", "var", "errs", "[", "]", "string", "\n", "for", "{", "err", ",", "ok", ":=", "<-", "ch", "\n", "if", "!", "ok", "{", "break", "\n", "}", "\n", "errs", "=", "append", "(", "errs", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "if", "len", "(", "errs", ")", ">", "0", "{", "panic", "(", "\"", "\"", "+", "strings", ".", "Join", "(", "errs", ",", "\"", "\\n", "\"", ")", ")", "\n", "}", "\n", "}", "\n\n", "// Write meta to disk.", "if", "err", ":=", "tx", ".", "writeMeta", "(", ")", ";", "err", "!=", "nil", "{", "tx", ".", "rollback", "(", ")", "\n", "return", "err", "\n", "}", "\n", "tx", ".", "stats", ".", "WriteTime", "+=", "time", ".", "Since", "(", "startTime", ")", "\n\n", "// Finalize the transaction.", "tx", ".", "close", "(", ")", "\n\n", "// Execute commit handlers now that the locks have been removed.", "for", "_", ",", "fn", ":=", "range", "tx", ".", "commitHandlers", "{", "fn", "(", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Commit writes all changes to disk and updates the meta page. // Returns an error if a disk write error occurs, or if Commit is // called on a read-only transaction.
[ "Commit", "writes", "all", "changes", "to", "disk", "and", "updates", "the", "meta", "page", ".", "Returns", "an", "error", "if", "a", "disk", "write", "error", "occurs", "or", "if", "Commit", "is", "called", "on", "a", "read", "-", "only", "transaction", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/tx.go#L144-L236
train
boltdb/bolt
tx.go
Rollback
func (tx *Tx) Rollback() error { _assert(!tx.managed, "managed tx rollback not allowed") if tx.db == nil { return ErrTxClosed } tx.rollback() return nil }
go
func (tx *Tx) Rollback() error { _assert(!tx.managed, "managed tx rollback not allowed") if tx.db == nil { return ErrTxClosed } tx.rollback() return nil }
[ "func", "(", "tx", "*", "Tx", ")", "Rollback", "(", ")", "error", "{", "_assert", "(", "!", "tx", ".", "managed", ",", "\"", "\"", ")", "\n", "if", "tx", ".", "db", "==", "nil", "{", "return", "ErrTxClosed", "\n", "}", "\n", "tx", ".", "rollback", "(", ")", "\n", "return", "nil", "\n", "}" ]
// Rollback closes the transaction and ignores all previous updates. Read-only // transactions must be rolled back and not committed.
[ "Rollback", "closes", "the", "transaction", "and", "ignores", "all", "previous", "updates", ".", "Read", "-", "only", "transactions", "must", "be", "rolled", "back", "and", "not", "committed", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/tx.go#L240-L247
train
boltdb/bolt
tx.go
CopyFile
func (tx *Tx) CopyFile(path string, mode os.FileMode) error { f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, mode) if err != nil { return err } err = tx.Copy(f) if err != nil { _ = f.Close() return err } return f.Close() }
go
func (tx *Tx) CopyFile(path string, mode os.FileMode) error { f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, mode) if err != nil { return err } err = tx.Copy(f) if err != nil { _ = f.Close() return err } return f.Close() }
[ "func", "(", "tx", "*", "Tx", ")", "CopyFile", "(", "path", "string", ",", "mode", "os", ".", "FileMode", ")", "error", "{", "f", ",", "err", ":=", "os", ".", "OpenFile", "(", "path", ",", "os", ".", "O_RDWR", "|", "os", ".", "O_CREATE", "|", "os", ".", "O_TRUNC", ",", "mode", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "err", "=", "tx", ".", "Copy", "(", "f", ")", "\n", "if", "err", "!=", "nil", "{", "_", "=", "f", ".", "Close", "(", ")", "\n", "return", "err", "\n", "}", "\n", "return", "f", ".", "Close", "(", ")", "\n", "}" ]
// CopyFile copies the entire database to file at the given path. // A reader transaction is maintained during the copy so it is safe to continue // using the database while a copy is in progress.
[ "CopyFile", "copies", "the", "entire", "database", "to", "file", "at", "the", "given", "path", ".", "A", "reader", "transaction", "is", "maintained", "during", "the", "copy", "so", "it", "is", "safe", "to", "continue", "using", "the", "database", "while", "a", "copy", "is", "in", "progress", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/tx.go#L355-L367
train
boltdb/bolt
tx.go
Check
func (tx *Tx) Check() <-chan error { ch := make(chan error) go tx.check(ch) return ch }
go
func (tx *Tx) Check() <-chan error { ch := make(chan error) go tx.check(ch) return ch }
[ "func", "(", "tx", "*", "Tx", ")", "Check", "(", ")", "<-", "chan", "error", "{", "ch", ":=", "make", "(", "chan", "error", ")", "\n", "go", "tx", ".", "check", "(", "ch", ")", "\n", "return", "ch", "\n", "}" ]
// Check performs several consistency checks on the database for this transaction. // An error is returned if any inconsistency is found. // // It can be safely run concurrently on a writable transaction. However, this // incurs a high cost for large databases and databases with a lot of subbuckets // because of caching. This overhead can be removed if running on a read-only // transaction, however, it is not safe to execute other writer transactions at // the same time.
[ "Check", "performs", "several", "consistency", "checks", "on", "the", "database", "for", "this", "transaction", ".", "An", "error", "is", "returned", "if", "any", "inconsistency", "is", "found", ".", "It", "can", "be", "safely", "run", "concurrently", "on", "a", "writable", "transaction", ".", "However", "this", "incurs", "a", "high", "cost", "for", "large", "databases", "and", "databases", "with", "a", "lot", "of", "subbuckets", "because", "of", "caching", ".", "This", "overhead", "can", "be", "removed", "if", "running", "on", "a", "read", "-", "only", "transaction", "however", "it", "is", "not", "safe", "to", "execute", "other", "writer", "transactions", "at", "the", "same", "time", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/tx.go#L377-L381
train
boltdb/bolt
tx.go
write
func (tx *Tx) write() error { // Sort pages by id. pages := make(pages, 0, len(tx.pages)) for _, p := range tx.pages { pages = append(pages, p) } // Clear out page cache early. tx.pages = make(map[pgid]*page) sort.Sort(pages) // Write pages to disk in order. for _, p := range pages { size := (int(p.overflow) + 1) * tx.db.pageSize offset := int64(p.id) * int64(tx.db.pageSize) // Write out page in "max allocation" sized chunks. ptr := (*[maxAllocSize]byte)(unsafe.Pointer(p)) for { // Limit our write to our max allocation size. sz := size if sz > maxAllocSize-1 { sz = maxAllocSize - 1 } // Write chunk to disk. buf := ptr[:sz] if _, err := tx.db.ops.writeAt(buf, offset); err != nil { return err } // Update statistics. tx.stats.Write++ // Exit inner for loop if we've written all the chunks. size -= sz if size == 0 { break } // Otherwise move offset forward and move pointer to next chunk. offset += int64(sz) ptr = (*[maxAllocSize]byte)(unsafe.Pointer(&ptr[sz])) } } // Ignore file sync if flag is set on DB. if !tx.db.NoSync || IgnoreNoSync { if err := fdatasync(tx.db); err != nil { return err } } // Put small pages back to page pool. for _, p := range pages { // Ignore page sizes over 1 page. // These are allocated using make() instead of the page pool. if int(p.overflow) != 0 { continue } buf := (*[maxAllocSize]byte)(unsafe.Pointer(p))[:tx.db.pageSize] // See https://go.googlesource.com/go/+/f03c9202c43e0abb130669852082117ca50aa9b1 for i := range buf { buf[i] = 0 } tx.db.pagePool.Put(buf) } return nil }
go
func (tx *Tx) write() error { // Sort pages by id. pages := make(pages, 0, len(tx.pages)) for _, p := range tx.pages { pages = append(pages, p) } // Clear out page cache early. tx.pages = make(map[pgid]*page) sort.Sort(pages) // Write pages to disk in order. for _, p := range pages { size := (int(p.overflow) + 1) * tx.db.pageSize offset := int64(p.id) * int64(tx.db.pageSize) // Write out page in "max allocation" sized chunks. ptr := (*[maxAllocSize]byte)(unsafe.Pointer(p)) for { // Limit our write to our max allocation size. sz := size if sz > maxAllocSize-1 { sz = maxAllocSize - 1 } // Write chunk to disk. buf := ptr[:sz] if _, err := tx.db.ops.writeAt(buf, offset); err != nil { return err } // Update statistics. tx.stats.Write++ // Exit inner for loop if we've written all the chunks. size -= sz if size == 0 { break } // Otherwise move offset forward and move pointer to next chunk. offset += int64(sz) ptr = (*[maxAllocSize]byte)(unsafe.Pointer(&ptr[sz])) } } // Ignore file sync if flag is set on DB. if !tx.db.NoSync || IgnoreNoSync { if err := fdatasync(tx.db); err != nil { return err } } // Put small pages back to page pool. for _, p := range pages { // Ignore page sizes over 1 page. // These are allocated using make() instead of the page pool. if int(p.overflow) != 0 { continue } buf := (*[maxAllocSize]byte)(unsafe.Pointer(p))[:tx.db.pageSize] // See https://go.googlesource.com/go/+/f03c9202c43e0abb130669852082117ca50aa9b1 for i := range buf { buf[i] = 0 } tx.db.pagePool.Put(buf) } return nil }
[ "func", "(", "tx", "*", "Tx", ")", "write", "(", ")", "error", "{", "// Sort pages by id.", "pages", ":=", "make", "(", "pages", ",", "0", ",", "len", "(", "tx", ".", "pages", ")", ")", "\n", "for", "_", ",", "p", ":=", "range", "tx", ".", "pages", "{", "pages", "=", "append", "(", "pages", ",", "p", ")", "\n", "}", "\n", "// Clear out page cache early.", "tx", ".", "pages", "=", "make", "(", "map", "[", "pgid", "]", "*", "page", ")", "\n", "sort", ".", "Sort", "(", "pages", ")", "\n\n", "// Write pages to disk in order.", "for", "_", ",", "p", ":=", "range", "pages", "{", "size", ":=", "(", "int", "(", "p", ".", "overflow", ")", "+", "1", ")", "*", "tx", ".", "db", ".", "pageSize", "\n", "offset", ":=", "int64", "(", "p", ".", "id", ")", "*", "int64", "(", "tx", ".", "db", ".", "pageSize", ")", "\n\n", "// Write out page in \"max allocation\" sized chunks.", "ptr", ":=", "(", "*", "[", "maxAllocSize", "]", "byte", ")", "(", "unsafe", ".", "Pointer", "(", "p", ")", ")", "\n", "for", "{", "// Limit our write to our max allocation size.", "sz", ":=", "size", "\n", "if", "sz", ">", "maxAllocSize", "-", "1", "{", "sz", "=", "maxAllocSize", "-", "1", "\n", "}", "\n\n", "// Write chunk to disk.", "buf", ":=", "ptr", "[", ":", "sz", "]", "\n", "if", "_", ",", "err", ":=", "tx", ".", "db", ".", "ops", ".", "writeAt", "(", "buf", ",", "offset", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Update statistics.", "tx", ".", "stats", ".", "Write", "++", "\n\n", "// Exit inner for loop if we've written all the chunks.", "size", "-=", "sz", "\n", "if", "size", "==", "0", "{", "break", "\n", "}", "\n\n", "// Otherwise move offset forward and move pointer to next chunk.", "offset", "+=", "int64", "(", "sz", ")", "\n", "ptr", "=", "(", "*", "[", "maxAllocSize", "]", "byte", ")", "(", "unsafe", ".", "Pointer", "(", "&", "ptr", "[", "sz", "]", ")", ")", "\n", "}", "\n", "}", "\n\n", "// Ignore file sync if flag is set on DB.", "if", "!", "tx", ".", "db", ".", "NoSync", "||", "IgnoreNoSync", "{", "if", "err", ":=", "fdatasync", "(", "tx", ".", "db", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "// Put small pages back to page pool.", "for", "_", ",", "p", ":=", "range", "pages", "{", "// Ignore page sizes over 1 page.", "// These are allocated using make() instead of the page pool.", "if", "int", "(", "p", ".", "overflow", ")", "!=", "0", "{", "continue", "\n", "}", "\n\n", "buf", ":=", "(", "*", "[", "maxAllocSize", "]", "byte", ")", "(", "unsafe", ".", "Pointer", "(", "p", ")", ")", "[", ":", "tx", ".", "db", ".", "pageSize", "]", "\n\n", "// See https://go.googlesource.com/go/+/f03c9202c43e0abb130669852082117ca50aa9b1", "for", "i", ":=", "range", "buf", "{", "buf", "[", "i", "]", "=", "0", "\n", "}", "\n", "tx", ".", "db", ".", "pagePool", ".", "Put", "(", "buf", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// write writes any dirty pages to disk.
[ "write", "writes", "any", "dirty", "pages", "to", "disk", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/tx.go#L474-L544
train
boltdb/bolt
tx.go
writeMeta
func (tx *Tx) writeMeta() error { // Create a temporary buffer for the meta page. buf := make([]byte, tx.db.pageSize) p := tx.db.pageInBuffer(buf, 0) tx.meta.write(p) // Write the meta page to file. if _, err := tx.db.ops.writeAt(buf, int64(p.id)*int64(tx.db.pageSize)); err != nil { return err } if !tx.db.NoSync || IgnoreNoSync { if err := fdatasync(tx.db); err != nil { return err } } // Update statistics. tx.stats.Write++ return nil }
go
func (tx *Tx) writeMeta() error { // Create a temporary buffer for the meta page. buf := make([]byte, tx.db.pageSize) p := tx.db.pageInBuffer(buf, 0) tx.meta.write(p) // Write the meta page to file. if _, err := tx.db.ops.writeAt(buf, int64(p.id)*int64(tx.db.pageSize)); err != nil { return err } if !tx.db.NoSync || IgnoreNoSync { if err := fdatasync(tx.db); err != nil { return err } } // Update statistics. tx.stats.Write++ return nil }
[ "func", "(", "tx", "*", "Tx", ")", "writeMeta", "(", ")", "error", "{", "// Create a temporary buffer for the meta page.", "buf", ":=", "make", "(", "[", "]", "byte", ",", "tx", ".", "db", ".", "pageSize", ")", "\n", "p", ":=", "tx", ".", "db", ".", "pageInBuffer", "(", "buf", ",", "0", ")", "\n", "tx", ".", "meta", ".", "write", "(", "p", ")", "\n\n", "// Write the meta page to file.", "if", "_", ",", "err", ":=", "tx", ".", "db", ".", "ops", ".", "writeAt", "(", "buf", ",", "int64", "(", "p", ".", "id", ")", "*", "int64", "(", "tx", ".", "db", ".", "pageSize", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "!", "tx", ".", "db", ".", "NoSync", "||", "IgnoreNoSync", "{", "if", "err", ":=", "fdatasync", "(", "tx", ".", "db", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "// Update statistics.", "tx", ".", "stats", ".", "Write", "++", "\n\n", "return", "nil", "\n", "}" ]
// writeMeta writes the meta to the disk.
[ "writeMeta", "writes", "the", "meta", "to", "the", "disk", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/tx.go#L547-L567
train
boltdb/bolt
tx.go
page
func (tx *Tx) page(id pgid) *page { // Check the dirty pages first. if tx.pages != nil { if p, ok := tx.pages[id]; ok { return p } } // Otherwise return directly from the mmap. return tx.db.page(id) }
go
func (tx *Tx) page(id pgid) *page { // Check the dirty pages first. if tx.pages != nil { if p, ok := tx.pages[id]; ok { return p } } // Otherwise return directly from the mmap. return tx.db.page(id) }
[ "func", "(", "tx", "*", "Tx", ")", "page", "(", "id", "pgid", ")", "*", "page", "{", "// Check the dirty pages first.", "if", "tx", ".", "pages", "!=", "nil", "{", "if", "p", ",", "ok", ":=", "tx", ".", "pages", "[", "id", "]", ";", "ok", "{", "return", "p", "\n", "}", "\n", "}", "\n\n", "// Otherwise return directly from the mmap.", "return", "tx", ".", "db", ".", "page", "(", "id", ")", "\n", "}" ]
// page returns a reference to the page with a given id. // If page has been written to then a temporary buffered page is returned.
[ "page", "returns", "a", "reference", "to", "the", "page", "with", "a", "given", "id", ".", "If", "page", "has", "been", "written", "to", "then", "a", "temporary", "buffered", "page", "is", "returned", "." ]
fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5
https://github.com/boltdb/bolt/blob/fd01fc79c553a8e99d512a07e8e0c63d4a3ccfc5/tx.go#L571-L581
train