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
git-lfs/git-lfs
lfshttp/certs.go
isClientCertEnabledForHost
func isClientCertEnabledForHost(c *Client, host string) bool { _, hostSslKeyOk := c.uc.Get("http", fmt.Sprintf("https://%v/", host), "sslKey") _, hostSslCertOk := c.uc.Get("http", fmt.Sprintf("https://%v/", host), "sslCert") return hostSslKeyOk && hostSslCertOk }
go
func isClientCertEnabledForHost(c *Client, host string) bool { _, hostSslKeyOk := c.uc.Get("http", fmt.Sprintf("https://%v/", host), "sslKey") _, hostSslCertOk := c.uc.Get("http", fmt.Sprintf("https://%v/", host), "sslCert") return hostSslKeyOk && hostSslCertOk }
[ "func", "isClientCertEnabledForHost", "(", "c", "*", "Client", ",", "host", "string", ")", "bool", "{", "_", ",", "hostSslKeyOk", ":=", "c", ".", "uc", ".", "Get", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "host", ")", ",", "\"", "\"", ")", "\n", "_", ",", "hostSslCertOk", ":=", "c", ".", "uc", ".", "Get", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "host", ")", ",", "\"", "\"", ")", "\n\n", "return", "hostSslKeyOk", "&&", "hostSslCertOk", "\n", "}" ]
// isClientCertEnabledForHost returns whether client certificate // are configured for the given host
[ "isClientCertEnabledForHost", "returns", "whether", "client", "certificate", "are", "configured", "for", "the", "given", "host" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/lfshttp/certs.go#L29-L34
train
git-lfs/git-lfs
lfshttp/certs.go
decryptPEMBlock
func decryptPEMBlock(c *Client, block *pem.Block, path string, key []byte) ([]byte, error) { fileurl := fmt.Sprintf("cert:///%s", filepath.ToSlash(path)) url, err := url.Parse(fileurl) if err != nil { return nil, err } credHelper, input := c.credHelperContext.GetCredentialHelper(nil, url) input["username"] = "" creds, err := credHelper.Fill(input) if err != nil { tracerx.Printf("Error filling credentials for %q: %v", fileurl, err) return nil, err } pass := creds["password"] decrypted, err := x509.DecryptPEMBlock(block, []byte(pass)) if err != nil { credHelper.Reject(creds) return nil, err } credHelper.Approve(creds) // decrypted is a DER blob, but we need a PEM-encoded block. toEncode := &pem.Block{Type: block.Type, Headers: nil, Bytes: decrypted} buf := pem.EncodeToMemory(toEncode) return buf, nil }
go
func decryptPEMBlock(c *Client, block *pem.Block, path string, key []byte) ([]byte, error) { fileurl := fmt.Sprintf("cert:///%s", filepath.ToSlash(path)) url, err := url.Parse(fileurl) if err != nil { return nil, err } credHelper, input := c.credHelperContext.GetCredentialHelper(nil, url) input["username"] = "" creds, err := credHelper.Fill(input) if err != nil { tracerx.Printf("Error filling credentials for %q: %v", fileurl, err) return nil, err } pass := creds["password"] decrypted, err := x509.DecryptPEMBlock(block, []byte(pass)) if err != nil { credHelper.Reject(creds) return nil, err } credHelper.Approve(creds) // decrypted is a DER blob, but we need a PEM-encoded block. toEncode := &pem.Block{Type: block.Type, Headers: nil, Bytes: decrypted} buf := pem.EncodeToMemory(toEncode) return buf, nil }
[ "func", "decryptPEMBlock", "(", "c", "*", "Client", ",", "block", "*", "pem", ".", "Block", ",", "path", "string", ",", "key", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "fileurl", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "filepath", ".", "ToSlash", "(", "path", ")", ")", "\n", "url", ",", "err", ":=", "url", ".", "Parse", "(", "fileurl", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "credHelper", ",", "input", ":=", "c", ".", "credHelperContext", ".", "GetCredentialHelper", "(", "nil", ",", "url", ")", "\n\n", "input", "[", "\"", "\"", "]", "=", "\"", "\"", "\n\n", "creds", ",", "err", ":=", "credHelper", ".", "Fill", "(", "input", ")", "\n", "if", "err", "!=", "nil", "{", "tracerx", ".", "Printf", "(", "\"", "\"", ",", "fileurl", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "pass", ":=", "creds", "[", "\"", "\"", "]", "\n", "decrypted", ",", "err", ":=", "x509", ".", "DecryptPEMBlock", "(", "block", ",", "[", "]", "byte", "(", "pass", ")", ")", "\n", "if", "err", "!=", "nil", "{", "credHelper", ".", "Reject", "(", "creds", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "credHelper", ".", "Approve", "(", "creds", ")", "\n\n", "// decrypted is a DER blob, but we need a PEM-encoded block.", "toEncode", ":=", "&", "pem", ".", "Block", "{", "Type", ":", "block", ".", "Type", ",", "Headers", ":", "nil", ",", "Bytes", ":", "decrypted", "}", "\n", "buf", ":=", "pem", ".", "EncodeToMemory", "(", "toEncode", ")", "\n", "return", "buf", ",", "nil", "\n", "}" ]
// decryptPEMBlock decrypts an encrypted PEM block representing a private key, // prompting for credentials using the credential helper, and returns a // decrypted PEM block representing that same private key.
[ "decryptPEMBlock", "decrypts", "an", "encrypted", "PEM", "block", "representing", "a", "private", "key", "prompting", "for", "credentials", "using", "the", "credential", "helper", "and", "returns", "a", "decrypted", "PEM", "block", "representing", "that", "same", "private", "key", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/lfshttp/certs.go#L39-L66
train
git-lfs/git-lfs
commands/commands.go
getTransferManifestOperationRemote
func getTransferManifestOperationRemote(operation, remote string) *tq.Manifest { c := getAPIClient() global.Lock() defer global.Unlock() k := fmt.Sprintf("%s.%s", operation, remote) if tqManifest[k] == nil { tqManifest[k] = tq.NewManifest(cfg.Filesystem(), c, operation, remote) } return tqManifest[k] }
go
func getTransferManifestOperationRemote(operation, remote string) *tq.Manifest { c := getAPIClient() global.Lock() defer global.Unlock() k := fmt.Sprintf("%s.%s", operation, remote) if tqManifest[k] == nil { tqManifest[k] = tq.NewManifest(cfg.Filesystem(), c, operation, remote) } return tqManifest[k] }
[ "func", "getTransferManifestOperationRemote", "(", "operation", ",", "remote", "string", ")", "*", "tq", ".", "Manifest", "{", "c", ":=", "getAPIClient", "(", ")", "\n\n", "global", ".", "Lock", "(", ")", "\n", "defer", "global", ".", "Unlock", "(", ")", "\n\n", "k", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "operation", ",", "remote", ")", "\n", "if", "tqManifest", "[", "k", "]", "==", "nil", "{", "tqManifest", "[", "k", "]", "=", "tq", ".", "NewManifest", "(", "cfg", ".", "Filesystem", "(", ")", ",", "c", ",", "operation", ",", "remote", ")", "\n", "}", "\n\n", "return", "tqManifest", "[", "k", "]", "\n", "}" ]
// getTransferManifestOperationRemote builds a tq.Manifest from the global os // and git environments and operation-specific and remote-specific settings. // Operation must be "download", "upload", or the empty string.
[ "getTransferManifestOperationRemote", "builds", "a", "tq", ".", "Manifest", "from", "the", "global", "os", "and", "git", "environments", "and", "operation", "-", "specific", "and", "remote", "-", "specific", "settings", ".", "Operation", "must", "be", "download", "upload", "or", "the", "empty", "string", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/commands/commands.go#L55-L67
train
git-lfs/git-lfs
commands/commands.go
newDownloadCheckQueue
func newDownloadCheckQueue(manifest *tq.Manifest, remote string, options ...tq.Option) *tq.TransferQueue { return newDownloadQueue(manifest, remote, append(options, tq.DryRun(true), )...) }
go
func newDownloadCheckQueue(manifest *tq.Manifest, remote string, options ...tq.Option) *tq.TransferQueue { return newDownloadQueue(manifest, remote, append(options, tq.DryRun(true), )...) }
[ "func", "newDownloadCheckQueue", "(", "manifest", "*", "tq", ".", "Manifest", ",", "remote", "string", ",", "options", "...", "tq", ".", "Option", ")", "*", "tq", ".", "TransferQueue", "{", "return", "newDownloadQueue", "(", "manifest", ",", "remote", ",", "append", "(", "options", ",", "tq", ".", "DryRun", "(", "true", ")", ",", ")", "...", ")", "\n", "}" ]
// newDownloadCheckQueue builds a checking queue, checks that objects are there but doesn't download
[ "newDownloadCheckQueue", "builds", "a", "checking", "queue", "checks", "that", "objects", "are", "there", "but", "doesn", "t", "download" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/commands/commands.go#L112-L116
train
git-lfs/git-lfs
commands/commands.go
newDownloadQueue
func newDownloadQueue(manifest *tq.Manifest, remote string, options ...tq.Option) *tq.TransferQueue { return tq.NewTransferQueue(tq.Download, manifest, remote, append(options, tq.RemoteRef(currentRemoteRef()), )...) }
go
func newDownloadQueue(manifest *tq.Manifest, remote string, options ...tq.Option) *tq.TransferQueue { return tq.NewTransferQueue(tq.Download, manifest, remote, append(options, tq.RemoteRef(currentRemoteRef()), )...) }
[ "func", "newDownloadQueue", "(", "manifest", "*", "tq", ".", "Manifest", ",", "remote", "string", ",", "options", "...", "tq", ".", "Option", ")", "*", "tq", ".", "TransferQueue", "{", "return", "tq", ".", "NewTransferQueue", "(", "tq", ".", "Download", ",", "manifest", ",", "remote", ",", "append", "(", "options", ",", "tq", ".", "RemoteRef", "(", "currentRemoteRef", "(", ")", ")", ",", ")", "...", ")", "\n", "}" ]
// newDownloadQueue builds a DownloadQueue, allowing concurrent downloads.
[ "newDownloadQueue", "builds", "a", "DownloadQueue", "allowing", "concurrent", "downloads", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/commands/commands.go#L119-L123
train
git-lfs/git-lfs
commands/commands.go
getHookInstallSteps
func getHookInstallSteps() string { hookDir, err := cfg.HookDir() if err != nil { ExitWithError(err) } hooks := lfs.LoadHooks(hookDir, cfg) steps := make([]string, 0, len(hooks)) for _, h := range hooks { steps = append(steps, fmt.Sprintf( "Add the following to .git/hooks/%s:\n\n%s", h.Type, tools.Indent(h.Contents))) } return strings.Join(steps, "\n\n") }
go
func getHookInstallSteps() string { hookDir, err := cfg.HookDir() if err != nil { ExitWithError(err) } hooks := lfs.LoadHooks(hookDir, cfg) steps := make([]string, 0, len(hooks)) for _, h := range hooks { steps = append(steps, fmt.Sprintf( "Add the following to .git/hooks/%s:\n\n%s", h.Type, tools.Indent(h.Contents))) } return strings.Join(steps, "\n\n") }
[ "func", "getHookInstallSteps", "(", ")", "string", "{", "hookDir", ",", "err", ":=", "cfg", ".", "HookDir", "(", ")", "\n", "if", "err", "!=", "nil", "{", "ExitWithError", "(", "err", ")", "\n", "}", "\n", "hooks", ":=", "lfs", ".", "LoadHooks", "(", "hookDir", ",", "cfg", ")", "\n", "steps", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "hooks", ")", ")", "\n", "for", "_", ",", "h", ":=", "range", "hooks", "{", "steps", "=", "append", "(", "steps", ",", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\\n", "\"", ",", "h", ".", "Type", ",", "tools", ".", "Indent", "(", "h", ".", "Contents", ")", ")", ")", "\n", "}", "\n\n", "return", "strings", ".", "Join", "(", "steps", ",", "\"", "\\n", "\\n", "\"", ")", "\n", "}" ]
// Get user-readable manual install steps for hooks
[ "Get", "user", "-", "readable", "manual", "install", "steps", "for", "hooks" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/commands/commands.go#L140-L154
train
git-lfs/git-lfs
commands/commands.go
uninstallHooks
func uninstallHooks() error { if !cfg.InRepo() { return errors.New("Not in a git repository") } hookDir, err := cfg.HookDir() if err != nil { return err } hooks := lfs.LoadHooks(hookDir, cfg) for _, h := range hooks { if err := h.Uninstall(); err != nil { return err } } return nil }
go
func uninstallHooks() error { if !cfg.InRepo() { return errors.New("Not in a git repository") } hookDir, err := cfg.HookDir() if err != nil { return err } hooks := lfs.LoadHooks(hookDir, cfg) for _, h := range hooks { if err := h.Uninstall(); err != nil { return err } } return nil }
[ "func", "uninstallHooks", "(", ")", "error", "{", "if", "!", "cfg", ".", "InRepo", "(", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "hookDir", ",", "err", ":=", "cfg", ".", "HookDir", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "hooks", ":=", "lfs", ".", "LoadHooks", "(", "hookDir", ",", "cfg", ")", "\n", "for", "_", ",", "h", ":=", "range", "hooks", "{", "if", "err", ":=", "h", ".", "Uninstall", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// uninstallHooks removes all hooks in range of the `hooks` var.
[ "uninstallHooks", "removes", "all", "hooks", "in", "range", "of", "the", "hooks", "var", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/commands/commands.go#L172-L189
train
git-lfs/git-lfs
commands/commands.go
Error
func Error(format string, args ...interface{}) { if len(args) == 0 { fmt.Fprintln(ErrorWriter, format) return } fmt.Fprintf(ErrorWriter, format+"\n", args...) }
go
func Error(format string, args ...interface{}) { if len(args) == 0 { fmt.Fprintln(ErrorWriter, format) return } fmt.Fprintf(ErrorWriter, format+"\n", args...) }
[ "func", "Error", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "if", "len", "(", "args", ")", "==", "0", "{", "fmt", ".", "Fprintln", "(", "ErrorWriter", ",", "format", ")", "\n", "return", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "ErrorWriter", ",", "format", "+", "\"", "\\n", "\"", ",", "args", "...", ")", "\n", "}" ]
// Error prints a formatted message to Stderr. It also gets printed to the // panic log if one is created for this command.
[ "Error", "prints", "a", "formatted", "message", "to", "Stderr", ".", "It", "also", "gets", "printed", "to", "the", "panic", "log", "if", "one", "is", "created", "for", "this", "command", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/commands/commands.go#L193-L199
train
git-lfs/git-lfs
commands/commands.go
Print
func Print(format string, args ...interface{}) { if len(args) == 0 { fmt.Fprintln(OutputWriter, format) return } fmt.Fprintf(OutputWriter, format+"\n", args...) }
go
func Print(format string, args ...interface{}) { if len(args) == 0 { fmt.Fprintln(OutputWriter, format) return } fmt.Fprintf(OutputWriter, format+"\n", args...) }
[ "func", "Print", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "if", "len", "(", "args", ")", "==", "0", "{", "fmt", ".", "Fprintln", "(", "OutputWriter", ",", "format", ")", "\n", "return", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "OutputWriter", ",", "format", "+", "\"", "\\n", "\"", ",", "args", "...", ")", "\n", "}" ]
// Print prints a formatted message to Stdout. It also gets printed to the // panic log if one is created for this command.
[ "Print", "prints", "a", "formatted", "message", "to", "Stdout", ".", "It", "also", "gets", "printed", "to", "the", "panic", "log", "if", "one", "is", "created", "for", "this", "command", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/commands/commands.go#L203-L209
train
git-lfs/git-lfs
commands/commands.go
Panic
func Panic(err error, format string, args ...interface{}) { LoggedError(err, format, args...) os.Exit(2) }
go
func Panic(err error, format string, args ...interface{}) { LoggedError(err, format, args...) os.Exit(2) }
[ "func", "Panic", "(", "err", "error", ",", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "LoggedError", "(", "err", ",", "format", ",", "args", "...", ")", "\n", "os", ".", "Exit", "(", "2", ")", "\n", "}" ]
// Panic prints a formatted message, and writes a stack trace for the error to // a log file before exiting.
[ "Panic", "prints", "a", "formatted", "message", "and", "writes", "a", "stack", "trace", "for", "the", "error", "to", "a", "log", "file", "before", "exiting", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/commands/commands.go#L266-L269
train
git-lfs/git-lfs
git/attribs.go
GetRootAttributePaths
func GetRootAttributePaths(mp *gitattr.MacroProcessor, cfg Env) []AttributePath { af, _ := cfg.Get("core.attributesfile") af, err := tools.ExpandConfigPath(af, "git/attributes") if err != nil { return nil } if _, err := os.Stat(af); os.IsNotExist(err) { return nil } // The working directory for the root gitattributes file is blank. return attrPaths(mp, af, "", true) }
go
func GetRootAttributePaths(mp *gitattr.MacroProcessor, cfg Env) []AttributePath { af, _ := cfg.Get("core.attributesfile") af, err := tools.ExpandConfigPath(af, "git/attributes") if err != nil { return nil } if _, err := os.Stat(af); os.IsNotExist(err) { return nil } // The working directory for the root gitattributes file is blank. return attrPaths(mp, af, "", true) }
[ "func", "GetRootAttributePaths", "(", "mp", "*", "gitattr", ".", "MacroProcessor", ",", "cfg", "Env", ")", "[", "]", "AttributePath", "{", "af", ",", "_", ":=", "cfg", ".", "Get", "(", "\"", "\"", ")", "\n", "af", ",", "err", ":=", "tools", ".", "ExpandConfigPath", "(", "af", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "af", ")", ";", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "nil", "\n", "}", "\n\n", "// The working directory for the root gitattributes file is blank.", "return", "attrPaths", "(", "mp", ",", "af", ",", "\"", "\"", ",", "true", ")", "\n", "}" ]
// GetRootAttributePaths beahves as GetRootAttributePaths, and loads information // only from the global gitattributes file.
[ "GetRootAttributePaths", "beahves", "as", "GetRootAttributePaths", "and", "loads", "information", "only", "from", "the", "global", "gitattributes", "file", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/git/attribs.go#L46-L59
train
git-lfs/git-lfs
git/attribs.go
GetAttributePaths
func GetAttributePaths(mp *gitattr.MacroProcessor, workingDir, gitDir string) []AttributePath { paths := make([]AttributePath, 0) for _, file := range findAttributeFiles(workingDir, gitDir) { paths = append(paths, attrPaths(mp, file.path, workingDir, file.readMacros)...) } return paths }
go
func GetAttributePaths(mp *gitattr.MacroProcessor, workingDir, gitDir string) []AttributePath { paths := make([]AttributePath, 0) for _, file := range findAttributeFiles(workingDir, gitDir) { paths = append(paths, attrPaths(mp, file.path, workingDir, file.readMacros)...) } return paths }
[ "func", "GetAttributePaths", "(", "mp", "*", "gitattr", ".", "MacroProcessor", ",", "workingDir", ",", "gitDir", "string", ")", "[", "]", "AttributePath", "{", "paths", ":=", "make", "(", "[", "]", "AttributePath", ",", "0", ")", "\n\n", "for", "_", ",", "file", ":=", "range", "findAttributeFiles", "(", "workingDir", ",", "gitDir", ")", "{", "paths", "=", "append", "(", "paths", ",", "attrPaths", "(", "mp", ",", "file", ".", "path", ",", "workingDir", ",", "file", ".", "readMacros", ")", "...", ")", "\n", "}", "\n\n", "return", "paths", "\n", "}" ]
// GetAttributePaths returns a list of entries in .gitattributes which are // configured with the filter=lfs attribute // workingDir is the root of the working copy // gitDir is the root of the git repo
[ "GetAttributePaths", "returns", "a", "list", "of", "entries", "in", ".", "gitattributes", "which", "are", "configured", "with", "the", "filter", "=", "lfs", "attribute", "workingDir", "is", "the", "root", "of", "the", "working", "copy", "gitDir", "is", "the", "root", "of", "the", "git", "repo" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/git/attribs.go#L83-L91
train
git-lfs/git-lfs
git/attribs.go
GetAttributeFilter
func GetAttributeFilter(workingDir, gitDir string) *filepathfilter.Filter { paths := GetAttributePaths(gitattr.NewMacroProcessor(), workingDir, gitDir) patterns := make([]filepathfilter.Pattern, 0, len(paths)) for _, path := range paths { // Convert all separators to `/` before creating a pattern to // avoid characters being escaped in situations like `subtree\*.md` patterns = append(patterns, filepathfilter.NewPattern(filepath.ToSlash(path.Path))) } return filepathfilter.NewFromPatterns(patterns, nil) }
go
func GetAttributeFilter(workingDir, gitDir string) *filepathfilter.Filter { paths := GetAttributePaths(gitattr.NewMacroProcessor(), workingDir, gitDir) patterns := make([]filepathfilter.Pattern, 0, len(paths)) for _, path := range paths { // Convert all separators to `/` before creating a pattern to // avoid characters being escaped in situations like `subtree\*.md` patterns = append(patterns, filepathfilter.NewPattern(filepath.ToSlash(path.Path))) } return filepathfilter.NewFromPatterns(patterns, nil) }
[ "func", "GetAttributeFilter", "(", "workingDir", ",", "gitDir", "string", ")", "*", "filepathfilter", ".", "Filter", "{", "paths", ":=", "GetAttributePaths", "(", "gitattr", ".", "NewMacroProcessor", "(", ")", ",", "workingDir", ",", "gitDir", ")", "\n", "patterns", ":=", "make", "(", "[", "]", "filepathfilter", ".", "Pattern", ",", "0", ",", "len", "(", "paths", ")", ")", "\n\n", "for", "_", ",", "path", ":=", "range", "paths", "{", "// Convert all separators to `/` before creating a pattern to", "// avoid characters being escaped in situations like `subtree\\*.md`", "patterns", "=", "append", "(", "patterns", ",", "filepathfilter", ".", "NewPattern", "(", "filepath", ".", "ToSlash", "(", "path", ".", "Path", ")", ")", ")", "\n", "}", "\n\n", "return", "filepathfilter", ".", "NewFromPatterns", "(", "patterns", ",", "nil", ")", "\n", "}" ]
// GetAttributeFilter returns a list of entries in .gitattributes which are // configured with the filter=lfs attribute as a file path filter which // file paths can be matched against // workingDir is the root of the working copy // gitDir is the root of the git repo
[ "GetAttributeFilter", "returns", "a", "list", "of", "entries", "in", ".", "gitattributes", "which", "are", "configured", "with", "the", "filter", "=", "lfs", "attribute", "as", "a", "file", "path", "filter", "which", "file", "paths", "can", "be", "matched", "against", "workingDir", "is", "the", "root", "of", "the", "working", "copy", "gitDir", "is", "the", "root", "of", "the", "git", "repo" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/git/attribs.go#L154-L165
train
git-lfs/git-lfs
config/map_fetcher.go
Get
func (m mapFetcher) Get(key string) (val string, ok bool) { all := m.GetAll(key) if len(all) == 0 { return "", false } return all[len(all)-1], true }
go
func (m mapFetcher) Get(key string) (val string, ok bool) { all := m.GetAll(key) if len(all) == 0 { return "", false } return all[len(all)-1], true }
[ "func", "(", "m", "mapFetcher", ")", "Get", "(", "key", "string", ")", "(", "val", "string", ",", "ok", "bool", ")", "{", "all", ":=", "m", ".", "GetAll", "(", "key", ")", "\n\n", "if", "len", "(", "all", ")", "==", "0", "{", "return", "\"", "\"", ",", "false", "\n", "}", "\n", "return", "all", "[", "len", "(", "all", ")", "-", "1", "]", ",", "true", "\n", "}" ]
// Get implements the func `Fetcher.Get`.
[ "Get", "implements", "the", "func", "Fetcher", ".", "Get", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/config/map_fetcher.go#L21-L28
train
git-lfs/git-lfs
commands/uploader.go
HasUploaded
func (c *uploadContext) HasUploaded(oid string) bool { return c.uploadedOids.Contains(oid) }
go
func (c *uploadContext) HasUploaded(oid string) bool { return c.uploadedOids.Contains(oid) }
[ "func", "(", "c", "*", "uploadContext", ")", "HasUploaded", "(", "oid", "string", ")", "bool", "{", "return", "c", ".", "uploadedOids", ".", "Contains", "(", "oid", ")", "\n", "}" ]
// HasUploaded determines if the given oid has already been uploaded in the // current process.
[ "HasUploaded", "determines", "if", "the", "given", "oid", "has", "already", "been", "uploaded", "in", "the", "current", "process", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/commands/uploader.go#L173-L175
train
git-lfs/git-lfs
commands/uploader.go
ensureFile
func (c *uploadContext) ensureFile(smudgePath, cleanPath, oid string) error { if _, err := os.Stat(cleanPath); err == nil { return nil } localPath := filepath.Join(cfg.LocalWorkingDir(), smudgePath) file, err := os.Open(localPath) if err != nil { if c.allowMissing { return nil } return errors.Wrapf(err, "Unable to find source for object %v (try running git lfs fetch --all)", oid) } defer file.Close() stat, err := file.Stat() if err != nil { return err } cleaned, err := c.gitfilter.Clean(file, file.Name(), stat.Size(), nil) if cleaned != nil { cleaned.Teardown() } if err != nil { return err } return nil }
go
func (c *uploadContext) ensureFile(smudgePath, cleanPath, oid string) error { if _, err := os.Stat(cleanPath); err == nil { return nil } localPath := filepath.Join(cfg.LocalWorkingDir(), smudgePath) file, err := os.Open(localPath) if err != nil { if c.allowMissing { return nil } return errors.Wrapf(err, "Unable to find source for object %v (try running git lfs fetch --all)", oid) } defer file.Close() stat, err := file.Stat() if err != nil { return err } cleaned, err := c.gitfilter.Clean(file, file.Name(), stat.Size(), nil) if cleaned != nil { cleaned.Teardown() } if err != nil { return err } return nil }
[ "func", "(", "c", "*", "uploadContext", ")", "ensureFile", "(", "smudgePath", ",", "cleanPath", ",", "oid", "string", ")", "error", "{", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "cleanPath", ")", ";", "err", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "localPath", ":=", "filepath", ".", "Join", "(", "cfg", ".", "LocalWorkingDir", "(", ")", ",", "smudgePath", ")", "\n", "file", ",", "err", ":=", "os", ".", "Open", "(", "localPath", ")", "\n", "if", "err", "!=", "nil", "{", "if", "c", ".", "allowMissing", "{", "return", "nil", "\n", "}", "\n", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "oid", ")", "\n", "}", "\n\n", "defer", "file", ".", "Close", "(", ")", "\n\n", "stat", ",", "err", ":=", "file", ".", "Stat", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "cleaned", ",", "err", ":=", "c", ".", "gitfilter", ".", "Clean", "(", "file", ",", "file", ".", "Name", "(", ")", ",", "stat", ".", "Size", "(", ")", ",", "nil", ")", "\n", "if", "cleaned", "!=", "nil", "{", "cleaned", ".", "Teardown", "(", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ensureFile makes sure that the cleanPath exists before pushing it. If it // does not exist, it attempts to clean it by reading the file at smudgePath.
[ "ensureFile", "makes", "sure", "that", "the", "cleanPath", "exists", "before", "pushing", "it", ".", "If", "it", "does", "not", "exist", "it", "attempts", "to", "clean", "it", "by", "reading", "the", "file", "at", "smudgePath", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/commands/uploader.go#L365-L395
train
git-lfs/git-lfs
commands/uploader.go
supportsLockingAPI
func supportsLockingAPI(rawurl string) bool { u, err := url.Parse(rawurl) if err != nil { tracerx.Printf("commands: unable to parse %q to determine locking support: %v", rawurl, err) return false } for _, supported := range hostsWithKnownLockingSupport { if supported.Scheme == u.Scheme && supported.Hostname() == u.Hostname() && strings.HasPrefix(u.Path, supported.Path) { return true } } return false }
go
func supportsLockingAPI(rawurl string) bool { u, err := url.Parse(rawurl) if err != nil { tracerx.Printf("commands: unable to parse %q to determine locking support: %v", rawurl, err) return false } for _, supported := range hostsWithKnownLockingSupport { if supported.Scheme == u.Scheme && supported.Hostname() == u.Hostname() && strings.HasPrefix(u.Path, supported.Path) { return true } } return false }
[ "func", "supportsLockingAPI", "(", "rawurl", "string", ")", "bool", "{", "u", ",", "err", ":=", "url", ".", "Parse", "(", "rawurl", ")", "\n", "if", "err", "!=", "nil", "{", "tracerx", ".", "Printf", "(", "\"", "\"", ",", "rawurl", ",", "err", ")", "\n", "return", "false", "\n", "}", "\n\n", "for", "_", ",", "supported", ":=", "range", "hostsWithKnownLockingSupport", "{", "if", "supported", ".", "Scheme", "==", "u", ".", "Scheme", "&&", "supported", ".", "Hostname", "(", ")", "==", "u", ".", "Hostname", "(", ")", "&&", "strings", ".", "HasPrefix", "(", "u", ".", "Path", ",", "supported", ".", "Path", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// supportsLockingAPI returns whether or not a given url is known to support // the LFS locking API by whether or not its hostname is included in the list // above.
[ "supportsLockingAPI", "returns", "whether", "or", "not", "a", "given", "url", "is", "known", "to", "support", "the", "LFS", "locking", "API", "by", "whether", "or", "not", "its", "hostname", "is", "included", "in", "the", "list", "above", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/commands/uploader.go#L400-L415
train
git-lfs/git-lfs
commands/uploader.go
disableFor
func disableFor(rawurl string) error { tracerx.Printf("commands: disabling lock verification for %q", rawurl) key := strings.Join([]string{"lfs", rawurl, "locksverify"}, ".") _, err := cfg.SetGitLocalKey(key, "false") return err }
go
func disableFor(rawurl string) error { tracerx.Printf("commands: disabling lock verification for %q", rawurl) key := strings.Join([]string{"lfs", rawurl, "locksverify"}, ".") _, err := cfg.SetGitLocalKey(key, "false") return err }
[ "func", "disableFor", "(", "rawurl", "string", ")", "error", "{", "tracerx", ".", "Printf", "(", "\"", "\"", ",", "rawurl", ")", "\n\n", "key", ":=", "strings", ".", "Join", "(", "[", "]", "string", "{", "\"", "\"", ",", "rawurl", ",", "\"", "\"", "}", ",", "\"", "\"", ")", "\n\n", "_", ",", "err", ":=", "cfg", ".", "SetGitLocalKey", "(", "key", ",", "\"", "\"", ")", "\n", "return", "err", "\n", "}" ]
// disableFor disables lock verification for the given lfsapi.Endpoint, // "endpoint".
[ "disableFor", "disables", "lock", "verification", "for", "the", "given", "lfsapi", ".", "Endpoint", "endpoint", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/commands/uploader.go#L419-L426
train
git-lfs/git-lfs
commands/command_migrate_import.go
checkoutNonBare
func checkoutNonBare(l *tasklog.Logger) error { if bare, _ := git.IsBare(); bare { return nil } t := l.Waiter("migrate: checkout") defer t.Complete() return git.Checkout("", nil, true) }
go
func checkoutNonBare(l *tasklog.Logger) error { if bare, _ := git.IsBare(); bare { return nil } t := l.Waiter("migrate: checkout") defer t.Complete() return git.Checkout("", nil, true) }
[ "func", "checkoutNonBare", "(", "l", "*", "tasklog", ".", "Logger", ")", "error", "{", "if", "bare", ",", "_", ":=", "git", ".", "IsBare", "(", ")", ";", "bare", "{", "return", "nil", "\n", "}", "\n\n", "t", ":=", "l", ".", "Waiter", "(", "\"", "\"", ")", "\n", "defer", "t", ".", "Complete", "(", ")", "\n\n", "return", "git", ".", "Checkout", "(", "\"", "\"", ",", "nil", ",", "true", ")", "\n", "}" ]
// checkoutNonBare forces a checkout of the current reference, so long as the // repository is non-bare. // // It returns nil on success, and a non-nil error on failure.
[ "checkoutNonBare", "forces", "a", "checkout", "of", "the", "current", "reference", "so", "long", "as", "the", "repository", "is", "non", "-", "bare", ".", "It", "returns", "nil", "on", "success", "and", "a", "non", "-", "nil", "error", "on", "failure", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/commands/command_migrate_import.go#L264-L273
train
git-lfs/git-lfs
commands/command_migrate_import.go
trackedFromAttrs
func trackedFromAttrs(db *gitobj.ObjectDatabase, t *gitobj.Tree) (*tools.OrderedSet, error) { var oid []byte for _, e := range t.Entries { if strings.ToLower(e.Name) == ".gitattributes" && e.Type() == gitobj.BlobObjectType { oid = e.Oid break } } if oid == nil { // TODO(@ttaylorr): make (*tools.OrderedSet)(nil) a valid // receiver for non-mutative methods. return tools.NewOrderedSet(), nil } sha1 := hex.EncodeToString(oid) if s, ok := attrsCache[sha1]; ok { return s, nil } blob, err := db.Blob(oid) if err != nil { return nil, err } attrs := tools.NewOrderedSet() scanner := bufio.NewScanner(blob.Contents) for scanner.Scan() { attrs.Add(scanner.Text()) } if err := scanner.Err(); err != nil { return nil, err } attrsCache[sha1] = attrs return attrsCache[sha1], nil }
go
func trackedFromAttrs(db *gitobj.ObjectDatabase, t *gitobj.Tree) (*tools.OrderedSet, error) { var oid []byte for _, e := range t.Entries { if strings.ToLower(e.Name) == ".gitattributes" && e.Type() == gitobj.BlobObjectType { oid = e.Oid break } } if oid == nil { // TODO(@ttaylorr): make (*tools.OrderedSet)(nil) a valid // receiver for non-mutative methods. return tools.NewOrderedSet(), nil } sha1 := hex.EncodeToString(oid) if s, ok := attrsCache[sha1]; ok { return s, nil } blob, err := db.Blob(oid) if err != nil { return nil, err } attrs := tools.NewOrderedSet() scanner := bufio.NewScanner(blob.Contents) for scanner.Scan() { attrs.Add(scanner.Text()) } if err := scanner.Err(); err != nil { return nil, err } attrsCache[sha1] = attrs return attrsCache[sha1], nil }
[ "func", "trackedFromAttrs", "(", "db", "*", "gitobj", ".", "ObjectDatabase", ",", "t", "*", "gitobj", ".", "Tree", ")", "(", "*", "tools", ".", "OrderedSet", ",", "error", ")", "{", "var", "oid", "[", "]", "byte", "\n\n", "for", "_", ",", "e", ":=", "range", "t", ".", "Entries", "{", "if", "strings", ".", "ToLower", "(", "e", ".", "Name", ")", "==", "\"", "\"", "&&", "e", ".", "Type", "(", ")", "==", "gitobj", ".", "BlobObjectType", "{", "oid", "=", "e", ".", "Oid", "\n", "break", "\n", "}", "\n", "}", "\n\n", "if", "oid", "==", "nil", "{", "// TODO(@ttaylorr): make (*tools.OrderedSet)(nil) a valid", "// receiver for non-mutative methods.", "return", "tools", ".", "NewOrderedSet", "(", ")", ",", "nil", "\n", "}", "\n\n", "sha1", ":=", "hex", ".", "EncodeToString", "(", "oid", ")", "\n\n", "if", "s", ",", "ok", ":=", "attrsCache", "[", "sha1", "]", ";", "ok", "{", "return", "s", ",", "nil", "\n", "}", "\n\n", "blob", ",", "err", ":=", "db", ".", "Blob", "(", "oid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "attrs", ":=", "tools", ".", "NewOrderedSet", "(", ")", "\n\n", "scanner", ":=", "bufio", ".", "NewScanner", "(", "blob", ".", "Contents", ")", "\n", "for", "scanner", ".", "Scan", "(", ")", "{", "attrs", ".", "Add", "(", "scanner", ".", "Text", "(", ")", ")", "\n", "}", "\n\n", "if", "err", ":=", "scanner", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "attrsCache", "[", "sha1", "]", "=", "attrs", "\n\n", "return", "attrsCache", "[", "sha1", "]", ",", "nil", "\n", "}" ]
// trackedFromAttrs returns an ordered line-delimited set of the contents of a // .gitattributes blob in a given tree "t". // // It returns an empty set if no attributes file could be found, or an error if // it could not otherwise be opened.
[ "trackedFromAttrs", "returns", "an", "ordered", "line", "-", "delimited", "set", "of", "the", "contents", "of", "a", ".", "gitattributes", "blob", "in", "a", "given", "tree", "t", ".", "It", "returns", "an", "empty", "set", "if", "no", "attributes", "file", "could", "be", "found", "or", "an", "error", "if", "it", "could", "not", "otherwise", "be", "opened", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/commands/command_migrate_import.go#L303-L344
train
git-lfs/git-lfs
commands/command_migrate_import.go
trackedToBlob
func trackedToBlob(db *gitobj.ObjectDatabase, patterns *tools.OrderedSet) ([]byte, error) { var attrs bytes.Buffer for pattern := range patterns.Iter() { fmt.Fprintf(&attrs, "%s\n", pattern) } return db.WriteBlob(&gitobj.Blob{ Contents: &attrs, Size: int64(attrs.Len()), }) }
go
func trackedToBlob(db *gitobj.ObjectDatabase, patterns *tools.OrderedSet) ([]byte, error) { var attrs bytes.Buffer for pattern := range patterns.Iter() { fmt.Fprintf(&attrs, "%s\n", pattern) } return db.WriteBlob(&gitobj.Blob{ Contents: &attrs, Size: int64(attrs.Len()), }) }
[ "func", "trackedToBlob", "(", "db", "*", "gitobj", ".", "ObjectDatabase", ",", "patterns", "*", "tools", ".", "OrderedSet", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "attrs", "bytes", ".", "Buffer", "\n\n", "for", "pattern", ":=", "range", "patterns", ".", "Iter", "(", ")", "{", "fmt", ".", "Fprintf", "(", "&", "attrs", ",", "\"", "\\n", "\"", ",", "pattern", ")", "\n", "}", "\n\n", "return", "db", ".", "WriteBlob", "(", "&", "gitobj", ".", "Blob", "{", "Contents", ":", "&", "attrs", ",", "Size", ":", "int64", "(", "attrs", ".", "Len", "(", ")", ")", ",", "}", ")", "\n", "}" ]
// trackedToBlob writes and returns the OID of a .gitattributes blob based on // the patterns given in the ordered set of patterns, "patterns".
[ "trackedToBlob", "writes", "and", "returns", "the", "OID", "of", "a", ".", "gitattributes", "blob", "based", "on", "the", "patterns", "given", "in", "the", "ordered", "set", "of", "patterns", "patterns", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/commands/command_migrate_import.go#L348-L359
train
git-lfs/git-lfs
commands/command_migrate_import.go
rewriteTree
func rewriteTree(gf *lfs.GitFilter, db *gitobj.ObjectDatabase, root []byte, path string) ([]byte, error) { tree, err := db.Tree(root) if err != nil { return nil, err } splits := strings.SplitN(path, "/", 2) switch len(splits) { case 1: // The path points to an entry at the root of this tree, so it must be a blob. // Try to replace this blob with a Git LFS pointer. index := findEntry(tree, splits[0]) if index < 0 { return nil, errors.Errorf("unable to find entry %s in tree", splits[0]) } blobEntry := tree.Entries[index] blob, err := db.Blob(blobEntry.Oid) if err != nil { return nil, err } var buf bytes.Buffer if _, err := clean(gf, &buf, blob.Contents, blobEntry.Name, blob.Size); err != nil { return nil, err } newOid, err := db.WriteBlob(&gitobj.Blob{ Contents: &buf, Size: int64(buf.Len()), }) if err != nil { return nil, err } tree = tree.Merge(&gitobj.TreeEntry{ Name: splits[0], Filemode: blobEntry.Filemode, Oid: newOid, }) return db.WriteTree(tree) case 2: // The path points to an entry in a subtree contained at the root of the tree. // Recursively rewrite the subtree. head, tail := splits[0], splits[1] index := findEntry(tree, head) if index < 0 { return nil, errors.Errorf("unable to find entry %s in tree", head) } subtreeEntry := tree.Entries[index] if subtreeEntry.Type() != gitobj.TreeObjectType { return nil, errors.Errorf("migrate: expected %s to be a tree, got %s", head, subtreeEntry.Type()) } rewrittenSubtree, err := rewriteTree(gf, db, subtreeEntry.Oid, tail) if err != nil { return nil, err } tree = tree.Merge(&gitobj.TreeEntry{ Filemode: subtreeEntry.Filemode, Name: subtreeEntry.Name, Oid: rewrittenSubtree, }) return db.WriteTree(tree) default: return nil, errors.Errorf("error parsing path %s", path) } }
go
func rewriteTree(gf *lfs.GitFilter, db *gitobj.ObjectDatabase, root []byte, path string) ([]byte, error) { tree, err := db.Tree(root) if err != nil { return nil, err } splits := strings.SplitN(path, "/", 2) switch len(splits) { case 1: // The path points to an entry at the root of this tree, so it must be a blob. // Try to replace this blob with a Git LFS pointer. index := findEntry(tree, splits[0]) if index < 0 { return nil, errors.Errorf("unable to find entry %s in tree", splits[0]) } blobEntry := tree.Entries[index] blob, err := db.Blob(blobEntry.Oid) if err != nil { return nil, err } var buf bytes.Buffer if _, err := clean(gf, &buf, blob.Contents, blobEntry.Name, blob.Size); err != nil { return nil, err } newOid, err := db.WriteBlob(&gitobj.Blob{ Contents: &buf, Size: int64(buf.Len()), }) if err != nil { return nil, err } tree = tree.Merge(&gitobj.TreeEntry{ Name: splits[0], Filemode: blobEntry.Filemode, Oid: newOid, }) return db.WriteTree(tree) case 2: // The path points to an entry in a subtree contained at the root of the tree. // Recursively rewrite the subtree. head, tail := splits[0], splits[1] index := findEntry(tree, head) if index < 0 { return nil, errors.Errorf("unable to find entry %s in tree", head) } subtreeEntry := tree.Entries[index] if subtreeEntry.Type() != gitobj.TreeObjectType { return nil, errors.Errorf("migrate: expected %s to be a tree, got %s", head, subtreeEntry.Type()) } rewrittenSubtree, err := rewriteTree(gf, db, subtreeEntry.Oid, tail) if err != nil { return nil, err } tree = tree.Merge(&gitobj.TreeEntry{ Filemode: subtreeEntry.Filemode, Name: subtreeEntry.Name, Oid: rewrittenSubtree, }) return db.WriteTree(tree) default: return nil, errors.Errorf("error parsing path %s", path) } }
[ "func", "rewriteTree", "(", "gf", "*", "lfs", ".", "GitFilter", ",", "db", "*", "gitobj", ".", "ObjectDatabase", ",", "root", "[", "]", "byte", ",", "path", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "tree", ",", "err", ":=", "db", ".", "Tree", "(", "root", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "splits", ":=", "strings", ".", "SplitN", "(", "path", ",", "\"", "\"", ",", "2", ")", "\n\n", "switch", "len", "(", "splits", ")", "{", "case", "1", ":", "// The path points to an entry at the root of this tree, so it must be a blob.", "// Try to replace this blob with a Git LFS pointer.", "index", ":=", "findEntry", "(", "tree", ",", "splits", "[", "0", "]", ")", "\n", "if", "index", "<", "0", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "splits", "[", "0", "]", ")", "\n", "}", "\n\n", "blobEntry", ":=", "tree", ".", "Entries", "[", "index", "]", "\n", "blob", ",", "err", ":=", "db", ".", "Blob", "(", "blobEntry", ".", "Oid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "buf", "bytes", ".", "Buffer", "\n\n", "if", "_", ",", "err", ":=", "clean", "(", "gf", ",", "&", "buf", ",", "blob", ".", "Contents", ",", "blobEntry", ".", "Name", ",", "blob", ".", "Size", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "newOid", ",", "err", ":=", "db", ".", "WriteBlob", "(", "&", "gitobj", ".", "Blob", "{", "Contents", ":", "&", "buf", ",", "Size", ":", "int64", "(", "buf", ".", "Len", "(", ")", ")", ",", "}", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "tree", "=", "tree", ".", "Merge", "(", "&", "gitobj", ".", "TreeEntry", "{", "Name", ":", "splits", "[", "0", "]", ",", "Filemode", ":", "blobEntry", ".", "Filemode", ",", "Oid", ":", "newOid", ",", "}", ")", "\n", "return", "db", ".", "WriteTree", "(", "tree", ")", "\n\n", "case", "2", ":", "// The path points to an entry in a subtree contained at the root of the tree.", "// Recursively rewrite the subtree.", "head", ",", "tail", ":=", "splits", "[", "0", "]", ",", "splits", "[", "1", "]", "\n\n", "index", ":=", "findEntry", "(", "tree", ",", "head", ")", "\n", "if", "index", "<", "0", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "head", ")", "\n", "}", "\n\n", "subtreeEntry", ":=", "tree", ".", "Entries", "[", "index", "]", "\n", "if", "subtreeEntry", ".", "Type", "(", ")", "!=", "gitobj", ".", "TreeObjectType", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "head", ",", "subtreeEntry", ".", "Type", "(", ")", ")", "\n", "}", "\n\n", "rewrittenSubtree", ",", "err", ":=", "rewriteTree", "(", "gf", ",", "db", ",", "subtreeEntry", ".", "Oid", ",", "tail", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "tree", "=", "tree", ".", "Merge", "(", "&", "gitobj", ".", "TreeEntry", "{", "Filemode", ":", "subtreeEntry", ".", "Filemode", ",", "Name", ":", "subtreeEntry", ".", "Name", ",", "Oid", ":", "rewrittenSubtree", ",", "}", ")", "\n\n", "return", "db", ".", "WriteTree", "(", "tree", ")", "\n\n", "default", ":", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "path", ")", "\n", "}", "\n", "}" ]
// rewriteTree replaces the blob at the provided path within the given tree with // a git lfs pointer. It will recursively rewrite any subtrees along the path to the // blob.
[ "rewriteTree", "replaces", "the", "blob", "at", "the", "provided", "path", "within", "the", "given", "tree", "with", "a", "git", "lfs", "pointer", ".", "It", "will", "recursively", "rewrite", "any", "subtrees", "along", "the", "path", "to", "the", "blob", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/commands/command_migrate_import.go#L364-L440
train
git-lfs/git-lfs
commands/command_migrate_import.go
findEntry
func findEntry(t *gitobj.Tree, name string) int { for i, entry := range t.Entries { if entry.Name == name { return i } } return -1 }
go
func findEntry(t *gitobj.Tree, name string) int { for i, entry := range t.Entries { if entry.Name == name { return i } } return -1 }
[ "func", "findEntry", "(", "t", "*", "gitobj", ".", "Tree", ",", "name", "string", ")", "int", "{", "for", "i", ",", "entry", ":=", "range", "t", ".", "Entries", "{", "if", "entry", ".", "Name", "==", "name", "{", "return", "i", "\n", "}", "\n", "}", "\n\n", "return", "-", "1", "\n", "}" ]
// findEntry searches a tree for the desired entry, and returns the index of that // entry within the tree's Entries array
[ "findEntry", "searches", "a", "tree", "for", "the", "desired", "entry", "and", "returns", "the", "index", "of", "that", "entry", "within", "the", "tree", "s", "Entries", "array" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/commands/command_migrate_import.go#L444-L452
train
git-lfs/git-lfs
subprocess/subprocess.go
BufferedExec
func BufferedExec(name string, args ...string) (*BufferedCmd, error) { cmd := ExecCommand(name, args...) stdout, err := cmd.StdoutPipe() if err != nil { return nil, err } stderr, err := cmd.StderrPipe() if err != nil { return nil, err } stdin, err := cmd.StdinPipe() if err != nil { return nil, err } if err := cmd.Start(); err != nil { return nil, err } return &BufferedCmd{ cmd, stdin, bufio.NewReaderSize(stdout, stdoutBufSize), bufio.NewReaderSize(stderr, stdoutBufSize), }, nil }
go
func BufferedExec(name string, args ...string) (*BufferedCmd, error) { cmd := ExecCommand(name, args...) stdout, err := cmd.StdoutPipe() if err != nil { return nil, err } stderr, err := cmd.StderrPipe() if err != nil { return nil, err } stdin, err := cmd.StdinPipe() if err != nil { return nil, err } if err := cmd.Start(); err != nil { return nil, err } return &BufferedCmd{ cmd, stdin, bufio.NewReaderSize(stdout, stdoutBufSize), bufio.NewReaderSize(stderr, stdoutBufSize), }, nil }
[ "func", "BufferedExec", "(", "name", "string", ",", "args", "...", "string", ")", "(", "*", "BufferedCmd", ",", "error", ")", "{", "cmd", ":=", "ExecCommand", "(", "name", ",", "args", "...", ")", "\n", "stdout", ",", "err", ":=", "cmd", ".", "StdoutPipe", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "stderr", ",", "err", ":=", "cmd", ".", "StderrPipe", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "stdin", ",", "err", ":=", "cmd", ".", "StdinPipe", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "err", ":=", "cmd", ".", "Start", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "BufferedCmd", "{", "cmd", ",", "stdin", ",", "bufio", ".", "NewReaderSize", "(", "stdout", ",", "stdoutBufSize", ")", ",", "bufio", ".", "NewReaderSize", "(", "stderr", ",", "stdoutBufSize", ")", ",", "}", ",", "nil", "\n", "}" ]
// BufferedExec starts up a command and creates a stdin pipe and a buffered // stdout & stderr pipes, wrapped in a BufferedCmd. The stdout buffer will be // of stdoutBufSize bytes.
[ "BufferedExec", "starts", "up", "a", "command", "and", "creates", "a", "stdin", "pipe", "and", "a", "buffered", "stdout", "&", "stderr", "pipes", "wrapped", "in", "a", "BufferedCmd", ".", "The", "stdout", "buffer", "will", "be", "of", "stdoutBufSize", "bytes", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/subprocess/subprocess.go#L21-L47
train
git-lfs/git-lfs
subprocess/subprocess.go
ShellQuoteSingle
func ShellQuoteSingle(str string) string { // Quote anything that looks slightly complicated. if shellWordRe.FindStringIndex(str) == nil { return "'" + strings.Replace(str, "'", "'\\''", -1) + "'" } return str }
go
func ShellQuoteSingle(str string) string { // Quote anything that looks slightly complicated. if shellWordRe.FindStringIndex(str) == nil { return "'" + strings.Replace(str, "'", "'\\''", -1) + "'" } return str }
[ "func", "ShellQuoteSingle", "(", "str", "string", ")", "string", "{", "// Quote anything that looks slightly complicated.", "if", "shellWordRe", ".", "FindStringIndex", "(", "str", ")", "==", "nil", "{", "return", "\"", "\"", "+", "strings", ".", "Replace", "(", "str", ",", "\"", "\"", ",", "\"", "\\\\", "\"", ",", "-", "1", ")", "+", "\"", "\"", "\n", "}", "\n", "return", "str", "\n", "}" ]
// ShellQuoteSingle returns a string which is quoted suitably for sh.
[ "ShellQuoteSingle", "returns", "a", "string", "which", "is", "quoted", "suitably", "for", "sh", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/subprocess/subprocess.go#L90-L96
train
git-lfs/git-lfs
subprocess/subprocess.go
ShellQuote
func ShellQuote(strs []string) []string { dup := make([]string, 0, len(strs)) for _, str := range strs { dup = append(dup, ShellQuoteSingle(str)) } return dup }
go
func ShellQuote(strs []string) []string { dup := make([]string, 0, len(strs)) for _, str := range strs { dup = append(dup, ShellQuoteSingle(str)) } return dup }
[ "func", "ShellQuote", "(", "strs", "[", "]", "string", ")", "[", "]", "string", "{", "dup", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "strs", ")", ")", "\n\n", "for", "_", ",", "str", ":=", "range", "strs", "{", "dup", "=", "append", "(", "dup", ",", "ShellQuoteSingle", "(", "str", ")", ")", "\n", "}", "\n", "return", "dup", "\n", "}" ]
// ShellQuote returns a copied string slice where each element is quoted // suitably for sh.
[ "ShellQuote", "returns", "a", "copied", "string", "slice", "where", "each", "element", "is", "quoted", "suitably", "for", "sh", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/subprocess/subprocess.go#L100-L107
train
git-lfs/git-lfs
subprocess/subprocess.go
FormatForShell
func FormatForShell(name string, args string) (string, []string) { return "sh", []string{"-c", name + " " + args} }
go
func FormatForShell(name string, args string) (string, []string) { return "sh", []string{"-c", name + " " + args} }
[ "func", "FormatForShell", "(", "name", "string", ",", "args", "string", ")", "(", "string", ",", "[", "]", "string", ")", "{", "return", "\"", "\"", ",", "[", "]", "string", "{", "\"", "\"", ",", "name", "+", "\"", "\"", "+", "args", "}", "\n", "}" ]
// FormatForShell takes a command name and an argument string and returns a // command and arguments that pass this command to the shell. Note that neither // the command nor the arguments are quoted. Consider FormatForShellQuoted // instead.
[ "FormatForShell", "takes", "a", "command", "name", "and", "an", "argument", "string", "and", "returns", "a", "command", "and", "arguments", "that", "pass", "this", "command", "to", "the", "shell", ".", "Note", "that", "neither", "the", "command", "nor", "the", "arguments", "are", "quoted", ".", "Consider", "FormatForShellQuoted", "instead", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/subprocess/subprocess.go#L113-L115
train
git-lfs/git-lfs
subprocess/subprocess.go
FormatForShellQuotedArgs
func FormatForShellQuotedArgs(name string, args []string) (string, []string) { return FormatForShell(name, strings.Join(ShellQuote(args), " ")) }
go
func FormatForShellQuotedArgs(name string, args []string) (string, []string) { return FormatForShell(name, strings.Join(ShellQuote(args), " ")) }
[ "func", "FormatForShellQuotedArgs", "(", "name", "string", ",", "args", "[", "]", "string", ")", "(", "string", ",", "[", "]", "string", ")", "{", "return", "FormatForShell", "(", "name", ",", "strings", ".", "Join", "(", "ShellQuote", "(", "args", ")", ",", "\"", "\"", ")", ")", "\n", "}" ]
// FormatForShellQuotedArgs takes a command name and an argument string and // returns a command and arguments that pass this command to the shell. The // arguments are escaped, but the name of the command is not.
[ "FormatForShellQuotedArgs", "takes", "a", "command", "name", "and", "an", "argument", "string", "and", "returns", "a", "command", "and", "arguments", "that", "pass", "this", "command", "to", "the", "shell", ".", "The", "arguments", "are", "escaped", "but", "the", "name", "of", "the", "command", "is", "not", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/subprocess/subprocess.go#L120-L122
train
git-lfs/git-lfs
errors/errors.go
Wrapf
func Wrapf(err error, format string, args ...interface{}) error { if err == nil { err = errors.New("") } message := fmt.Sprintf(format, args...) return newWrappedError(err, message) }
go
func Wrapf(err error, format string, args ...interface{}) error { if err == nil { err = errors.New("") } message := fmt.Sprintf(format, args...) return newWrappedError(err, message) }
[ "func", "Wrapf", "(", "err", "error", ",", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "error", "{", "if", "err", "==", "nil", "{", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "message", ":=", "fmt", ".", "Sprintf", "(", "format", ",", "args", "...", ")", "\n\n", "return", "newWrappedError", "(", "err", ",", "message", ")", "\n", "}" ]
// Wrapf wraps an error with an additional formatted message.
[ "Wrapf", "wraps", "an", "error", "with", "an", "additional", "formatted", "message", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/errors/errors.go#L78-L86
train
git-lfs/git-lfs
tq/transfer.go
newTransfer
func newTransfer(tr *Transfer, name string, path string) *Transfer { t := &Transfer{ Name: name, Path: path, Oid: tr.Oid, Size: tr.Size, Authenticated: tr.Authenticated, Actions: make(ActionSet), } if tr.Error != nil { t.Error = &ObjectError{ Code: tr.Error.Code, Message: tr.Error.Message, } } for rel, action := range tr.Actions { t.Actions[rel] = &Action{ Href: action.Href, Header: action.Header, ExpiresAt: action.ExpiresAt, ExpiresIn: action.ExpiresIn, createdAt: action.createdAt, } } if tr.Links != nil { t.Links = make(ActionSet) for rel, link := range tr.Links { t.Links[rel] = &Action{ Href: link.Href, Header: link.Header, ExpiresAt: link.ExpiresAt, ExpiresIn: link.ExpiresIn, createdAt: link.createdAt, } } } return t }
go
func newTransfer(tr *Transfer, name string, path string) *Transfer { t := &Transfer{ Name: name, Path: path, Oid: tr.Oid, Size: tr.Size, Authenticated: tr.Authenticated, Actions: make(ActionSet), } if tr.Error != nil { t.Error = &ObjectError{ Code: tr.Error.Code, Message: tr.Error.Message, } } for rel, action := range tr.Actions { t.Actions[rel] = &Action{ Href: action.Href, Header: action.Header, ExpiresAt: action.ExpiresAt, ExpiresIn: action.ExpiresIn, createdAt: action.createdAt, } } if tr.Links != nil { t.Links = make(ActionSet) for rel, link := range tr.Links { t.Links[rel] = &Action{ Href: link.Href, Header: link.Header, ExpiresAt: link.ExpiresAt, ExpiresIn: link.ExpiresIn, createdAt: link.createdAt, } } } return t }
[ "func", "newTransfer", "(", "tr", "*", "Transfer", ",", "name", "string", ",", "path", "string", ")", "*", "Transfer", "{", "t", ":=", "&", "Transfer", "{", "Name", ":", "name", ",", "Path", ":", "path", ",", "Oid", ":", "tr", ".", "Oid", ",", "Size", ":", "tr", ".", "Size", ",", "Authenticated", ":", "tr", ".", "Authenticated", ",", "Actions", ":", "make", "(", "ActionSet", ")", ",", "}", "\n\n", "if", "tr", ".", "Error", "!=", "nil", "{", "t", ".", "Error", "=", "&", "ObjectError", "{", "Code", ":", "tr", ".", "Error", ".", "Code", ",", "Message", ":", "tr", ".", "Error", ".", "Message", ",", "}", "\n", "}", "\n\n", "for", "rel", ",", "action", ":=", "range", "tr", ".", "Actions", "{", "t", ".", "Actions", "[", "rel", "]", "=", "&", "Action", "{", "Href", ":", "action", ".", "Href", ",", "Header", ":", "action", ".", "Header", ",", "ExpiresAt", ":", "action", ".", "ExpiresAt", ",", "ExpiresIn", ":", "action", ".", "ExpiresIn", ",", "createdAt", ":", "action", ".", "createdAt", ",", "}", "\n", "}", "\n\n", "if", "tr", ".", "Links", "!=", "nil", "{", "t", ".", "Links", "=", "make", "(", "ActionSet", ")", "\n\n", "for", "rel", ",", "link", ":=", "range", "tr", ".", "Links", "{", "t", ".", "Links", "[", "rel", "]", "=", "&", "Action", "{", "Href", ":", "link", ".", "Href", ",", "Header", ":", "link", ".", "Header", ",", "ExpiresAt", ":", "link", ".", "ExpiresAt", ",", "ExpiresIn", ":", "link", ".", "ExpiresIn", ",", "createdAt", ":", "link", ".", "createdAt", ",", "}", "\n", "}", "\n", "}", "\n\n", "return", "t", "\n", "}" ]
// newTransfer returns a copy of the given Transfer, with the name and path // values set.
[ "newTransfer", "returns", "a", "copy", "of", "the", "given", "Transfer", "with", "the", "name", "and", "path", "values", "set", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tq/transfer.go#L87-L129
train
git-lfs/git-lfs
commands/command_migrate.go
getRemoteRefs
func getRemoteRefs(l *tasklog.Logger) (map[string][]*git.Ref, error) { refs := make(map[string][]*git.Ref) remotes, err := git.RemoteList() if err != nil { return nil, err } if !migrateSkipFetch { w := l.Waiter("migrate: Fetching remote refs") if err := git.Fetch(remotes...); err != nil { return nil, err } w.Complete() } for _, remote := range remotes { var refsForRemote []*git.Ref if migrateSkipFetch { refsForRemote, err = git.CachedRemoteRefs(remote) } else { refsForRemote, err = git.RemoteRefs(remote) } if err != nil { return nil, err } refs[remote] = refsForRemote } return refs, nil }
go
func getRemoteRefs(l *tasklog.Logger) (map[string][]*git.Ref, error) { refs := make(map[string][]*git.Ref) remotes, err := git.RemoteList() if err != nil { return nil, err } if !migrateSkipFetch { w := l.Waiter("migrate: Fetching remote refs") if err := git.Fetch(remotes...); err != nil { return nil, err } w.Complete() } for _, remote := range remotes { var refsForRemote []*git.Ref if migrateSkipFetch { refsForRemote, err = git.CachedRemoteRefs(remote) } else { refsForRemote, err = git.RemoteRefs(remote) } if err != nil { return nil, err } refs[remote] = refsForRemote } return refs, nil }
[ "func", "getRemoteRefs", "(", "l", "*", "tasklog", ".", "Logger", ")", "(", "map", "[", "string", "]", "[", "]", "*", "git", ".", "Ref", ",", "error", ")", "{", "refs", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "*", "git", ".", "Ref", ")", "\n\n", "remotes", ",", "err", ":=", "git", ".", "RemoteList", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "!", "migrateSkipFetch", "{", "w", ":=", "l", ".", "Waiter", "(", "\"", "\"", ")", "\n", "if", "err", ":=", "git", ".", "Fetch", "(", "remotes", "...", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "w", ".", "Complete", "(", ")", "\n", "}", "\n\n", "for", "_", ",", "remote", ":=", "range", "remotes", "{", "var", "refsForRemote", "[", "]", "*", "git", ".", "Ref", "\n", "if", "migrateSkipFetch", "{", "refsForRemote", ",", "err", "=", "git", ".", "CachedRemoteRefs", "(", "remote", ")", "\n", "}", "else", "{", "refsForRemote", ",", "err", "=", "git", ".", "RemoteRefs", "(", "remote", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "refs", "[", "remote", "]", "=", "refsForRemote", "\n", "}", "\n\n", "return", "refs", ",", "nil", "\n", "}" ]
// getRemoteRefs returns a fully qualified set of references belonging to all // remotes known by the currently checked-out repository, or an error if those // references could not be determined.
[ "getRemoteRefs", "returns", "a", "fully", "qualified", "set", "of", "references", "belonging", "to", "all", "remotes", "known", "by", "the", "currently", "checked", "-", "out", "repository", "or", "an", "error", "if", "those", "references", "could", "not", "be", "determined", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/commands/command_migrate.go#L239-L271
train
git-lfs/git-lfs
commands/command_migrate.go
formatRefName
func formatRefName(ref *git.Ref, remote string) string { if ref.Type == git.RefTypeRemoteBranch { return strings.Join([]string{ "refs", "remotes", remote, ref.Name}, "/") } return ref.Refspec() }
go
func formatRefName(ref *git.Ref, remote string) string { if ref.Type == git.RefTypeRemoteBranch { return strings.Join([]string{ "refs", "remotes", remote, ref.Name}, "/") } return ref.Refspec() }
[ "func", "formatRefName", "(", "ref", "*", "git", ".", "Ref", ",", "remote", "string", ")", "string", "{", "if", "ref", ".", "Type", "==", "git", ".", "RefTypeRemoteBranch", "{", "return", "strings", ".", "Join", "(", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "remote", ",", "ref", ".", "Name", "}", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "ref", ".", "Refspec", "(", ")", "\n\n", "}" ]
// formatRefName returns the fully-qualified name for the given Git reference // "ref".
[ "formatRefName", "returns", "the", "fully", "-", "qualified", "name", "for", "the", "given", "Git", "reference", "ref", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/commands/command_migrate.go#L275-L282
train
git-lfs/git-lfs
commands/command_migrate.go
currentRefToMigrate
func currentRefToMigrate() (*git.Ref, error) { current, err := git.CurrentRef() if err != nil { return nil, err } if current.Type == git.RefTypeOther || current.Type == git.RefTypeRemoteBranch { return nil, errors.Errorf("fatal: cannot migrate non-local ref: %s", current.Name) } return current, nil }
go
func currentRefToMigrate() (*git.Ref, error) { current, err := git.CurrentRef() if err != nil { return nil, err } if current.Type == git.RefTypeOther || current.Type == git.RefTypeRemoteBranch { return nil, errors.Errorf("fatal: cannot migrate non-local ref: %s", current.Name) } return current, nil }
[ "func", "currentRefToMigrate", "(", ")", "(", "*", "git", ".", "Ref", ",", "error", ")", "{", "current", ",", "err", ":=", "git", ".", "CurrentRef", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "current", ".", "Type", "==", "git", ".", "RefTypeOther", "||", "current", ".", "Type", "==", "git", ".", "RefTypeRemoteBranch", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "current", ".", "Name", ")", "\n", "}", "\n", "return", "current", ",", "nil", "\n", "}" ]
// currentRefToMigrate returns the fully-qualified name of the currently // checked-out reference, or an error if the reference's type was not a local // branch.
[ "currentRefToMigrate", "returns", "the", "fully", "-", "qualified", "name", "of", "the", "currently", "checked", "-", "out", "reference", "or", "an", "error", "if", "the", "reference", "s", "type", "was", "not", "a", "local", "branch", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/commands/command_migrate.go#L287-L299
train
git-lfs/git-lfs
commands/command_track.go
blocklistItem
func blocklistItem(name string) string { base := filepath.Base(name) for _, p := range prefixBlocklist { if strings.HasPrefix(base, p) { return p } } return "" }
go
func blocklistItem(name string) string { base := filepath.Base(name) for _, p := range prefixBlocklist { if strings.HasPrefix(base, p) { return p } } return "" }
[ "func", "blocklistItem", "(", "name", "string", ")", "string", "{", "base", ":=", "filepath", ".", "Base", "(", "name", ")", "\n\n", "for", "_", ",", "p", ":=", "range", "prefixBlocklist", "{", "if", "strings", ".", "HasPrefix", "(", "base", ",", "p", ")", "{", "return", "p", "\n", "}", "\n", "}", "\n\n", "return", "\"", "\"", "\n", "}" ]
// blocklistItem returns the name of the blocklist item preventing the given // file-name from being tracked, or an empty string, if there is none.
[ "blocklistItem", "returns", "the", "name", "of", "the", "blocklist", "item", "preventing", "the", "given", "file", "-", "name", "from", "being", "tracked", "or", "an", "empty", "string", "if", "there", "is", "none", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/commands/command_track.go#L276-L286
train
git-lfs/git-lfs
config/config.go
HookDir
func (c *Configuration) HookDir() (string, error) { if git.IsGitVersionAtLeast("2.9.0") { hp, ok := c.Git.Get("core.hooksPath") if ok { return tools.ExpandPath(hp, false) } } return filepath.Join(c.LocalGitStorageDir(), "hooks"), nil }
go
func (c *Configuration) HookDir() (string, error) { if git.IsGitVersionAtLeast("2.9.0") { hp, ok := c.Git.Get("core.hooksPath") if ok { return tools.ExpandPath(hp, false) } } return filepath.Join(c.LocalGitStorageDir(), "hooks"), nil }
[ "func", "(", "c", "*", "Configuration", ")", "HookDir", "(", ")", "(", "string", ",", "error", ")", "{", "if", "git", ".", "IsGitVersionAtLeast", "(", "\"", "\"", ")", "{", "hp", ",", "ok", ":=", "c", ".", "Git", ".", "Get", "(", "\"", "\"", ")", "\n", "if", "ok", "{", "return", "tools", ".", "ExpandPath", "(", "hp", ",", "false", ")", "\n", "}", "\n", "}", "\n", "return", "filepath", ".", "Join", "(", "c", ".", "LocalGitStorageDir", "(", ")", ",", "\"", "\"", ")", ",", "nil", "\n", "}" ]
// HookDir returns the location of the hooks owned by this repository. If the // core.hooksPath configuration variable is supported, we prefer that and expand // paths appropriately.
[ "HookDir", "returns", "the", "location", "of", "the", "hooks", "owned", "by", "this", "repository", ".", "If", "the", "core", ".", "hooksPath", "configuration", "variable", "is", "supported", "we", "prefer", "that", "and", "expand", "paths", "appropriately", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/config/config.go#L328-L336
train
git-lfs/git-lfs
config/config.go
RepositoryPermissions
func (c *Configuration) RepositoryPermissions(executable bool) os.FileMode { perms := os.FileMode(0666 & ^c.getMask()) if executable { return tools.ExecutablePermissions(perms) } return perms }
go
func (c *Configuration) RepositoryPermissions(executable bool) os.FileMode { perms := os.FileMode(0666 & ^c.getMask()) if executable { return tools.ExecutablePermissions(perms) } return perms }
[ "func", "(", "c", "*", "Configuration", ")", "RepositoryPermissions", "(", "executable", "bool", ")", "os", ".", "FileMode", "{", "perms", ":=", "os", ".", "FileMode", "(", "0666", "&", "^", "c", ".", "getMask", "(", ")", ")", "\n", "if", "executable", "{", "return", "tools", ".", "ExecutablePermissions", "(", "perms", ")", "\n", "}", "\n", "return", "perms", "\n", "}" ]
// RepositoryPermissions returns the permissions that should be used to write // files in the repository.
[ "RepositoryPermissions", "returns", "the", "permissions", "that", "should", "be", "used", "to", "write", "files", "in", "the", "repository", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/config/config.go#L625-L631
train
git-lfs/git-lfs
lfshttp/stats.go
LogRequest
func (c *Client) LogRequest(r *http.Request, reqKey string) *http.Request { if c.httpLogger == nil { return r } t := &httpTransfer{ URL: strings.SplitN(r.URL.String(), "?", 2)[0], Method: r.Method, Key: reqKey, } ctx := httptrace.WithClientTrace(r.Context(), &httptrace.ClientTrace{ GetConn: func(_ string) { atomic.CompareAndSwapInt64(&t.Start, 0, time.Now().UnixNano()) }, DNSStart: func(_ httptrace.DNSStartInfo) { atomic.CompareAndSwapInt64(&t.DNSStart, 0, time.Now().UnixNano()) }, DNSDone: func(_ httptrace.DNSDoneInfo) { atomic.CompareAndSwapInt64(&t.DNSEnd, 0, time.Now().UnixNano()) }, ConnectStart: func(_, _ string) { atomic.CompareAndSwapInt64(&t.ConnStart, 0, time.Now().UnixNano()) }, ConnectDone: func(_, _ string, _ error) { atomic.CompareAndSwapInt64(&t.ConnEnd, 0, time.Now().UnixNano()) }, TLSHandshakeStart: func() { atomic.CompareAndSwapInt64(&t.TLSStart, 0, time.Now().UnixNano()) }, TLSHandshakeDone: func(_ tls.ConnectionState, _ error) { atomic.CompareAndSwapInt64(&t.TLSEnd, 0, time.Now().UnixNano()) }, GotFirstResponseByte: func() { atomic.CompareAndSwapInt64(&t.ResponseStart, 0, time.Now().UnixNano()) }, }) return r.WithContext(context.WithValue(ctx, transferKey, t)) }
go
func (c *Client) LogRequest(r *http.Request, reqKey string) *http.Request { if c.httpLogger == nil { return r } t := &httpTransfer{ URL: strings.SplitN(r.URL.String(), "?", 2)[0], Method: r.Method, Key: reqKey, } ctx := httptrace.WithClientTrace(r.Context(), &httptrace.ClientTrace{ GetConn: func(_ string) { atomic.CompareAndSwapInt64(&t.Start, 0, time.Now().UnixNano()) }, DNSStart: func(_ httptrace.DNSStartInfo) { atomic.CompareAndSwapInt64(&t.DNSStart, 0, time.Now().UnixNano()) }, DNSDone: func(_ httptrace.DNSDoneInfo) { atomic.CompareAndSwapInt64(&t.DNSEnd, 0, time.Now().UnixNano()) }, ConnectStart: func(_, _ string) { atomic.CompareAndSwapInt64(&t.ConnStart, 0, time.Now().UnixNano()) }, ConnectDone: func(_, _ string, _ error) { atomic.CompareAndSwapInt64(&t.ConnEnd, 0, time.Now().UnixNano()) }, TLSHandshakeStart: func() { atomic.CompareAndSwapInt64(&t.TLSStart, 0, time.Now().UnixNano()) }, TLSHandshakeDone: func(_ tls.ConnectionState, _ error) { atomic.CompareAndSwapInt64(&t.TLSEnd, 0, time.Now().UnixNano()) }, GotFirstResponseByte: func() { atomic.CompareAndSwapInt64(&t.ResponseStart, 0, time.Now().UnixNano()) }, }) return r.WithContext(context.WithValue(ctx, transferKey, t)) }
[ "func", "(", "c", "*", "Client", ")", "LogRequest", "(", "r", "*", "http", ".", "Request", ",", "reqKey", "string", ")", "*", "http", ".", "Request", "{", "if", "c", ".", "httpLogger", "==", "nil", "{", "return", "r", "\n", "}", "\n\n", "t", ":=", "&", "httpTransfer", "{", "URL", ":", "strings", ".", "SplitN", "(", "r", ".", "URL", ".", "String", "(", ")", ",", "\"", "\"", ",", "2", ")", "[", "0", "]", ",", "Method", ":", "r", ".", "Method", ",", "Key", ":", "reqKey", ",", "}", "\n\n", "ctx", ":=", "httptrace", ".", "WithClientTrace", "(", "r", ".", "Context", "(", ")", ",", "&", "httptrace", ".", "ClientTrace", "{", "GetConn", ":", "func", "(", "_", "string", ")", "{", "atomic", ".", "CompareAndSwapInt64", "(", "&", "t", ".", "Start", ",", "0", ",", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ")", "\n", "}", ",", "DNSStart", ":", "func", "(", "_", "httptrace", ".", "DNSStartInfo", ")", "{", "atomic", ".", "CompareAndSwapInt64", "(", "&", "t", ".", "DNSStart", ",", "0", ",", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ")", "\n", "}", ",", "DNSDone", ":", "func", "(", "_", "httptrace", ".", "DNSDoneInfo", ")", "{", "atomic", ".", "CompareAndSwapInt64", "(", "&", "t", ".", "DNSEnd", ",", "0", ",", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ")", "\n", "}", ",", "ConnectStart", ":", "func", "(", "_", ",", "_", "string", ")", "{", "atomic", ".", "CompareAndSwapInt64", "(", "&", "t", ".", "ConnStart", ",", "0", ",", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ")", "\n", "}", ",", "ConnectDone", ":", "func", "(", "_", ",", "_", "string", ",", "_", "error", ")", "{", "atomic", ".", "CompareAndSwapInt64", "(", "&", "t", ".", "ConnEnd", ",", "0", ",", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ")", "\n", "}", ",", "TLSHandshakeStart", ":", "func", "(", ")", "{", "atomic", ".", "CompareAndSwapInt64", "(", "&", "t", ".", "TLSStart", ",", "0", ",", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ")", "\n", "}", ",", "TLSHandshakeDone", ":", "func", "(", "_", "tls", ".", "ConnectionState", ",", "_", "error", ")", "{", "atomic", ".", "CompareAndSwapInt64", "(", "&", "t", ".", "TLSEnd", ",", "0", ",", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ")", "\n", "}", ",", "GotFirstResponseByte", ":", "func", "(", ")", "{", "atomic", ".", "CompareAndSwapInt64", "(", "&", "t", ".", "ResponseStart", ",", "0", ",", "time", ".", "Now", "(", ")", ".", "UnixNano", "(", ")", ")", "\n", "}", ",", "}", ")", "\n\n", "return", "r", ".", "WithContext", "(", "context", ".", "WithValue", "(", "ctx", ",", "transferKey", ",", "t", ")", ")", "\n", "}" ]
// LogRequest tells the client to log the request's stats to the http log // after the response body has been read.
[ "LogRequest", "tells", "the", "client", "to", "log", "the", "request", "s", "stats", "to", "the", "http", "log", "after", "the", "response", "body", "has", "been", "read", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/lfshttp/stats.go#L54-L93
train
git-lfs/git-lfs
tools/kv/keyvaluestore.go
Visit
func (k *Store) Visit(cb func(string, interface{}) bool) { // Read-only lock k.mu.RLock() defer k.mu.RUnlock() for k, v := range k.db { if !cb(k, v) { break } } }
go
func (k *Store) Visit(cb func(string, interface{}) bool) { // Read-only lock k.mu.RLock() defer k.mu.RUnlock() for k, v := range k.db { if !cb(k, v) { break } } }
[ "func", "(", "k", "*", "Store", ")", "Visit", "(", "cb", "func", "(", "string", ",", "interface", "{", "}", ")", "bool", ")", "{", "// Read-only lock", "k", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "k", ".", "mu", ".", "RUnlock", "(", ")", "\n\n", "for", "k", ",", "v", ":=", "range", "k", ".", "db", "{", "if", "!", "cb", "(", "k", ",", "v", ")", "{", "break", "\n", "}", "\n", "}", "\n", "}" ]
// Visit walks through the entire store via a function; return false from // your visitor function to halt the walk
[ "Visit", "walks", "through", "the", "entire", "store", "via", "a", "function", ";", "return", "false", "from", "your", "visitor", "function", "to", "halt", "the", "walk" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/kv/keyvaluestore.go#L89-L99
train
git-lfs/git-lfs
tools/kv/keyvaluestore.go
logChange
func (k *Store) logChange(op operation, key string, value interface{}) { k.log = append(k.log, change{op, key, value}) }
go
func (k *Store) logChange(op operation, key string, value interface{}) { k.log = append(k.log, change{op, key, value}) }
[ "func", "(", "k", "*", "Store", ")", "logChange", "(", "op", "operation", ",", "key", "string", ",", "value", "interface", "{", "}", ")", "{", "k", ".", "log", "=", "append", "(", "k", ".", "log", ",", "change", "{", "op", ",", "key", ",", "value", "}", ")", "\n", "}" ]
// Append a change to the log; mutex must already be locked
[ "Append", "a", "change", "to", "the", "log", ";", "mutex", "must", "already", "be", "locked" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/kv/keyvaluestore.go#L102-L104
train
git-lfs/git-lfs
tools/kv/keyvaluestore.go
Get
func (k *Store) Get(key string) interface{} { // Read-only lock k.mu.RLock() defer k.mu.RUnlock() // zero value of interface{} is nil so this does what we want return k.db[key] }
go
func (k *Store) Get(key string) interface{} { // Read-only lock k.mu.RLock() defer k.mu.RUnlock() // zero value of interface{} is nil so this does what we want return k.db[key] }
[ "func", "(", "k", "*", "Store", ")", "Get", "(", "key", "string", ")", "interface", "{", "}", "{", "// Read-only lock", "k", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "k", ".", "mu", ".", "RUnlock", "(", ")", "\n\n", "// zero value of interface{} is nil so this does what we want", "return", "k", ".", "db", "[", "key", "]", "\n", "}" ]
// Get retrieves a value from the store, or nil if it is not present
[ "Get", "retrieves", "a", "value", "from", "the", "store", "or", "nil", "if", "it", "is", "not", "present" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/kv/keyvaluestore.go#L107-L114
train
git-lfs/git-lfs
tools/kv/keyvaluestore.go
Save
func (k *Store) Save() error { k.mu.Lock() defer k.mu.Unlock() // Short-circuit if we have no changes if len(k.log) == 0 { return nil } // firstly peek at version; open read/write to keep lock between check & write f, err := os.OpenFile(k.filename, os.O_RDWR|os.O_CREATE, 0664) if err != nil { return err } defer f.Close() // Only try to merge if > 0 bytes, ignore empty files (decoder will fail) if stat, _ := f.Stat(); stat.Size() > 0 { k.loadAndMergeReaderIfNeeded(f) // Now we overwrite the file f.Seek(0, os.SEEK_SET) f.Truncate(0) } k.version++ enc := gob.NewEncoder(f) if err := enc.Encode(k.version); err != nil { return fmt.Errorf("Error while writing version data to %v: %v", k.filename, err) } if err := enc.Encode(k.db); err != nil { return fmt.Errorf("Error while writing new key/value data to %v: %v", k.filename, err) } // Clear log now that it's saved k.log = nil return nil }
go
func (k *Store) Save() error { k.mu.Lock() defer k.mu.Unlock() // Short-circuit if we have no changes if len(k.log) == 0 { return nil } // firstly peek at version; open read/write to keep lock between check & write f, err := os.OpenFile(k.filename, os.O_RDWR|os.O_CREATE, 0664) if err != nil { return err } defer f.Close() // Only try to merge if > 0 bytes, ignore empty files (decoder will fail) if stat, _ := f.Stat(); stat.Size() > 0 { k.loadAndMergeReaderIfNeeded(f) // Now we overwrite the file f.Seek(0, os.SEEK_SET) f.Truncate(0) } k.version++ enc := gob.NewEncoder(f) if err := enc.Encode(k.version); err != nil { return fmt.Errorf("Error while writing version data to %v: %v", k.filename, err) } if err := enc.Encode(k.db); err != nil { return fmt.Errorf("Error while writing new key/value data to %v: %v", k.filename, err) } // Clear log now that it's saved k.log = nil return nil }
[ "func", "(", "k", "*", "Store", ")", "Save", "(", ")", "error", "{", "k", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "k", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "// Short-circuit if we have no changes", "if", "len", "(", "k", ".", "log", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "// firstly peek at version; open read/write to keep lock between check & write", "f", ",", "err", ":=", "os", ".", "OpenFile", "(", "k", ".", "filename", ",", "os", ".", "O_RDWR", "|", "os", ".", "O_CREATE", ",", "0664", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "// Only try to merge if > 0 bytes, ignore empty files (decoder will fail)", "if", "stat", ",", "_", ":=", "f", ".", "Stat", "(", ")", ";", "stat", ".", "Size", "(", ")", ">", "0", "{", "k", ".", "loadAndMergeReaderIfNeeded", "(", "f", ")", "\n", "// Now we overwrite the file", "f", ".", "Seek", "(", "0", ",", "os", ".", "SEEK_SET", ")", "\n", "f", ".", "Truncate", "(", "0", ")", "\n", "}", "\n\n", "k", ".", "version", "++", "\n\n", "enc", ":=", "gob", ".", "NewEncoder", "(", "f", ")", "\n", "if", "err", ":=", "enc", ".", "Encode", "(", "k", ".", "version", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "k", ".", "filename", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "enc", ".", "Encode", "(", "k", ".", "db", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "k", ".", "filename", ",", "err", ")", "\n", "}", "\n", "// Clear log now that it's saved", "k", ".", "log", "=", "nil", "\n\n", "return", "nil", "\n", "}" ]
// Save persists the changes made to disk // If any changes have been written by other code they will be merged
[ "Save", "persists", "the", "changes", "made", "to", "disk", "If", "any", "changes", "have", "been", "written", "by", "other", "code", "they", "will", "be", "merged" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/kv/keyvaluestore.go#L118-L156
train
git-lfs/git-lfs
tools/kv/keyvaluestore.go
loadAndMergeIfNeeded
func (k *Store) loadAndMergeIfNeeded() error { stat, err := os.Stat(k.filename) if err != nil { if os.IsNotExist(err) { return nil // missing is OK } return err } // Do nothing if empty file if stat.Size() == 0 { return nil } f, err := os.OpenFile(k.filename, os.O_RDONLY, 0664) if err == nil { defer f.Close() return k.loadAndMergeReaderIfNeeded(f) } else { return err } }
go
func (k *Store) loadAndMergeIfNeeded() error { stat, err := os.Stat(k.filename) if err != nil { if os.IsNotExist(err) { return nil // missing is OK } return err } // Do nothing if empty file if stat.Size() == 0 { return nil } f, err := os.OpenFile(k.filename, os.O_RDONLY, 0664) if err == nil { defer f.Close() return k.loadAndMergeReaderIfNeeded(f) } else { return err } }
[ "func", "(", "k", "*", "Store", ")", "loadAndMergeIfNeeded", "(", ")", "error", "{", "stat", ",", "err", ":=", "os", ".", "Stat", "(", "k", ".", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "nil", "// missing is OK", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "// Do nothing if empty file", "if", "stat", ".", "Size", "(", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "f", ",", "err", ":=", "os", ".", "OpenFile", "(", "k", ".", "filename", ",", "os", ".", "O_RDONLY", ",", "0664", ")", "\n", "if", "err", "==", "nil", "{", "defer", "f", ".", "Close", "(", ")", "\n", "return", "k", ".", "loadAndMergeReaderIfNeeded", "(", "f", ")", "\n", "}", "else", "{", "return", "err", "\n", "}", "\n", "}" ]
// Reads as little as possible from the passed in file to determine if the // contents are different from the version already held. If so, reads the // contents and merges with any outstanding changes. If not, stops early without // reading the rest of the file
[ "Reads", "as", "little", "as", "possible", "from", "the", "passed", "in", "file", "to", "determine", "if", "the", "contents", "are", "different", "from", "the", "version", "already", "held", ".", "If", "so", "reads", "the", "contents", "and", "merges", "with", "any", "outstanding", "changes", ".", "If", "not", "stops", "early", "without", "reading", "the", "rest", "of", "the", "file" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/kv/keyvaluestore.go#L162-L182
train
git-lfs/git-lfs
tools/kv/keyvaluestore.go
loadAndMergeReaderIfNeeded
func (k *Store) loadAndMergeReaderIfNeeded(f io.Reader) error { var versionOnDisk int64 // Decode *only* the version field to check whether anyone else has // modified the db; gob serializes structs in order so it will always be 1st dec := gob.NewDecoder(f) err := dec.Decode(&versionOnDisk) if err != nil { return fmt.Errorf("Problem checking version of key/value data from %v: %v", k.filename, err) } // Totally uninitialised Version == 0, saved versions are always >=1 if versionOnDisk != k.version { // Reload data & merge var dbOnDisk map[string]interface{} err = dec.Decode(&dbOnDisk) if err != nil { return fmt.Errorf("Problem reading updated key/value data from %v: %v", k.filename, err) } k.reapplyChanges(dbOnDisk) k.version = versionOnDisk } return nil }
go
func (k *Store) loadAndMergeReaderIfNeeded(f io.Reader) error { var versionOnDisk int64 // Decode *only* the version field to check whether anyone else has // modified the db; gob serializes structs in order so it will always be 1st dec := gob.NewDecoder(f) err := dec.Decode(&versionOnDisk) if err != nil { return fmt.Errorf("Problem checking version of key/value data from %v: %v", k.filename, err) } // Totally uninitialised Version == 0, saved versions are always >=1 if versionOnDisk != k.version { // Reload data & merge var dbOnDisk map[string]interface{} err = dec.Decode(&dbOnDisk) if err != nil { return fmt.Errorf("Problem reading updated key/value data from %v: %v", k.filename, err) } k.reapplyChanges(dbOnDisk) k.version = versionOnDisk } return nil }
[ "func", "(", "k", "*", "Store", ")", "loadAndMergeReaderIfNeeded", "(", "f", "io", ".", "Reader", ")", "error", "{", "var", "versionOnDisk", "int64", "\n", "// Decode *only* the version field to check whether anyone else has", "// modified the db; gob serializes structs in order so it will always be 1st", "dec", ":=", "gob", ".", "NewDecoder", "(", "f", ")", "\n", "err", ":=", "dec", ".", "Decode", "(", "&", "versionOnDisk", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "k", ".", "filename", ",", "err", ")", "\n", "}", "\n", "// Totally uninitialised Version == 0, saved versions are always >=1", "if", "versionOnDisk", "!=", "k", ".", "version", "{", "// Reload data & merge", "var", "dbOnDisk", "map", "[", "string", "]", "interface", "{", "}", "\n", "err", "=", "dec", ".", "Decode", "(", "&", "dbOnDisk", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "k", ".", "filename", ",", "err", ")", "\n", "}", "\n", "k", ".", "reapplyChanges", "(", "dbOnDisk", ")", "\n", "k", ".", "version", "=", "versionOnDisk", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// As loadAndMergeIfNeeded but lets caller decide how to manage file handles
[ "As", "loadAndMergeIfNeeded", "but", "lets", "caller", "decide", "how", "to", "manage", "file", "handles" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/kv/keyvaluestore.go#L185-L206
train
git-lfs/git-lfs
tools/kv/keyvaluestore.go
reapplyChanges
func (k *Store) reapplyChanges(baseDb map[string]interface{}) { for _, change := range k.log { switch change.op { case setOperation: baseDb[change.key] = change.value case removeOperation: delete(baseDb, change.key) } } // Note, log is not cleared here, that only happens on Save since it's a // list of unsaved changes k.db = baseDb }
go
func (k *Store) reapplyChanges(baseDb map[string]interface{}) { for _, change := range k.log { switch change.op { case setOperation: baseDb[change.key] = change.value case removeOperation: delete(baseDb, change.key) } } // Note, log is not cleared here, that only happens on Save since it's a // list of unsaved changes k.db = baseDb }
[ "func", "(", "k", "*", "Store", ")", "reapplyChanges", "(", "baseDb", "map", "[", "string", "]", "interface", "{", "}", ")", "{", "for", "_", ",", "change", ":=", "range", "k", ".", "log", "{", "switch", "change", ".", "op", "{", "case", "setOperation", ":", "baseDb", "[", "change", ".", "key", "]", "=", "change", ".", "value", "\n", "case", "removeOperation", ":", "delete", "(", "baseDb", ",", "change", ".", "key", ")", "\n", "}", "\n", "}", "\n", "// Note, log is not cleared here, that only happens on Save since it's a", "// list of unsaved changes", "k", ".", "db", "=", "baseDb", "\n\n", "}" ]
// reapplyChanges replays the changes made since the last load onto baseDb // and stores the result as our own DB
[ "reapplyChanges", "replays", "the", "changes", "made", "since", "the", "last", "load", "onto", "baseDb", "and", "stores", "the", "result", "as", "our", "own", "DB" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/kv/keyvaluestore.go#L210-L223
train
git-lfs/git-lfs
locking/lockable.go
refreshLockablePatterns
func (c *Client) refreshLockablePatterns() { paths := git.GetAttributePaths(gitattr.NewMacroProcessor(), c.LocalWorkingDir, c.LocalGitDir) // Always make non-nil even if empty c.lockablePatterns = make([]string, 0, len(paths)) for _, p := range paths { if p.Lockable { c.lockablePatterns = append(c.lockablePatterns, p.Path) } } c.lockableFilter = filepathfilter.New(c.lockablePatterns, nil) }
go
func (c *Client) refreshLockablePatterns() { paths := git.GetAttributePaths(gitattr.NewMacroProcessor(), c.LocalWorkingDir, c.LocalGitDir) // Always make non-nil even if empty c.lockablePatterns = make([]string, 0, len(paths)) for _, p := range paths { if p.Lockable { c.lockablePatterns = append(c.lockablePatterns, p.Path) } } c.lockableFilter = filepathfilter.New(c.lockablePatterns, nil) }
[ "func", "(", "c", "*", "Client", ")", "refreshLockablePatterns", "(", ")", "{", "paths", ":=", "git", ".", "GetAttributePaths", "(", "gitattr", ".", "NewMacroProcessor", "(", ")", ",", "c", ".", "LocalWorkingDir", ",", "c", ".", "LocalGitDir", ")", "\n", "// Always make non-nil even if empty", "c", ".", "lockablePatterns", "=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "paths", ")", ")", "\n", "for", "_", ",", "p", ":=", "range", "paths", "{", "if", "p", ".", "Lockable", "{", "c", ".", "lockablePatterns", "=", "append", "(", "c", ".", "lockablePatterns", ",", "p", ".", "Path", ")", "\n", "}", "\n", "}", "\n", "c", ".", "lockableFilter", "=", "filepathfilter", ".", "New", "(", "c", ".", "lockablePatterns", ",", "nil", ")", "\n", "}" ]
// Internal function to repopulate lockable patterns // You must have locked the c.lockableMutex in the caller
[ "Internal", "function", "to", "repopulate", "lockable", "patterns", "You", "must", "have", "locked", "the", "c", ".", "lockableMutex", "in", "the", "caller" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/locking/lockable.go#L42-L52
train
git-lfs/git-lfs
locking/lockable.go
IsFileLockable
func (c *Client) IsFileLockable(path string) bool { return c.getLockableFilter().Allows(path) }
go
func (c *Client) IsFileLockable(path string) bool { return c.getLockableFilter().Allows(path) }
[ "func", "(", "c", "*", "Client", ")", "IsFileLockable", "(", "path", "string", ")", "bool", "{", "return", "c", ".", "getLockableFilter", "(", ")", ".", "Allows", "(", "path", ")", "\n", "}" ]
// IsFileLockable returns whether a specific file path is marked as Lockable, // ie has the 'lockable' attribute in .gitattributes // Lockable patterns are cached once for performance, unless you call RefreshLockablePatterns // path should be relative to repository root
[ "IsFileLockable", "returns", "whether", "a", "specific", "file", "path", "is", "marked", "as", "Lockable", "ie", "has", "the", "lockable", "attribute", "in", ".", "gitattributes", "Lockable", "patterns", "are", "cached", "once", "for", "performance", "unless", "you", "call", "RefreshLockablePatterns", "path", "should", "be", "relative", "to", "repository", "root" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/locking/lockable.go#L58-L60
train
git-lfs/git-lfs
locking/lockable.go
FixAllLockableFileWriteFlags
func (c *Client) FixAllLockableFileWriteFlags() error { return c.fixFileWriteFlags(c.LocalWorkingDir, c.LocalWorkingDir, c.getLockableFilter(), nil) }
go
func (c *Client) FixAllLockableFileWriteFlags() error { return c.fixFileWriteFlags(c.LocalWorkingDir, c.LocalWorkingDir, c.getLockableFilter(), nil) }
[ "func", "(", "c", "*", "Client", ")", "FixAllLockableFileWriteFlags", "(", ")", "error", "{", "return", "c", ".", "fixFileWriteFlags", "(", "c", ".", "LocalWorkingDir", ",", "c", ".", "LocalWorkingDir", ",", "c", ".", "getLockableFilter", "(", ")", ",", "nil", ")", "\n", "}" ]
// FixAllLockableFileWriteFlags recursively scans the repo looking for files which // are lockable, and makes sure their write flags are set correctly based on // whether they are currently locked or unlocked. // Files which are unlocked are made read-only, files which are locked are made // writeable. // This function can be used after a clone or checkout to ensure that file // state correctly reflects the locking state
[ "FixAllLockableFileWriteFlags", "recursively", "scans", "the", "repo", "looking", "for", "files", "which", "are", "lockable", "and", "makes", "sure", "their", "write", "flags", "are", "set", "correctly", "based", "on", "whether", "they", "are", "currently", "locked", "or", "unlocked", ".", "Files", "which", "are", "unlocked", "are", "made", "read", "-", "only", "files", "which", "are", "locked", "are", "made", "writeable", ".", "This", "function", "can", "be", "used", "after", "a", "clone", "or", "checkout", "to", "ensure", "that", "file", "state", "correctly", "reflects", "the", "locking", "state" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/locking/lockable.go#L69-L71
train
git-lfs/git-lfs
locking/lockable.go
fixFileWriteFlags
func (c *Client) fixFileWriteFlags(absPath, workingDir string, lockable, unlockable *filepathfilter.Filter) error { var errs []error var errMux sync.Mutex addErr := func(err error) { errMux.Lock() defer errMux.Unlock() errs = append(errs, err) } recursor := tools.FastWalkGitRepo if c.ModifyIgnoredFiles { recursor = tools.FastWalkGitRepoAll } recursor(absPath, func(parentDir string, fi os.FileInfo, err error) { if err != nil { addErr(err) return } // Skip dirs, we only need to check files if fi.IsDir() { return } abschild := filepath.Join(parentDir, fi.Name()) // This is a file, get relative to repo root relpath, err := filepath.Rel(workingDir, abschild) if err != nil { addErr(err) return } err = c.fixSingleFileWriteFlags(relpath, lockable, unlockable) if err != nil { addErr(err) } }) return errors.Combine(errs) }
go
func (c *Client) fixFileWriteFlags(absPath, workingDir string, lockable, unlockable *filepathfilter.Filter) error { var errs []error var errMux sync.Mutex addErr := func(err error) { errMux.Lock() defer errMux.Unlock() errs = append(errs, err) } recursor := tools.FastWalkGitRepo if c.ModifyIgnoredFiles { recursor = tools.FastWalkGitRepoAll } recursor(absPath, func(parentDir string, fi os.FileInfo, err error) { if err != nil { addErr(err) return } // Skip dirs, we only need to check files if fi.IsDir() { return } abschild := filepath.Join(parentDir, fi.Name()) // This is a file, get relative to repo root relpath, err := filepath.Rel(workingDir, abschild) if err != nil { addErr(err) return } err = c.fixSingleFileWriteFlags(relpath, lockable, unlockable) if err != nil { addErr(err) } }) return errors.Combine(errs) }
[ "func", "(", "c", "*", "Client", ")", "fixFileWriteFlags", "(", "absPath", ",", "workingDir", "string", ",", "lockable", ",", "unlockable", "*", "filepathfilter", ".", "Filter", ")", "error", "{", "var", "errs", "[", "]", "error", "\n", "var", "errMux", "sync", ".", "Mutex", "\n\n", "addErr", ":=", "func", "(", "err", "error", ")", "{", "errMux", ".", "Lock", "(", ")", "\n", "defer", "errMux", ".", "Unlock", "(", ")", "\n\n", "errs", "=", "append", "(", "errs", ",", "err", ")", "\n", "}", "\n\n", "recursor", ":=", "tools", ".", "FastWalkGitRepo", "\n", "if", "c", ".", "ModifyIgnoredFiles", "{", "recursor", "=", "tools", ".", "FastWalkGitRepoAll", "\n", "}", "\n\n", "recursor", "(", "absPath", ",", "func", "(", "parentDir", "string", ",", "fi", "os", ".", "FileInfo", ",", "err", "error", ")", "{", "if", "err", "!=", "nil", "{", "addErr", "(", "err", ")", "\n", "return", "\n", "}", "\n", "// Skip dirs, we only need to check files", "if", "fi", ".", "IsDir", "(", ")", "{", "return", "\n", "}", "\n", "abschild", ":=", "filepath", ".", "Join", "(", "parentDir", ",", "fi", ".", "Name", "(", ")", ")", "\n\n", "// This is a file, get relative to repo root", "relpath", ",", "err", ":=", "filepath", ".", "Rel", "(", "workingDir", ",", "abschild", ")", "\n", "if", "err", "!=", "nil", "{", "addErr", "(", "err", ")", "\n", "return", "\n", "}", "\n\n", "err", "=", "c", ".", "fixSingleFileWriteFlags", "(", "relpath", ",", "lockable", ",", "unlockable", ")", "\n", "if", "err", "!=", "nil", "{", "addErr", "(", "err", ")", "\n", "}", "\n\n", "}", ")", "\n", "return", "errors", ".", "Combine", "(", "errs", ")", "\n", "}" ]
// Internal implementation of fixing file write flags with precompiled filters
[ "Internal", "implementation", "of", "fixing", "file", "write", "flags", "with", "precompiled", "filters" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/locking/lockable.go#L114-L156
train
git-lfs/git-lfs
locking/lockable.go
FixLockableFileWriteFlags
func (c *Client) FixLockableFileWriteFlags(files []string) error { // early-out if no lockable patterns if len(c.GetLockablePatterns()) == 0 { return nil } var errs []error for _, f := range files { err := c.fixSingleFileWriteFlags(f, c.getLockableFilter(), nil) if err != nil { errs = append(errs, err) } } return errors.Combine(errs) }
go
func (c *Client) FixLockableFileWriteFlags(files []string) error { // early-out if no lockable patterns if len(c.GetLockablePatterns()) == 0 { return nil } var errs []error for _, f := range files { err := c.fixSingleFileWriteFlags(f, c.getLockableFilter(), nil) if err != nil { errs = append(errs, err) } } return errors.Combine(errs) }
[ "func", "(", "c", "*", "Client", ")", "FixLockableFileWriteFlags", "(", "files", "[", "]", "string", ")", "error", "{", "// early-out if no lockable patterns", "if", "len", "(", "c", ".", "GetLockablePatterns", "(", ")", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "var", "errs", "[", "]", "error", "\n", "for", "_", ",", "f", ":=", "range", "files", "{", "err", ":=", "c", ".", "fixSingleFileWriteFlags", "(", "f", ",", "c", ".", "getLockableFilter", "(", ")", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "errs", "=", "append", "(", "errs", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "errors", ".", "Combine", "(", "errs", ")", "\n", "}" ]
// FixLockableFileWriteFlags checks each file in the provided list, and for // those which are lockable, makes sure their write flags are set correctly // based on whether they are currently locked or unlocked. Files which are // unlocked are made read-only, files which are locked are made writeable. // Files which are not lockable are ignored. // This function can be used after a clone or checkout to ensure that file // state correctly reflects the locking state, and is more efficient than // FixAllLockableFileWriteFlags when you know which files changed
[ "FixLockableFileWriteFlags", "checks", "each", "file", "in", "the", "provided", "list", "and", "for", "those", "which", "are", "lockable", "makes", "sure", "their", "write", "flags", "are", "set", "correctly", "based", "on", "whether", "they", "are", "currently", "locked", "or", "unlocked", ".", "Files", "which", "are", "unlocked", "are", "made", "read", "-", "only", "files", "which", "are", "locked", "are", "made", "writeable", ".", "Files", "which", "are", "not", "lockable", "are", "ignored", ".", "This", "function", "can", "be", "used", "after", "a", "clone", "or", "checkout", "to", "ensure", "that", "file", "state", "correctly", "reflects", "the", "locking", "state", "and", "is", "more", "efficient", "than", "FixAllLockableFileWriteFlags", "when", "you", "know", "which", "files", "changed" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/locking/lockable.go#L166-L181
train
git-lfs/git-lfs
locking/lockable.go
fixSingleFileWriteFlags
func (c *Client) fixSingleFileWriteFlags(file string, lockable, unlockable *filepathfilter.Filter) error { // Convert to git-style forward slash separators if necessary // Necessary to match attributes if filepath.Separator == '\\' { file = strings.Replace(file, "\\", "/", -1) } if lockable != nil && lockable.Allows(file) { // Lockable files are writeable only if they're currently locked err := tools.SetFileWriteFlag(file, c.IsFileLockedByCurrentCommitter(file)) // Ignore not exist errors if err != nil && !os.IsNotExist(err) { return err } } else if unlockable != nil && unlockable.Allows(file) { // Unlockable files are always writeable // We only check files which match the incoming patterns to avoid // checking every file in the system all the time, and only do it // when a file has had its lockable attribute removed err := tools.SetFileWriteFlag(file, true) if err != nil && !os.IsNotExist(err) { return err } } return nil }
go
func (c *Client) fixSingleFileWriteFlags(file string, lockable, unlockable *filepathfilter.Filter) error { // Convert to git-style forward slash separators if necessary // Necessary to match attributes if filepath.Separator == '\\' { file = strings.Replace(file, "\\", "/", -1) } if lockable != nil && lockable.Allows(file) { // Lockable files are writeable only if they're currently locked err := tools.SetFileWriteFlag(file, c.IsFileLockedByCurrentCommitter(file)) // Ignore not exist errors if err != nil && !os.IsNotExist(err) { return err } } else if unlockable != nil && unlockable.Allows(file) { // Unlockable files are always writeable // We only check files which match the incoming patterns to avoid // checking every file in the system all the time, and only do it // when a file has had its lockable attribute removed err := tools.SetFileWriteFlag(file, true) if err != nil && !os.IsNotExist(err) { return err } } return nil }
[ "func", "(", "c", "*", "Client", ")", "fixSingleFileWriteFlags", "(", "file", "string", ",", "lockable", ",", "unlockable", "*", "filepathfilter", ".", "Filter", ")", "error", "{", "// Convert to git-style forward slash separators if necessary", "// Necessary to match attributes", "if", "filepath", ".", "Separator", "==", "'\\\\'", "{", "file", "=", "strings", ".", "Replace", "(", "file", ",", "\"", "\\\\", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "}", "\n", "if", "lockable", "!=", "nil", "&&", "lockable", ".", "Allows", "(", "file", ")", "{", "// Lockable files are writeable only if they're currently locked", "err", ":=", "tools", ".", "SetFileWriteFlag", "(", "file", ",", "c", ".", "IsFileLockedByCurrentCommitter", "(", "file", ")", ")", "\n", "// Ignore not exist errors", "if", "err", "!=", "nil", "&&", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "err", "\n", "}", "\n", "}", "else", "if", "unlockable", "!=", "nil", "&&", "unlockable", ".", "Allows", "(", "file", ")", "{", "// Unlockable files are always writeable", "// We only check files which match the incoming patterns to avoid", "// checking every file in the system all the time, and only do it", "// when a file has had its lockable attribute removed", "err", ":=", "tools", ".", "SetFileWriteFlag", "(", "file", ",", "true", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// fixSingleFileWriteFlags fixes write flags on a single file // If lockablePatterns is non-nil, then any file matching those patterns will be // checked to see if it is currently locked by the current committer, and if so // it will be writeable, and if not locked it will be read-only. // If unlockablePatterns is non-nil, then any file matching those patterns will // be made writeable if it is not already. This can be used to reset files to // writeable when their 'lockable' attribute is turned off.
[ "fixSingleFileWriteFlags", "fixes", "write", "flags", "on", "a", "single", "file", "If", "lockablePatterns", "is", "non", "-", "nil", "then", "any", "file", "matching", "those", "patterns", "will", "be", "checked", "to", "see", "if", "it", "is", "currently", "locked", "by", "the", "current", "committer", "and", "if", "so", "it", "will", "be", "writeable", "and", "if", "not", "locked", "it", "will", "be", "read", "-", "only", ".", "If", "unlockablePatterns", "is", "non", "-", "nil", "then", "any", "file", "matching", "those", "patterns", "will", "be", "made", "writeable", "if", "it", "is", "not", "already", ".", "This", "can", "be", "used", "to", "reset", "files", "to", "writeable", "when", "their", "lockable", "attribute", "is", "turned", "off", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/locking/lockable.go#L190-L214
train
git-lfs/git-lfs
tools/ordered_set.go
NewOrderedSetWithCapacity
func NewOrderedSetWithCapacity(capacity int) *OrderedSet { return &OrderedSet{ s: make([]string, 0, capacity), m: make(map[string]int, capacity), } }
go
func NewOrderedSetWithCapacity(capacity int) *OrderedSet { return &OrderedSet{ s: make([]string, 0, capacity), m: make(map[string]int, capacity), } }
[ "func", "NewOrderedSetWithCapacity", "(", "capacity", "int", ")", "*", "OrderedSet", "{", "return", "&", "OrderedSet", "{", "s", ":", "make", "(", "[", "]", "string", ",", "0", ",", "capacity", ")", ",", "m", ":", "make", "(", "map", "[", "string", "]", "int", ",", "capacity", ")", ",", "}", "\n", "}" ]
// NewOrderedSetWithCapacity creates a new ordered set with no values. The // returned ordered set can be appended to "capacity" number of times before it // grows internally.
[ "NewOrderedSetWithCapacity", "creates", "a", "new", "ordered", "set", "with", "no", "values", ".", "The", "returned", "ordered", "set", "can", "be", "appended", "to", "capacity", "number", "of", "times", "before", "it", "grows", "internally", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/ordered_set.go#L20-L25
train
git-lfs/git-lfs
tools/ordered_set.go
NewOrderedSetFromSlice
func NewOrderedSetFromSlice(s []string) *OrderedSet { set := NewOrderedSetWithCapacity(len(s)) for _, e := range s { set.Add(e) } return set }
go
func NewOrderedSetFromSlice(s []string) *OrderedSet { set := NewOrderedSetWithCapacity(len(s)) for _, e := range s { set.Add(e) } return set }
[ "func", "NewOrderedSetFromSlice", "(", "s", "[", "]", "string", ")", "*", "OrderedSet", "{", "set", ":=", "NewOrderedSetWithCapacity", "(", "len", "(", "s", ")", ")", "\n", "for", "_", ",", "e", ":=", "range", "s", "{", "set", ".", "Add", "(", "e", ")", "\n", "}", "\n\n", "return", "set", "\n", "}" ]
// NewOrderedSetFromSlice returns a new ordered set with the elements given in // the slice "s".
[ "NewOrderedSetFromSlice", "returns", "a", "new", "ordered", "set", "with", "the", "elements", "given", "in", "the", "slice", "s", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/ordered_set.go#L29-L36
train
git-lfs/git-lfs
tools/ordered_set.go
Add
func (s *OrderedSet) Add(i string) bool { if _, ok := s.m[i]; ok { return false } s.s = append(s.s, i) s.m[i] = len(s.s) - 1 return true }
go
func (s *OrderedSet) Add(i string) bool { if _, ok := s.m[i]; ok { return false } s.s = append(s.s, i) s.m[i] = len(s.s) - 1 return true }
[ "func", "(", "s", "*", "OrderedSet", ")", "Add", "(", "i", "string", ")", "bool", "{", "if", "_", ",", "ok", ":=", "s", ".", "m", "[", "i", "]", ";", "ok", "{", "return", "false", "\n", "}", "\n\n", "s", ".", "s", "=", "append", "(", "s", ".", "s", ",", "i", ")", "\n", "s", ".", "m", "[", "i", "]", "=", "len", "(", "s", ".", "s", ")", "-", "1", "\n\n", "return", "true", "\n", "}" ]
// Add adds the given element "i" to the ordered set, unless the element is // already present. It returns whether or not the element was added.
[ "Add", "adds", "the", "given", "element", "i", "to", "the", "ordered", "set", "unless", "the", "element", "is", "already", "present", ".", "It", "returns", "whether", "or", "not", "the", "element", "was", "added", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/ordered_set.go#L40-L49
train
git-lfs/git-lfs
tools/ordered_set.go
Contains
func (s *OrderedSet) Contains(i string) bool { if _, ok := s.m[i]; ok { return true } return false }
go
func (s *OrderedSet) Contains(i string) bool { if _, ok := s.m[i]; ok { return true } return false }
[ "func", "(", "s", "*", "OrderedSet", ")", "Contains", "(", "i", "string", ")", "bool", "{", "if", "_", ",", "ok", ":=", "s", ".", "m", "[", "i", "]", ";", "ok", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Contains returns whether or not the given "i" is contained in this ordered // set. It is a constant-time operation.
[ "Contains", "returns", "whether", "or", "not", "the", "given", "i", "is", "contained", "in", "this", "ordered", "set", ".", "It", "is", "a", "constant", "-", "time", "operation", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/ordered_set.go#L53-L58
train
git-lfs/git-lfs
tools/ordered_set.go
ContainsAll
func (s *OrderedSet) ContainsAll(i ...string) bool { for _, item := range i { if !s.Contains(item) { return false } } return true }
go
func (s *OrderedSet) ContainsAll(i ...string) bool { for _, item := range i { if !s.Contains(item) { return false } } return true }
[ "func", "(", "s", "*", "OrderedSet", ")", "ContainsAll", "(", "i", "...", "string", ")", "bool", "{", "for", "_", ",", "item", ":=", "range", "i", "{", "if", "!", "s", ".", "Contains", "(", "item", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// ContainsAll returns whether or not all of the given items in "i" are present // in the ordered set.
[ "ContainsAll", "returns", "whether", "or", "not", "all", "of", "the", "given", "items", "in", "i", "are", "present", "in", "the", "ordered", "set", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/ordered_set.go#L62-L69
train
git-lfs/git-lfs
tools/ordered_set.go
IsSubset
func (s *OrderedSet) IsSubset(other *OrderedSet) bool { for _, i := range other.s { if !s.Contains(i) { return false } } return true }
go
func (s *OrderedSet) IsSubset(other *OrderedSet) bool { for _, i := range other.s { if !s.Contains(i) { return false } } return true }
[ "func", "(", "s", "*", "OrderedSet", ")", "IsSubset", "(", "other", "*", "OrderedSet", ")", "bool", "{", "for", "_", ",", "i", ":=", "range", "other", ".", "s", "{", "if", "!", "s", ".", "Contains", "(", "i", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// IsSubset returns whether other is a subset of this ordered set. In other // words, it returns whether or not all of the elements in "other" are also // present in this set.
[ "IsSubset", "returns", "whether", "other", "is", "a", "subset", "of", "this", "ordered", "set", ".", "In", "other", "words", "it", "returns", "whether", "or", "not", "all", "of", "the", "elements", "in", "other", "are", "also", "present", "in", "this", "set", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/ordered_set.go#L74-L81
train
git-lfs/git-lfs
tools/ordered_set.go
Difference
func (s *OrderedSet) Difference(other *OrderedSet) *OrderedSet { diff := NewOrderedSetWithCapacity(s.Cardinality()) for _, e := range s.s { if !other.Contains(e) { diff.Add(e) } } return diff }
go
func (s *OrderedSet) Difference(other *OrderedSet) *OrderedSet { diff := NewOrderedSetWithCapacity(s.Cardinality()) for _, e := range s.s { if !other.Contains(e) { diff.Add(e) } } return diff }
[ "func", "(", "s", "*", "OrderedSet", ")", "Difference", "(", "other", "*", "OrderedSet", ")", "*", "OrderedSet", "{", "diff", ":=", "NewOrderedSetWithCapacity", "(", "s", ".", "Cardinality", "(", ")", ")", "\n", "for", "_", ",", "e", ":=", "range", "s", ".", "s", "{", "if", "!", "other", ".", "Contains", "(", "e", ")", "{", "diff", ".", "Add", "(", "e", ")", "\n", "}", "\n", "}", "\n\n", "return", "diff", "\n", "}" ]
// Difference returns the elements that are in this set, but not included in // other.
[ "Difference", "returns", "the", "elements", "that", "are", "in", "this", "set", "but", "not", "included", "in", "other", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/ordered_set.go#L134-L143
train
git-lfs/git-lfs
tools/ordered_set.go
SymmetricDifference
func (s *OrderedSet) SymmetricDifference(other *OrderedSet) *OrderedSet { left := s.Difference(other) right := other.Difference(s) return left.Union(right) }
go
func (s *OrderedSet) SymmetricDifference(other *OrderedSet) *OrderedSet { left := s.Difference(other) right := other.Difference(s) return left.Union(right) }
[ "func", "(", "s", "*", "OrderedSet", ")", "SymmetricDifference", "(", "other", "*", "OrderedSet", ")", "*", "OrderedSet", "{", "left", ":=", "s", ".", "Difference", "(", "other", ")", "\n", "right", ":=", "other", ".", "Difference", "(", "s", ")", "\n\n", "return", "left", ".", "Union", "(", "right", ")", "\n", "}" ]
// SymmetricDifference returns the elements that are not present in both sets.
[ "SymmetricDifference", "returns", "the", "elements", "that", "are", "not", "present", "in", "both", "sets", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/ordered_set.go#L146-L151
train
git-lfs/git-lfs
tools/ordered_set.go
Clear
func (s *OrderedSet) Clear() { s.s = make([]string, 0) s.m = make(map[string]int, 0) }
go
func (s *OrderedSet) Clear() { s.s = make([]string, 0) s.m = make(map[string]int, 0) }
[ "func", "(", "s", "*", "OrderedSet", ")", "Clear", "(", ")", "{", "s", ".", "s", "=", "make", "(", "[", "]", "string", ",", "0", ")", "\n", "s", ".", "m", "=", "make", "(", "map", "[", "string", "]", "int", ",", "0", ")", "\n", "}" ]
// Clear removes all elements from this set.
[ "Clear", "removes", "all", "elements", "from", "this", "set", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/ordered_set.go#L154-L157
train
git-lfs/git-lfs
tools/ordered_set.go
Remove
func (s *OrderedSet) Remove(i string) { idx, ok := s.m[i] if !ok { return } rest := MinInt(idx+1, len(s.s)-1) s.s = append(s.s[:idx], s.s[rest:]...) for _, e := range s.s[rest:] { s.m[e] = s.m[e] - 1 } delete(s.m, i) }
go
func (s *OrderedSet) Remove(i string) { idx, ok := s.m[i] if !ok { return } rest := MinInt(idx+1, len(s.s)-1) s.s = append(s.s[:idx], s.s[rest:]...) for _, e := range s.s[rest:] { s.m[e] = s.m[e] - 1 } delete(s.m, i) }
[ "func", "(", "s", "*", "OrderedSet", ")", "Remove", "(", "i", "string", ")", "{", "idx", ",", "ok", ":=", "s", ".", "m", "[", "i", "]", "\n", "if", "!", "ok", "{", "return", "\n", "}", "\n\n", "rest", ":=", "MinInt", "(", "idx", "+", "1", ",", "len", "(", "s", ".", "s", ")", "-", "1", ")", "\n\n", "s", ".", "s", "=", "append", "(", "s", ".", "s", "[", ":", "idx", "]", ",", "s", ".", "s", "[", "rest", ":", "]", "...", ")", "\n", "for", "_", ",", "e", ":=", "range", "s", ".", "s", "[", "rest", ":", "]", "{", "s", ".", "m", "[", "e", "]", "=", "s", ".", "m", "[", "e", "]", "-", "1", "\n", "}", "\n", "delete", "(", "s", ".", "m", ",", "i", ")", "\n", "}" ]
// Remove removes the given element "i" from this set.
[ "Remove", "removes", "the", "given", "element", "i", "from", "this", "set", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/ordered_set.go#L160-L173
train
git-lfs/git-lfs
tools/ordered_set.go
Iter
func (s *OrderedSet) Iter() <-chan string { c := make(chan string) go func() { for _, i := range s.s { c <- i } close(c) }() return c }
go
func (s *OrderedSet) Iter() <-chan string { c := make(chan string) go func() { for _, i := range s.s { c <- i } close(c) }() return c }
[ "func", "(", "s", "*", "OrderedSet", ")", "Iter", "(", ")", "<-", "chan", "string", "{", "c", ":=", "make", "(", "chan", "string", ")", "\n", "go", "func", "(", ")", "{", "for", "_", ",", "i", ":=", "range", "s", ".", "s", "{", "c", "<-", "i", "\n", "}", "\n", "close", "(", "c", ")", "\n", "}", "(", ")", "\n\n", "return", "c", "\n", "}" ]
// Iter returns a channel which yields the elements in this set in insertion // order.
[ "Iter", "returns", "a", "channel", "which", "yields", "the", "elements", "in", "this", "set", "in", "insertion", "order", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/ordered_set.go#L182-L192
train
git-lfs/git-lfs
tools/ordered_set.go
Equal
func (s *OrderedSet) Equal(other *OrderedSet) bool { if s.Cardinality() != other.Cardinality() { return false } for e, i := range s.m { if ci, ok := other.m[e]; !ok || ci != i { return false } } return true }
go
func (s *OrderedSet) Equal(other *OrderedSet) bool { if s.Cardinality() != other.Cardinality() { return false } for e, i := range s.m { if ci, ok := other.m[e]; !ok || ci != i { return false } } return true }
[ "func", "(", "s", "*", "OrderedSet", ")", "Equal", "(", "other", "*", "OrderedSet", ")", "bool", "{", "if", "s", ".", "Cardinality", "(", ")", "!=", "other", ".", "Cardinality", "(", ")", "{", "return", "false", "\n", "}", "\n\n", "for", "e", ",", "i", ":=", "range", "s", ".", "m", "{", "if", "ci", ",", "ok", ":=", "other", ".", "m", "[", "e", "]", ";", "!", "ok", "||", "ci", "!=", "i", "{", "return", "false", "\n", "}", "\n", "}", "\n\n", "return", "true", "\n", "}" ]
// Equal returns whether this element has the same number, identity and ordering // elements as given in "other".
[ "Equal", "returns", "whether", "this", "element", "has", "the", "same", "number", "identity", "and", "ordering", "elements", "as", "given", "in", "other", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/ordered_set.go#L196-L208
train
git-lfs/git-lfs
tools/ordered_set.go
Clone
func (s *OrderedSet) Clone() *OrderedSet { clone := NewOrderedSetWithCapacity(s.Cardinality()) for _, i := range s.s { clone.Add(i) } return clone }
go
func (s *OrderedSet) Clone() *OrderedSet { clone := NewOrderedSetWithCapacity(s.Cardinality()) for _, i := range s.s { clone.Add(i) } return clone }
[ "func", "(", "s", "*", "OrderedSet", ")", "Clone", "(", ")", "*", "OrderedSet", "{", "clone", ":=", "NewOrderedSetWithCapacity", "(", "s", ".", "Cardinality", "(", ")", ")", "\n", "for", "_", ",", "i", ":=", "range", "s", ".", "s", "{", "clone", ".", "Add", "(", "i", ")", "\n", "}", "\n", "return", "clone", "\n", "}" ]
// Clone returns a deep copy of this set.
[ "Clone", "returns", "a", "deep", "copy", "of", "this", "set", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tools/ordered_set.go#L211-L217
train
git-lfs/git-lfs
commands/command_uninstall.go
uninstallCommand
func uninstallCommand(cmd *cobra.Command, args []string) { if err := cmdInstallOptions().Uninstall(); err != nil { Error(err.Error()) } if !skipRepoInstall && (localInstall || cfg.InRepo()) { uninstallHooksCommand(cmd, args) } if systemInstall { Print("System Git LFS configuration has been removed.") } else if !localInstall { Print("Global Git LFS configuration has been removed.") } }
go
func uninstallCommand(cmd *cobra.Command, args []string) { if err := cmdInstallOptions().Uninstall(); err != nil { Error(err.Error()) } if !skipRepoInstall && (localInstall || cfg.InRepo()) { uninstallHooksCommand(cmd, args) } if systemInstall { Print("System Git LFS configuration has been removed.") } else if !localInstall { Print("Global Git LFS configuration has been removed.") } }
[ "func", "uninstallCommand", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "if", "err", ":=", "cmdInstallOptions", "(", ")", ".", "Uninstall", "(", ")", ";", "err", "!=", "nil", "{", "Error", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "if", "!", "skipRepoInstall", "&&", "(", "localInstall", "||", "cfg", ".", "InRepo", "(", ")", ")", "{", "uninstallHooksCommand", "(", "cmd", ",", "args", ")", "\n", "}", "\n\n", "if", "systemInstall", "{", "Print", "(", "\"", "\"", ")", "\n", "}", "else", "if", "!", "localInstall", "{", "Print", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// uninstallCmd removes any configuration and hooks set by Git LFS.
[ "uninstallCmd", "removes", "any", "configuration", "and", "hooks", "set", "by", "Git", "LFS", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/commands/command_uninstall.go#L8-L22
train
git-lfs/git-lfs
commands/command_uninstall.go
uninstallHooksCommand
func uninstallHooksCommand(cmd *cobra.Command, args []string) { if err := uninstallHooks(); err != nil { Error(err.Error()) } Print("Hooks for this repository have been removed.") }
go
func uninstallHooksCommand(cmd *cobra.Command, args []string) { if err := uninstallHooks(); err != nil { Error(err.Error()) } Print("Hooks for this repository have been removed.") }
[ "func", "uninstallHooksCommand", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "if", "err", ":=", "uninstallHooks", "(", ")", ";", "err", "!=", "nil", "{", "Error", "(", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n\n", "Print", "(", "\"", "\"", ")", "\n", "}" ]
// uninstallHooksCmd removes any hooks created by Git LFS.
[ "uninstallHooksCmd", "removes", "any", "hooks", "created", "by", "Git", "LFS", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/commands/command_uninstall.go#L25-L31
train
git-lfs/git-lfs
lfs/gitscanner_index.go
scanIndex
func scanIndex(cb GitScannerFoundPointer, ref string, f *filepathfilter.Filter) error { indexMap := &indexFileMap{ nameMap: make(map[string][]*indexFile), nameShaPairs: make(map[string]bool), mutex: &sync.Mutex{}, } revs, err := revListIndex(ref, false, indexMap) if err != nil { return err } cachedRevs, err := revListIndex(ref, true, indexMap) if err != nil { return err } allRevsErr := make(chan error, 5) // can be multiple errors below allRevsChan := make(chan string, 1) allRevs := NewStringChannelWrapper(allRevsChan, allRevsErr) go func() { seenRevs := make(map[string]bool, 0) for rev := range cachedRevs.Results { if !seenRevs[rev] { allRevsChan <- rev seenRevs[rev] = true } } err = cachedRevs.Wait() if err != nil { allRevsErr <- err } for rev := range revs.Results { if !seenRevs[rev] { allRevsChan <- rev seenRevs[rev] = true } } err := revs.Wait() if err != nil { allRevsErr <- err } close(allRevsChan) close(allRevsErr) }() smallShas, _, err := catFileBatchCheck(allRevs, nil) if err != nil { return err } ch := make(chan gitscannerResult, chanBufSize) barePointerCh, _, err := catFileBatch(smallShas, nil) if err != nil { return err } go func() { for p := range barePointerCh.Results { for _, file := range indexMap.FilesFor(p.Sha1) { // Append a new *WrappedPointer that combines the data // from the index file, and the pointer "p". ch <- gitscannerResult{ Pointer: &WrappedPointer{ Sha1: p.Sha1, Name: file.Name, SrcName: file.SrcName, Status: file.Status, Pointer: p.Pointer, }, } } } if err := barePointerCh.Wait(); err != nil { ch <- gitscannerResult{Err: err} } close(ch) }() for result := range ch { if f.Allows(result.Pointer.Name) { cb(result.Pointer, result.Err) } } return nil }
go
func scanIndex(cb GitScannerFoundPointer, ref string, f *filepathfilter.Filter) error { indexMap := &indexFileMap{ nameMap: make(map[string][]*indexFile), nameShaPairs: make(map[string]bool), mutex: &sync.Mutex{}, } revs, err := revListIndex(ref, false, indexMap) if err != nil { return err } cachedRevs, err := revListIndex(ref, true, indexMap) if err != nil { return err } allRevsErr := make(chan error, 5) // can be multiple errors below allRevsChan := make(chan string, 1) allRevs := NewStringChannelWrapper(allRevsChan, allRevsErr) go func() { seenRevs := make(map[string]bool, 0) for rev := range cachedRevs.Results { if !seenRevs[rev] { allRevsChan <- rev seenRevs[rev] = true } } err = cachedRevs.Wait() if err != nil { allRevsErr <- err } for rev := range revs.Results { if !seenRevs[rev] { allRevsChan <- rev seenRevs[rev] = true } } err := revs.Wait() if err != nil { allRevsErr <- err } close(allRevsChan) close(allRevsErr) }() smallShas, _, err := catFileBatchCheck(allRevs, nil) if err != nil { return err } ch := make(chan gitscannerResult, chanBufSize) barePointerCh, _, err := catFileBatch(smallShas, nil) if err != nil { return err } go func() { for p := range barePointerCh.Results { for _, file := range indexMap.FilesFor(p.Sha1) { // Append a new *WrappedPointer that combines the data // from the index file, and the pointer "p". ch <- gitscannerResult{ Pointer: &WrappedPointer{ Sha1: p.Sha1, Name: file.Name, SrcName: file.SrcName, Status: file.Status, Pointer: p.Pointer, }, } } } if err := barePointerCh.Wait(); err != nil { ch <- gitscannerResult{Err: err} } close(ch) }() for result := range ch { if f.Allows(result.Pointer.Name) { cb(result.Pointer, result.Err) } } return nil }
[ "func", "scanIndex", "(", "cb", "GitScannerFoundPointer", ",", "ref", "string", ",", "f", "*", "filepathfilter", ".", "Filter", ")", "error", "{", "indexMap", ":=", "&", "indexFileMap", "{", "nameMap", ":", "make", "(", "map", "[", "string", "]", "[", "]", "*", "indexFile", ")", ",", "nameShaPairs", ":", "make", "(", "map", "[", "string", "]", "bool", ")", ",", "mutex", ":", "&", "sync", ".", "Mutex", "{", "}", ",", "}", "\n\n", "revs", ",", "err", ":=", "revListIndex", "(", "ref", ",", "false", ",", "indexMap", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "cachedRevs", ",", "err", ":=", "revListIndex", "(", "ref", ",", "true", ",", "indexMap", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "allRevsErr", ":=", "make", "(", "chan", "error", ",", "5", ")", "// can be multiple errors below", "\n", "allRevsChan", ":=", "make", "(", "chan", "string", ",", "1", ")", "\n", "allRevs", ":=", "NewStringChannelWrapper", "(", "allRevsChan", ",", "allRevsErr", ")", "\n", "go", "func", "(", ")", "{", "seenRevs", ":=", "make", "(", "map", "[", "string", "]", "bool", ",", "0", ")", "\n\n", "for", "rev", ":=", "range", "cachedRevs", ".", "Results", "{", "if", "!", "seenRevs", "[", "rev", "]", "{", "allRevsChan", "<-", "rev", "\n", "seenRevs", "[", "rev", "]", "=", "true", "\n", "}", "\n", "}", "\n", "err", "=", "cachedRevs", ".", "Wait", "(", ")", "\n", "if", "err", "!=", "nil", "{", "allRevsErr", "<-", "err", "\n", "}", "\n\n", "for", "rev", ":=", "range", "revs", ".", "Results", "{", "if", "!", "seenRevs", "[", "rev", "]", "{", "allRevsChan", "<-", "rev", "\n", "seenRevs", "[", "rev", "]", "=", "true", "\n", "}", "\n", "}", "\n", "err", ":=", "revs", ".", "Wait", "(", ")", "\n", "if", "err", "!=", "nil", "{", "allRevsErr", "<-", "err", "\n", "}", "\n", "close", "(", "allRevsChan", ")", "\n", "close", "(", "allRevsErr", ")", "\n", "}", "(", ")", "\n\n", "smallShas", ",", "_", ",", "err", ":=", "catFileBatchCheck", "(", "allRevs", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "ch", ":=", "make", "(", "chan", "gitscannerResult", ",", "chanBufSize", ")", "\n\n", "barePointerCh", ",", "_", ",", "err", ":=", "catFileBatch", "(", "smallShas", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "go", "func", "(", ")", "{", "for", "p", ":=", "range", "barePointerCh", ".", "Results", "{", "for", "_", ",", "file", ":=", "range", "indexMap", ".", "FilesFor", "(", "p", ".", "Sha1", ")", "{", "// Append a new *WrappedPointer that combines the data", "// from the index file, and the pointer \"p\".", "ch", "<-", "gitscannerResult", "{", "Pointer", ":", "&", "WrappedPointer", "{", "Sha1", ":", "p", ".", "Sha1", ",", "Name", ":", "file", ".", "Name", ",", "SrcName", ":", "file", ".", "SrcName", ",", "Status", ":", "file", ".", "Status", ",", "Pointer", ":", "p", ".", "Pointer", ",", "}", ",", "}", "\n", "}", "\n", "}", "\n\n", "if", "err", ":=", "barePointerCh", ".", "Wait", "(", ")", ";", "err", "!=", "nil", "{", "ch", "<-", "gitscannerResult", "{", "Err", ":", "err", "}", "\n", "}", "\n\n", "close", "(", "ch", ")", "\n", "}", "(", ")", "\n\n", "for", "result", ":=", "range", "ch", "{", "if", "f", ".", "Allows", "(", "result", ".", "Pointer", ".", "Name", ")", "{", "cb", "(", "result", ".", "Pointer", ",", "result", ".", "Err", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// ScanIndex returns a slice of WrappedPointer objects for all Git LFS pointers // it finds in the index. // // Ref is the ref at which to scan, which may be "HEAD" if there is at least one // commit.
[ "ScanIndex", "returns", "a", "slice", "of", "WrappedPointer", "objects", "for", "all", "Git", "LFS", "pointers", "it", "finds", "in", "the", "index", ".", "Ref", "is", "the", "ref", "at", "which", "to", "scan", "which", "may", "be", "HEAD", "if", "there", "is", "at", "least", "one", "commit", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/lfs/gitscanner_index.go#L15-L106
train
git-lfs/git-lfs
lfs/gitscanner_index.go
revListIndex
func revListIndex(atRef string, cache bool, indexMap *indexFileMap) (*StringChannelWrapper, error) { scanner, err := NewDiffIndexScanner(atRef, cache) if err != nil { return nil, err } revs := make(chan string, chanBufSize) errs := make(chan error, 1) go func() { for scanner.Scan() { var name string = scanner.Entry().DstName if len(name) == 0 { name = scanner.Entry().SrcName } indexMap.Add(scanner.Entry().DstSha, &indexFile{ Name: name, SrcName: scanner.Entry().SrcName, Status: string(scanner.Entry().Status), }) revs <- scanner.Entry().DstSha } if err := scanner.Err(); err != nil { errs <- err } close(revs) close(errs) }() return NewStringChannelWrapper(revs, errs), nil }
go
func revListIndex(atRef string, cache bool, indexMap *indexFileMap) (*StringChannelWrapper, error) { scanner, err := NewDiffIndexScanner(atRef, cache) if err != nil { return nil, err } revs := make(chan string, chanBufSize) errs := make(chan error, 1) go func() { for scanner.Scan() { var name string = scanner.Entry().DstName if len(name) == 0 { name = scanner.Entry().SrcName } indexMap.Add(scanner.Entry().DstSha, &indexFile{ Name: name, SrcName: scanner.Entry().SrcName, Status: string(scanner.Entry().Status), }) revs <- scanner.Entry().DstSha } if err := scanner.Err(); err != nil { errs <- err } close(revs) close(errs) }() return NewStringChannelWrapper(revs, errs), nil }
[ "func", "revListIndex", "(", "atRef", "string", ",", "cache", "bool", ",", "indexMap", "*", "indexFileMap", ")", "(", "*", "StringChannelWrapper", ",", "error", ")", "{", "scanner", ",", "err", ":=", "NewDiffIndexScanner", "(", "atRef", ",", "cache", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "revs", ":=", "make", "(", "chan", "string", ",", "chanBufSize", ")", "\n", "errs", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n\n", "go", "func", "(", ")", "{", "for", "scanner", ".", "Scan", "(", ")", "{", "var", "name", "string", "=", "scanner", ".", "Entry", "(", ")", ".", "DstName", "\n", "if", "len", "(", "name", ")", "==", "0", "{", "name", "=", "scanner", ".", "Entry", "(", ")", ".", "SrcName", "\n", "}", "\n\n", "indexMap", ".", "Add", "(", "scanner", ".", "Entry", "(", ")", ".", "DstSha", ",", "&", "indexFile", "{", "Name", ":", "name", ",", "SrcName", ":", "scanner", ".", "Entry", "(", ")", ".", "SrcName", ",", "Status", ":", "string", "(", "scanner", ".", "Entry", "(", ")", ".", "Status", ")", ",", "}", ")", "\n\n", "revs", "<-", "scanner", ".", "Entry", "(", ")", ".", "DstSha", "\n", "}", "\n\n", "if", "err", ":=", "scanner", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "errs", "<-", "err", "\n", "}", "\n\n", "close", "(", "revs", ")", "\n", "close", "(", "errs", ")", "\n", "}", "(", ")", "\n\n", "return", "NewStringChannelWrapper", "(", "revs", ",", "errs", ")", ",", "nil", "\n", "}" ]
// revListIndex uses git diff-index to return the list of object sha1s // for in the indexf. It returns a channel from which sha1 strings can be read. // The namMap will be filled indexFile pointers mapping sha1s to indexFiles.
[ "revListIndex", "uses", "git", "diff", "-", "index", "to", "return", "the", "list", "of", "object", "sha1s", "for", "in", "the", "indexf", ".", "It", "returns", "a", "channel", "from", "which", "sha1", "strings", "can", "be", "read", ".", "The", "namMap", "will", "be", "filled", "indexFile", "pointers", "mapping", "sha1s", "to", "indexFiles", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/lfs/gitscanner_index.go#L111-L145
train
git-lfs/git-lfs
tq/transfer_queue.go
Increment
func (r *retryCounter) Increment(oid string) { r.cmu.Lock() defer r.cmu.Unlock() r.count[oid]++ }
go
func (r *retryCounter) Increment(oid string) { r.cmu.Lock() defer r.cmu.Unlock() r.count[oid]++ }
[ "func", "(", "r", "*", "retryCounter", ")", "Increment", "(", "oid", "string", ")", "{", "r", ".", "cmu", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "cmu", ".", "Unlock", "(", ")", "\n\n", "r", ".", "count", "[", "oid", "]", "++", "\n", "}" ]
// Increment increments the number of retries for a given OID. It is safe to // call across multiple goroutines.
[ "Increment", "increments", "the", "number", "of", "retries", "for", "a", "given", "OID", ".", "It", "is", "safe", "to", "call", "across", "multiple", "goroutines", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tq/transfer_queue.go#L46-L51
train
git-lfs/git-lfs
tq/transfer_queue.go
CountFor
func (r *retryCounter) CountFor(oid string) int { r.cmu.Lock() defer r.cmu.Unlock() return r.count[oid] }
go
func (r *retryCounter) CountFor(oid string) int { r.cmu.Lock() defer r.cmu.Unlock() return r.count[oid] }
[ "func", "(", "r", "*", "retryCounter", ")", "CountFor", "(", "oid", "string", ")", "int", "{", "r", ".", "cmu", ".", "Lock", "(", ")", "\n", "defer", "r", ".", "cmu", ".", "Unlock", "(", ")", "\n\n", "return", "r", ".", "count", "[", "oid", "]", "\n", "}" ]
// CountFor returns the current number of retries for a given OID. It is safe to // call across multiple goroutines.
[ "CountFor", "returns", "the", "current", "number", "of", "retries", "for", "a", "given", "OID", ".", "It", "is", "safe", "to", "call", "across", "multiple", "goroutines", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tq/transfer_queue.go#L55-L60
train
git-lfs/git-lfs
tq/transfer_queue.go
NewTransferQueue
func NewTransferQueue(dir Direction, manifest *Manifest, remote string, options ...Option) *TransferQueue { q := &TransferQueue{ direction: dir, client: &tqClient{Client: manifest.APIClient()}, remote: remote, errorc: make(chan error), transfers: make(map[string]*objects), trMutex: &sync.Mutex{}, manifest: manifest, rc: newRetryCounter(), } for _, opt := range options { opt(q) } q.rc.MaxRetries = q.manifest.maxRetries q.client.MaxRetries = q.manifest.maxRetries if q.batchSize <= 0 { q.batchSize = defaultBatchSize } if q.bufferDepth <= 0 { q.bufferDepth = q.batchSize } if q.meter != nil { q.meter.Direction = q.direction } q.incoming = make(chan *objectTuple, q.bufferDepth) q.collectorWait.Add(1) q.errorwait.Add(1) q.run() return q }
go
func NewTransferQueue(dir Direction, manifest *Manifest, remote string, options ...Option) *TransferQueue { q := &TransferQueue{ direction: dir, client: &tqClient{Client: manifest.APIClient()}, remote: remote, errorc: make(chan error), transfers: make(map[string]*objects), trMutex: &sync.Mutex{}, manifest: manifest, rc: newRetryCounter(), } for _, opt := range options { opt(q) } q.rc.MaxRetries = q.manifest.maxRetries q.client.MaxRetries = q.manifest.maxRetries if q.batchSize <= 0 { q.batchSize = defaultBatchSize } if q.bufferDepth <= 0 { q.bufferDepth = q.batchSize } if q.meter != nil { q.meter.Direction = q.direction } q.incoming = make(chan *objectTuple, q.bufferDepth) q.collectorWait.Add(1) q.errorwait.Add(1) q.run() return q }
[ "func", "NewTransferQueue", "(", "dir", "Direction", ",", "manifest", "*", "Manifest", ",", "remote", "string", ",", "options", "...", "Option", ")", "*", "TransferQueue", "{", "q", ":=", "&", "TransferQueue", "{", "direction", ":", "dir", ",", "client", ":", "&", "tqClient", "{", "Client", ":", "manifest", ".", "APIClient", "(", ")", "}", ",", "remote", ":", "remote", ",", "errorc", ":", "make", "(", "chan", "error", ")", ",", "transfers", ":", "make", "(", "map", "[", "string", "]", "*", "objects", ")", ",", "trMutex", ":", "&", "sync", ".", "Mutex", "{", "}", ",", "manifest", ":", "manifest", ",", "rc", ":", "newRetryCounter", "(", ")", ",", "}", "\n\n", "for", "_", ",", "opt", ":=", "range", "options", "{", "opt", "(", "q", ")", "\n", "}", "\n\n", "q", ".", "rc", ".", "MaxRetries", "=", "q", ".", "manifest", ".", "maxRetries", "\n", "q", ".", "client", ".", "MaxRetries", "=", "q", ".", "manifest", ".", "maxRetries", "\n\n", "if", "q", ".", "batchSize", "<=", "0", "{", "q", ".", "batchSize", "=", "defaultBatchSize", "\n", "}", "\n", "if", "q", ".", "bufferDepth", "<=", "0", "{", "q", ".", "bufferDepth", "=", "q", ".", "batchSize", "\n", "}", "\n", "if", "q", ".", "meter", "!=", "nil", "{", "q", ".", "meter", ".", "Direction", "=", "q", ".", "direction", "\n", "}", "\n\n", "q", ".", "incoming", "=", "make", "(", "chan", "*", "objectTuple", ",", "q", ".", "bufferDepth", ")", "\n", "q", ".", "collectorWait", ".", "Add", "(", "1", ")", "\n", "q", ".", "errorwait", ".", "Add", "(", "1", ")", "\n", "q", ".", "run", "(", ")", "\n\n", "return", "q", "\n", "}" ]
// NewTransferQueue builds a TransferQueue, direction and underlying mechanism determined by adapter
[ "NewTransferQueue", "builds", "a", "TransferQueue", "direction", "and", "underlying", "mechanism", "determined", "by", "adapter" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tq/transfer_queue.go#L241-L276
train
git-lfs/git-lfs
tq/transfer_queue.go
collectPendingUntil
func (q *TransferQueue) collectPendingUntil(done <-chan struct{}) (pending batch, closing bool) { for { select { case t, ok := <-q.incoming: if !ok { closing = true <-done return } pending = append(pending, t) case <-done: return } } }
go
func (q *TransferQueue) collectPendingUntil(done <-chan struct{}) (pending batch, closing bool) { for { select { case t, ok := <-q.incoming: if !ok { closing = true <-done return } pending = append(pending, t) case <-done: return } } }
[ "func", "(", "q", "*", "TransferQueue", ")", "collectPendingUntil", "(", "done", "<-", "chan", "struct", "{", "}", ")", "(", "pending", "batch", ",", "closing", "bool", ")", "{", "for", "{", "select", "{", "case", "t", ",", "ok", ":=", "<-", "q", ".", "incoming", ":", "if", "!", "ok", "{", "closing", "=", "true", "\n", "<-", "done", "\n", "return", "\n", "}", "\n\n", "pending", "=", "append", "(", "pending", ",", "t", ")", "\n", "case", "<-", "done", ":", "return", "\n", "}", "\n", "}", "\n", "}" ]
// collectPendingUntil collects items from q.incoming into a "pending" batch // until the given "done" channel is written to, or is closed. // // A "pending" batch is returned, along with whether or not "q.incoming" is // closed.
[ "collectPendingUntil", "collects", "items", "from", "q", ".", "incoming", "into", "a", "pending", "batch", "until", "the", "given", "done", "channel", "is", "written", "to", "or", "is", "closed", ".", "A", "pending", "batch", "is", "returned", "along", "with", "whether", "or", "not", "q", ".", "incoming", "is", "closed", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tq/transfer_queue.go#L423-L438
train
git-lfs/git-lfs
tq/transfer_queue.go
addToAdapter
func (q *TransferQueue) addToAdapter(e lfshttp.Endpoint, pending []*Transfer) <-chan *objectTuple { retries := make(chan *objectTuple, len(pending)) if err := q.ensureAdapterBegun(e); err != nil { close(retries) q.errorc <- err for _, t := range pending { q.Skip(t.Size) q.wait.Done() } return retries } present, missingResults := q.partitionTransfers(pending) go func() { defer close(retries) var results <-chan TransferResult if q.dryRun { results = q.makeDryRunResults(present) } else { results = q.adapter.Add(present...) } for _, res := range missingResults { q.handleTransferResult(res, retries) } for res := range results { q.handleTransferResult(res, retries) } }() return retries }
go
func (q *TransferQueue) addToAdapter(e lfshttp.Endpoint, pending []*Transfer) <-chan *objectTuple { retries := make(chan *objectTuple, len(pending)) if err := q.ensureAdapterBegun(e); err != nil { close(retries) q.errorc <- err for _, t := range pending { q.Skip(t.Size) q.wait.Done() } return retries } present, missingResults := q.partitionTransfers(pending) go func() { defer close(retries) var results <-chan TransferResult if q.dryRun { results = q.makeDryRunResults(present) } else { results = q.adapter.Add(present...) } for _, res := range missingResults { q.handleTransferResult(res, retries) } for res := range results { q.handleTransferResult(res, retries) } }() return retries }
[ "func", "(", "q", "*", "TransferQueue", ")", "addToAdapter", "(", "e", "lfshttp", ".", "Endpoint", ",", "pending", "[", "]", "*", "Transfer", ")", "<-", "chan", "*", "objectTuple", "{", "retries", ":=", "make", "(", "chan", "*", "objectTuple", ",", "len", "(", "pending", ")", ")", "\n\n", "if", "err", ":=", "q", ".", "ensureAdapterBegun", "(", "e", ")", ";", "err", "!=", "nil", "{", "close", "(", "retries", ")", "\n\n", "q", ".", "errorc", "<-", "err", "\n", "for", "_", ",", "t", ":=", "range", "pending", "{", "q", ".", "Skip", "(", "t", ".", "Size", ")", "\n", "q", ".", "wait", ".", "Done", "(", ")", "\n", "}", "\n\n", "return", "retries", "\n", "}", "\n\n", "present", ",", "missingResults", ":=", "q", ".", "partitionTransfers", "(", "pending", ")", "\n\n", "go", "func", "(", ")", "{", "defer", "close", "(", "retries", ")", "\n\n", "var", "results", "<-", "chan", "TransferResult", "\n", "if", "q", ".", "dryRun", "{", "results", "=", "q", ".", "makeDryRunResults", "(", "present", ")", "\n", "}", "else", "{", "results", "=", "q", ".", "adapter", ".", "Add", "(", "present", "...", ")", "\n", "}", "\n\n", "for", "_", ",", "res", ":=", "range", "missingResults", "{", "q", ".", "handleTransferResult", "(", "res", ",", "retries", ")", "\n", "}", "\n", "for", "res", ":=", "range", "results", "{", "q", ".", "handleTransferResult", "(", "res", ",", "retries", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "return", "retries", "\n", "}" ]
// addToAdapter adds the given "pending" transfers to the transfer adapters and // returns a channel of Transfers that are to be retried in the next batch. // After all of the items in the batch have been processed, the channel is // closed. // // addToAdapter returns immediately, and does not block.
[ "addToAdapter", "adds", "the", "given", "pending", "transfers", "to", "the", "transfer", "adapters", "and", "returns", "a", "channel", "of", "Transfers", "that", "are", "to", "be", "retried", "in", "the", "next", "batch", ".", "After", "all", "of", "the", "items", "in", "the", "batch", "have", "been", "processed", "the", "channel", "is", "closed", ".", "addToAdapter", "returns", "immediately", "and", "does", "not", "block", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tq/transfer_queue.go#L577-L613
train
git-lfs/git-lfs
tq/transfer_queue.go
makeDryRunResults
func (q *TransferQueue) makeDryRunResults(ts []*Transfer) <-chan TransferResult { results := make(chan TransferResult, len(ts)) for _, t := range ts { results <- TransferResult{t, nil} } close(results) return results }
go
func (q *TransferQueue) makeDryRunResults(ts []*Transfer) <-chan TransferResult { results := make(chan TransferResult, len(ts)) for _, t := range ts { results <- TransferResult{t, nil} } close(results) return results }
[ "func", "(", "q", "*", "TransferQueue", ")", "makeDryRunResults", "(", "ts", "[", "]", "*", "Transfer", ")", "<-", "chan", "TransferResult", "{", "results", ":=", "make", "(", "chan", "TransferResult", ",", "len", "(", "ts", ")", ")", "\n", "for", "_", ",", "t", ":=", "range", "ts", "{", "results", "<-", "TransferResult", "{", "t", ",", "nil", "}", "\n", "}", "\n\n", "close", "(", "results", ")", "\n\n", "return", "results", "\n", "}" ]
// makeDryRunResults returns a channel populated immediately with "successful" // results for all of the given transfers in "ts".
[ "makeDryRunResults", "returns", "a", "channel", "populated", "immediately", "with", "successful", "results", "for", "all", "of", "the", "given", "transfers", "in", "ts", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tq/transfer_queue.go#L656-L665
train
git-lfs/git-lfs
tq/transfer_queue.go
handleTransferResult
func (q *TransferQueue) handleTransferResult( res TransferResult, retries chan<- *objectTuple, ) { oid := res.Transfer.Oid if res.Error != nil { // If there was an error encountered when processing the // transfer (res.Transfer), handle the error as is appropriate: if readyTime, canRetry := q.canRetryObjectLater(oid, res.Error); canRetry { // If the object can't be retried now, but can be // after a certain period of time, send it to // the retry channel with a time when it's ready. tracerx.Printf("tq: retrying object %s after %s seconds.", oid, time.Until(readyTime).Seconds()) q.trMutex.Lock() objects, ok := q.transfers[oid] q.trMutex.Unlock() if ok { t := objects.First() t.ReadyTime = readyTime retries <- t } else { q.errorc <- res.Error } } else if q.canRetryObject(oid, res.Error) { // If the object can be retried, send it on the retries // channel, where it will be read at the call-site and // its retry count will be incremented. tracerx.Printf("tq: retrying object %s: %s", oid, res.Error) q.trMutex.Lock() objects, ok := q.transfers[oid] q.trMutex.Unlock() if ok { retries <- objects.First() } else { q.errorc <- res.Error } } else { // If the error wasn't retriable, OR the object has // exceeded its retry budget, it will be NOT be sent to // the retry channel, and the error will be reported // immediately (unless the error is in response to a // HTTP 422). if errors.IsUnprocessableEntityError(res.Error) { q.unsupportedContentType = true } else { q.errorc <- res.Error } q.wait.Done() } } else { q.trMutex.Lock() objects := q.transfers[oid] objects.completed = true // Otherwise, if the transfer was successful, notify all of the // watchers, and mark it as finished. for _, c := range q.watchers { // Send one update for each transfer with the // same OID. for _, t := range objects.All() { c <- &Transfer{ Name: t.Name, Path: t.Path, Oid: t.Oid, Size: t.Size, } } } q.trMutex.Unlock() q.meter.FinishTransfer(res.Transfer.Name) q.wait.Done() } }
go
func (q *TransferQueue) handleTransferResult( res TransferResult, retries chan<- *objectTuple, ) { oid := res.Transfer.Oid if res.Error != nil { // If there was an error encountered when processing the // transfer (res.Transfer), handle the error as is appropriate: if readyTime, canRetry := q.canRetryObjectLater(oid, res.Error); canRetry { // If the object can't be retried now, but can be // after a certain period of time, send it to // the retry channel with a time when it's ready. tracerx.Printf("tq: retrying object %s after %s seconds.", oid, time.Until(readyTime).Seconds()) q.trMutex.Lock() objects, ok := q.transfers[oid] q.trMutex.Unlock() if ok { t := objects.First() t.ReadyTime = readyTime retries <- t } else { q.errorc <- res.Error } } else if q.canRetryObject(oid, res.Error) { // If the object can be retried, send it on the retries // channel, where it will be read at the call-site and // its retry count will be incremented. tracerx.Printf("tq: retrying object %s: %s", oid, res.Error) q.trMutex.Lock() objects, ok := q.transfers[oid] q.trMutex.Unlock() if ok { retries <- objects.First() } else { q.errorc <- res.Error } } else { // If the error wasn't retriable, OR the object has // exceeded its retry budget, it will be NOT be sent to // the retry channel, and the error will be reported // immediately (unless the error is in response to a // HTTP 422). if errors.IsUnprocessableEntityError(res.Error) { q.unsupportedContentType = true } else { q.errorc <- res.Error } q.wait.Done() } } else { q.trMutex.Lock() objects := q.transfers[oid] objects.completed = true // Otherwise, if the transfer was successful, notify all of the // watchers, and mark it as finished. for _, c := range q.watchers { // Send one update for each transfer with the // same OID. for _, t := range objects.All() { c <- &Transfer{ Name: t.Name, Path: t.Path, Oid: t.Oid, Size: t.Size, } } } q.trMutex.Unlock() q.meter.FinishTransfer(res.Transfer.Name) q.wait.Done() } }
[ "func", "(", "q", "*", "TransferQueue", ")", "handleTransferResult", "(", "res", "TransferResult", ",", "retries", "chan", "<-", "*", "objectTuple", ",", ")", "{", "oid", ":=", "res", ".", "Transfer", ".", "Oid", "\n\n", "if", "res", ".", "Error", "!=", "nil", "{", "// If there was an error encountered when processing the", "// transfer (res.Transfer), handle the error as is appropriate:", "if", "readyTime", ",", "canRetry", ":=", "q", ".", "canRetryObjectLater", "(", "oid", ",", "res", ".", "Error", ")", ";", "canRetry", "{", "// If the object can't be retried now, but can be", "// after a certain period of time, send it to", "// the retry channel with a time when it's ready.", "tracerx", ".", "Printf", "(", "\"", "\"", ",", "oid", ",", "time", ".", "Until", "(", "readyTime", ")", ".", "Seconds", "(", ")", ")", "\n", "q", ".", "trMutex", ".", "Lock", "(", ")", "\n", "objects", ",", "ok", ":=", "q", ".", "transfers", "[", "oid", "]", "\n", "q", ".", "trMutex", ".", "Unlock", "(", ")", "\n\n", "if", "ok", "{", "t", ":=", "objects", ".", "First", "(", ")", "\n", "t", ".", "ReadyTime", "=", "readyTime", "\n", "retries", "<-", "t", "\n", "}", "else", "{", "q", ".", "errorc", "<-", "res", ".", "Error", "\n", "}", "\n", "}", "else", "if", "q", ".", "canRetryObject", "(", "oid", ",", "res", ".", "Error", ")", "{", "// If the object can be retried, send it on the retries", "// channel, where it will be read at the call-site and", "// its retry count will be incremented.", "tracerx", ".", "Printf", "(", "\"", "\"", ",", "oid", ",", "res", ".", "Error", ")", "\n\n", "q", ".", "trMutex", ".", "Lock", "(", ")", "\n", "objects", ",", "ok", ":=", "q", ".", "transfers", "[", "oid", "]", "\n", "q", ".", "trMutex", ".", "Unlock", "(", ")", "\n\n", "if", "ok", "{", "retries", "<-", "objects", ".", "First", "(", ")", "\n", "}", "else", "{", "q", ".", "errorc", "<-", "res", ".", "Error", "\n", "}", "\n", "}", "else", "{", "// If the error wasn't retriable, OR the object has", "// exceeded its retry budget, it will be NOT be sent to", "// the retry channel, and the error will be reported", "// immediately (unless the error is in response to a", "// HTTP 422).", "if", "errors", ".", "IsUnprocessableEntityError", "(", "res", ".", "Error", ")", "{", "q", ".", "unsupportedContentType", "=", "true", "\n", "}", "else", "{", "q", ".", "errorc", "<-", "res", ".", "Error", "\n", "}", "\n", "q", ".", "wait", ".", "Done", "(", ")", "\n", "}", "\n", "}", "else", "{", "q", ".", "trMutex", ".", "Lock", "(", ")", "\n", "objects", ":=", "q", ".", "transfers", "[", "oid", "]", "\n", "objects", ".", "completed", "=", "true", "\n\n", "// Otherwise, if the transfer was successful, notify all of the", "// watchers, and mark it as finished.", "for", "_", ",", "c", ":=", "range", "q", ".", "watchers", "{", "// Send one update for each transfer with the", "// same OID.", "for", "_", ",", "t", ":=", "range", "objects", ".", "All", "(", ")", "{", "c", "<-", "&", "Transfer", "{", "Name", ":", "t", ".", "Name", ",", "Path", ":", "t", ".", "Path", ",", "Oid", ":", "t", ".", "Oid", ",", "Size", ":", "t", ".", "Size", ",", "}", "\n", "}", "\n", "}", "\n\n", "q", ".", "trMutex", ".", "Unlock", "(", ")", "\n\n", "q", ".", "meter", ".", "FinishTransfer", "(", "res", ".", "Transfer", ".", "Name", ")", "\n", "q", ".", "wait", ".", "Done", "(", ")", "\n", "}", "\n", "}" ]
// handleTransferResult observes the transfer result, sending it on the retries // channel if it was able to be retried.
[ "handleTransferResult", "observes", "the", "transfer", "result", "sending", "it", "on", "the", "retries", "channel", "if", "it", "was", "able", "to", "be", "retried", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tq/transfer_queue.go#L669-L746
train
git-lfs/git-lfs
tq/transfer_queue.go
Wait
func (q *TransferQueue) Wait() { close(q.incoming) q.wait.Wait() q.collectorWait.Wait() q.finishAdapter() close(q.errorc) for _, watcher := range q.watchers { close(watcher) } q.meter.Flush() q.errorwait.Wait() if q.unsupportedContentType { for _, line := range contentTypeWarning { fmt.Fprintf(os.Stderr, "info: %s\n", line) } } }
go
func (q *TransferQueue) Wait() { close(q.incoming) q.wait.Wait() q.collectorWait.Wait() q.finishAdapter() close(q.errorc) for _, watcher := range q.watchers { close(watcher) } q.meter.Flush() q.errorwait.Wait() if q.unsupportedContentType { for _, line := range contentTypeWarning { fmt.Fprintf(os.Stderr, "info: %s\n", line) } } }
[ "func", "(", "q", "*", "TransferQueue", ")", "Wait", "(", ")", "{", "close", "(", "q", ".", "incoming", ")", "\n\n", "q", ".", "wait", ".", "Wait", "(", ")", "\n", "q", ".", "collectorWait", ".", "Wait", "(", ")", "\n\n", "q", ".", "finishAdapter", "(", ")", "\n", "close", "(", "q", ".", "errorc", ")", "\n\n", "for", "_", ",", "watcher", ":=", "range", "q", ".", "watchers", "{", "close", "(", "watcher", ")", "\n", "}", "\n\n", "q", ".", "meter", ".", "Flush", "(", ")", "\n", "q", ".", "errorwait", ".", "Wait", "(", ")", "\n\n", "if", "q", ".", "unsupportedContentType", "{", "for", "_", ",", "line", ":=", "range", "contentTypeWarning", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"", "\\n", "\"", ",", "line", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Wait waits for the queue to finish processing all transfers. Once Wait is // called, Add will no longer add transfers to the queue. Any failed // transfers will be automatically retried once.
[ "Wait", "waits", "for", "the", "queue", "to", "finish", "processing", "all", "transfers", ".", "Once", "Wait", "is", "called", "Add", "will", "no", "longer", "add", "transfers", "to", "the", "queue", ".", "Any", "failed", "transfers", "will", "be", "automatically", "retried", "once", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tq/transfer_queue.go#L844-L865
train
git-lfs/git-lfs
tq/transfer_queue.go
Watch
func (q *TransferQueue) Watch() chan *Transfer { c := make(chan *Transfer, q.batchSize) q.watchers = append(q.watchers, c) return c }
go
func (q *TransferQueue) Watch() chan *Transfer { c := make(chan *Transfer, q.batchSize) q.watchers = append(q.watchers, c) return c }
[ "func", "(", "q", "*", "TransferQueue", ")", "Watch", "(", ")", "chan", "*", "Transfer", "{", "c", ":=", "make", "(", "chan", "*", "Transfer", ",", "q", ".", "batchSize", ")", "\n", "q", ".", "watchers", "=", "append", "(", "q", ".", "watchers", ",", "c", ")", "\n", "return", "c", "\n", "}" ]
// Watch returns a channel where the queue will write the value of each transfer // as it completes. If multiple transfers exist with the same OID, they will all // be recorded here, even though only one actual transfer took place. The // channel will be closed when the queue finishes processing.
[ "Watch", "returns", "a", "channel", "where", "the", "queue", "will", "write", "the", "value", "of", "each", "transfer", "as", "it", "completes", ".", "If", "multiple", "transfers", "exist", "with", "the", "same", "OID", "they", "will", "all", "be", "recorded", "here", "even", "though", "only", "one", "actual", "transfer", "took", "place", ".", "The", "channel", "will", "be", "closed", "when", "the", "queue", "finishes", "processing", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tq/transfer_queue.go#L871-L875
train
git-lfs/git-lfs
tq/transfer_queue.go
errorCollector
func (q *TransferQueue) errorCollector() { for err := range q.errorc { q.errors = append(q.errors, err) } q.errorwait.Done() }
go
func (q *TransferQueue) errorCollector() { for err := range q.errorc { q.errors = append(q.errors, err) } q.errorwait.Done() }
[ "func", "(", "q", "*", "TransferQueue", ")", "errorCollector", "(", ")", "{", "for", "err", ":=", "range", "q", ".", "errorc", "{", "q", ".", "errors", "=", "append", "(", "q", ".", "errors", ",", "err", ")", "\n", "}", "\n", "q", ".", "errorwait", ".", "Done", "(", ")", "\n", "}" ]
// This goroutine collects errors returned from transfers
[ "This", "goroutine", "collects", "errors", "returned", "from", "transfers" ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tq/transfer_queue.go#L878-L883
train
git-lfs/git-lfs
tq/transfer_queue.go
canRetryLater
func (q *TransferQueue) canRetryLater(err error) (time.Time, bool) { return errors.IsRetriableLaterError(err) }
go
func (q *TransferQueue) canRetryLater(err error) (time.Time, bool) { return errors.IsRetriableLaterError(err) }
[ "func", "(", "q", "*", "TransferQueue", ")", "canRetryLater", "(", "err", "error", ")", "(", "time", ".", "Time", ",", "bool", ")", "{", "return", "errors", ".", "IsRetriableLaterError", "(", "err", ")", "\n", "}" ]
// canRetryLater returns the number of seconds until an error can be retried and if the error // is a delayed-retriable error.
[ "canRetryLater", "returns", "the", "number", "of", "seconds", "until", "an", "error", "can", "be", "retried", "and", "if", "the", "error", "is", "a", "delayed", "-", "retriable", "error", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tq/transfer_queue.go#L901-L903
train
git-lfs/git-lfs
tq/transfer_queue.go
canRetryObject
func (q *TransferQueue) canRetryObject(oid string, err error) bool { if count, ok := q.rc.CanRetry(oid); !ok { tracerx.Printf("tq: refusing to retry %q, too many retries (%d)", oid, count) return false } return q.canRetry(err) }
go
func (q *TransferQueue) canRetryObject(oid string, err error) bool { if count, ok := q.rc.CanRetry(oid); !ok { tracerx.Printf("tq: refusing to retry %q, too many retries (%d)", oid, count) return false } return q.canRetry(err) }
[ "func", "(", "q", "*", "TransferQueue", ")", "canRetryObject", "(", "oid", "string", ",", "err", "error", ")", "bool", "{", "if", "count", ",", "ok", ":=", "q", ".", "rc", ".", "CanRetry", "(", "oid", ")", ";", "!", "ok", "{", "tracerx", ".", "Printf", "(", "\"", "\"", ",", "oid", ",", "count", ")", "\n", "return", "false", "\n", "}", "\n\n", "return", "q", ".", "canRetry", "(", "err", ")", "\n", "}" ]
// canRetryObject returns whether the given error is retriable for the object // given by "oid". If the an OID has met its retry limit, then it will not be // able to be retried again. If so, canRetryObject returns whether or not that // given error "err" is retriable.
[ "canRetryObject", "returns", "whether", "the", "given", "error", "is", "retriable", "for", "the", "object", "given", "by", "oid", ".", "If", "the", "an", "OID", "has", "met", "its", "retry", "limit", "then", "it", "will", "not", "be", "able", "to", "be", "retried", "again", ".", "If", "so", "canRetryObject", "returns", "whether", "or", "not", "that", "given", "error", "err", "is", "retriable", "." ]
fe8f7002c6efb083feadc0a078fa2fbb389127c7
https://github.com/git-lfs/git-lfs/blob/fe8f7002c6efb083feadc0a078fa2fbb389127c7/tq/transfer_queue.go#L909-L916
train
go-swagger/go-swagger
generator/shared.go
Init
func (l *LanguageOpts) Init() { if !l.initialized { l.initialized = true l.reservedWordsSet = make(map[string]struct{}) for _, rw := range l.ReservedWords { l.reservedWordsSet[rw] = struct{}{} } } }
go
func (l *LanguageOpts) Init() { if !l.initialized { l.initialized = true l.reservedWordsSet = make(map[string]struct{}) for _, rw := range l.ReservedWords { l.reservedWordsSet[rw] = struct{}{} } } }
[ "func", "(", "l", "*", "LanguageOpts", ")", "Init", "(", ")", "{", "if", "!", "l", ".", "initialized", "{", "l", ".", "initialized", "=", "true", "\n", "l", ".", "reservedWordsSet", "=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", "\n", "for", "_", ",", "rw", ":=", "range", "l", ".", "ReservedWords", "{", "l", ".", "reservedWordsSet", "[", "rw", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "}", "\n", "}" ]
// Init the language option
[ "Init", "the", "language", "option" ]
ffefbd274717d6fa3bcca1c494487edf1f48104b
https://github.com/go-swagger/go-swagger/blob/ffefbd274717d6fa3bcca1c494487edf1f48104b/generator/shared.go#L56-L64
train
go-swagger/go-swagger
generator/shared.go
MangleName
func (l *LanguageOpts) MangleName(name, suffix string) string { if _, ok := l.reservedWordsSet[swag.ToFileName(name)]; !ok { return name } return strings.Join([]string{name, suffix}, "_") }
go
func (l *LanguageOpts) MangleName(name, suffix string) string { if _, ok := l.reservedWordsSet[swag.ToFileName(name)]; !ok { return name } return strings.Join([]string{name, suffix}, "_") }
[ "func", "(", "l", "*", "LanguageOpts", ")", "MangleName", "(", "name", ",", "suffix", "string", ")", "string", "{", "if", "_", ",", "ok", ":=", "l", ".", "reservedWordsSet", "[", "swag", ".", "ToFileName", "(", "name", ")", "]", ";", "!", "ok", "{", "return", "name", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "[", "]", "string", "{", "name", ",", "suffix", "}", ",", "\"", "\"", ")", "\n", "}" ]
// MangleName makes sure a reserved word gets a safe name
[ "MangleName", "makes", "sure", "a", "reserved", "word", "gets", "a", "safe", "name" ]
ffefbd274717d6fa3bcca1c494487edf1f48104b
https://github.com/go-swagger/go-swagger/blob/ffefbd274717d6fa3bcca1c494487edf1f48104b/generator/shared.go#L67-L72
train
go-swagger/go-swagger
generator/shared.go
MangleVarName
func (l *LanguageOpts) MangleVarName(name string) string { nm := swag.ToVarName(name) if _, ok := l.reservedWordsSet[nm]; !ok { return nm } return nm + "Var" }
go
func (l *LanguageOpts) MangleVarName(name string) string { nm := swag.ToVarName(name) if _, ok := l.reservedWordsSet[nm]; !ok { return nm } return nm + "Var" }
[ "func", "(", "l", "*", "LanguageOpts", ")", "MangleVarName", "(", "name", "string", ")", "string", "{", "nm", ":=", "swag", ".", "ToVarName", "(", "name", ")", "\n", "if", "_", ",", "ok", ":=", "l", ".", "reservedWordsSet", "[", "nm", "]", ";", "!", "ok", "{", "return", "nm", "\n", "}", "\n", "return", "nm", "+", "\"", "\"", "\n", "}" ]
// MangleVarName makes sure a reserved word gets a safe name
[ "MangleVarName", "makes", "sure", "a", "reserved", "word", "gets", "a", "safe", "name" ]
ffefbd274717d6fa3bcca1c494487edf1f48104b
https://github.com/go-swagger/go-swagger/blob/ffefbd274717d6fa3bcca1c494487edf1f48104b/generator/shared.go#L75-L81
train
go-swagger/go-swagger
generator/shared.go
MangleFileName
func (l *LanguageOpts) MangleFileName(name string) string { if l.fileNameFunc != nil { return l.fileNameFunc(name) } return swag.ToFileName(name) }
go
func (l *LanguageOpts) MangleFileName(name string) string { if l.fileNameFunc != nil { return l.fileNameFunc(name) } return swag.ToFileName(name) }
[ "func", "(", "l", "*", "LanguageOpts", ")", "MangleFileName", "(", "name", "string", ")", "string", "{", "if", "l", ".", "fileNameFunc", "!=", "nil", "{", "return", "l", ".", "fileNameFunc", "(", "name", ")", "\n", "}", "\n", "return", "swag", ".", "ToFileName", "(", "name", ")", "\n", "}" ]
// MangleFileName makes sure a file name gets a safe name
[ "MangleFileName", "makes", "sure", "a", "file", "name", "gets", "a", "safe", "name" ]
ffefbd274717d6fa3bcca1c494487edf1f48104b
https://github.com/go-swagger/go-swagger/blob/ffefbd274717d6fa3bcca1c494487edf1f48104b/generator/shared.go#L84-L89
train
go-swagger/go-swagger
generator/shared.go
ManglePackagePath
func (l *LanguageOpts) ManglePackagePath(name string, suffix string) string { if name == "" { return suffix } target := filepath.ToSlash(filepath.Clean(name)) // preserve path parts := strings.Split(target, "/") parts[len(parts)-1] = l.ManglePackageName(parts[len(parts)-1], suffix) return strings.Join(parts, "/") }
go
func (l *LanguageOpts) ManglePackagePath(name string, suffix string) string { if name == "" { return suffix } target := filepath.ToSlash(filepath.Clean(name)) // preserve path parts := strings.Split(target, "/") parts[len(parts)-1] = l.ManglePackageName(parts[len(parts)-1], suffix) return strings.Join(parts, "/") }
[ "func", "(", "l", "*", "LanguageOpts", ")", "ManglePackagePath", "(", "name", "string", ",", "suffix", "string", ")", "string", "{", "if", "name", "==", "\"", "\"", "{", "return", "suffix", "\n", "}", "\n", "target", ":=", "filepath", ".", "ToSlash", "(", "filepath", ".", "Clean", "(", "name", ")", ")", "// preserve path", "\n", "parts", ":=", "strings", ".", "Split", "(", "target", ",", "\"", "\"", ")", "\n", "parts", "[", "len", "(", "parts", ")", "-", "1", "]", "=", "l", ".", "ManglePackageName", "(", "parts", "[", "len", "(", "parts", ")", "-", "1", "]", ",", "suffix", ")", "\n", "return", "strings", ".", "Join", "(", "parts", ",", "\"", "\"", ")", "\n", "}" ]
// ManglePackagePath makes sure a full package path gets a safe name. // Only the last part of the path is altered.
[ "ManglePackagePath", "makes", "sure", "a", "full", "package", "path", "gets", "a", "safe", "name", ".", "Only", "the", "last", "part", "of", "the", "path", "is", "altered", "." ]
ffefbd274717d6fa3bcca1c494487edf1f48104b
https://github.com/go-swagger/go-swagger/blob/ffefbd274717d6fa3bcca1c494487edf1f48104b/generator/shared.go#L104-L112
train
go-swagger/go-swagger
generator/shared.go
FormatContent
func (l *LanguageOpts) FormatContent(name string, content []byte) ([]byte, error) { if l.formatFunc != nil { return l.formatFunc(name, content) } return content, nil }
go
func (l *LanguageOpts) FormatContent(name string, content []byte) ([]byte, error) { if l.formatFunc != nil { return l.formatFunc(name, content) } return content, nil }
[ "func", "(", "l", "*", "LanguageOpts", ")", "FormatContent", "(", "name", "string", ",", "content", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "l", ".", "formatFunc", "!=", "nil", "{", "return", "l", ".", "formatFunc", "(", "name", ",", "content", ")", "\n", "}", "\n", "return", "content", ",", "nil", "\n", "}" ]
// FormatContent formats a file with a language specific formatter
[ "FormatContent", "formats", "a", "file", "with", "a", "language", "specific", "formatter" ]
ffefbd274717d6fa3bcca1c494487edf1f48104b
https://github.com/go-swagger/go-swagger/blob/ffefbd274717d6fa3bcca1c494487edf1f48104b/generator/shared.go#L115-L120
train
go-swagger/go-swagger
generator/shared.go
resolveGoModFile
func resolveGoModFile(dir string) (*os.File, string, error) { goModPath := filepath.Join(dir, "go.mod") f, err := os.Open(goModPath) if err != nil { if os.IsNotExist(err) && dir != filepath.Dir(dir) { return resolveGoModFile(filepath.Dir(dir)) } return nil, "", err } return f, dir, nil }
go
func resolveGoModFile(dir string) (*os.File, string, error) { goModPath := filepath.Join(dir, "go.mod") f, err := os.Open(goModPath) if err != nil { if os.IsNotExist(err) && dir != filepath.Dir(dir) { return resolveGoModFile(filepath.Dir(dir)) } return nil, "", err } return f, dir, nil }
[ "func", "resolveGoModFile", "(", "dir", "string", ")", "(", "*", "os", ".", "File", ",", "string", ",", "error", ")", "{", "goModPath", ":=", "filepath", ".", "Join", "(", "dir", ",", "\"", "\"", ")", "\n", "f", ",", "err", ":=", "os", ".", "Open", "(", "goModPath", ")", "\n", "if", "err", "!=", "nil", "{", "if", "os", ".", "IsNotExist", "(", "err", ")", "&&", "dir", "!=", "filepath", ".", "Dir", "(", "dir", ")", "{", "return", "resolveGoModFile", "(", "filepath", ".", "Dir", "(", "dir", ")", ")", "\n", "}", "\n", "return", "nil", ",", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "f", ",", "dir", ",", "nil", "\n", "}" ]
// resolveGoModFile walks up the directory tree starting from 'dir' until it // finds a go.mod file. If go.mod is found it will return the related file // object. If no go.mod file is found it will return an error.
[ "resolveGoModFile", "walks", "up", "the", "directory", "tree", "starting", "from", "dir", "until", "it", "finds", "a", "go", ".", "mod", "file", ".", "If", "go", ".", "mod", "is", "found", "it", "will", "return", "the", "related", "file", "object", ".", "If", "no", "go", ".", "mod", "file", "is", "found", "it", "will", "return", "an", "error", "." ]
ffefbd274717d6fa3bcca1c494487edf1f48104b
https://github.com/go-swagger/go-swagger/blob/ffefbd274717d6fa3bcca1c494487edf1f48104b/generator/shared.go#L309-L319
train
go-swagger/go-swagger
generator/shared.go
EnsureDefaults
func (g *GenOpts) EnsureDefaults() error { if g.defaultsEnsured { return nil } DefaultSectionOpts(g) if g.LanguageOpts == nil { g.LanguageOpts = GoLangOpts() } // set defaults for flattening options g.FlattenOpts = &analysis.FlattenOpts{ Minimal: true, Verbose: true, RemoveUnused: false, Expand: false, } g.defaultsEnsured = true return nil }
go
func (g *GenOpts) EnsureDefaults() error { if g.defaultsEnsured { return nil } DefaultSectionOpts(g) if g.LanguageOpts == nil { g.LanguageOpts = GoLangOpts() } // set defaults for flattening options g.FlattenOpts = &analysis.FlattenOpts{ Minimal: true, Verbose: true, RemoveUnused: false, Expand: false, } g.defaultsEnsured = true return nil }
[ "func", "(", "g", "*", "GenOpts", ")", "EnsureDefaults", "(", ")", "error", "{", "if", "g", ".", "defaultsEnsured", "{", "return", "nil", "\n", "}", "\n", "DefaultSectionOpts", "(", "g", ")", "\n", "if", "g", ".", "LanguageOpts", "==", "nil", "{", "g", ".", "LanguageOpts", "=", "GoLangOpts", "(", ")", "\n", "}", "\n", "// set defaults for flattening options", "g", ".", "FlattenOpts", "=", "&", "analysis", ".", "FlattenOpts", "{", "Minimal", ":", "true", ",", "Verbose", ":", "true", ",", "RemoveUnused", ":", "false", ",", "Expand", ":", "false", ",", "}", "\n", "g", ".", "defaultsEnsured", "=", "true", "\n", "return", "nil", "\n", "}" ]
// EnsureDefaults for these gen opts
[ "EnsureDefaults", "for", "these", "gen", "opts" ]
ffefbd274717d6fa3bcca1c494487edf1f48104b
https://github.com/go-swagger/go-swagger/blob/ffefbd274717d6fa3bcca1c494487edf1f48104b/generator/shared.go#L665-L682
train
go-swagger/go-swagger
generator/shared.go
gatherSecuritySchemes
func gatherSecuritySchemes(securitySchemes map[string]spec.SecurityScheme, appName, principal, receiver string) (security GenSecuritySchemes) { for scheme, req := range securitySchemes { isOAuth2 := strings.ToLower(req.Type) == "oauth2" var scopes []string if isOAuth2 { for k := range req.Scopes { scopes = append(scopes, k) } } sort.Strings(scopes) security = append(security, GenSecurityScheme{ AppName: appName, ID: scheme, ReceiverName: receiver, Name: req.Name, IsBasicAuth: strings.ToLower(req.Type) == "basic", IsAPIKeyAuth: strings.ToLower(req.Type) == "apikey", IsOAuth2: isOAuth2, Scopes: scopes, Principal: principal, Source: req.In, // from original spec Description: req.Description, Type: strings.ToLower(req.Type), In: req.In, Flow: req.Flow, AuthorizationURL: req.AuthorizationURL, TokenURL: req.TokenURL, Extensions: req.Extensions, }) } sort.Sort(security) return }
go
func gatherSecuritySchemes(securitySchemes map[string]spec.SecurityScheme, appName, principal, receiver string) (security GenSecuritySchemes) { for scheme, req := range securitySchemes { isOAuth2 := strings.ToLower(req.Type) == "oauth2" var scopes []string if isOAuth2 { for k := range req.Scopes { scopes = append(scopes, k) } } sort.Strings(scopes) security = append(security, GenSecurityScheme{ AppName: appName, ID: scheme, ReceiverName: receiver, Name: req.Name, IsBasicAuth: strings.ToLower(req.Type) == "basic", IsAPIKeyAuth: strings.ToLower(req.Type) == "apikey", IsOAuth2: isOAuth2, Scopes: scopes, Principal: principal, Source: req.In, // from original spec Description: req.Description, Type: strings.ToLower(req.Type), In: req.In, Flow: req.Flow, AuthorizationURL: req.AuthorizationURL, TokenURL: req.TokenURL, Extensions: req.Extensions, }) } sort.Sort(security) return }
[ "func", "gatherSecuritySchemes", "(", "securitySchemes", "map", "[", "string", "]", "spec", ".", "SecurityScheme", ",", "appName", ",", "principal", ",", "receiver", "string", ")", "(", "security", "GenSecuritySchemes", ")", "{", "for", "scheme", ",", "req", ":=", "range", "securitySchemes", "{", "isOAuth2", ":=", "strings", ".", "ToLower", "(", "req", ".", "Type", ")", "==", "\"", "\"", "\n", "var", "scopes", "[", "]", "string", "\n", "if", "isOAuth2", "{", "for", "k", ":=", "range", "req", ".", "Scopes", "{", "scopes", "=", "append", "(", "scopes", ",", "k", ")", "\n", "}", "\n", "}", "\n", "sort", ".", "Strings", "(", "scopes", ")", "\n\n", "security", "=", "append", "(", "security", ",", "GenSecurityScheme", "{", "AppName", ":", "appName", ",", "ID", ":", "scheme", ",", "ReceiverName", ":", "receiver", ",", "Name", ":", "req", ".", "Name", ",", "IsBasicAuth", ":", "strings", ".", "ToLower", "(", "req", ".", "Type", ")", "==", "\"", "\"", ",", "IsAPIKeyAuth", ":", "strings", ".", "ToLower", "(", "req", ".", "Type", ")", "==", "\"", "\"", ",", "IsOAuth2", ":", "isOAuth2", ",", "Scopes", ":", "scopes", ",", "Principal", ":", "principal", ",", "Source", ":", "req", ".", "In", ",", "// from original spec", "Description", ":", "req", ".", "Description", ",", "Type", ":", "strings", ".", "ToLower", "(", "req", ".", "Type", ")", ",", "In", ":", "req", ".", "In", ",", "Flow", ":", "req", ".", "Flow", ",", "AuthorizationURL", ":", "req", ".", "AuthorizationURL", ",", "TokenURL", ":", "req", ".", "TokenURL", ",", "Extensions", ":", "req", ".", "Extensions", ",", "}", ")", "\n", "}", "\n", "sort", ".", "Sort", "(", "security", ")", "\n", "return", "\n", "}" ]
// gatherSecuritySchemes produces a sorted representation from a map of spec security schemes
[ "gatherSecuritySchemes", "produces", "a", "sorted", "representation", "from", "a", "map", "of", "spec", "security", "schemes" ]
ffefbd274717d6fa3bcca1c494487edf1f48104b
https://github.com/go-swagger/go-swagger/blob/ffefbd274717d6fa3bcca1c494487edf1f48104b/generator/shared.go#L1169-L1203
train
go-swagger/go-swagger
generator/shared.go
gatherExtraSchemas
func gatherExtraSchemas(extraMap map[string]GenSchema) (extras GenSchemaList) { var extraKeys []string for k := range extraMap { extraKeys = append(extraKeys, k) } sort.Strings(extraKeys) for _, k := range extraKeys { // figure out if top level validations are needed p := extraMap[k] p.HasValidations = shallowValidationLookup(p) extras = append(extras, p) } return }
go
func gatherExtraSchemas(extraMap map[string]GenSchema) (extras GenSchemaList) { var extraKeys []string for k := range extraMap { extraKeys = append(extraKeys, k) } sort.Strings(extraKeys) for _, k := range extraKeys { // figure out if top level validations are needed p := extraMap[k] p.HasValidations = shallowValidationLookup(p) extras = append(extras, p) } return }
[ "func", "gatherExtraSchemas", "(", "extraMap", "map", "[", "string", "]", "GenSchema", ")", "(", "extras", "GenSchemaList", ")", "{", "var", "extraKeys", "[", "]", "string", "\n", "for", "k", ":=", "range", "extraMap", "{", "extraKeys", "=", "append", "(", "extraKeys", ",", "k", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "extraKeys", ")", "\n", "for", "_", ",", "k", ":=", "range", "extraKeys", "{", "// figure out if top level validations are needed", "p", ":=", "extraMap", "[", "k", "]", "\n", "p", ".", "HasValidations", "=", "shallowValidationLookup", "(", "p", ")", "\n", "extras", "=", "append", "(", "extras", ",", "p", ")", "\n", "}", "\n", "return", "\n", "}" ]
// gatherExtraSchemas produces a sorted list of extra schemas. // // ExtraSchemas are inlined types rendered in the same model file.
[ "gatherExtraSchemas", "produces", "a", "sorted", "list", "of", "extra", "schemas", ".", "ExtraSchemas", "are", "inlined", "types", "rendered", "in", "the", "same", "model", "file", "." ]
ffefbd274717d6fa3bcca1c494487edf1f48104b
https://github.com/go-swagger/go-swagger/blob/ffefbd274717d6fa3bcca1c494487edf1f48104b/generator/shared.go#L1208-L1221
train
go-swagger/go-swagger
examples/stream-server/biz/count.go
Down
func (mc *MyCounter) Down(max int64, w io.Writer) error { if max == 11 { return fmt.Errorf("we don't *do* elevensies") } e := json.NewEncoder(w) for ix := int64(0); ix <= max; ix++ { r := max - ix fmt.Printf("Iteration %d\n", r) _ = e.Encode(models.Mark{Remains: &r}) if ix != max { time.Sleep(1 * time.Second) } } return nil }
go
func (mc *MyCounter) Down(max int64, w io.Writer) error { if max == 11 { return fmt.Errorf("we don't *do* elevensies") } e := json.NewEncoder(w) for ix := int64(0); ix <= max; ix++ { r := max - ix fmt.Printf("Iteration %d\n", r) _ = e.Encode(models.Mark{Remains: &r}) if ix != max { time.Sleep(1 * time.Second) } } return nil }
[ "func", "(", "mc", "*", "MyCounter", ")", "Down", "(", "max", "int64", ",", "w", "io", ".", "Writer", ")", "error", "{", "if", "max", "==", "11", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "e", ":=", "json", ".", "NewEncoder", "(", "w", ")", "\n", "for", "ix", ":=", "int64", "(", "0", ")", ";", "ix", "<=", "max", ";", "ix", "++", "{", "r", ":=", "max", "-", "ix", "\n", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "r", ")", "\n", "_", "=", "e", ".", "Encode", "(", "models", ".", "Mark", "{", "Remains", ":", "&", "r", "}", ")", "\n", "if", "ix", "!=", "max", "{", "time", ".", "Sleep", "(", "1", "*", "time", ".", "Second", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Down is the concrete implementation that spits out the JSON bodies
[ "Down", "is", "the", "concrete", "implementation", "that", "spits", "out", "the", "JSON", "bodies" ]
ffefbd274717d6fa3bcca1c494487edf1f48104b
https://github.com/go-swagger/go-swagger/blob/ffefbd274717d6fa3bcca1c494487edf1f48104b/examples/stream-server/biz/count.go#L16-L30
train
go-swagger/go-swagger
examples/tutorials/todo-list/server-complete/restapi/operations/todo_list_api.go
Context
func (o *TodoListAPI) Context() *middleware.Context { if o.context == nil { o.context = middleware.NewRoutableContext(o.spec, o, nil) } return o.context }
go
func (o *TodoListAPI) Context() *middleware.Context { if o.context == nil { o.context = middleware.NewRoutableContext(o.spec, o, nil) } return o.context }
[ "func", "(", "o", "*", "TodoListAPI", ")", "Context", "(", ")", "*", "middleware", ".", "Context", "{", "if", "o", ".", "context", "==", "nil", "{", "o", ".", "context", "=", "middleware", ".", "NewRoutableContext", "(", "o", ".", "spec", ",", "o", ",", "nil", ")", "\n", "}", "\n\n", "return", "o", ".", "context", "\n", "}" ]
// Context returns the middleware context for the todo list API
[ "Context", "returns", "the", "middleware", "context", "for", "the", "todo", "list", "API" ]
ffefbd274717d6fa3bcca1c494487edf1f48104b
https://github.com/go-swagger/go-swagger/blob/ffefbd274717d6fa3bcca1c494487edf1f48104b/examples/tutorials/todo-list/server-complete/restapi/operations/todo_list_api.go#L255-L261
train
go-swagger/go-swagger
examples/authentication/restapi/operations/auth_sample_api.go
NewAuthSampleAPI
func NewAuthSampleAPI(spec *loads.Document) *AuthSampleAPI { return &AuthSampleAPI{ handlers: make(map[string]map[string]http.Handler), formats: strfmt.Default, defaultConsumes: "application/json", defaultProduces: "application/json", customConsumers: make(map[string]runtime.Consumer), customProducers: make(map[string]runtime.Producer), ServerShutdown: func() {}, spec: spec, ServeError: errors.ServeError, BasicAuthenticator: security.BasicAuth, APIKeyAuthenticator: security.APIKeyAuth, BearerAuthenticator: security.BearerAuth, JSONConsumer: runtime.JSONConsumer(), JSONProducer: runtime.JSONProducer(), CustomersCreateHandler: customers.CreateHandlerFunc(func(params customers.CreateParams, principal *models.Principal) middleware.Responder { return middleware.NotImplemented("operation CustomersCreate has not yet been implemented") }), CustomersGetIDHandler: customers.GetIDHandlerFunc(func(params customers.GetIDParams, principal *models.Principal) middleware.Responder { return middleware.NotImplemented("operation CustomersGetID has not yet been implemented") }), // Applies when the "x-token" header is set KeyAuth: func(token string) (*models.Principal, error) { return nil, errors.NotImplemented("api key auth (key) x-token from header param [x-token] has not yet been implemented") }, // default authorizer is authorized meaning no requests are blocked APIAuthorizer: security.Authorized(), } }
go
func NewAuthSampleAPI(spec *loads.Document) *AuthSampleAPI { return &AuthSampleAPI{ handlers: make(map[string]map[string]http.Handler), formats: strfmt.Default, defaultConsumes: "application/json", defaultProduces: "application/json", customConsumers: make(map[string]runtime.Consumer), customProducers: make(map[string]runtime.Producer), ServerShutdown: func() {}, spec: spec, ServeError: errors.ServeError, BasicAuthenticator: security.BasicAuth, APIKeyAuthenticator: security.APIKeyAuth, BearerAuthenticator: security.BearerAuth, JSONConsumer: runtime.JSONConsumer(), JSONProducer: runtime.JSONProducer(), CustomersCreateHandler: customers.CreateHandlerFunc(func(params customers.CreateParams, principal *models.Principal) middleware.Responder { return middleware.NotImplemented("operation CustomersCreate has not yet been implemented") }), CustomersGetIDHandler: customers.GetIDHandlerFunc(func(params customers.GetIDParams, principal *models.Principal) middleware.Responder { return middleware.NotImplemented("operation CustomersGetID has not yet been implemented") }), // Applies when the "x-token" header is set KeyAuth: func(token string) (*models.Principal, error) { return nil, errors.NotImplemented("api key auth (key) x-token from header param [x-token] has not yet been implemented") }, // default authorizer is authorized meaning no requests are blocked APIAuthorizer: security.Authorized(), } }
[ "func", "NewAuthSampleAPI", "(", "spec", "*", "loads", ".", "Document", ")", "*", "AuthSampleAPI", "{", "return", "&", "AuthSampleAPI", "{", "handlers", ":", "make", "(", "map", "[", "string", "]", "map", "[", "string", "]", "http", ".", "Handler", ")", ",", "formats", ":", "strfmt", ".", "Default", ",", "defaultConsumes", ":", "\"", "\"", ",", "defaultProduces", ":", "\"", "\"", ",", "customConsumers", ":", "make", "(", "map", "[", "string", "]", "runtime", ".", "Consumer", ")", ",", "customProducers", ":", "make", "(", "map", "[", "string", "]", "runtime", ".", "Producer", ")", ",", "ServerShutdown", ":", "func", "(", ")", "{", "}", ",", "spec", ":", "spec", ",", "ServeError", ":", "errors", ".", "ServeError", ",", "BasicAuthenticator", ":", "security", ".", "BasicAuth", ",", "APIKeyAuthenticator", ":", "security", ".", "APIKeyAuth", ",", "BearerAuthenticator", ":", "security", ".", "BearerAuth", ",", "JSONConsumer", ":", "runtime", ".", "JSONConsumer", "(", ")", ",", "JSONProducer", ":", "runtime", ".", "JSONProducer", "(", ")", ",", "CustomersCreateHandler", ":", "customers", ".", "CreateHandlerFunc", "(", "func", "(", "params", "customers", ".", "CreateParams", ",", "principal", "*", "models", ".", "Principal", ")", "middleware", ".", "Responder", "{", "return", "middleware", ".", "NotImplemented", "(", "\"", "\"", ")", "\n", "}", ")", ",", "CustomersGetIDHandler", ":", "customers", ".", "GetIDHandlerFunc", "(", "func", "(", "params", "customers", ".", "GetIDParams", ",", "principal", "*", "models", ".", "Principal", ")", "middleware", ".", "Responder", "{", "return", "middleware", ".", "NotImplemented", "(", "\"", "\"", ")", "\n", "}", ")", ",", "// Applies when the \"x-token\" header is set", "KeyAuth", ":", "func", "(", "token", "string", ")", "(", "*", "models", ".", "Principal", ",", "error", ")", "{", "return", "nil", ",", "errors", ".", "NotImplemented", "(", "\"", "\"", ")", "\n", "}", ",", "// default authorizer is authorized meaning no requests are blocked", "APIAuthorizer", ":", "security", ".", "Authorized", "(", ")", ",", "}", "\n", "}" ]
// NewAuthSampleAPI creates a new AuthSample instance
[ "NewAuthSampleAPI", "creates", "a", "new", "AuthSample", "instance" ]
ffefbd274717d6fa3bcca1c494487edf1f48104b
https://github.com/go-swagger/go-swagger/blob/ffefbd274717d6fa3bcca1c494487edf1f48104b/examples/authentication/restapi/operations/auth_sample_api.go#L28-L59
train
go-swagger/go-swagger
examples/authentication/restapi/operations/auth_sample_api.go
Validate
func (o *AuthSampleAPI) Validate() error { var unregistered []string if o.JSONConsumer == nil { unregistered = append(unregistered, "JSONConsumer") } if o.JSONProducer == nil { unregistered = append(unregistered, "JSONProducer") } if o.KeyAuth == nil { unregistered = append(unregistered, "XTokenAuth") } if o.CustomersCreateHandler == nil { unregistered = append(unregistered, "customers.CreateHandler") } if o.CustomersGetIDHandler == nil { unregistered = append(unregistered, "customers.GetIDHandler") } if len(unregistered) > 0 { return fmt.Errorf("missing registration: %s", strings.Join(unregistered, ", ")) } return nil }
go
func (o *AuthSampleAPI) Validate() error { var unregistered []string if o.JSONConsumer == nil { unregistered = append(unregistered, "JSONConsumer") } if o.JSONProducer == nil { unregistered = append(unregistered, "JSONProducer") } if o.KeyAuth == nil { unregistered = append(unregistered, "XTokenAuth") } if o.CustomersCreateHandler == nil { unregistered = append(unregistered, "customers.CreateHandler") } if o.CustomersGetIDHandler == nil { unregistered = append(unregistered, "customers.GetIDHandler") } if len(unregistered) > 0 { return fmt.Errorf("missing registration: %s", strings.Join(unregistered, ", ")) } return nil }
[ "func", "(", "o", "*", "AuthSampleAPI", ")", "Validate", "(", ")", "error", "{", "var", "unregistered", "[", "]", "string", "\n\n", "if", "o", ".", "JSONConsumer", "==", "nil", "{", "unregistered", "=", "append", "(", "unregistered", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "o", ".", "JSONProducer", "==", "nil", "{", "unregistered", "=", "append", "(", "unregistered", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "o", ".", "KeyAuth", "==", "nil", "{", "unregistered", "=", "append", "(", "unregistered", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "o", ".", "CustomersCreateHandler", "==", "nil", "{", "unregistered", "=", "append", "(", "unregistered", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "o", ".", "CustomersGetIDHandler", "==", "nil", "{", "unregistered", "=", "append", "(", "unregistered", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "len", "(", "unregistered", ")", ">", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "strings", ".", "Join", "(", "unregistered", ",", "\"", "\"", ")", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Validate validates the registrations in the AuthSampleAPI
[ "Validate", "validates", "the", "registrations", "in", "the", "AuthSampleAPI" ]
ffefbd274717d6fa3bcca1c494487edf1f48104b
https://github.com/go-swagger/go-swagger/blob/ffefbd274717d6fa3bcca1c494487edf1f48104b/examples/authentication/restapi/operations/auth_sample_api.go#L152-L180
train
go-swagger/go-swagger
examples/authentication/restapi/operations/auth_sample_api.go
Context
func (o *AuthSampleAPI) Context() *middleware.Context { if o.context == nil { o.context = middleware.NewRoutableContext(o.spec, o, nil) } return o.context }
go
func (o *AuthSampleAPI) Context() *middleware.Context { if o.context == nil { o.context = middleware.NewRoutableContext(o.spec, o, nil) } return o.context }
[ "func", "(", "o", "*", "AuthSampleAPI", ")", "Context", "(", ")", "*", "middleware", ".", "Context", "{", "if", "o", ".", "context", "==", "nil", "{", "o", ".", "context", "=", "middleware", ".", "NewRoutableContext", "(", "o", ".", "spec", ",", "o", ",", "nil", ")", "\n", "}", "\n\n", "return", "o", ".", "context", "\n", "}" ]
// Context returns the middleware context for the auth sample API
[ "Context", "returns", "the", "middleware", "context", "for", "the", "auth", "sample", "API" ]
ffefbd274717d6fa3bcca1c494487edf1f48104b
https://github.com/go-swagger/go-swagger/blob/ffefbd274717d6fa3bcca1c494487edf1f48104b/examples/authentication/restapi/operations/auth_sample_api.go#L270-L276
train
go-swagger/go-swagger
examples/oauth2/restapi/operations/get_login.go
NewGetLogin
func NewGetLogin(ctx *middleware.Context, handler GetLoginHandler) *GetLogin { return &GetLogin{Context: ctx, Handler: handler} }
go
func NewGetLogin(ctx *middleware.Context, handler GetLoginHandler) *GetLogin { return &GetLogin{Context: ctx, Handler: handler} }
[ "func", "NewGetLogin", "(", "ctx", "*", "middleware", ".", "Context", ",", "handler", "GetLoginHandler", ")", "*", "GetLogin", "{", "return", "&", "GetLogin", "{", "Context", ":", "ctx", ",", "Handler", ":", "handler", "}", "\n", "}" ]
// NewGetLogin creates a new http.Handler for the get login operation
[ "NewGetLogin", "creates", "a", "new", "http", ".", "Handler", "for", "the", "get", "login", "operation" ]
ffefbd274717d6fa3bcca1c494487edf1f48104b
https://github.com/go-swagger/go-swagger/blob/ffefbd274717d6fa3bcca1c494487edf1f48104b/examples/oauth2/restapi/operations/get_login.go#L30-L32
train
go-swagger/go-swagger
examples/task-tracker/restapi/operations/tasks/get_task_details.go
NewGetTaskDetails
func NewGetTaskDetails(ctx *middleware.Context, handler GetTaskDetailsHandler) *GetTaskDetails { return &GetTaskDetails{Context: ctx, Handler: handler} }
go
func NewGetTaskDetails(ctx *middleware.Context, handler GetTaskDetailsHandler) *GetTaskDetails { return &GetTaskDetails{Context: ctx, Handler: handler} }
[ "func", "NewGetTaskDetails", "(", "ctx", "*", "middleware", ".", "Context", ",", "handler", "GetTaskDetailsHandler", ")", "*", "GetTaskDetails", "{", "return", "&", "GetTaskDetails", "{", "Context", ":", "ctx", ",", "Handler", ":", "handler", "}", "\n", "}" ]
// NewGetTaskDetails creates a new http.Handler for the get task details operation
[ "NewGetTaskDetails", "creates", "a", "new", "http", ".", "Handler", "for", "the", "get", "task", "details", "operation" ]
ffefbd274717d6fa3bcca1c494487edf1f48104b
https://github.com/go-swagger/go-swagger/blob/ffefbd274717d6fa3bcca1c494487edf1f48104b/examples/task-tracker/restapi/operations/tasks/get_task_details.go#L28-L30
train
go-swagger/go-swagger
examples/task-tracker/client/task_tracker_client.go
New
func New(transport runtime.ClientTransport, formats strfmt.Registry) *TaskTracker { // ensure nullable parameters have default if formats == nil { formats = strfmt.Default } cli := new(TaskTracker) cli.Transport = transport cli.Tasks = tasks.New(transport, formats) return cli }
go
func New(transport runtime.ClientTransport, formats strfmt.Registry) *TaskTracker { // ensure nullable parameters have default if formats == nil { formats = strfmt.Default } cli := new(TaskTracker) cli.Transport = transport cli.Tasks = tasks.New(transport, formats) return cli }
[ "func", "New", "(", "transport", "runtime", ".", "ClientTransport", ",", "formats", "strfmt", ".", "Registry", ")", "*", "TaskTracker", "{", "// ensure nullable parameters have default", "if", "formats", "==", "nil", "{", "formats", "=", "strfmt", ".", "Default", "\n", "}", "\n\n", "cli", ":=", "new", "(", "TaskTracker", ")", "\n", "cli", ".", "Transport", "=", "transport", "\n\n", "cli", ".", "Tasks", "=", "tasks", ".", "New", "(", "transport", ",", "formats", ")", "\n\n", "return", "cli", "\n", "}" ]
// New creates a new task tracker client
[ "New", "creates", "a", "new", "task", "tracker", "client" ]
ffefbd274717d6fa3bcca1c494487edf1f48104b
https://github.com/go-swagger/go-swagger/blob/ffefbd274717d6fa3bcca1c494487edf1f48104b/examples/task-tracker/client/task_tracker_client.go#L51-L63
train
go-swagger/go-swagger
examples/contributed-templates/stratoscale/client/petstore_client.go
New
func New(c Config) *Petstore { var ( host = DefaultHost basePath = DefaultBasePath schemes = DefaultSchemes ) if c.URL != nil { host = c.URL.Host basePath = c.URL.Path schemes = []string{c.URL.Scheme} } transport := rtclient.New(host, basePath, schemes) if c.Transport != nil { transport.Transport = c.Transport } cli := new(Petstore) cli.Transport = transport cli.Pet = pet.New(transport, strfmt.Default, c.AuthInfo) cli.Store = store.New(transport, strfmt.Default, c.AuthInfo) return cli }
go
func New(c Config) *Petstore { var ( host = DefaultHost basePath = DefaultBasePath schemes = DefaultSchemes ) if c.URL != nil { host = c.URL.Host basePath = c.URL.Path schemes = []string{c.URL.Scheme} } transport := rtclient.New(host, basePath, schemes) if c.Transport != nil { transport.Transport = c.Transport } cli := new(Petstore) cli.Transport = transport cli.Pet = pet.New(transport, strfmt.Default, c.AuthInfo) cli.Store = store.New(transport, strfmt.Default, c.AuthInfo) return cli }
[ "func", "New", "(", "c", "Config", ")", "*", "Petstore", "{", "var", "(", "host", "=", "DefaultHost", "\n", "basePath", "=", "DefaultBasePath", "\n", "schemes", "=", "DefaultSchemes", "\n", ")", "\n\n", "if", "c", ".", "URL", "!=", "nil", "{", "host", "=", "c", ".", "URL", ".", "Host", "\n", "basePath", "=", "c", ".", "URL", ".", "Path", "\n", "schemes", "=", "[", "]", "string", "{", "c", ".", "URL", ".", "Scheme", "}", "\n", "}", "\n\n", "transport", ":=", "rtclient", ".", "New", "(", "host", ",", "basePath", ",", "schemes", ")", "\n", "if", "c", ".", "Transport", "!=", "nil", "{", "transport", ".", "Transport", "=", "c", ".", "Transport", "\n", "}", "\n\n", "cli", ":=", "new", "(", "Petstore", ")", "\n", "cli", ".", "Transport", "=", "transport", "\n", "cli", ".", "Pet", "=", "pet", ".", "New", "(", "transport", ",", "strfmt", ".", "Default", ",", "c", ".", "AuthInfo", ")", "\n", "cli", ".", "Store", "=", "store", ".", "New", "(", "transport", ",", "strfmt", ".", "Default", ",", "c", ".", "AuthInfo", ")", "\n", "return", "cli", "\n", "}" ]
// New creates a new petstore HTTP client.
[ "New", "creates", "a", "new", "petstore", "HTTP", "client", "." ]
ffefbd274717d6fa3bcca1c494487edf1f48104b
https://github.com/go-swagger/go-swagger/blob/ffefbd274717d6fa3bcca1c494487edf1f48104b/examples/contributed-templates/stratoscale/client/petstore_client.go#L42-L65
train
go-swagger/go-swagger
examples/generated/restapi/operations/user/create_user.go
NewCreateUser
func NewCreateUser(ctx *middleware.Context, handler CreateUserHandler) *CreateUser { return &CreateUser{Context: ctx, Handler: handler} }
go
func NewCreateUser(ctx *middleware.Context, handler CreateUserHandler) *CreateUser { return &CreateUser{Context: ctx, Handler: handler} }
[ "func", "NewCreateUser", "(", "ctx", "*", "middleware", ".", "Context", ",", "handler", "CreateUserHandler", ")", "*", "CreateUser", "{", "return", "&", "CreateUser", "{", "Context", ":", "ctx", ",", "Handler", ":", "handler", "}", "\n", "}" ]
// NewCreateUser creates a new http.Handler for the create user operation
[ "NewCreateUser", "creates", "a", "new", "http", ".", "Handler", "for", "the", "create", "user", "operation" ]
ffefbd274717d6fa3bcca1c494487edf1f48104b
https://github.com/go-swagger/go-swagger/blob/ffefbd274717d6fa3bcca1c494487edf1f48104b/examples/generated/restapi/operations/user/create_user.go#L28-L30
train
go-swagger/go-swagger
scan/parameters.go
Parse
func (pp *paramStructParser) Parse(gofile *ast.File, target interface{}) error { tgt := target.(map[string]*spec.Operation) for _, decl := range gofile.Decls { switch x1 := decl.(type) { // Check for parameters at the package level. case *ast.GenDecl: for _, spc := range x1.Specs { switch x2 := spc.(type) { case *ast.TypeSpec: sd := paramDecl{gofile, x1, x2, nil} sd.inferOperationIDs() if err := pp.parseDecl(tgt, sd); err != nil { return err } } } // Check for parameters inside functions. case *ast.FuncDecl: for _, b := range x1.Body.List { switch x2 := b.(type) { case *ast.DeclStmt: switch x3 := x2.Decl.(type) { case *ast.GenDecl: for _, spc := range x3.Specs { switch x4 := spc.(type) { case *ast.TypeSpec: sd := paramDecl{gofile, x3, x4, nil} sd.inferOperationIDs() if err := pp.parseDecl(tgt, sd); err != nil { return err } } } } } } } } return nil }
go
func (pp *paramStructParser) Parse(gofile *ast.File, target interface{}) error { tgt := target.(map[string]*spec.Operation) for _, decl := range gofile.Decls { switch x1 := decl.(type) { // Check for parameters at the package level. case *ast.GenDecl: for _, spc := range x1.Specs { switch x2 := spc.(type) { case *ast.TypeSpec: sd := paramDecl{gofile, x1, x2, nil} sd.inferOperationIDs() if err := pp.parseDecl(tgt, sd); err != nil { return err } } } // Check for parameters inside functions. case *ast.FuncDecl: for _, b := range x1.Body.List { switch x2 := b.(type) { case *ast.DeclStmt: switch x3 := x2.Decl.(type) { case *ast.GenDecl: for _, spc := range x3.Specs { switch x4 := spc.(type) { case *ast.TypeSpec: sd := paramDecl{gofile, x3, x4, nil} sd.inferOperationIDs() if err := pp.parseDecl(tgt, sd); err != nil { return err } } } } } } } } return nil }
[ "func", "(", "pp", "*", "paramStructParser", ")", "Parse", "(", "gofile", "*", "ast", ".", "File", ",", "target", "interface", "{", "}", ")", "error", "{", "tgt", ":=", "target", ".", "(", "map", "[", "string", "]", "*", "spec", ".", "Operation", ")", "\n", "for", "_", ",", "decl", ":=", "range", "gofile", ".", "Decls", "{", "switch", "x1", ":=", "decl", ".", "(", "type", ")", "{", "// Check for parameters at the package level.", "case", "*", "ast", ".", "GenDecl", ":", "for", "_", ",", "spc", ":=", "range", "x1", ".", "Specs", "{", "switch", "x2", ":=", "spc", ".", "(", "type", ")", "{", "case", "*", "ast", ".", "TypeSpec", ":", "sd", ":=", "paramDecl", "{", "gofile", ",", "x1", ",", "x2", ",", "nil", "}", "\n", "sd", ".", "inferOperationIDs", "(", ")", "\n", "if", "err", ":=", "pp", ".", "parseDecl", "(", "tgt", ",", "sd", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "// Check for parameters inside functions.", "case", "*", "ast", ".", "FuncDecl", ":", "for", "_", ",", "b", ":=", "range", "x1", ".", "Body", ".", "List", "{", "switch", "x2", ":=", "b", ".", "(", "type", ")", "{", "case", "*", "ast", ".", "DeclStmt", ":", "switch", "x3", ":=", "x2", ".", "Decl", ".", "(", "type", ")", "{", "case", "*", "ast", ".", "GenDecl", ":", "for", "_", ",", "spc", ":=", "range", "x3", ".", "Specs", "{", "switch", "x4", ":=", "spc", ".", "(", "type", ")", "{", "case", "*", "ast", ".", "TypeSpec", ":", "sd", ":=", "paramDecl", "{", "gofile", ",", "x3", ",", "x4", ",", "nil", "}", "\n", "sd", ".", "inferOperationIDs", "(", ")", "\n", "if", "err", ":=", "pp", ".", "parseDecl", "(", "tgt", ",", "sd", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Parse will traverse a file and look for parameters.
[ "Parse", "will", "traverse", "a", "file", "and", "look", "for", "parameters", "." ]
ffefbd274717d6fa3bcca1c494487edf1f48104b
https://github.com/go-swagger/go-swagger/blob/ffefbd274717d6fa3bcca1c494487edf1f48104b/scan/parameters.go#L204-L243
train