id
int32
0
167k
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
8,800
luci/luci-go
tools/cmd/assets/main.go
findAssets
func findAssets(pkgDir string, exts []string) (assetMap, error) { assets := assetMap{} err := filepath.Walk(pkgDir, func(path string, info os.FileInfo, err error) error { if err != nil || info.IsDir() || !isAssetFile(path, exts) { return err } rel, err := filepath.Rel(pkgDir, path) if err != nil { return err } blob, err := ioutil.ReadFile(path) if err != nil { return err } assets[filepath.ToSlash(rel)] = asset{ Path: filepath.ToSlash(rel), Body: blob, } return nil }) if err != nil { return nil, err } return assets, nil }
go
func findAssets(pkgDir string, exts []string) (assetMap, error) { assets := assetMap{} err := filepath.Walk(pkgDir, func(path string, info os.FileInfo, err error) error { if err != nil || info.IsDir() || !isAssetFile(path, exts) { return err } rel, err := filepath.Rel(pkgDir, path) if err != nil { return err } blob, err := ioutil.ReadFile(path) if err != nil { return err } assets[filepath.ToSlash(rel)] = asset{ Path: filepath.ToSlash(rel), Body: blob, } return nil }) if err != nil { return nil, err } return assets, nil }
[ "func", "findAssets", "(", "pkgDir", "string", ",", "exts", "[", "]", "string", ")", "(", "assetMap", ",", "error", ")", "{", "assets", ":=", "assetMap", "{", "}", "\n\n", "err", ":=", "filepath", ".", "Walk", "(", "pkgDir", ",", "func", "(", "path", "string", ",", "info", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "if", "err", "!=", "nil", "||", "info", ".", "IsDir", "(", ")", "||", "!", "isAssetFile", "(", "path", ",", "exts", ")", "{", "return", "err", "\n", "}", "\n", "rel", ",", "err", ":=", "filepath", ".", "Rel", "(", "pkgDir", ",", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "blob", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "assets", "[", "filepath", ".", "ToSlash", "(", "rel", ")", "]", "=", "asset", "{", "Path", ":", "filepath", ".", "ToSlash", "(", "rel", ")", ",", "Body", ":", "blob", ",", "}", "\n", "return", "nil", "\n", "}", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "assets", ",", "nil", "\n", "}" ]
// findAssets recursively scans pkgDir for asset files.
[ "findAssets", "recursively", "scans", "pkgDir", "for", "asset", "files", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tools/cmd/assets/main.go#L256-L282
8,801
luci/luci-go
tools/cmd/assets/main.go
isAssetFile
func isAssetFile(path string, assetExts []string) (ok bool) { base := filepath.Base(path) for _, pattern := range assetExts { if match, _ := filepath.Match(pattern, base); match { return true } } return false }
go
func isAssetFile(path string, assetExts []string) (ok bool) { base := filepath.Base(path) for _, pattern := range assetExts { if match, _ := filepath.Match(pattern, base); match { return true } } return false }
[ "func", "isAssetFile", "(", "path", "string", ",", "assetExts", "[", "]", "string", ")", "(", "ok", "bool", ")", "{", "base", ":=", "filepath", ".", "Base", "(", "path", ")", "\n", "for", "_", ",", "pattern", ":=", "range", "assetExts", "{", "if", "match", ",", "_", ":=", "filepath", ".", "Match", "(", "pattern", ",", "base", ")", ";", "match", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// isAssetFile returns true if `path` base name matches some of // `assetExts` glob.
[ "isAssetFile", "returns", "true", "if", "path", "base", "name", "matches", "some", "of", "assetExts", "glob", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tools/cmd/assets/main.go#L286-L294
8,802
luci/luci-go
tools/cmd/assets/main.go
generate
func generate(t *template.Template, pkg *build.Package, assets assetMap, assetExts []string, path string) error { keys := make([]string, 0, len(assets)) for k := range assets { keys = append(keys, k) } sort.Strings(keys) data := templateData{ Patterns: assetExts, PackageName: pkg.Name, } for _, key := range keys { data.Assets = append(data.Assets, assets[key]) } out := bytes.Buffer{} if err := t.Execute(&out, data); err != nil { return err } formatted, err := gofmt(out.Bytes()) if err != nil { return fmt.Errorf("can't gofmt %s - %s", path, err) } return ioutil.WriteFile(path, formatted, 0666) }
go
func generate(t *template.Template, pkg *build.Package, assets assetMap, assetExts []string, path string) error { keys := make([]string, 0, len(assets)) for k := range assets { keys = append(keys, k) } sort.Strings(keys) data := templateData{ Patterns: assetExts, PackageName: pkg.Name, } for _, key := range keys { data.Assets = append(data.Assets, assets[key]) } out := bytes.Buffer{} if err := t.Execute(&out, data); err != nil { return err } formatted, err := gofmt(out.Bytes()) if err != nil { return fmt.Errorf("can't gofmt %s - %s", path, err) } return ioutil.WriteFile(path, formatted, 0666) }
[ "func", "generate", "(", "t", "*", "template", ".", "Template", ",", "pkg", "*", "build", ".", "Package", ",", "assets", "assetMap", ",", "assetExts", "[", "]", "string", ",", "path", "string", ")", "error", "{", "keys", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "assets", ")", ")", "\n", "for", "k", ":=", "range", "assets", "{", "keys", "=", "append", "(", "keys", ",", "k", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "keys", ")", "\n\n", "data", ":=", "templateData", "{", "Patterns", ":", "assetExts", ",", "PackageName", ":", "pkg", ".", "Name", ",", "}", "\n", "for", "_", ",", "key", ":=", "range", "keys", "{", "data", ".", "Assets", "=", "append", "(", "data", ".", "Assets", ",", "assets", "[", "key", "]", ")", "\n", "}", "\n\n", "out", ":=", "bytes", ".", "Buffer", "{", "}", "\n", "if", "err", ":=", "t", ".", "Execute", "(", "&", "out", ",", "data", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "formatted", ",", "err", ":=", "gofmt", "(", "out", ".", "Bytes", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "path", ",", "err", ")", "\n", "}", "\n\n", "return", "ioutil", ".", "WriteFile", "(", "path", ",", "formatted", ",", "0666", ")", "\n", "}" ]
// generate executes the template, runs output through gofmt and dumps it to disk.
[ "generate", "executes", "the", "template", "runs", "output", "through", "gofmt", "and", "dumps", "it", "to", "disk", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tools/cmd/assets/main.go#L297-L323
8,803
luci/luci-go
tumble/config.go
getConfig
func getConfig(c context.Context) *Config { cfg := Config{} switch err := settings.Get(c, baseName, &cfg); err { case nil: break case settings.ErrNoSettings: // Defaults. cfg = defaultConfig default: panic(fmt.Errorf("could not fetch Tumble settings - %s", err)) } return &cfg }
go
func getConfig(c context.Context) *Config { cfg := Config{} switch err := settings.Get(c, baseName, &cfg); err { case nil: break case settings.ErrNoSettings: // Defaults. cfg = defaultConfig default: panic(fmt.Errorf("could not fetch Tumble settings - %s", err)) } return &cfg }
[ "func", "getConfig", "(", "c", "context", ".", "Context", ")", "*", "Config", "{", "cfg", ":=", "Config", "{", "}", "\n", "switch", "err", ":=", "settings", ".", "Get", "(", "c", ",", "baseName", ",", "&", "cfg", ")", ";", "err", "{", "case", "nil", ":", "break", "\n", "case", "settings", ".", "ErrNoSettings", ":", "// Defaults.", "cfg", "=", "defaultConfig", "\n", "default", ":", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n", "return", "&", "cfg", "\n", "}" ]
// getConfig returns the current configuration. // // It first tries to load it from settings. If no settings is installed, or if // there is no configuration in settings, defaultConfig is returned.
[ "getConfig", "returns", "the", "current", "configuration", ".", "It", "first", "tries", "to", "load", "it", "from", "settings", ".", "If", "no", "settings", "is", "installed", "or", "if", "there", "is", "no", "configuration", "in", "settings", "defaultConfig", "is", "returned", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tumble/config.go#L136-L148
8,804
luci/luci-go
machine-db/client/cli/printer.go
Row
func (p *humanReadable) Row(args ...interface{}) { for i, arg := range args { if i > 0 { fmt.Fprint(p, "\t") } switch a := arg.(type) { case common.State: fmt.Fprint(p, a.Name()) default: fmt.Fprint(p, arg) } } fmt.Fprint(p, "\n") }
go
func (p *humanReadable) Row(args ...interface{}) { for i, arg := range args { if i > 0 { fmt.Fprint(p, "\t") } switch a := arg.(type) { case common.State: fmt.Fprint(p, a.Name()) default: fmt.Fprint(p, arg) } } fmt.Fprint(p, "\n") }
[ "func", "(", "p", "*", "humanReadable", ")", "Row", "(", "args", "...", "interface", "{", "}", ")", "{", "for", "i", ",", "arg", ":=", "range", "args", "{", "if", "i", ">", "0", "{", "fmt", ".", "Fprint", "(", "p", ",", "\"", "\\t", "\"", ")", "\n", "}", "\n", "switch", "a", ":=", "arg", ".", "(", "type", ")", "{", "case", "common", ".", "State", ":", "fmt", ".", "Fprint", "(", "p", ",", "a", ".", "Name", "(", ")", ")", "\n", "default", ":", "fmt", ".", "Fprint", "(", "p", ",", "arg", ")", "\n", "}", "\n", "}", "\n", "fmt", ".", "Fprint", "(", "p", ",", "\"", "\\n", "\"", ")", "\n", "}" ]
// Row prints one row of space-separated columns. // Aligns mixed-length columns regardless of how many spaces it takes.
[ "Row", "prints", "one", "row", "of", "space", "-", "separated", "columns", ".", "Aligns", "mixed", "-", "length", "columns", "regardless", "of", "how", "many", "spaces", "it", "takes", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/printer.go#L41-L54
8,805
luci/luci-go
machine-db/client/cli/printer.go
Row
func (p *machineReadable) Row(args ...interface{}) { row := make([]string, len(args)) for i, arg := range args { switch a := arg.(type) { case common.State: row[i] = a.Name() default: row[i] = fmt.Sprint(arg) } } p.Write(row) }
go
func (p *machineReadable) Row(args ...interface{}) { row := make([]string, len(args)) for i, arg := range args { switch a := arg.(type) { case common.State: row[i] = a.Name() default: row[i] = fmt.Sprint(arg) } } p.Write(row) }
[ "func", "(", "p", "*", "machineReadable", ")", "Row", "(", "args", "...", "interface", "{", "}", ")", "{", "row", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "args", ")", ")", "\n", "for", "i", ",", "arg", ":=", "range", "args", "{", "switch", "a", ":=", "arg", ".", "(", "type", ")", "{", "case", "common", ".", "State", ":", "row", "[", "i", "]", "=", "a", ".", "Name", "(", ")", "\n", "default", ":", "row", "[", "i", "]", "=", "fmt", ".", "Sprint", "(", "arg", ")", "\n", "}", "\n", "}", "\n", "p", ".", "Write", "(", "row", ")", "\n", "}" ]
// Row prints one row of tab-separated columns. // Does not attempt to align mixed-length columns.
[ "Row", "prints", "one", "row", "of", "tab", "-", "separated", "columns", ".", "Does", "not", "attempt", "to", "align", "mixed", "-", "length", "columns", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/printer.go#L76-L87
8,806
luci/luci-go
machine-db/client/cli/printer.go
newStdoutPrinter
func newStdoutPrinter(forMachines bool) tablePrinter { if forMachines { return newMachineReadable(os.Stdout) } return newHumanReadable(os.Stdout) }
go
func newStdoutPrinter(forMachines bool) tablePrinter { if forMachines { return newMachineReadable(os.Stdout) } return newHumanReadable(os.Stdout) }
[ "func", "newStdoutPrinter", "(", "forMachines", "bool", ")", "tablePrinter", "{", "if", "forMachines", "{", "return", "newMachineReadable", "(", "os", ".", "Stdout", ")", "\n", "}", "\n", "return", "newHumanReadable", "(", "os", ".", "Stdout", ")", "\n", "}" ]
// newStdoutPrinter returns a tablePrinter which writes to os.Stdout.
[ "newStdoutPrinter", "returns", "a", "tablePrinter", "which", "writes", "to", "os", ".", "Stdout", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/printer.go#L96-L101
8,807
luci/luci-go
mmutex/lib/lock_file_helpers.go
computeMutexPaths
func computeMutexPaths(env subcommands.Env) (lockFilePath string, drainFilePath string, err error) { envVar := env[LockFileEnvVariable] if !envVar.Exists { return "", "", nil } lockFileDir := envVar.Value if !filepath.IsAbs(lockFileDir) { return "", "", errors.Reason("Lock file directory %s must be an absolute path", lockFileDir).Err() } if _, err := os.Stat(lockFileDir); os.IsNotExist(err) { fmt.Printf("Lock file directory %s does not exist, mmutex acting as a passthrough.\n", lockFileDir) return "", "", nil } return filepath.Join(lockFileDir, LockFileName), filepath.Join(lockFileDir, DrainFileName), nil }
go
func computeMutexPaths(env subcommands.Env) (lockFilePath string, drainFilePath string, err error) { envVar := env[LockFileEnvVariable] if !envVar.Exists { return "", "", nil } lockFileDir := envVar.Value if !filepath.IsAbs(lockFileDir) { return "", "", errors.Reason("Lock file directory %s must be an absolute path", lockFileDir).Err() } if _, err := os.Stat(lockFileDir); os.IsNotExist(err) { fmt.Printf("Lock file directory %s does not exist, mmutex acting as a passthrough.\n", lockFileDir) return "", "", nil } return filepath.Join(lockFileDir, LockFileName), filepath.Join(lockFileDir, DrainFileName), nil }
[ "func", "computeMutexPaths", "(", "env", "subcommands", ".", "Env", ")", "(", "lockFilePath", "string", ",", "drainFilePath", "string", ",", "err", "error", ")", "{", "envVar", ":=", "env", "[", "LockFileEnvVariable", "]", "\n", "if", "!", "envVar", ".", "Exists", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "nil", "\n", "}", "\n\n", "lockFileDir", ":=", "envVar", ".", "Value", "\n", "if", "!", "filepath", ".", "IsAbs", "(", "lockFileDir", ")", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "errors", ".", "Reason", "(", "\"", "\"", ",", "lockFileDir", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "lockFileDir", ")", ";", "os", ".", "IsNotExist", "(", "err", ")", "{", "fmt", ".", "Printf", "(", "\"", "\\n", "\"", ",", "lockFileDir", ")", "\n", "return", "\"", "\"", ",", "\"", "\"", ",", "nil", "\n", "}", "\n\n", "return", "filepath", ".", "Join", "(", "lockFileDir", ",", "LockFileName", ")", ",", "filepath", ".", "Join", "(", "lockFileDir", ",", "DrainFileName", ")", ",", "nil", "\n", "}" ]
// computeMutexPaths returns the lock and drain file paths based on the environment, // or empty strings if no lock files should be used.
[ "computeMutexPaths", "returns", "the", "lock", "and", "drain", "file", "paths", "based", "on", "the", "environment", "or", "empty", "strings", "if", "no", "lock", "files", "should", "be", "used", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mmutex/lib/lock_file_helpers.go#L55-L72
8,808
luci/luci-go
mmutex/lib/lock_file_helpers.go
blockWhileFileExists
func blockWhileFileExists(path string, blocker fslock.Blocker) error { for { if _, err := os.Stat(path); os.IsNotExist(err) { break } else if err != nil { return errors.Annotate(err, "failed to stat %s", path).Err() } if err := blocker(); err != nil { return errors.New("timed out waiting for drain file to disappear") } } return nil }
go
func blockWhileFileExists(path string, blocker fslock.Blocker) error { for { if _, err := os.Stat(path); os.IsNotExist(err) { break } else if err != nil { return errors.Annotate(err, "failed to stat %s", path).Err() } if err := blocker(); err != nil { return errors.New("timed out waiting for drain file to disappear") } } return nil }
[ "func", "blockWhileFileExists", "(", "path", "string", ",", "blocker", "fslock", ".", "Blocker", ")", "error", "{", "for", "{", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "path", ")", ";", "os", ".", "IsNotExist", "(", "err", ")", "{", "break", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "path", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "if", "err", ":=", "blocker", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// blockWhileFileExists blocks until the file located at path no longer exists. // For convenience, this method reuses the Blocker interface exposed by fslock // and used elsewhere in this package.
[ "blockWhileFileExists", "blocks", "until", "the", "file", "located", "at", "path", "no", "longer", "exists", ".", "For", "convenience", "this", "method", "reuses", "the", "Blocker", "interface", "exposed", "by", "fslock", "and", "used", "elsewhere", "in", "this", "package", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mmutex/lib/lock_file_helpers.go#L93-L107
8,809
luci/luci-go
logdog/client/butler/buffered_callback/text.go
assertGetText
func assertGetText(le *logpb.LogEntry) *logpb.Text { if txt := le.GetText(); txt == nil { panic( errors.Annotate( InvalidStreamType, fmt.Sprintf("got %T, expected *logpb.LogEntry_Text", le.Content), ).Err(), ) } else { return txt } }
go
func assertGetText(le *logpb.LogEntry) *logpb.Text { if txt := le.GetText(); txt == nil { panic( errors.Annotate( InvalidStreamType, fmt.Sprintf("got %T, expected *logpb.LogEntry_Text", le.Content), ).Err(), ) } else { return txt } }
[ "func", "assertGetText", "(", "le", "*", "logpb", ".", "LogEntry", ")", "*", "logpb", ".", "Text", "{", "if", "txt", ":=", "le", ".", "GetText", "(", ")", ";", "txt", "==", "nil", "{", "panic", "(", "errors", ".", "Annotate", "(", "InvalidStreamType", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "le", ".", "Content", ")", ",", ")", ".", "Err", "(", ")", ",", ")", "\n", "}", "else", "{", "return", "txt", "\n", "}", "\n", "}" ]
// assertGetText panics if the passed LogEntry does not contain Text data, or returns it.
[ "assertGetText", "panics", "if", "the", "passed", "LogEntry", "does", "not", "contain", "Text", "data", "or", "returns", "it", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/buffered_callback/text.go#L26-L37
8,810
luci/luci-go
gce/appengine/backend/instances.go
setCreated
func setCreated(c context.Context, id, url string, at time.Time) error { vm := &model.VM{ ID: id, } return datastore.RunInTransaction(c, func(c context.Context) error { if err := datastore.Get(c, vm); err != nil { return errors.Annotate(err, "failed to fetch VM").Err() } if vm.URL != "" { // Already created. return nil } vm.Created = at.Unix() vm.URL = url if err := datastore.Put(c, vm); err != nil { return errors.Annotate(err, "failed to store VM").Err() } return nil }, nil) }
go
func setCreated(c context.Context, id, url string, at time.Time) error { vm := &model.VM{ ID: id, } return datastore.RunInTransaction(c, func(c context.Context) error { if err := datastore.Get(c, vm); err != nil { return errors.Annotate(err, "failed to fetch VM").Err() } if vm.URL != "" { // Already created. return nil } vm.Created = at.Unix() vm.URL = url if err := datastore.Put(c, vm); err != nil { return errors.Annotate(err, "failed to store VM").Err() } return nil }, nil) }
[ "func", "setCreated", "(", "c", "context", ".", "Context", ",", "id", ",", "url", "string", ",", "at", "time", ".", "Time", ")", "error", "{", "vm", ":=", "&", "model", ".", "VM", "{", "ID", ":", "id", ",", "}", "\n", "return", "datastore", ".", "RunInTransaction", "(", "c", ",", "func", "(", "c", "context", ".", "Context", ")", "error", "{", "if", "err", ":=", "datastore", ".", "Get", "(", "c", ",", "vm", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "if", "vm", ".", "URL", "!=", "\"", "\"", "{", "// Already created.", "return", "nil", "\n", "}", "\n", "vm", ".", "Created", "=", "at", ".", "Unix", "(", ")", "\n", "vm", ".", "URL", "=", "url", "\n", "if", "err", ":=", "datastore", ".", "Put", "(", "c", ",", "vm", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}", ",", "nil", ")", "\n", "}" ]
// setCreated sets the GCE instance as created in the datastore if it isn't already.
[ "setCreated", "sets", "the", "GCE", "instance", "as", "created", "in", "the", "datastore", "if", "it", "isn", "t", "already", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/instances.go#L40-L59
8,811
luci/luci-go
gce/appengine/backend/instances.go
conflictingInstance
func conflictingInstance(c context.Context, vm *model.VM) error { // Hostnames are required to be unique per project. // A conflict only occurs in the case of name collision. srv := getCompute(c).Instances call := srv.Get(vm.Attributes.GetProject(), vm.Attributes.GetZone(), vm.Hostname) inst, err := call.Context(c).Do() if err != nil { if gerr, ok := err.(*googleapi.Error); ok { if gerr.Code == http.StatusNotFound { // Instance doesn't exist in this zone. metrics.UpdateFailures(c, 1, vm) if err := deleteVM(c, vm.ID, vm.Hostname); err != nil { return errors.Annotate(err, "instance exists in another zone").Err() } return errors.Reason("instance exists in another zone").Err() } logErrors(c, gerr) } return errors.Annotate(err, "failed to fetch instance").Err() } // Instance exists in this zone. logging.Debugf(c, "instance exists: %s", inst.SelfLink) t, err := time.Parse(time.RFC3339, inst.CreationTimestamp) if err != nil { return errors.Annotate(err, "failed to parse instance creation time").Err() } return setCreated(c, vm.ID, inst.SelfLink, t) }
go
func conflictingInstance(c context.Context, vm *model.VM) error { // Hostnames are required to be unique per project. // A conflict only occurs in the case of name collision. srv := getCompute(c).Instances call := srv.Get(vm.Attributes.GetProject(), vm.Attributes.GetZone(), vm.Hostname) inst, err := call.Context(c).Do() if err != nil { if gerr, ok := err.(*googleapi.Error); ok { if gerr.Code == http.StatusNotFound { // Instance doesn't exist in this zone. metrics.UpdateFailures(c, 1, vm) if err := deleteVM(c, vm.ID, vm.Hostname); err != nil { return errors.Annotate(err, "instance exists in another zone").Err() } return errors.Reason("instance exists in another zone").Err() } logErrors(c, gerr) } return errors.Annotate(err, "failed to fetch instance").Err() } // Instance exists in this zone. logging.Debugf(c, "instance exists: %s", inst.SelfLink) t, err := time.Parse(time.RFC3339, inst.CreationTimestamp) if err != nil { return errors.Annotate(err, "failed to parse instance creation time").Err() } return setCreated(c, vm.ID, inst.SelfLink, t) }
[ "func", "conflictingInstance", "(", "c", "context", ".", "Context", ",", "vm", "*", "model", ".", "VM", ")", "error", "{", "// Hostnames are required to be unique per project.", "// A conflict only occurs in the case of name collision.", "srv", ":=", "getCompute", "(", "c", ")", ".", "Instances", "\n", "call", ":=", "srv", ".", "Get", "(", "vm", ".", "Attributes", ".", "GetProject", "(", ")", ",", "vm", ".", "Attributes", ".", "GetZone", "(", ")", ",", "vm", ".", "Hostname", ")", "\n", "inst", ",", "err", ":=", "call", ".", "Context", "(", "c", ")", ".", "Do", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "gerr", ",", "ok", ":=", "err", ".", "(", "*", "googleapi", ".", "Error", ")", ";", "ok", "{", "if", "gerr", ".", "Code", "==", "http", ".", "StatusNotFound", "{", "// Instance doesn't exist in this zone.", "metrics", ".", "UpdateFailures", "(", "c", ",", "1", ",", "vm", ")", "\n", "if", "err", ":=", "deleteVM", "(", "c", ",", "vm", ".", "ID", ",", "vm", ".", "Hostname", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "errors", ".", "Reason", "(", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "logErrors", "(", "c", ",", "gerr", ")", "\n", "}", "\n", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "// Instance exists in this zone.", "logging", ".", "Debugf", "(", "c", ",", "\"", "\"", ",", "inst", ".", "SelfLink", ")", "\n", "t", ",", "err", ":=", "time", ".", "Parse", "(", "time", ".", "RFC3339", ",", "inst", ".", "CreationTimestamp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "setCreated", "(", "c", ",", "vm", ".", "ID", ",", "inst", ".", "SelfLink", ",", "t", ")", "\n", "}" ]
// conflictingInstance deals with a GCE instance creation conflict.
[ "conflictingInstance", "deals", "with", "a", "GCE", "instance", "creation", "conflict", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/instances.go#L81-L108
8,812
luci/luci-go
gce/appengine/backend/instances.go
destroyInstanceAsync
func destroyInstanceAsync(c context.Context, id, url string) error { t := &tq.Task{ Payload: &tasks.DestroyInstance{ Id: id, Url: url, }, } if err := getDispatcher(c).AddTask(c, t); err != nil { return errors.Annotate(err, "failed to schedule destroy task").Err() } return nil }
go
func destroyInstanceAsync(c context.Context, id, url string) error { t := &tq.Task{ Payload: &tasks.DestroyInstance{ Id: id, Url: url, }, } if err := getDispatcher(c).AddTask(c, t); err != nil { return errors.Annotate(err, "failed to schedule destroy task").Err() } return nil }
[ "func", "destroyInstanceAsync", "(", "c", "context", ".", "Context", ",", "id", ",", "url", "string", ")", "error", "{", "t", ":=", "&", "tq", ".", "Task", "{", "Payload", ":", "&", "tasks", ".", "DestroyInstance", "{", "Id", ":", "id", ",", "Url", ":", "url", ",", "}", ",", "}", "\n", "if", "err", ":=", "getDispatcher", "(", "c", ")", ".", "AddTask", "(", "c", ",", "t", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// destroyInstanceAsync schedules a task queue task to destroy a GCE instance.
[ "destroyInstanceAsync", "schedules", "a", "task", "queue", "task", "to", "destroy", "a", "GCE", "instance", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/instances.go#L183-L194
8,813
luci/luci-go
gce/appengine/backend/instances.go
destroyInstance
func destroyInstance(c context.Context, payload proto.Message) error { task, ok := payload.(*tasks.DestroyInstance) switch { case !ok: return errors.Reason("unexpected payload type %T", payload).Err() case task.GetId() == "": return errors.Reason("ID is required").Err() case task.GetUrl() == "": return errors.Reason("URL is required").Err() } vm := &model.VM{ ID: task.Id, } switch err := datastore.Get(c, vm); { case err == datastore.ErrNoSuchEntity: return nil case err != nil: return errors.Annotate(err, "failed to fetch VM").Err() case vm.URL != task.Url: // Instance is already destroyed and replaced. Don't destroy the new one. return errors.Reason("instance does not exist: %s", task.Url).Err() } logging.Debugf(c, "destroying instance %q", vm.Hostname) // Generate a request ID based on the hostname. // Ensures duplicate operations aren't created in GCE. rID := uuid.NewSHA1(uuid.Nil, []byte(fmt.Sprintf("destroy-%s", vm.Hostname))) srv := getCompute(c).Instances call := srv.Delete(vm.Attributes.GetProject(), vm.Attributes.GetZone(), vm.Hostname) op, err := call.RequestId(rID.String()).Context(c).Do() if err != nil { if gerr, ok := err.(*googleapi.Error); ok { if gerr.Code == http.StatusNotFound { // Instance is already destroyed. logging.Debugf(c, "instance does not exist: %s", vm.URL) return deleteBotAsync(c, task.Id, vm.Hostname) } logErrors(c, gerr) } return errors.Annotate(err, "failed to destroy instance").Err() } if op.Error != nil && len(op.Error.Errors) > 0 { for _, err := range op.Error.Errors { logging.Errorf(c, "%s: %s", err.Code, err.Message) } return errors.Reason("failed to destroy instance").Err() } if op.Status == "DONE" { logging.Debugf(c, "destroyed instance: %s", op.TargetLink) return deleteBotAsync(c, task.Id, vm.Hostname) } // Instance destruction is pending. return nil }
go
func destroyInstance(c context.Context, payload proto.Message) error { task, ok := payload.(*tasks.DestroyInstance) switch { case !ok: return errors.Reason("unexpected payload type %T", payload).Err() case task.GetId() == "": return errors.Reason("ID is required").Err() case task.GetUrl() == "": return errors.Reason("URL is required").Err() } vm := &model.VM{ ID: task.Id, } switch err := datastore.Get(c, vm); { case err == datastore.ErrNoSuchEntity: return nil case err != nil: return errors.Annotate(err, "failed to fetch VM").Err() case vm.URL != task.Url: // Instance is already destroyed and replaced. Don't destroy the new one. return errors.Reason("instance does not exist: %s", task.Url).Err() } logging.Debugf(c, "destroying instance %q", vm.Hostname) // Generate a request ID based on the hostname. // Ensures duplicate operations aren't created in GCE. rID := uuid.NewSHA1(uuid.Nil, []byte(fmt.Sprintf("destroy-%s", vm.Hostname))) srv := getCompute(c).Instances call := srv.Delete(vm.Attributes.GetProject(), vm.Attributes.GetZone(), vm.Hostname) op, err := call.RequestId(rID.String()).Context(c).Do() if err != nil { if gerr, ok := err.(*googleapi.Error); ok { if gerr.Code == http.StatusNotFound { // Instance is already destroyed. logging.Debugf(c, "instance does not exist: %s", vm.URL) return deleteBotAsync(c, task.Id, vm.Hostname) } logErrors(c, gerr) } return errors.Annotate(err, "failed to destroy instance").Err() } if op.Error != nil && len(op.Error.Errors) > 0 { for _, err := range op.Error.Errors { logging.Errorf(c, "%s: %s", err.Code, err.Message) } return errors.Reason("failed to destroy instance").Err() } if op.Status == "DONE" { logging.Debugf(c, "destroyed instance: %s", op.TargetLink) return deleteBotAsync(c, task.Id, vm.Hostname) } // Instance destruction is pending. return nil }
[ "func", "destroyInstance", "(", "c", "context", ".", "Context", ",", "payload", "proto", ".", "Message", ")", "error", "{", "task", ",", "ok", ":=", "payload", ".", "(", "*", "tasks", ".", "DestroyInstance", ")", "\n", "switch", "{", "case", "!", "ok", ":", "return", "errors", ".", "Reason", "(", "\"", "\"", ",", "payload", ")", ".", "Err", "(", ")", "\n", "case", "task", ".", "GetId", "(", ")", "==", "\"", "\"", ":", "return", "errors", ".", "Reason", "(", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "case", "task", ".", "GetUrl", "(", ")", "==", "\"", "\"", ":", "return", "errors", ".", "Reason", "(", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "vm", ":=", "&", "model", ".", "VM", "{", "ID", ":", "task", ".", "Id", ",", "}", "\n", "switch", "err", ":=", "datastore", ".", "Get", "(", "c", ",", "vm", ")", ";", "{", "case", "err", "==", "datastore", ".", "ErrNoSuchEntity", ":", "return", "nil", "\n", "case", "err", "!=", "nil", ":", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "case", "vm", ".", "URL", "!=", "task", ".", "Url", ":", "// Instance is already destroyed and replaced. Don't destroy the new one.", "return", "errors", ".", "Reason", "(", "\"", "\"", ",", "task", ".", "Url", ")", ".", "Err", "(", ")", "\n", "}", "\n", "logging", ".", "Debugf", "(", "c", ",", "\"", "\"", ",", "vm", ".", "Hostname", ")", "\n", "// Generate a request ID based on the hostname.", "// Ensures duplicate operations aren't created in GCE.", "rID", ":=", "uuid", ".", "NewSHA1", "(", "uuid", ".", "Nil", ",", "[", "]", "byte", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "vm", ".", "Hostname", ")", ")", ")", "\n", "srv", ":=", "getCompute", "(", "c", ")", ".", "Instances", "\n", "call", ":=", "srv", ".", "Delete", "(", "vm", ".", "Attributes", ".", "GetProject", "(", ")", ",", "vm", ".", "Attributes", ".", "GetZone", "(", ")", ",", "vm", ".", "Hostname", ")", "\n", "op", ",", "err", ":=", "call", ".", "RequestId", "(", "rID", ".", "String", "(", ")", ")", ".", "Context", "(", "c", ")", ".", "Do", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "gerr", ",", "ok", ":=", "err", ".", "(", "*", "googleapi", ".", "Error", ")", ";", "ok", "{", "if", "gerr", ".", "Code", "==", "http", ".", "StatusNotFound", "{", "// Instance is already destroyed.", "logging", ".", "Debugf", "(", "c", ",", "\"", "\"", ",", "vm", ".", "URL", ")", "\n", "return", "deleteBotAsync", "(", "c", ",", "task", ".", "Id", ",", "vm", ".", "Hostname", ")", "\n", "}", "\n", "logErrors", "(", "c", ",", "gerr", ")", "\n", "}", "\n", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "if", "op", ".", "Error", "!=", "nil", "&&", "len", "(", "op", ".", "Error", ".", "Errors", ")", ">", "0", "{", "for", "_", ",", "err", ":=", "range", "op", ".", "Error", ".", "Errors", "{", "logging", ".", "Errorf", "(", "c", ",", "\"", "\"", ",", "err", ".", "Code", ",", "err", ".", "Message", ")", "\n", "}", "\n", "return", "errors", ".", "Reason", "(", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "if", "op", ".", "Status", "==", "\"", "\"", "{", "logging", ".", "Debugf", "(", "c", ",", "\"", "\"", ",", "op", ".", "TargetLink", ")", "\n", "return", "deleteBotAsync", "(", "c", ",", "task", ".", "Id", ",", "vm", ".", "Hostname", ")", "\n", "}", "\n", "// Instance destruction is pending.", "return", "nil", "\n", "}" ]
// destroyInstance destroys a GCE instance.
[ "destroyInstance", "destroys", "a", "GCE", "instance", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/backend/instances.go#L200-L252
8,814
luci/luci-go
grpc/cmd/cproto/service.go
trimPhrase
func trimPhrase(v, prefix, suffix string) string { if !strings.HasPrefix(v, prefix) { return "" } v = strings.TrimPrefix(v, prefix) if !strings.HasSuffix(v, suffix) { return "" } return strings.TrimSuffix(v, suffix) }
go
func trimPhrase(v, prefix, suffix string) string { if !strings.HasPrefix(v, prefix) { return "" } v = strings.TrimPrefix(v, prefix) if !strings.HasSuffix(v, suffix) { return "" } return strings.TrimSuffix(v, suffix) }
[ "func", "trimPhrase", "(", "v", ",", "prefix", ",", "suffix", "string", ")", "string", "{", "if", "!", "strings", ".", "HasPrefix", "(", "v", ",", "prefix", ")", "{", "return", "\"", "\"", "\n", "}", "\n", "v", "=", "strings", ".", "TrimPrefix", "(", "v", ",", "prefix", ")", "\n\n", "if", "!", "strings", ".", "HasSuffix", "(", "v", ",", "suffix", ")", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "strings", ".", "TrimSuffix", "(", "v", ",", "suffix", ")", "\n", "}" ]
// trimPhrase removes the specified prefix and suffix strings from the supplied // v. If either prefix is missing, suffix is missing, or v consists entirely of // prefix and suffix, the empty string is returned.
[ "trimPhrase", "removes", "the", "specified", "prefix", "and", "suffix", "strings", "from", "the", "supplied", "v", ".", "If", "either", "prefix", "is", "missing", "suffix", "is", "missing", "or", "v", "consists", "entirely", "of", "prefix", "and", "suffix", "the", "empty", "string", "is", "returned", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/cmd/cproto/service.go#L169-L179
8,815
luci/luci-go
common/api/buildbucket/buildbucket/v1/search.go
Fetch
func (c *SearchCall) Fetch(limit int, ret retry.Factory) ([]*ApiCommonBuildMessage, string, error) { // Default page size to 100 because we are fetching everything. maxBuildsKey := "max_builds" origMaxBuilds := c.urlParams_.Get(maxBuildsKey) if origMaxBuilds == "" { c.MaxBuilds(100) defer c.urlParams_.Set(maxBuildsKey, origMaxBuilds) } ch := make(chan *ApiCommonBuildMessage) var err error var cursor string go func() { defer close(ch) cursor, err = c.Run(ch, limit, ret) }() var builds []*ApiCommonBuildMessage for b := range ch { builds = append(builds, b) } return builds, cursor, err }
go
func (c *SearchCall) Fetch(limit int, ret retry.Factory) ([]*ApiCommonBuildMessage, string, error) { // Default page size to 100 because we are fetching everything. maxBuildsKey := "max_builds" origMaxBuilds := c.urlParams_.Get(maxBuildsKey) if origMaxBuilds == "" { c.MaxBuilds(100) defer c.urlParams_.Set(maxBuildsKey, origMaxBuilds) } ch := make(chan *ApiCommonBuildMessage) var err error var cursor string go func() { defer close(ch) cursor, err = c.Run(ch, limit, ret) }() var builds []*ApiCommonBuildMessage for b := range ch { builds = append(builds, b) } return builds, cursor, err }
[ "func", "(", "c", "*", "SearchCall", ")", "Fetch", "(", "limit", "int", ",", "ret", "retry", ".", "Factory", ")", "(", "[", "]", "*", "ApiCommonBuildMessage", ",", "string", ",", "error", ")", "{", "// Default page size to 100 because we are fetching everything.", "maxBuildsKey", ":=", "\"", "\"", "\n", "origMaxBuilds", ":=", "c", ".", "urlParams_", ".", "Get", "(", "maxBuildsKey", ")", "\n", "if", "origMaxBuilds", "==", "\"", "\"", "{", "c", ".", "MaxBuilds", "(", "100", ")", "\n", "defer", "c", ".", "urlParams_", ".", "Set", "(", "maxBuildsKey", ",", "origMaxBuilds", ")", "\n", "}", "\n\n", "ch", ":=", "make", "(", "chan", "*", "ApiCommonBuildMessage", ")", "\n", "var", "err", "error", "\n", "var", "cursor", "string", "\n", "go", "func", "(", ")", "{", "defer", "close", "(", "ch", ")", "\n", "cursor", ",", "err", "=", "c", ".", "Run", "(", "ch", ",", "limit", ",", "ret", ")", "\n", "}", "(", ")", "\n\n", "var", "builds", "[", "]", "*", "ApiCommonBuildMessage", "\n", "for", "b", ":=", "range", "ch", "{", "builds", "=", "append", "(", "builds", ",", "b", ")", "\n", "}", "\n", "return", "builds", ",", "cursor", ",", "err", "\n", "}" ]
// Fetch fetches builds matching the search criteria. // It stops when all builds are found or when context is cancelled. // The order of returned builds is from most-recently-created to least-recently-created. // // c.MaxBuilds value is used as a result page size, defaults to 100. // limit, if >0, specifies the maximum number of builds to return. // // If ret is nil, retries transient errors with exponential back-off. // Logs errors on retries. // // Returns nil only if the search results are exhausted. // May return context.Canceled.
[ "Fetch", "fetches", "builds", "matching", "the", "search", "criteria", ".", "It", "stops", "when", "all", "builds", "are", "found", "or", "when", "context", "is", "cancelled", ".", "The", "order", "of", "returned", "builds", "is", "from", "most", "-", "recently", "-", "created", "to", "least", "-", "recently", "-", "created", ".", "c", ".", "MaxBuilds", "value", "is", "used", "as", "a", "result", "page", "size", "defaults", "to", "100", ".", "limit", "if", ">", "0", "specifies", "the", "maximum", "number", "of", "builds", "to", "return", ".", "If", "ret", "is", "nil", "retries", "transient", "errors", "with", "exponential", "back", "-", "off", ".", "Logs", "errors", "on", "retries", ".", "Returns", "nil", "only", "if", "the", "search", "results", "are", "exhausted", ".", "May", "return", "context", ".", "Canceled", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/api/buildbucket/buildbucket/v1/search.go#L41-L63
8,816
luci/luci-go
common/tsmon/context.go
WithState
func WithState(ctx context.Context, s *State) context.Context { return context.WithValue(ctx, stateKey, s) }
go
func WithState(ctx context.Context, s *State) context.Context { return context.WithValue(ctx, stateKey, s) }
[ "func", "WithState", "(", "ctx", "context", ".", "Context", ",", "s", "*", "State", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "ctx", ",", "stateKey", ",", "s", ")", "\n", "}" ]
// WithState returns a new context holding the given State instance.
[ "WithState", "returns", "a", "new", "context", "holding", "the", "given", "State", "instance", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/context.go#L26-L28
8,817
luci/luci-go
common/tsmon/context.go
WithFakes
func WithFakes(ctx context.Context) (context.Context, *store.Fake, *monitor.Fake) { s := &store.Fake{} m := &monitor.Fake{} return WithState(ctx, &State{ store: s, monitor: m, invokeGlobalCallbacksOnFlush: true, }), s, m }
go
func WithFakes(ctx context.Context) (context.Context, *store.Fake, *monitor.Fake) { s := &store.Fake{} m := &monitor.Fake{} return WithState(ctx, &State{ store: s, monitor: m, invokeGlobalCallbacksOnFlush: true, }), s, m }
[ "func", "WithFakes", "(", "ctx", "context", ".", "Context", ")", "(", "context", ".", "Context", ",", "*", "store", ".", "Fake", ",", "*", "monitor", ".", "Fake", ")", "{", "s", ":=", "&", "store", ".", "Fake", "{", "}", "\n", "m", ":=", "&", "monitor", ".", "Fake", "{", "}", "\n", "return", "WithState", "(", "ctx", ",", "&", "State", "{", "store", ":", "s", ",", "monitor", ":", "m", ",", "invokeGlobalCallbacksOnFlush", ":", "true", ",", "}", ")", ",", "s", ",", "m", "\n", "}" ]
// WithFakes returns a new context holding a new State with a fake store and a // fake monitor.
[ "WithFakes", "returns", "a", "new", "context", "holding", "a", "new", "State", "with", "a", "fake", "store", "and", "a", "fake", "monitor", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/context.go#L32-L40
8,818
luci/luci-go
common/tsmon/context.go
WithDummyInMemory
func WithDummyInMemory(ctx context.Context) (context.Context, *monitor.Fake) { m := &monitor.Fake{} return WithState(ctx, &State{ store: store.NewInMemory(&target.Task{}), monitor: m, invokeGlobalCallbacksOnFlush: true, }), m }
go
func WithDummyInMemory(ctx context.Context) (context.Context, *monitor.Fake) { m := &monitor.Fake{} return WithState(ctx, &State{ store: store.NewInMemory(&target.Task{}), monitor: m, invokeGlobalCallbacksOnFlush: true, }), m }
[ "func", "WithDummyInMemory", "(", "ctx", "context", ".", "Context", ")", "(", "context", ".", "Context", ",", "*", "monitor", ".", "Fake", ")", "{", "m", ":=", "&", "monitor", ".", "Fake", "{", "}", "\n", "return", "WithState", "(", "ctx", ",", "&", "State", "{", "store", ":", "store", ".", "NewInMemory", "(", "&", "target", ".", "Task", "{", "}", ")", ",", "monitor", ":", "m", ",", "invokeGlobalCallbacksOnFlush", ":", "true", ",", "}", ")", ",", "m", "\n", "}" ]
// WithDummyInMemory returns a new context holding a new State with a new in- // memory store and a fake monitor.
[ "WithDummyInMemory", "returns", "a", "new", "context", "holding", "a", "new", "State", "with", "a", "new", "in", "-", "memory", "store", "and", "a", "fake", "monitor", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/context.go#L44-L51
8,819
luci/luci-go
common/tsmon/context.go
stateFromContext
func stateFromContext(ctx context.Context) *State { if ret := ctx.Value(stateKey); ret != nil { return ret.(*State) } return globalState }
go
func stateFromContext(ctx context.Context) *State { if ret := ctx.Value(stateKey); ret != nil { return ret.(*State) } return globalState }
[ "func", "stateFromContext", "(", "ctx", "context", ".", "Context", ")", "*", "State", "{", "if", "ret", ":=", "ctx", ".", "Value", "(", "stateKey", ")", ";", "ret", "!=", "nil", "{", "return", "ret", ".", "(", "*", "State", ")", "\n", "}", "\n\n", "return", "globalState", "\n", "}" ]
// stateFromContext returns a State instance from the given context, if there // is one; otherwise the default State is returned.
[ "stateFromContext", "returns", "a", "State", "instance", "from", "the", "given", "context", "if", "there", "is", "one", ";", "otherwise", "the", "default", "State", "is", "returned", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/context.go#L55-L61
8,820
luci/luci-go
buildbucket/luciexe/client.go
Init
func (c *Client) Init() error { stdin, err := ioutil.ReadAll(os.Stdin) if err != nil { return errors.Annotate(err, "failed to read stdin").Err() } c.InitBuild = &pb.Build{} if err := proto.Unmarshal(stdin, c.InitBuild); err != nil { return errors.Annotate(err, "failed to parse buildbucket.v2.Build from stdin").Err() } if c.Logdog, err = bootstrap.Get(); err != nil { return err } buildTimestamp := c.BuildTimestamp if buildTimestamp.IsZero() { buildTimestamp = time.Now() } c.buildStream, err = c.Logdog.Client.NewStream(streamproto.Flags{ Name: streamproto.StreamNameFlag(BuildStreamName), Type: streamproto.StreamType(logpb.StreamType_DATAGRAM), ContentType: protoutil.BuildMediaType, Timestamp: clockflag.Time(buildTimestamp), }) return err }
go
func (c *Client) Init() error { stdin, err := ioutil.ReadAll(os.Stdin) if err != nil { return errors.Annotate(err, "failed to read stdin").Err() } c.InitBuild = &pb.Build{} if err := proto.Unmarshal(stdin, c.InitBuild); err != nil { return errors.Annotate(err, "failed to parse buildbucket.v2.Build from stdin").Err() } if c.Logdog, err = bootstrap.Get(); err != nil { return err } buildTimestamp := c.BuildTimestamp if buildTimestamp.IsZero() { buildTimestamp = time.Now() } c.buildStream, err = c.Logdog.Client.NewStream(streamproto.Flags{ Name: streamproto.StreamNameFlag(BuildStreamName), Type: streamproto.StreamType(logpb.StreamType_DATAGRAM), ContentType: protoutil.BuildMediaType, Timestamp: clockflag.Time(buildTimestamp), }) return err }
[ "func", "(", "c", "*", "Client", ")", "Init", "(", ")", "error", "{", "stdin", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "os", ".", "Stdin", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "c", ".", "InitBuild", "=", "&", "pb", ".", "Build", "{", "}", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "stdin", ",", "c", ".", "InitBuild", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "if", "c", ".", "Logdog", ",", "err", "=", "bootstrap", ".", "Get", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "buildTimestamp", ":=", "c", ".", "BuildTimestamp", "\n", "if", "buildTimestamp", ".", "IsZero", "(", ")", "{", "buildTimestamp", "=", "time", ".", "Now", "(", ")", "\n", "}", "\n\n", "c", ".", "buildStream", ",", "err", "=", "c", ".", "Logdog", ".", "Client", ".", "NewStream", "(", "streamproto", ".", "Flags", "{", "Name", ":", "streamproto", ".", "StreamNameFlag", "(", "BuildStreamName", ")", ",", "Type", ":", "streamproto", ".", "StreamType", "(", "logpb", ".", "StreamType_DATAGRAM", ")", ",", "ContentType", ":", "protoutil", ".", "BuildMediaType", ",", "Timestamp", ":", "clockflag", ".", "Time", "(", "buildTimestamp", ")", ",", "}", ")", "\n", "return", "err", "\n", "}" ]
// Init initializes the client. Populates c.InitBuild and c.ButlerClient.
[ "Init", "initializes", "the", "client", ".", "Populates", "c", ".", "InitBuild", "and", "c", ".", "ButlerClient", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/luciexe/client.go#L77-L104
8,821
luci/luci-go
buildbucket/luciexe/client.go
WriteBuild
func (c *Client) WriteBuild(build *pb.Build) error { c.assertInitialized() buf, err := proto.Marshal(build) if err != nil { return err } return c.buildStream.WriteDatagram(buf) }
go
func (c *Client) WriteBuild(build *pb.Build) error { c.assertInitialized() buf, err := proto.Marshal(build) if err != nil { return err } return c.buildStream.WriteDatagram(buf) }
[ "func", "(", "c", "*", "Client", ")", "WriteBuild", "(", "build", "*", "pb", ".", "Build", ")", "error", "{", "c", ".", "assertInitialized", "(", ")", "\n", "buf", ",", "err", ":=", "proto", ".", "Marshal", "(", "build", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "c", ".", "buildStream", ".", "WriteDatagram", "(", "buf", ")", "\n", "}" ]
// WriteBuild sends a new version of Build message to the other side // of the protocol, that is the host of the LUCI executable.
[ "WriteBuild", "sends", "a", "new", "version", "of", "Build", "message", "to", "the", "other", "side", "of", "the", "protocol", "that", "is", "the", "host", "of", "the", "LUCI", "executable", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/luciexe/client.go#L108-L115
8,822
luci/luci-go
buildbucket/luciexe/client.go
assertInitialized
func (c *Client) assertInitialized() { if c.buildStream == nil { panic(errors.Reason("client is not initialized").Err()) } }
go
func (c *Client) assertInitialized() { if c.buildStream == nil { panic(errors.Reason("client is not initialized").Err()) } }
[ "func", "(", "c", "*", "Client", ")", "assertInitialized", "(", ")", "{", "if", "c", ".", "buildStream", "==", "nil", "{", "panic", "(", "errors", ".", "Reason", "(", "\"", "\"", ")", ".", "Err", "(", ")", ")", "\n", "}", "\n", "}" ]
// assertInitialized panics if c is not initialized.
[ "assertInitialized", "panics", "if", "c", "is", "not", "initialized", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/luciexe/client.go#L118-L122
8,823
luci/luci-go
cipd/common/common.go
String
func (pin Pin) String() string { return fmt.Sprintf("%s:%s", pin.PackageName, pin.InstanceID) }
go
func (pin Pin) String() string { return fmt.Sprintf("%s:%s", pin.PackageName, pin.InstanceID) }
[ "func", "(", "pin", "Pin", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "pin", ".", "PackageName", ",", "pin", ".", "InstanceID", ")", "\n", "}" ]
// String converts pin to a human readable string.
[ "String", "converts", "pin", "to", "a", "human", "readable", "string", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/common/common.go#L66-L68
8,824
luci/luci-go
cipd/common/common.go
validatePathishString
func validatePathishString(p, title string) error { if !packageNameRe.MatchString(p) { return fmt.Errorf("invalid %s: %q", title, p) } for _, chunk := range strings.Split(p, "/") { if strings.Count(chunk, ".") == len(chunk) { return fmt.Errorf("invalid %s (dots-only names are forbidden): %q", title, p) } } return nil }
go
func validatePathishString(p, title string) error { if !packageNameRe.MatchString(p) { return fmt.Errorf("invalid %s: %q", title, p) } for _, chunk := range strings.Split(p, "/") { if strings.Count(chunk, ".") == len(chunk) { return fmt.Errorf("invalid %s (dots-only names are forbidden): %q", title, p) } } return nil }
[ "func", "validatePathishString", "(", "p", ",", "title", "string", ")", "error", "{", "if", "!", "packageNameRe", ".", "MatchString", "(", "p", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "title", ",", "p", ")", "\n", "}", "\n", "for", "_", ",", "chunk", ":=", "range", "strings", ".", "Split", "(", "p", ",", "\"", "\"", ")", "{", "if", "strings", ".", "Count", "(", "chunk", ",", "\"", "\"", ")", "==", "len", "(", "chunk", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "title", ",", "p", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// validatePathishString is common implementation of ValidatePackageName and // ValidatePackagePrefix.
[ "validatePathishString", "is", "common", "implementation", "of", "ValidatePackageName", "and", "ValidatePackagePrefix", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/common/common.go#L92-L102
8,825
luci/luci-go
cipd/common/common.go
ValidatePin
func ValidatePin(pin Pin, v HashAlgoValidation) error { if err := ValidatePackageName(pin.PackageName); err != nil { return err } return ValidateInstanceID(pin.InstanceID, v) }
go
func ValidatePin(pin Pin, v HashAlgoValidation) error { if err := ValidatePackageName(pin.PackageName); err != nil { return err } return ValidateInstanceID(pin.InstanceID, v) }
[ "func", "ValidatePin", "(", "pin", "Pin", ",", "v", "HashAlgoValidation", ")", "error", "{", "if", "err", ":=", "ValidatePackageName", "(", "pin", ".", "PackageName", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "ValidateInstanceID", "(", "pin", ".", "InstanceID", ",", "v", ")", "\n", "}" ]
// ValidatePin returns error if package name or instance id are invalid.
[ "ValidatePin", "returns", "error", "if", "package", "name", "or", "instance", "id", "are", "invalid", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/common/common.go#L105-L110
8,826
luci/luci-go
cipd/common/common.go
ValidatePackageRef
func ValidatePackageRef(r string) error { if ValidateInstanceID(r, AnyHash) == nil { return fmt.Errorf("invalid ref name (looks like an instance ID): %q", r) } if !packageRefRe.MatchString(r) { return fmt.Errorf("invalid ref name: %q", r) } return nil }
go
func ValidatePackageRef(r string) error { if ValidateInstanceID(r, AnyHash) == nil { return fmt.Errorf("invalid ref name (looks like an instance ID): %q", r) } if !packageRefRe.MatchString(r) { return fmt.Errorf("invalid ref name: %q", r) } return nil }
[ "func", "ValidatePackageRef", "(", "r", "string", ")", "error", "{", "if", "ValidateInstanceID", "(", "r", ",", "AnyHash", ")", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "r", ")", "\n", "}", "\n", "if", "!", "packageRefRe", ".", "MatchString", "(", "r", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "r", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ValidatePackageRef returns error if a string doesn't look like a valid ref.
[ "ValidatePackageRef", "returns", "error", "if", "a", "string", "doesn", "t", "look", "like", "a", "valid", "ref", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/common/common.go#L113-L121
8,827
luci/luci-go
cipd/common/common.go
ValidateSubdir
func ValidateSubdir(subdir string) error { if subdir == "" { // empty is fine return nil } if strings.Contains(subdir, "\\") { return fmt.Errorf(`bad subdir: backslashes not allowed (use "/"): %q`, subdir) } if strings.Contains(subdir, ":") { return fmt.Errorf(`bad subdir: colons are not allowed: %q`, subdir) } if cleaned := path.Clean(subdir); cleaned != subdir { return fmt.Errorf("bad subdir: %q (should be %q)", subdir, cleaned) } if strings.HasPrefix(subdir, "./") || strings.HasPrefix(subdir, "../") || subdir == "." { return fmt.Errorf(`bad subdir: invalid ".": %q`, subdir) } if strings.HasPrefix(subdir, "/") { return fmt.Errorf("bad subdir: absolute paths not allowed: %q", subdir) } return nil }
go
func ValidateSubdir(subdir string) error { if subdir == "" { // empty is fine return nil } if strings.Contains(subdir, "\\") { return fmt.Errorf(`bad subdir: backslashes not allowed (use "/"): %q`, subdir) } if strings.Contains(subdir, ":") { return fmt.Errorf(`bad subdir: colons are not allowed: %q`, subdir) } if cleaned := path.Clean(subdir); cleaned != subdir { return fmt.Errorf("bad subdir: %q (should be %q)", subdir, cleaned) } if strings.HasPrefix(subdir, "./") || strings.HasPrefix(subdir, "../") || subdir == "." { return fmt.Errorf(`bad subdir: invalid ".": %q`, subdir) } if strings.HasPrefix(subdir, "/") { return fmt.Errorf("bad subdir: absolute paths not allowed: %q", subdir) } return nil }
[ "func", "ValidateSubdir", "(", "subdir", "string", ")", "error", "{", "if", "subdir", "==", "\"", "\"", "{", "// empty is fine", "return", "nil", "\n", "}", "\n", "if", "strings", ".", "Contains", "(", "subdir", ",", "\"", "\\\\", "\"", ")", "{", "return", "fmt", ".", "Errorf", "(", "`bad subdir: backslashes not allowed (use \"/\"): %q`", ",", "subdir", ")", "\n", "}", "\n", "if", "strings", ".", "Contains", "(", "subdir", ",", "\"", "\"", ")", "{", "return", "fmt", ".", "Errorf", "(", "`bad subdir: colons are not allowed: %q`", ",", "subdir", ")", "\n", "}", "\n", "if", "cleaned", ":=", "path", ".", "Clean", "(", "subdir", ")", ";", "cleaned", "!=", "subdir", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "subdir", ",", "cleaned", ")", "\n", "}", "\n", "if", "strings", ".", "HasPrefix", "(", "subdir", ",", "\"", "\"", ")", "||", "strings", ".", "HasPrefix", "(", "subdir", ",", "\"", "\"", ")", "||", "subdir", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "`bad subdir: invalid \".\": %q`", ",", "subdir", ")", "\n", "}", "\n", "if", "strings", ".", "HasPrefix", "(", "subdir", ",", "\"", "\"", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "subdir", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ValidateSubdir returns an error if the string can't be used as an ensure-file // subdir.
[ "ValidateSubdir", "returns", "an", "error", "if", "the", "string", "can", "t", "be", "used", "as", "an", "ensure", "-", "file", "subdir", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/common/common.go#L184-L204
8,828
luci/luci-go
cipd/common/common.go
Validate
func (s PinSlice) Validate(v HashAlgoValidation) error { dedup := stringset.New(len(s)) for _, p := range s { if err := ValidatePin(p, v); err != nil { return err } if !dedup.Add(p.PackageName) { return fmt.Errorf("duplicate package %q", p.PackageName) } } return nil }
go
func (s PinSlice) Validate(v HashAlgoValidation) error { dedup := stringset.New(len(s)) for _, p := range s { if err := ValidatePin(p, v); err != nil { return err } if !dedup.Add(p.PackageName) { return fmt.Errorf("duplicate package %q", p.PackageName) } } return nil }
[ "func", "(", "s", "PinSlice", ")", "Validate", "(", "v", "HashAlgoValidation", ")", "error", "{", "dedup", ":=", "stringset", ".", "New", "(", "len", "(", "s", ")", ")", "\n", "for", "_", ",", "p", ":=", "range", "s", "{", "if", "err", ":=", "ValidatePin", "(", "p", ",", "v", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "!", "dedup", ".", "Add", "(", "p", ".", "PackageName", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "p", ".", "PackageName", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate ensures that this PinSlice contains no duplicate packages or invalid // pins.
[ "Validate", "ensures", "that", "this", "PinSlice", "contains", "no", "duplicate", "packages", "or", "invalid", "pins", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/common/common.go#L275-L286
8,829
luci/luci-go
cipd/common/common.go
ToMap
func (s PinSlice) ToMap() PinMap { ret := make(PinMap, len(s)) for _, p := range s { ret[p.PackageName] = p.InstanceID } return ret }
go
func (s PinSlice) ToMap() PinMap { ret := make(PinMap, len(s)) for _, p := range s { ret[p.PackageName] = p.InstanceID } return ret }
[ "func", "(", "s", "PinSlice", ")", "ToMap", "(", ")", "PinMap", "{", "ret", ":=", "make", "(", "PinMap", ",", "len", "(", "s", ")", ")", "\n", "for", "_", ",", "p", ":=", "range", "s", "{", "ret", "[", "p", ".", "PackageName", "]", "=", "p", ".", "InstanceID", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// ToMap converts the PinSlice to a PinMap.
[ "ToMap", "converts", "the", "PinSlice", "to", "a", "PinMap", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/common/common.go#L289-L295
8,830
luci/luci-go
cipd/common/common.go
ToSlice
func (m PinMap) ToSlice() PinSlice { s := make(PinSlice, 0, len(m)) pkgs := make(sort.StringSlice, 0, len(m)) for k := range m { pkgs = append(pkgs, k) } pkgs.Sort() for _, pkg := range pkgs { s = append(s, Pin{pkg, m[pkg]}) } return s }
go
func (m PinMap) ToSlice() PinSlice { s := make(PinSlice, 0, len(m)) pkgs := make(sort.StringSlice, 0, len(m)) for k := range m { pkgs = append(pkgs, k) } pkgs.Sort() for _, pkg := range pkgs { s = append(s, Pin{pkg, m[pkg]}) } return s }
[ "func", "(", "m", "PinMap", ")", "ToSlice", "(", ")", "PinSlice", "{", "s", ":=", "make", "(", "PinSlice", ",", "0", ",", "len", "(", "m", ")", ")", "\n", "pkgs", ":=", "make", "(", "sort", ".", "StringSlice", ",", "0", ",", "len", "(", "m", ")", ")", "\n", "for", "k", ":=", "range", "m", "{", "pkgs", "=", "append", "(", "pkgs", ",", "k", ")", "\n", "}", "\n", "pkgs", ".", "Sort", "(", ")", "\n", "for", "_", ",", "pkg", ":=", "range", "pkgs", "{", "s", "=", "append", "(", "s", ",", "Pin", "{", "pkg", ",", "m", "[", "pkg", "]", "}", ")", "\n", "}", "\n", "return", "s", "\n", "}" ]
// ToSlice converts the PinMap to a PinSlice.
[ "ToSlice", "converts", "the", "PinMap", "to", "a", "PinSlice", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/common/common.go#L301-L312
8,831
luci/luci-go
cipd/common/common.go
Validate
func (p PinSliceBySubdir) Validate(v HashAlgoValidation) error { for subdir, pkgs := range p { if err := ValidateSubdir(subdir); err != nil { return err } if err := pkgs.Validate(v); err != nil { return fmt.Errorf("subdir %q: %s", subdir, err) } } return nil }
go
func (p PinSliceBySubdir) Validate(v HashAlgoValidation) error { for subdir, pkgs := range p { if err := ValidateSubdir(subdir); err != nil { return err } if err := pkgs.Validate(v); err != nil { return fmt.Errorf("subdir %q: %s", subdir, err) } } return nil }
[ "func", "(", "p", "PinSliceBySubdir", ")", "Validate", "(", "v", "HashAlgoValidation", ")", "error", "{", "for", "subdir", ",", "pkgs", ":=", "range", "p", "{", "if", "err", ":=", "ValidateSubdir", "(", "subdir", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "pkgs", ".", "Validate", "(", "v", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "subdir", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate ensures that this doesn't contain any invalid // subdirs, duplicate packages within the same subdir, or invalid pins.
[ "Validate", "ensures", "that", "this", "doesn", "t", "contain", "any", "invalid", "subdirs", "duplicate", "packages", "within", "the", "same", "subdir", "or", "invalid", "pins", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/common/common.go#L319-L329
8,832
luci/luci-go
cipd/common/common.go
ToMap
func (p PinSliceBySubdir) ToMap() PinMapBySubdir { ret := make(PinMapBySubdir, len(p)) for subdir, pkgs := range p { ret[subdir] = pkgs.ToMap() } return ret }
go
func (p PinSliceBySubdir) ToMap() PinMapBySubdir { ret := make(PinMapBySubdir, len(p)) for subdir, pkgs := range p { ret[subdir] = pkgs.ToMap() } return ret }
[ "func", "(", "p", "PinSliceBySubdir", ")", "ToMap", "(", ")", "PinMapBySubdir", "{", "ret", ":=", "make", "(", "PinMapBySubdir", ",", "len", "(", "p", ")", ")", "\n", "for", "subdir", ",", "pkgs", ":=", "range", "p", "{", "ret", "[", "subdir", "]", "=", "pkgs", ".", "ToMap", "(", ")", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// ToMap converts this to a PinMapBySubdir
[ "ToMap", "converts", "this", "to", "a", "PinMapBySubdir" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/common/common.go#L332-L338
8,833
luci/luci-go
client/archiver/checker.go
Count
func (cb *CountBytes) Count() int { cb.mu.Lock() defer cb.mu.Unlock() return cb.count }
go
func (cb *CountBytes) Count() int { cb.mu.Lock() defer cb.mu.Unlock() return cb.count }
[ "func", "(", "cb", "*", "CountBytes", ")", "Count", "(", ")", "int", "{", "cb", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "cb", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "cb", ".", "count", "\n", "}" ]
// Count returns the file count.
[ "Count", "returns", "the", "file", "count", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/archiver/checker.go#L95-L99
8,834
luci/luci-go
client/archiver/checker.go
Bytes
func (cb *CountBytes) Bytes() int64 { cb.mu.Lock() defer cb.mu.Unlock() return cb.bytes }
go
func (cb *CountBytes) Bytes() int64 { cb.mu.Lock() defer cb.mu.Unlock() return cb.bytes }
[ "func", "(", "cb", "*", "CountBytes", ")", "Bytes", "(", ")", "int64", "{", "cb", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "cb", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "cb", ".", "bytes", "\n", "}" ]
// Bytes returns total byte count.
[ "Bytes", "returns", "total", "byte", "count", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/archiver/checker.go#L102-L106
8,835
luci/luci-go
client/archiver/checker.go
NewChecker
func NewChecker(ctx context.Context, client *isolatedclient.Client, maxConcurrent int) *BundlingChecker { return newChecker(ctx, client, maxConcurrent) }
go
func NewChecker(ctx context.Context, client *isolatedclient.Client, maxConcurrent int) *BundlingChecker { return newChecker(ctx, client, maxConcurrent) }
[ "func", "NewChecker", "(", "ctx", "context", ".", "Context", ",", "client", "*", "isolatedclient", ".", "Client", ",", "maxConcurrent", "int", ")", "*", "BundlingChecker", "{", "return", "newChecker", "(", "ctx", ",", "client", ",", "maxConcurrent", ")", "\n", "}" ]
// NewChecker creates a new Checker with the given isolated client. // maxConcurrent controls maximum number of check requests to be in-flight at once. // The provided context is used to make all requests to the isolate server.
[ "NewChecker", "creates", "a", "new", "Checker", "with", "the", "given", "isolated", "client", ".", "maxConcurrent", "controls", "maximum", "number", "of", "check", "requests", "to", "be", "in", "-", "flight", "at", "once", ".", "The", "provided", "context", "is", "used", "to", "make", "all", "requests", "to", "the", "isolate", "server", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/archiver/checker.go#L111-L113
8,836
luci/luci-go
client/archiver/checker.go
PresumeExists
func (c *BundlingChecker) PresumeExists(item *Item) { c.mu.Lock() defer c.mu.Unlock() c.existingDigests[string(item.Digest)] = struct{}{} }
go
func (c *BundlingChecker) PresumeExists(item *Item) { c.mu.Lock() defer c.mu.Unlock() c.existingDigests[string(item.Digest)] = struct{}{} }
[ "func", "(", "c", "*", "BundlingChecker", ")", "PresumeExists", "(", "item", "*", "Item", ")", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "c", ".", "existingDigests", "[", "string", "(", "item", ".", "Digest", ")", "]", "=", "struct", "{", "}", "{", "}", "\n", "}" ]
// PresumeExists causes the Checker to report that item exists on the server.
[ "PresumeExists", "causes", "the", "Checker", "to", "report", "that", "item", "exists", "on", "the", "server", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/archiver/checker.go#L151-L155
8,837
luci/luci-go
client/archiver/checker.go
Close
func (c *BundlingChecker) Close() error { c.bundler.Flush() c.wg.Wait() close(c.waitc) // Sanity check that we don't do any more checks. // After Close has returned, we know there are no outstanding running // checks. return c.err }
go
func (c *BundlingChecker) Close() error { c.bundler.Flush() c.wg.Wait() close(c.waitc) // Sanity check that we don't do any more checks. // After Close has returned, we know there are no outstanding running // checks. return c.err }
[ "func", "(", "c", "*", "BundlingChecker", ")", "Close", "(", ")", "error", "{", "c", ".", "bundler", ".", "Flush", "(", ")", "\n", "c", ".", "wg", ".", "Wait", "(", ")", "\n", "close", "(", "c", ".", "waitc", ")", "// Sanity check that we don't do any more checks.", "\n\n", "// After Close has returned, we know there are no outstanding running", "// checks.", "return", "c", ".", "err", "\n", "}" ]
// Close shuts down the checker, blocking until all pending items have been // checked with the server. Close returns the first error encountered during // the checking process, if any. // After Close has returned, Checker is guaranteed to no longer invoke any // previously-provided callback.
[ "Close", "shuts", "down", "the", "checker", "blocking", "until", "all", "pending", "items", "have", "been", "checked", "with", "the", "server", ".", "Close", "returns", "the", "first", "error", "encountered", "during", "the", "checking", "process", "if", "any", ".", "After", "Close", "has", "returned", "Checker", "is", "guaranteed", "to", "no", "longer", "invoke", "any", "previously", "-", "provided", "callback", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/archiver/checker.go#L174-L182
8,838
luci/luci-go
client/archiver/checker.go
check
func (c *BundlingChecker) check(items []checkerItem) { c.waitc <- struct{}{} c.wg.Add(1) go func() { c.doCheck(items) c.wg.Done() <-c.waitc }() }
go
func (c *BundlingChecker) check(items []checkerItem) { c.waitc <- struct{}{} c.wg.Add(1) go func() { c.doCheck(items) c.wg.Done() <-c.waitc }() }
[ "func", "(", "c", "*", "BundlingChecker", ")", "check", "(", "items", "[", "]", "checkerItem", ")", "{", "c", ".", "waitc", "<-", "struct", "{", "}", "{", "}", "\n", "c", ".", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "c", ".", "doCheck", "(", "items", ")", "\n", "c", ".", "wg", ".", "Done", "(", ")", "\n", "<-", "c", ".", "waitc", "\n", "}", "(", ")", "\n\n", "}" ]
// check is invoked from the bundler's handler. // It launches a check in a new goroutine. Any error is communicated via c.err
[ "check", "is", "invoked", "from", "the", "bundler", "s", "handler", ".", "It", "launches", "a", "check", "in", "a", "new", "goroutine", ".", "Any", "error", "is", "communicated", "via", "c", ".", "err" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/archiver/checker.go#L186-L195
8,839
luci/luci-go
client/archiver/checker.go
contains
func (c *BundlingChecker) contains(items []checkerItem) ([]*isolatedclient.PushState, error) { var digests []*service.HandlersEndpointsV1Digest for _, item := range items { digests = append(digests, &service.HandlersEndpointsV1Digest{ Digest: string(item.item.Digest), Size: item.item.Size, IsIsolated: item.isolated, }) } pushStates, err := c.svc.Contains(c.ctx, digests) if err != nil { return nil, fmt.Errorf("isolate Contains call failed: %v", err) } return pushStates, nil }
go
func (c *BundlingChecker) contains(items []checkerItem) ([]*isolatedclient.PushState, error) { var digests []*service.HandlersEndpointsV1Digest for _, item := range items { digests = append(digests, &service.HandlersEndpointsV1Digest{ Digest: string(item.item.Digest), Size: item.item.Size, IsIsolated: item.isolated, }) } pushStates, err := c.svc.Contains(c.ctx, digests) if err != nil { return nil, fmt.Errorf("isolate Contains call failed: %v", err) } return pushStates, nil }
[ "func", "(", "c", "*", "BundlingChecker", ")", "contains", "(", "items", "[", "]", "checkerItem", ")", "(", "[", "]", "*", "isolatedclient", ".", "PushState", ",", "error", ")", "{", "var", "digests", "[", "]", "*", "service", ".", "HandlersEndpointsV1Digest", "\n", "for", "_", ",", "item", ":=", "range", "items", "{", "digests", "=", "append", "(", "digests", ",", "&", "service", ".", "HandlersEndpointsV1Digest", "{", "Digest", ":", "string", "(", "item", ".", "item", ".", "Digest", ")", ",", "Size", ":", "item", ".", "item", ".", "Size", ",", "IsIsolated", ":", "item", ".", "isolated", ",", "}", ")", "\n", "}", "\n", "pushStates", ",", "err", ":=", "c", ".", "svc", ".", "Contains", "(", "c", ".", "ctx", ",", "digests", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "pushStates", ",", "nil", "\n", "}" ]
// contains calls isolateService.Contains on the supplied checkerItems.
[ "contains", "calls", "isolateService", ".", "Contains", "on", "the", "supplied", "checkerItems", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/archiver/checker.go#L230-L244
8,840
luci/luci-go
buildbucket/luciexe/logdog_windows.go
newLogDogStreamServerForPlatform
func newLogDogStreamServerForPlatform(ctx context.Context, workDir string) (streamserver.StreamServer, error) { // Windows, use named pipe. return streamserver.NewNamedPipeServer(ctx, fmt.Sprintf("LUCILogDogRunBuild_%d", os.Getpid())) }
go
func newLogDogStreamServerForPlatform(ctx context.Context, workDir string) (streamserver.StreamServer, error) { // Windows, use named pipe. return streamserver.NewNamedPipeServer(ctx, fmt.Sprintf("LUCILogDogRunBuild_%d", os.Getpid())) }
[ "func", "newLogDogStreamServerForPlatform", "(", "ctx", "context", ".", "Context", ",", "workDir", "string", ")", "(", "streamserver", ".", "StreamServer", ",", "error", ")", "{", "// Windows, use named pipe.", "return", "streamserver", ".", "NewNamedPipeServer", "(", "ctx", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "os", ".", "Getpid", "(", ")", ")", ")", "\n", "}" ]
// newLogDogStreamServerForPlatform creates a StreamServer instance usable on // Windows.
[ "newLogDogStreamServerForPlatform", "creates", "a", "StreamServer", "instance", "usable", "on", "Windows", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/luciexe/logdog_windows.go#L27-L30
8,841
luci/luci-go
lucicfg/errors.go
Backtrace
func (e *Error) Backtrace() string { if e.Stack == nil { return e.Msg } return e.Stack.String() + "Error: " + e.Msg }
go
func (e *Error) Backtrace() string { if e.Stack == nil { return e.Msg } return e.Stack.String() + "Error: " + e.Msg }
[ "func", "(", "e", "*", "Error", ")", "Backtrace", "(", ")", "string", "{", "if", "e", ".", "Stack", "==", "nil", "{", "return", "e", ".", "Msg", "\n", "}", "\n", "return", "e", ".", "Stack", ".", "String", "(", ")", "+", "\"", "\"", "+", "e", ".", "Msg", "\n", "}" ]
// Backtrace is part of BacktracableError interface.
[ "Backtrace", "is", "part", "of", "BacktracableError", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/errors.go#L58-L63
8,842
luci/luci-go
luci_notify/notify/notify.go
createEmailTasks
func createEmailTasks(c context.Context, recipients []EmailNotify, input *EmailTemplateInput) ([]*tq.Task, error) { // Get templates. bundle, err := getBundle(c, input.Build.Builder.Project) if err != nil { return nil, errors.Annotate(err, "failed to get a bundle of email templates").Err() } // Generate emails. // An EmailTask with subject and body per template name. // They will be used as templates for actual tasks. taskTemplates := map[string]*internal.EmailTask{} for _, r := range recipients { name := r.Template if name == "" { name = defaultTemplate.Name } if _, ok := taskTemplates[name]; ok { continue } subject, body := bundle.GenerateEmail(name, input) // Note: this buffer should not be reused. buf := &bytes.Buffer{} gz := gzip.NewWriter(buf) io.WriteString(gz, body) if err := gz.Close(); err != nil { panic("failed to gzip HTML body in memory") } taskTemplates[name] = &internal.EmailTask{ Subject: subject, BodyGzip: buf.Bytes(), } } // Create a task per recipient. // Do not bundle multiple recipients into one task because we don't use BCC. tasks := make([]*tq.Task, 0, len(recipients)) seen := stringset.New(len(recipients)) for _, r := range recipients { name := r.Template if name == "" { name = defaultTemplate.Name } emailKey := fmt.Sprintf("%d-%s-%s", input.Build.Id, name, r.Email) if seen.Has(emailKey) { continue } seen.Add(emailKey) task := *taskTemplates[name] // copy task.Recipients = []string{r.Email} tasks = append(tasks, &tq.Task{ DeduplicationKey: emailKey, Payload: &task, }) } return tasks, nil }
go
func createEmailTasks(c context.Context, recipients []EmailNotify, input *EmailTemplateInput) ([]*tq.Task, error) { // Get templates. bundle, err := getBundle(c, input.Build.Builder.Project) if err != nil { return nil, errors.Annotate(err, "failed to get a bundle of email templates").Err() } // Generate emails. // An EmailTask with subject and body per template name. // They will be used as templates for actual tasks. taskTemplates := map[string]*internal.EmailTask{} for _, r := range recipients { name := r.Template if name == "" { name = defaultTemplate.Name } if _, ok := taskTemplates[name]; ok { continue } subject, body := bundle.GenerateEmail(name, input) // Note: this buffer should not be reused. buf := &bytes.Buffer{} gz := gzip.NewWriter(buf) io.WriteString(gz, body) if err := gz.Close(); err != nil { panic("failed to gzip HTML body in memory") } taskTemplates[name] = &internal.EmailTask{ Subject: subject, BodyGzip: buf.Bytes(), } } // Create a task per recipient. // Do not bundle multiple recipients into one task because we don't use BCC. tasks := make([]*tq.Task, 0, len(recipients)) seen := stringset.New(len(recipients)) for _, r := range recipients { name := r.Template if name == "" { name = defaultTemplate.Name } emailKey := fmt.Sprintf("%d-%s-%s", input.Build.Id, name, r.Email) if seen.Has(emailKey) { continue } seen.Add(emailKey) task := *taskTemplates[name] // copy task.Recipients = []string{r.Email} tasks = append(tasks, &tq.Task{ DeduplicationKey: emailKey, Payload: &task, }) } return tasks, nil }
[ "func", "createEmailTasks", "(", "c", "context", ".", "Context", ",", "recipients", "[", "]", "EmailNotify", ",", "input", "*", "EmailTemplateInput", ")", "(", "[", "]", "*", "tq", ".", "Task", ",", "error", ")", "{", "// Get templates.", "bundle", ",", "err", ":=", "getBundle", "(", "c", ",", "input", ".", "Build", ".", "Builder", ".", "Project", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "// Generate emails.", "// An EmailTask with subject and body per template name.", "// They will be used as templates for actual tasks.", "taskTemplates", ":=", "map", "[", "string", "]", "*", "internal", ".", "EmailTask", "{", "}", "\n", "for", "_", ",", "r", ":=", "range", "recipients", "{", "name", ":=", "r", ".", "Template", "\n", "if", "name", "==", "\"", "\"", "{", "name", "=", "defaultTemplate", ".", "Name", "\n", "}", "\n\n", "if", "_", ",", "ok", ":=", "taskTemplates", "[", "name", "]", ";", "ok", "{", "continue", "\n", "}", "\n\n", "subject", ",", "body", ":=", "bundle", ".", "GenerateEmail", "(", "name", ",", "input", ")", "\n\n", "// Note: this buffer should not be reused.", "buf", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "gz", ":=", "gzip", ".", "NewWriter", "(", "buf", ")", "\n", "io", ".", "WriteString", "(", "gz", ",", "body", ")", "\n", "if", "err", ":=", "gz", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "taskTemplates", "[", "name", "]", "=", "&", "internal", ".", "EmailTask", "{", "Subject", ":", "subject", ",", "BodyGzip", ":", "buf", ".", "Bytes", "(", ")", ",", "}", "\n", "}", "\n\n", "// Create a task per recipient.", "// Do not bundle multiple recipients into one task because we don't use BCC.", "tasks", ":=", "make", "(", "[", "]", "*", "tq", ".", "Task", ",", "0", ",", "len", "(", "recipients", ")", ")", "\n", "seen", ":=", "stringset", ".", "New", "(", "len", "(", "recipients", ")", ")", "\n", "for", "_", ",", "r", ":=", "range", "recipients", "{", "name", ":=", "r", ".", "Template", "\n", "if", "name", "==", "\"", "\"", "{", "name", "=", "defaultTemplate", ".", "Name", "\n", "}", "\n\n", "emailKey", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "input", ".", "Build", ".", "Id", ",", "name", ",", "r", ".", "Email", ")", "\n", "if", "seen", ".", "Has", "(", "emailKey", ")", "{", "continue", "\n", "}", "\n", "seen", ".", "Add", "(", "emailKey", ")", "\n\n", "task", ":=", "*", "taskTemplates", "[", "name", "]", "// copy", "\n", "task", ".", "Recipients", "=", "[", "]", "string", "{", "r", ".", "Email", "}", "\n", "tasks", "=", "append", "(", "tasks", ",", "&", "tq", ".", "Task", "{", "DeduplicationKey", ":", "emailKey", ",", "Payload", ":", "&", "task", ",", "}", ")", "\n", "}", "\n", "return", "tasks", ",", "nil", "\n", "}" ]
// createEmailTasks constructs EmailTasks to be dispatched onto the task queue.
[ "createEmailTasks", "constructs", "EmailTasks", "to", "be", "dispatched", "onto", "the", "task", "queue", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/notify/notify.go#L43-L103
8,843
luci/luci-go
luci_notify/notify/notify.go
isRecipientAllowed
func isRecipientAllowed(c context.Context, recipient string, build *buildbucketpb.Build) bool { // TODO(mknyszek): Do a real ACL check here. if strings.HasSuffix(recipient, "@google.com") || strings.HasSuffix(recipient, "@chromium.org") { return true } logging.Warningf(c, "Address %q is not allowed to be notified of build %d", recipient, build.Id) return false }
go
func isRecipientAllowed(c context.Context, recipient string, build *buildbucketpb.Build) bool { // TODO(mknyszek): Do a real ACL check here. if strings.HasSuffix(recipient, "@google.com") || strings.HasSuffix(recipient, "@chromium.org") { return true } logging.Warningf(c, "Address %q is not allowed to be notified of build %d", recipient, build.Id) return false }
[ "func", "isRecipientAllowed", "(", "c", "context", ".", "Context", ",", "recipient", "string", ",", "build", "*", "buildbucketpb", ".", "Build", ")", "bool", "{", "// TODO(mknyszek): Do a real ACL check here.", "if", "strings", ".", "HasSuffix", "(", "recipient", ",", "\"", "\"", ")", "||", "strings", ".", "HasSuffix", "(", "recipient", ",", "\"", "\"", ")", "{", "return", "true", "\n", "}", "\n", "logging", ".", "Warningf", "(", "c", ",", "\"", "\"", ",", "recipient", ",", "build", ".", "Id", ")", "\n", "return", "false", "\n", "}" ]
// isRecipientAllowed returns true if the given recipient is allowed to be notified about the given build.
[ "isRecipientAllowed", "returns", "true", "if", "the", "given", "recipient", "is", "allowed", "to", "be", "notified", "about", "the", "given", "build", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/notify/notify.go#L106-L113
8,844
luci/luci-go
luci_notify/notify/notify.go
BlamelistRepoWhiteset
func BlamelistRepoWhiteset(notifications notifypb.Notifications) stringset.Set { whiteset := stringset.New(0) for _, notification := range notifications.GetNotifications() { blamelistInfo := notification.GetNotifyBlamelist() for _, repo := range blamelistInfo.GetRepositoryWhitelist() { whiteset.Add(repo) } } return whiteset }
go
func BlamelistRepoWhiteset(notifications notifypb.Notifications) stringset.Set { whiteset := stringset.New(0) for _, notification := range notifications.GetNotifications() { blamelistInfo := notification.GetNotifyBlamelist() for _, repo := range blamelistInfo.GetRepositoryWhitelist() { whiteset.Add(repo) } } return whiteset }
[ "func", "BlamelistRepoWhiteset", "(", "notifications", "notifypb", ".", "Notifications", ")", "stringset", ".", "Set", "{", "whiteset", ":=", "stringset", ".", "New", "(", "0", ")", "\n", "for", "_", ",", "notification", ":=", "range", "notifications", ".", "GetNotifications", "(", ")", "{", "blamelistInfo", ":=", "notification", ".", "GetNotifyBlamelist", "(", ")", "\n", "for", "_", ",", "repo", ":=", "range", "blamelistInfo", ".", "GetRepositoryWhitelist", "(", ")", "{", "whiteset", ".", "Add", "(", "repo", ")", "\n", "}", "\n", "}", "\n", "return", "whiteset", "\n", "}" ]
// BlamelistRepoWhiteset computes the aggregate repository whitelist for all // blamelist notification configurations in a given set of notifications.
[ "BlamelistRepoWhiteset", "computes", "the", "aggregate", "repository", "whitelist", "for", "all", "blamelist", "notification", "configurations", "in", "a", "given", "set", "of", "notifications", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/notify/notify.go#L117-L126
8,845
luci/luci-go
luci_notify/notify/notify.go
ComputeRecipients
func ComputeRecipients(notifications notifypb.Notifications, inputBlame []*gitpb.Commit, outputBlame Logs) []EmailNotify { recipients := make([]EmailNotify, 0) for _, notification := range notifications.GetNotifications() { // Aggregate the static list of recipients from the Notifications. for _, recipient := range notification.GetEmail().GetRecipients() { recipients = append(recipients, EmailNotify{ Email: recipient, Template: notification.Template, }) } // Don't bother dealing with anything blamelist related if there's no config for it. if notification.NotifyBlamelist == nil { continue } // If the whitelist is empty, use the static blamelist. whitelist := notification.NotifyBlamelist.GetRepositoryWhitelist() if len(whitelist) == 0 { recipients = append(recipients, commitsBlamelist(inputBlame, notification.Template)...) continue } // If the whitelist is non-empty, use the dynamic blamelist. whiteset := stringset.NewFromSlice(whitelist...) recipients = append(recipients, outputBlame.Filter(whiteset).Blamelist(notification.Template)...) } return recipients }
go
func ComputeRecipients(notifications notifypb.Notifications, inputBlame []*gitpb.Commit, outputBlame Logs) []EmailNotify { recipients := make([]EmailNotify, 0) for _, notification := range notifications.GetNotifications() { // Aggregate the static list of recipients from the Notifications. for _, recipient := range notification.GetEmail().GetRecipients() { recipients = append(recipients, EmailNotify{ Email: recipient, Template: notification.Template, }) } // Don't bother dealing with anything blamelist related if there's no config for it. if notification.NotifyBlamelist == nil { continue } // If the whitelist is empty, use the static blamelist. whitelist := notification.NotifyBlamelist.GetRepositoryWhitelist() if len(whitelist) == 0 { recipients = append(recipients, commitsBlamelist(inputBlame, notification.Template)...) continue } // If the whitelist is non-empty, use the dynamic blamelist. whiteset := stringset.NewFromSlice(whitelist...) recipients = append(recipients, outputBlame.Filter(whiteset).Blamelist(notification.Template)...) } return recipients }
[ "func", "ComputeRecipients", "(", "notifications", "notifypb", ".", "Notifications", ",", "inputBlame", "[", "]", "*", "gitpb", ".", "Commit", ",", "outputBlame", "Logs", ")", "[", "]", "EmailNotify", "{", "recipients", ":=", "make", "(", "[", "]", "EmailNotify", ",", "0", ")", "\n", "for", "_", ",", "notification", ":=", "range", "notifications", ".", "GetNotifications", "(", ")", "{", "// Aggregate the static list of recipients from the Notifications.", "for", "_", ",", "recipient", ":=", "range", "notification", ".", "GetEmail", "(", ")", ".", "GetRecipients", "(", ")", "{", "recipients", "=", "append", "(", "recipients", ",", "EmailNotify", "{", "Email", ":", "recipient", ",", "Template", ":", "notification", ".", "Template", ",", "}", ")", "\n", "}", "\n\n", "// Don't bother dealing with anything blamelist related if there's no config for it.", "if", "notification", ".", "NotifyBlamelist", "==", "nil", "{", "continue", "\n", "}", "\n\n", "// If the whitelist is empty, use the static blamelist.", "whitelist", ":=", "notification", ".", "NotifyBlamelist", ".", "GetRepositoryWhitelist", "(", ")", "\n", "if", "len", "(", "whitelist", ")", "==", "0", "{", "recipients", "=", "append", "(", "recipients", ",", "commitsBlamelist", "(", "inputBlame", ",", "notification", ".", "Template", ")", "...", ")", "\n", "continue", "\n", "}", "\n\n", "// If the whitelist is non-empty, use the dynamic blamelist.", "whiteset", ":=", "stringset", ".", "NewFromSlice", "(", "whitelist", "...", ")", "\n", "recipients", "=", "append", "(", "recipients", ",", "outputBlame", ".", "Filter", "(", "whiteset", ")", ".", "Blamelist", "(", "notification", ".", "Template", ")", "...", ")", "\n", "}", "\n", "return", "recipients", "\n", "}" ]
// ComputeRecipients computes the set of recipients given a set of // notifications, and potentially "input" and "output" blamelists. // // An "input" blamelist is computed from the input commit to a build, while an // "output" blamelist is derived from output commits.
[ "ComputeRecipients", "computes", "the", "set", "of", "recipients", "given", "a", "set", "of", "notifications", "and", "potentially", "input", "and", "output", "blamelists", ".", "An", "input", "blamelist", "is", "computed", "from", "the", "input", "commit", "to", "a", "build", "while", "an", "output", "blamelist", "is", "derived", "from", "output", "commits", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/notify/notify.go#L133-L161
8,846
luci/luci-go
luci_notify/notify/notify.go
Notify
func Notify(c context.Context, d *tq.Dispatcher, recipients []EmailNotify, templateParams *EmailTemplateInput) error { c = datastore.WithoutTransaction(c) // Remove unallowed recipients. allRecipients := recipients recipients = recipients[:0] for _, r := range allRecipients { if isRecipientAllowed(c, r.Email, templateParams.Build) { recipients = append(recipients, r) } } if len(recipients) == 0 { logging.Infof(c, "Nobody to notify...") return nil } tasks, err := createEmailTasks(c, recipients, templateParams) if err != nil { return errors.Annotate(err, "failed to create email tasks").Err() } return d.AddTask(c, tasks...) }
go
func Notify(c context.Context, d *tq.Dispatcher, recipients []EmailNotify, templateParams *EmailTemplateInput) error { c = datastore.WithoutTransaction(c) // Remove unallowed recipients. allRecipients := recipients recipients = recipients[:0] for _, r := range allRecipients { if isRecipientAllowed(c, r.Email, templateParams.Build) { recipients = append(recipients, r) } } if len(recipients) == 0 { logging.Infof(c, "Nobody to notify...") return nil } tasks, err := createEmailTasks(c, recipients, templateParams) if err != nil { return errors.Annotate(err, "failed to create email tasks").Err() } return d.AddTask(c, tasks...) }
[ "func", "Notify", "(", "c", "context", ".", "Context", ",", "d", "*", "tq", ".", "Dispatcher", ",", "recipients", "[", "]", "EmailNotify", ",", "templateParams", "*", "EmailTemplateInput", ")", "error", "{", "c", "=", "datastore", ".", "WithoutTransaction", "(", "c", ")", "\n\n", "// Remove unallowed recipients.", "allRecipients", ":=", "recipients", "\n", "recipients", "=", "recipients", "[", ":", "0", "]", "\n", "for", "_", ",", "r", ":=", "range", "allRecipients", "{", "if", "isRecipientAllowed", "(", "c", ",", "r", ".", "Email", ",", "templateParams", ".", "Build", ")", "{", "recipients", "=", "append", "(", "recipients", ",", "r", ")", "\n", "}", "\n", "}", "\n\n", "if", "len", "(", "recipients", ")", "==", "0", "{", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n", "tasks", ",", "err", ":=", "createEmailTasks", "(", "c", ",", "recipients", ",", "templateParams", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "d", ".", "AddTask", "(", "c", ",", "tasks", "...", ")", "\n", "}" ]
// Notify discovers, consolidates and filters recipients from a Builder's notifications, // and 'email_notify' properties, then dispatches notifications if necessary. // Does not dispatch a notification for same email, template and build more than // once. Ignores current transaction in c, if any.
[ "Notify", "discovers", "consolidates", "and", "filters", "recipients", "from", "a", "Builder", "s", "notifications", "and", "email_notify", "properties", "then", "dispatches", "notifications", "if", "necessary", ".", "Does", "not", "dispatch", "a", "notification", "for", "same", "email", "template", "and", "build", "more", "than", "once", ".", "Ignores", "current", "transaction", "in", "c", "if", "any", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/notify/notify.go#L167-L188
8,847
luci/luci-go
luci_notify/notify/notify.go
InitDispatcher
func InitDispatcher(d *tq.Dispatcher) { d.RegisterTask(&internal.EmailTask{}, SendEmail, "email", nil) }
go
func InitDispatcher(d *tq.Dispatcher) { d.RegisterTask(&internal.EmailTask{}, SendEmail, "email", nil) }
[ "func", "InitDispatcher", "(", "d", "*", "tq", ".", "Dispatcher", ")", "{", "d", ".", "RegisterTask", "(", "&", "internal", ".", "EmailTask", "{", "}", ",", "SendEmail", ",", "\"", "\"", ",", "nil", ")", "\n", "}" ]
// InitDispatcher registers the send email task with the given dispatcher.
[ "InitDispatcher", "registers", "the", "send", "email", "task", "with", "the", "given", "dispatcher", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/notify/notify.go#L191-L193
8,848
luci/luci-go
luci_notify/notify/notify.go
SendEmail
func SendEmail(c context.Context, task proto.Message) error { appID := info.AppID(c) sender := fmt.Sprintf("%s <noreply@%s.appspotmail.com>", appID, appID) // TODO(mknyszek): Query Milo for additional build information. emailTask := task.(*internal.EmailTask) body := emailTask.Body if len(emailTask.BodyGzip) > 0 { r, err := gzip.NewReader(bytes.NewReader(emailTask.BodyGzip)) if err != nil { return err } buf, err := ioutil.ReadAll(r) if err != nil { return err } body = string(buf) } return mail.Send(c, &mail.Message{ Sender: sender, To: emailTask.Recipients, Subject: emailTask.Subject, HTMLBody: body, }) }
go
func SendEmail(c context.Context, task proto.Message) error { appID := info.AppID(c) sender := fmt.Sprintf("%s <noreply@%s.appspotmail.com>", appID, appID) // TODO(mknyszek): Query Milo for additional build information. emailTask := task.(*internal.EmailTask) body := emailTask.Body if len(emailTask.BodyGzip) > 0 { r, err := gzip.NewReader(bytes.NewReader(emailTask.BodyGzip)) if err != nil { return err } buf, err := ioutil.ReadAll(r) if err != nil { return err } body = string(buf) } return mail.Send(c, &mail.Message{ Sender: sender, To: emailTask.Recipients, Subject: emailTask.Subject, HTMLBody: body, }) }
[ "func", "SendEmail", "(", "c", "context", ".", "Context", ",", "task", "proto", ".", "Message", ")", "error", "{", "appID", ":=", "info", ".", "AppID", "(", "c", ")", "\n", "sender", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "appID", ",", "appID", ")", "\n\n", "// TODO(mknyszek): Query Milo for additional build information.", "emailTask", ":=", "task", ".", "(", "*", "internal", ".", "EmailTask", ")", "\n\n", "body", ":=", "emailTask", ".", "Body", "\n", "if", "len", "(", "emailTask", ".", "BodyGzip", ")", ">", "0", "{", "r", ",", "err", ":=", "gzip", ".", "NewReader", "(", "bytes", ".", "NewReader", "(", "emailTask", ".", "BodyGzip", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "buf", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "body", "=", "string", "(", "buf", ")", "\n", "}", "\n\n", "return", "mail", ".", "Send", "(", "c", ",", "&", "mail", ".", "Message", "{", "Sender", ":", "sender", ",", "To", ":", "emailTask", ".", "Recipients", ",", "Subject", ":", "emailTask", ".", "Subject", ",", "HTMLBody", ":", "body", ",", "}", ")", "\n", "}" ]
// SendEmail is a push queue handler that attempts to send an email.
[ "SendEmail", "is", "a", "push", "queue", "handler", "that", "attempts", "to", "send", "an", "email", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/notify/notify.go#L196-L222
8,849
luci/luci-go
machine-db/appengine/rpc/kvms.go
ListKVMs
func (*Service) ListKVMs(c context.Context, req *crimson.ListKVMsRequest) (*crimson.ListKVMsResponse, error) { kvms, err := listKVMs(c, req) if err != nil { return nil, err } return &crimson.ListKVMsResponse{ Kvms: kvms, }, nil }
go
func (*Service) ListKVMs(c context.Context, req *crimson.ListKVMsRequest) (*crimson.ListKVMsResponse, error) { kvms, err := listKVMs(c, req) if err != nil { return nil, err } return &crimson.ListKVMsResponse{ Kvms: kvms, }, nil }
[ "func", "(", "*", "Service", ")", "ListKVMs", "(", "c", "context", ".", "Context", ",", "req", "*", "crimson", ".", "ListKVMsRequest", ")", "(", "*", "crimson", ".", "ListKVMsResponse", ",", "error", ")", "{", "kvms", ",", "err", ":=", "listKVMs", "(", "c", ",", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "crimson", ".", "ListKVMsResponse", "{", "Kvms", ":", "kvms", ",", "}", ",", "nil", "\n", "}" ]
// ListKVMs handles a request to retrieve KVMs.
[ "ListKVMs", "handles", "a", "request", "to", "retrieve", "KVMs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/kvms.go#L30-L38
8,850
luci/luci-go
machine-db/appengine/rpc/kvms.go
listKVMs
func listKVMs(c context.Context, req *crimson.ListKVMsRequest) ([]*crimson.KVM, error) { ipv4s, err := parseIPv4s(req.Ipv4S) if err != nil { return nil, err } mac48s, err := parseMAC48s(req.MacAddresses) if err != nil { return nil, err } stmt := squirrel.Select( "h.name", "h.vlan_id", "p.name", "r.name", "d.name", "k.description", "k.mac_address", "i.ipv4", "k.state", ) stmt = stmt.From("kvms k, hostnames h, platforms p, racks r, datacenters d, ips i"). Where("k.hostname_id = h.id"). Where("k.platform_id = p.id"). Where("k.rack_id = r.id"). Where("r.datacenter_id = d.id"). Where("i.hostname_id = h.id") stmt = selectInInt64(stmt, "h.vlan_id", req.Vlans) stmt = selectInString(stmt, "h.name", req.Names) stmt = selectInString(stmt, "p.name", req.Platforms) stmt = selectInString(stmt, "d.name", req.Datacenters) stmt = selectInString(stmt, "r.name", req.Racks) stmt = selectInUint64(stmt, "k.mac_address", mac48s) stmt = selectInInt64(stmt, "i.ipv4", ipv4s) stmt = selectInState(stmt, "k.state", req.States) query, args, err := stmt.ToSql() if err != nil { return nil, errors.Annotate(err, "failed to generate statement").Err() } db := database.Get(c) rows, err := db.QueryContext(c, query, args...) if err != nil { return nil, errors.Annotate(err, "failed to fetch KVMs").Err() } defer rows.Close() var kvms []*crimson.KVM for rows.Next() { k := &crimson.KVM{} var ipv4 common.IPv4 var mac48 common.MAC48 if err = rows.Scan( &k.Name, &k.Vlan, &k.Platform, &k.Rack, &k.Datacenter, &k.Description, &mac48, &ipv4, &k.State, ); err != nil { return nil, errors.Annotate(err, "failed to fetch KVM").Err() } k.MacAddress = mac48.String() k.Ipv4 = ipv4.String() kvms = append(kvms, k) } return kvms, nil }
go
func listKVMs(c context.Context, req *crimson.ListKVMsRequest) ([]*crimson.KVM, error) { ipv4s, err := parseIPv4s(req.Ipv4S) if err != nil { return nil, err } mac48s, err := parseMAC48s(req.MacAddresses) if err != nil { return nil, err } stmt := squirrel.Select( "h.name", "h.vlan_id", "p.name", "r.name", "d.name", "k.description", "k.mac_address", "i.ipv4", "k.state", ) stmt = stmt.From("kvms k, hostnames h, platforms p, racks r, datacenters d, ips i"). Where("k.hostname_id = h.id"). Where("k.platform_id = p.id"). Where("k.rack_id = r.id"). Where("r.datacenter_id = d.id"). Where("i.hostname_id = h.id") stmt = selectInInt64(stmt, "h.vlan_id", req.Vlans) stmt = selectInString(stmt, "h.name", req.Names) stmt = selectInString(stmt, "p.name", req.Platforms) stmt = selectInString(stmt, "d.name", req.Datacenters) stmt = selectInString(stmt, "r.name", req.Racks) stmt = selectInUint64(stmt, "k.mac_address", mac48s) stmt = selectInInt64(stmt, "i.ipv4", ipv4s) stmt = selectInState(stmt, "k.state", req.States) query, args, err := stmt.ToSql() if err != nil { return nil, errors.Annotate(err, "failed to generate statement").Err() } db := database.Get(c) rows, err := db.QueryContext(c, query, args...) if err != nil { return nil, errors.Annotate(err, "failed to fetch KVMs").Err() } defer rows.Close() var kvms []*crimson.KVM for rows.Next() { k := &crimson.KVM{} var ipv4 common.IPv4 var mac48 common.MAC48 if err = rows.Scan( &k.Name, &k.Vlan, &k.Platform, &k.Rack, &k.Datacenter, &k.Description, &mac48, &ipv4, &k.State, ); err != nil { return nil, errors.Annotate(err, "failed to fetch KVM").Err() } k.MacAddress = mac48.String() k.Ipv4 = ipv4.String() kvms = append(kvms, k) } return kvms, nil }
[ "func", "listKVMs", "(", "c", "context", ".", "Context", ",", "req", "*", "crimson", ".", "ListKVMsRequest", ")", "(", "[", "]", "*", "crimson", ".", "KVM", ",", "error", ")", "{", "ipv4s", ",", "err", ":=", "parseIPv4s", "(", "req", ".", "Ipv4S", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "mac48s", ",", "err", ":=", "parseMAC48s", "(", "req", ".", "MacAddresses", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "stmt", ":=", "squirrel", ".", "Select", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", ")", "\n", "stmt", "=", "stmt", ".", "From", "(", "\"", "\"", ")", ".", "Where", "(", "\"", "\"", ")", ".", "Where", "(", "\"", "\"", ")", ".", "Where", "(", "\"", "\"", ")", ".", "Where", "(", "\"", "\"", ")", ".", "Where", "(", "\"", "\"", ")", "\n", "stmt", "=", "selectInInt64", "(", "stmt", ",", "\"", "\"", ",", "req", ".", "Vlans", ")", "\n", "stmt", "=", "selectInString", "(", "stmt", ",", "\"", "\"", ",", "req", ".", "Names", ")", "\n", "stmt", "=", "selectInString", "(", "stmt", ",", "\"", "\"", ",", "req", ".", "Platforms", ")", "\n", "stmt", "=", "selectInString", "(", "stmt", ",", "\"", "\"", ",", "req", ".", "Datacenters", ")", "\n", "stmt", "=", "selectInString", "(", "stmt", ",", "\"", "\"", ",", "req", ".", "Racks", ")", "\n", "stmt", "=", "selectInUint64", "(", "stmt", ",", "\"", "\"", ",", "mac48s", ")", "\n", "stmt", "=", "selectInInt64", "(", "stmt", ",", "\"", "\"", ",", "ipv4s", ")", "\n", "stmt", "=", "selectInState", "(", "stmt", ",", "\"", "\"", ",", "req", ".", "States", ")", "\n", "query", ",", "args", ",", "err", ":=", "stmt", ".", "ToSql", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "db", ":=", "database", ".", "Get", "(", "c", ")", "\n", "rows", ",", "err", ":=", "db", ".", "QueryContext", "(", "c", ",", "query", ",", "args", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "defer", "rows", ".", "Close", "(", ")", "\n\n", "var", "kvms", "[", "]", "*", "crimson", ".", "KVM", "\n", "for", "rows", ".", "Next", "(", ")", "{", "k", ":=", "&", "crimson", ".", "KVM", "{", "}", "\n", "var", "ipv4", "common", ".", "IPv4", "\n", "var", "mac48", "common", ".", "MAC48", "\n", "if", "err", "=", "rows", ".", "Scan", "(", "&", "k", ".", "Name", ",", "&", "k", ".", "Vlan", ",", "&", "k", ".", "Platform", ",", "&", "k", ".", "Rack", ",", "&", "k", ".", "Datacenter", ",", "&", "k", ".", "Description", ",", "&", "mac48", ",", "&", "ipv4", ",", "&", "k", ".", "State", ",", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "k", ".", "MacAddress", "=", "mac48", ".", "String", "(", ")", "\n", "k", ".", "Ipv4", "=", "ipv4", ".", "String", "(", ")", "\n", "kvms", "=", "append", "(", "kvms", ",", "k", ")", "\n", "}", "\n", "return", "kvms", ",", "nil", "\n", "}" ]
// listKVMs returns a slice of KVMs in the database.
[ "listKVMs", "returns", "a", "slice", "of", "KVMs", "in", "the", "database", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/kvms.go#L41-L111
8,851
luci/luci-go
lucicfg/configset.go
Files
func (cs ConfigSet) Files() []string { f := make([]string, 0, len(cs.Data)) for k := range cs.Data { f = append(f, k) } sort.Strings(f) return f }
go
func (cs ConfigSet) Files() []string { f := make([]string, 0, len(cs.Data)) for k := range cs.Data { f = append(f, k) } sort.Strings(f) return f }
[ "func", "(", "cs", "ConfigSet", ")", "Files", "(", ")", "[", "]", "string", "{", "f", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "cs", ".", "Data", ")", ")", "\n", "for", "k", ":=", "range", "cs", ".", "Data", "{", "f", "=", "append", "(", "f", ",", "k", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "f", ")", "\n", "return", "f", "\n", "}" ]
// Files returns a sorted list of file names in the config set.
[ "Files", "returns", "a", "sorted", "list", "of", "file", "names", "in", "the", "config", "set", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/configset.go#L113-L120
8,852
luci/luci-go
lucicfg/configset.go
Log
func (vr *ValidationResult) Log(ctx context.Context) { for _, msg := range vr.Messages { lvl := logging.Info switch msg.Severity { case "WARNING": lvl = logging.Warning case "ERROR", "CRITICAL": lvl = logging.Error } logging.Logf(ctx, lvl, "%s: %s", msg.Path, msg.Text) } }
go
func (vr *ValidationResult) Log(ctx context.Context) { for _, msg := range vr.Messages { lvl := logging.Info switch msg.Severity { case "WARNING": lvl = logging.Warning case "ERROR", "CRITICAL": lvl = logging.Error } logging.Logf(ctx, lvl, "%s: %s", msg.Path, msg.Text) } }
[ "func", "(", "vr", "*", "ValidationResult", ")", "Log", "(", "ctx", "context", ".", "Context", ")", "{", "for", "_", ",", "msg", ":=", "range", "vr", ".", "Messages", "{", "lvl", ":=", "logging", ".", "Info", "\n", "switch", "msg", ".", "Severity", "{", "case", "\"", "\"", ":", "lvl", "=", "logging", ".", "Warning", "\n", "case", "\"", "\"", ",", "\"", "\"", ":", "lvl", "=", "logging", ".", "Error", "\n", "}", "\n", "logging", ".", "Logf", "(", "ctx", ",", "lvl", ",", "\"", "\"", ",", "msg", ".", "Path", ",", "msg", ".", "Text", ")", "\n", "}", "\n", "}" ]
// Log all messages in the result to the logger at an appropriate logging level.
[ "Log", "all", "messages", "in", "the", "result", "to", "the", "logger", "at", "an", "appropriate", "logging", "level", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/configset.go#L158-L169
8,853
luci/luci-go
lucicfg/cli/cmds/validate/validate.go
Cmd
func Cmd(params base.Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "validate [CONFIG_DIR|SCRIPT]", ShortDesc: "sends configuration files to LUCI Config service for validation", LongDesc: `Sends configuration files to LUCI Config service for validation. If the first positional argument is a directory, takes all files there and sends them to LUCI Config service, to be validated as a single config set. The name of the config set (e.g. "projects/foo") MUST be provided via -config-set flag, it is required in this mode. If the first positional argument is a Starlark file, it is interpreted (as with 'generate' subcommand) and the resulting generated configs are compared to what's already on disk in -config-dir directory. If they are different, the subcommand exits with non-zero exit code (indicating files on disk are stale). Otherwise the configs are sent to LUCI Config service for validation. Partitioning into config sets is specified in the Starlark code in this case, -config-set flag is rejected if given. When interpreting Starlark script, flags like -config-dir and -fail-on-warnings work as overrides for values declared in the script via lucicfg.config(...) statement. See its doc for more details. `, CommandRun: func() subcommands.CommandRun { vr := &validateRun{} vr.Init(params) vr.AddMetaFlags() vr.Flags.StringVar(&vr.configSet, "config-set", "", "Name of the config set to validate against when validating existing *.cfg configs.") return vr }, } }
go
func Cmd(params base.Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "validate [CONFIG_DIR|SCRIPT]", ShortDesc: "sends configuration files to LUCI Config service for validation", LongDesc: `Sends configuration files to LUCI Config service for validation. If the first positional argument is a directory, takes all files there and sends them to LUCI Config service, to be validated as a single config set. The name of the config set (e.g. "projects/foo") MUST be provided via -config-set flag, it is required in this mode. If the first positional argument is a Starlark file, it is interpreted (as with 'generate' subcommand) and the resulting generated configs are compared to what's already on disk in -config-dir directory. If they are different, the subcommand exits with non-zero exit code (indicating files on disk are stale). Otherwise the configs are sent to LUCI Config service for validation. Partitioning into config sets is specified in the Starlark code in this case, -config-set flag is rejected if given. When interpreting Starlark script, flags like -config-dir and -fail-on-warnings work as overrides for values declared in the script via lucicfg.config(...) statement. See its doc for more details. `, CommandRun: func() subcommands.CommandRun { vr := &validateRun{} vr.Init(params) vr.AddMetaFlags() vr.Flags.StringVar(&vr.configSet, "config-set", "", "Name of the config set to validate against when validating existing *.cfg configs.") return vr }, } }
[ "func", "Cmd", "(", "params", "base", ".", "Parameters", ")", "*", "subcommands", ".", "Command", "{", "return", "&", "subcommands", ".", "Command", "{", "UsageLine", ":", "\"", "\"", ",", "ShortDesc", ":", "\"", "\"", ",", "LongDesc", ":", "`Sends configuration files to LUCI Config service for validation.\n\nIf the first positional argument is a directory, takes all files there and\nsends them to LUCI Config service, to be validated as a single config set. The\nname of the config set (e.g. \"projects/foo\") MUST be provided via -config-set\nflag, it is required in this mode.\n\nIf the first positional argument is a Starlark file, it is interpreted (as with\n'generate' subcommand) and the resulting generated configs are compared to\nwhat's already on disk in -config-dir directory. If they are different, the\nsubcommand exits with non-zero exit code (indicating files on disk are stale).\nOtherwise the configs are sent to LUCI Config service for validation.\nPartitioning into config sets is specified in the Starlark code in this case,\n-config-set flag is rejected if given.\n\nWhen interpreting Starlark script, flags like -config-dir and -fail-on-warnings\nwork as overrides for values declared in the script via lucicfg.config(...)\nstatement. See its doc for more details.\n\t\t`", ",", "CommandRun", ":", "func", "(", ")", "subcommands", ".", "CommandRun", "{", "vr", ":=", "&", "validateRun", "{", "}", "\n", "vr", ".", "Init", "(", "params", ")", "\n", "vr", ".", "AddMetaFlags", "(", ")", "\n", "vr", ".", "Flags", ".", "StringVar", "(", "&", "vr", ".", "configSet", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "vr", "\n", "}", ",", "}", "\n", "}" ]
// Cmd is 'validate' subcommand.
[ "Cmd", "is", "validate", "subcommand", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/cli/cmds/validate/validate.go#L33-L65
8,854
luci/luci-go
cipd/appengine/impl/gs/retry.go
StatusCode
func StatusCode(err error) int { if err == nil { return http.StatusOK } if val, ok := errors.TagValueIn(statusCodeTagKey, err); ok { return val.(int) } return 0 }
go
func StatusCode(err error) int { if err == nil { return http.StatusOK } if val, ok := errors.TagValueIn(statusCodeTagKey, err); ok { return val.(int) } return 0 }
[ "func", "StatusCode", "(", "err", "error", ")", "int", "{", "if", "err", "==", "nil", "{", "return", "http", ".", "StatusOK", "\n", "}", "\n", "if", "val", ",", "ok", ":=", "errors", ".", "TagValueIn", "(", "statusCodeTagKey", ",", "err", ")", ";", "ok", "{", "return", "val", ".", "(", "int", ")", "\n", "}", "\n", "return", "0", "\n", "}" ]
// StatusCode returns HTTP status code embedded inside the annotated error. // // Returns http.StatusOK if err is nil and 0 if the error doesn't have a status // code.
[ "StatusCode", "returns", "HTTP", "status", "code", "embedded", "inside", "the", "annotated", "error", ".", "Returns", "http", ".", "StatusOK", "if", "err", "is", "nil", "and", "0", "if", "the", "error", "doesn", "t", "have", "a", "status", "code", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/gs/retry.go#L36-L44
8,855
luci/luci-go
machine-db/appengine/model/hosts.go
AssignHostnameAndIP
func AssignHostnameAndIP(c context.Context, tx database.ExecerContext, hostname string, ipv4 common.IPv4) (int64, error) { // By setting hostnames.vlan_id as both FOREIGN KEY and NOT NULL when setting up the database, // we can avoid checking if the given VLAN is valid. MySQL will ensure the given VLAN exists. res, err := tx.ExecContext(c, ` INSERT INTO hostnames (name, vlan_id) VALUES (?, (SELECT vlan_id FROM ips WHERE ipv4 = ? AND hostname_id IS NULL)) `, hostname, ipv4) if err != nil { switch e, ok := err.(*mysql.MySQLError); { case !ok: // Type assertion failed. case e.Number == mysqlerr.ER_DUP_ENTRY && strings.Contains(e.Message, "'name'"): // e.g. "Error 1062: Duplicate entry 'hostname-vlanId' for key 'name'". return 0, status.Errorf(codes.AlreadyExists, "duplicate hostname %q", hostname) case e.Number == mysqlerr.ER_BAD_NULL_ERROR && strings.Contains(e.Message, "'vlan_id'"): // e.g. "Error 1048: Column 'vlan_id' cannot be null". return 0, status.Errorf(codes.NotFound, "ensure IPv4 address %q exists and is free first", ipv4) } return 0, errors.Annotate(err, "failed to create hostname").Err() } hostnameId, err := res.LastInsertId() if err != nil { return 0, errors.Annotate(err, "failed to fetch hostname").Err() } res, err = tx.ExecContext(c, ` UPDATE ips SET hostname_id = ? WHERE ipv4 = ? AND hostname_id IS NULL `, hostnameId, ipv4) if err != nil { return 0, errors.Annotate(err, "failed to assign IP address").Err() } switch rows, err := res.RowsAffected(); { case err != nil: return 0, errors.Annotate(err, "failed to fetch affected rows").Err() case rows == 1: return hostnameId, nil default: // Shouldn't happen because IP address is unique per VLAN in the database. return 0, errors.Reason("unexpected number of affected rows %d", rows).Err() } }
go
func AssignHostnameAndIP(c context.Context, tx database.ExecerContext, hostname string, ipv4 common.IPv4) (int64, error) { // By setting hostnames.vlan_id as both FOREIGN KEY and NOT NULL when setting up the database, // we can avoid checking if the given VLAN is valid. MySQL will ensure the given VLAN exists. res, err := tx.ExecContext(c, ` INSERT INTO hostnames (name, vlan_id) VALUES (?, (SELECT vlan_id FROM ips WHERE ipv4 = ? AND hostname_id IS NULL)) `, hostname, ipv4) if err != nil { switch e, ok := err.(*mysql.MySQLError); { case !ok: // Type assertion failed. case e.Number == mysqlerr.ER_DUP_ENTRY && strings.Contains(e.Message, "'name'"): // e.g. "Error 1062: Duplicate entry 'hostname-vlanId' for key 'name'". return 0, status.Errorf(codes.AlreadyExists, "duplicate hostname %q", hostname) case e.Number == mysqlerr.ER_BAD_NULL_ERROR && strings.Contains(e.Message, "'vlan_id'"): // e.g. "Error 1048: Column 'vlan_id' cannot be null". return 0, status.Errorf(codes.NotFound, "ensure IPv4 address %q exists and is free first", ipv4) } return 0, errors.Annotate(err, "failed to create hostname").Err() } hostnameId, err := res.LastInsertId() if err != nil { return 0, errors.Annotate(err, "failed to fetch hostname").Err() } res, err = tx.ExecContext(c, ` UPDATE ips SET hostname_id = ? WHERE ipv4 = ? AND hostname_id IS NULL `, hostnameId, ipv4) if err != nil { return 0, errors.Annotate(err, "failed to assign IP address").Err() } switch rows, err := res.RowsAffected(); { case err != nil: return 0, errors.Annotate(err, "failed to fetch affected rows").Err() case rows == 1: return hostnameId, nil default: // Shouldn't happen because IP address is unique per VLAN in the database. return 0, errors.Reason("unexpected number of affected rows %d", rows).Err() } }
[ "func", "AssignHostnameAndIP", "(", "c", "context", ".", "Context", ",", "tx", "database", ".", "ExecerContext", ",", "hostname", "string", ",", "ipv4", "common", ".", "IPv4", ")", "(", "int64", ",", "error", ")", "{", "// By setting hostnames.vlan_id as both FOREIGN KEY and NOT NULL when setting up the database,", "// we can avoid checking if the given VLAN is valid. MySQL will ensure the given VLAN exists.", "res", ",", "err", ":=", "tx", ".", "ExecContext", "(", "c", ",", "`\n\t\tINSERT INTO hostnames (name, vlan_id)\n\t\tVALUES (?, (SELECT vlan_id FROM ips WHERE ipv4 = ? AND hostname_id IS NULL))\n\t`", ",", "hostname", ",", "ipv4", ")", "\n", "if", "err", "!=", "nil", "{", "switch", "e", ",", "ok", ":=", "err", ".", "(", "*", "mysql", ".", "MySQLError", ")", ";", "{", "case", "!", "ok", ":", "// Type assertion failed.", "case", "e", ".", "Number", "==", "mysqlerr", ".", "ER_DUP_ENTRY", "&&", "strings", ".", "Contains", "(", "e", ".", "Message", ",", "\"", "\"", ")", ":", "// e.g. \"Error 1062: Duplicate entry 'hostname-vlanId' for key 'name'\".", "return", "0", ",", "status", ".", "Errorf", "(", "codes", ".", "AlreadyExists", ",", "\"", "\"", ",", "hostname", ")", "\n", "case", "e", ".", "Number", "==", "mysqlerr", ".", "ER_BAD_NULL_ERROR", "&&", "strings", ".", "Contains", "(", "e", ".", "Message", ",", "\"", "\"", ")", ":", "// e.g. \"Error 1048: Column 'vlan_id' cannot be null\".", "return", "0", ",", "status", ".", "Errorf", "(", "codes", ".", "NotFound", ",", "\"", "\"", ",", "ipv4", ")", "\n", "}", "\n", "return", "0", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "hostnameId", ",", "err", ":=", "res", ".", "LastInsertId", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "res", ",", "err", "=", "tx", ".", "ExecContext", "(", "c", ",", "`\n\t\tUPDATE ips\n\t\tSET hostname_id = ?\n\t\tWHERE ipv4 = ?\n\t\t\tAND hostname_id IS NULL\n\t`", ",", "hostnameId", ",", "ipv4", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "switch", "rows", ",", "err", ":=", "res", ".", "RowsAffected", "(", ")", ";", "{", "case", "err", "!=", "nil", ":", "return", "0", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "case", "rows", "==", "1", ":", "return", "hostnameId", ",", "nil", "\n", "default", ":", "// Shouldn't happen because IP address is unique per VLAN in the database.", "return", "0", ",", "errors", ".", "Reason", "(", "\"", "\"", ",", "rows", ")", ".", "Err", "(", ")", "\n", "}", "\n", "}" ]
// AssignHostnameAndIP assigns the given hostname and IP address using the given transaction. // The caller must commit or roll back the transaction appropriately.
[ "AssignHostnameAndIP", "assigns", "the", "given", "hostname", "and", "IP", "address", "using", "the", "given", "transaction", ".", "The", "caller", "must", "commit", "or", "roll", "back", "the", "transaction", "appropriately", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/hosts.go#L35-L78
8,856
luci/luci-go
milo/common/model/manifest_link.go
FromProperty
func (m *ManifestLink) FromProperty(p ds.Property) (err error) { val, err := p.Project(ds.PTBytes) if err != nil { return err } buf := bytes.NewReader(val.([]byte)) if m.Name, _, err = cmpbin.ReadString(buf); err != nil { return } m.ID, _, err = cmpbin.ReadBytes(buf) return }
go
func (m *ManifestLink) FromProperty(p ds.Property) (err error) { val, err := p.Project(ds.PTBytes) if err != nil { return err } buf := bytes.NewReader(val.([]byte)) if m.Name, _, err = cmpbin.ReadString(buf); err != nil { return } m.ID, _, err = cmpbin.ReadBytes(buf) return }
[ "func", "(", "m", "*", "ManifestLink", ")", "FromProperty", "(", "p", "ds", ".", "Property", ")", "(", "err", "error", ")", "{", "val", ",", "err", ":=", "p", ".", "Project", "(", "ds", ".", "PTBytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "buf", ":=", "bytes", ".", "NewReader", "(", "val", ".", "(", "[", "]", "byte", ")", ")", "\n", "if", "m", ".", "Name", ",", "_", ",", "err", "=", "cmpbin", ".", "ReadString", "(", "buf", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "m", ".", "ID", ",", "_", ",", "err", "=", "cmpbin", ".", "ReadBytes", "(", "buf", ")", "\n", "return", "\n", "}" ]
// FromProperty implements ds.PropertyConverter
[ "FromProperty", "implements", "ds", ".", "PropertyConverter" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/model/manifest_link.go#L36-L47
8,857
luci/luci-go
milo/common/model/manifest_link.go
ToProperty
func (m *ManifestLink) ToProperty() (ds.Property, error) { buf := bytes.NewBuffer(nil) cmpbin.WriteString(buf, m.Name) cmpbin.WriteBytes(buf, m.ID) return ds.MkProperty(buf.Bytes()), nil }
go
func (m *ManifestLink) ToProperty() (ds.Property, error) { buf := bytes.NewBuffer(nil) cmpbin.WriteString(buf, m.Name) cmpbin.WriteBytes(buf, m.ID) return ds.MkProperty(buf.Bytes()), nil }
[ "func", "(", "m", "*", "ManifestLink", ")", "ToProperty", "(", ")", "(", "ds", ".", "Property", ",", "error", ")", "{", "buf", ":=", "bytes", ".", "NewBuffer", "(", "nil", ")", "\n", "cmpbin", ".", "WriteString", "(", "buf", ",", "m", ".", "Name", ")", "\n", "cmpbin", ".", "WriteBytes", "(", "buf", ",", "m", ".", "ID", ")", "\n", "return", "ds", ".", "MkProperty", "(", "buf", ".", "Bytes", "(", ")", ")", ",", "nil", "\n", "}" ]
// ToProperty implements ds.PropertyConverter
[ "ToProperty", "implements", "ds", ".", "PropertyConverter" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/model/manifest_link.go#L50-L55
8,858
luci/luci-go
dm/appengine/model/template_info.go
Equals
func (ti TemplateInfo) Equals(other TemplateInfo) bool { if len(other) != len(ti) { return false } for i, me := range ti { if !me.Equals(&other[i]) { return false } } return true }
go
func (ti TemplateInfo) Equals(other TemplateInfo) bool { if len(other) != len(ti) { return false } for i, me := range ti { if !me.Equals(&other[i]) { return false } } return true }
[ "func", "(", "ti", "TemplateInfo", ")", "Equals", "(", "other", "TemplateInfo", ")", "bool", "{", "if", "len", "(", "other", ")", "!=", "len", "(", "ti", ")", "{", "return", "false", "\n", "}", "\n", "for", "i", ",", "me", ":=", "range", "ti", "{", "if", "!", "me", ".", "Equals", "(", "&", "other", "[", "i", "]", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Equals returns true iff this TemplateInfo is exactly same as `other`.
[ "Equals", "returns", "true", "iff", "this", "TemplateInfo", "is", "exactly", "same", "as", "other", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/model/template_info.go#L40-L50
8,859
luci/luci-go
dm/appengine/model/template_info.go
EqualsData
func (ti TemplateInfo) EqualsData(other []*dm.Quest_TemplateSpec) bool { if len(other) != len(ti) { return false } for i, me := range ti { if !me.Equals(other[i]) { return false } } return true }
go
func (ti TemplateInfo) EqualsData(other []*dm.Quest_TemplateSpec) bool { if len(other) != len(ti) { return false } for i, me := range ti { if !me.Equals(other[i]) { return false } } return true }
[ "func", "(", "ti", "TemplateInfo", ")", "EqualsData", "(", "other", "[", "]", "*", "dm", ".", "Quest_TemplateSpec", ")", "bool", "{", "if", "len", "(", "other", ")", "!=", "len", "(", "ti", ")", "{", "return", "false", "\n", "}", "\n", "for", "i", ",", "me", ":=", "range", "ti", "{", "if", "!", "me", ".", "Equals", "(", "other", "[", "i", "]", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// EqualsData returns true iff this TemplateInfo has the same content as the // proto-style TemplateInfo. This assumes that `other` is sorted.
[ "EqualsData", "returns", "true", "iff", "this", "TemplateInfo", "has", "the", "same", "content", "as", "the", "proto", "-", "style", "TemplateInfo", ".", "This", "assumes", "that", "other", "is", "sorted", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/model/template_info.go#L54-L64
8,860
luci/luci-go
dm/appengine/model/template_info.go
Add
func (ti *TemplateInfo) Add(ts ...dm.Quest_TemplateSpec) { *ti = append(*ti, ts...) sort.Sort(*ti) *ti = (*ti)[:set.Uniq(*ti)] }
go
func (ti *TemplateInfo) Add(ts ...dm.Quest_TemplateSpec) { *ti = append(*ti, ts...) sort.Sort(*ti) *ti = (*ti)[:set.Uniq(*ti)] }
[ "func", "(", "ti", "*", "TemplateInfo", ")", "Add", "(", "ts", "...", "dm", ".", "Quest_TemplateSpec", ")", "{", "*", "ti", "=", "append", "(", "*", "ti", ",", "ts", "...", ")", "\n", "sort", ".", "Sort", "(", "*", "ti", ")", "\n", "*", "ti", "=", "(", "*", "ti", ")", "[", ":", "set", ".", "Uniq", "(", "*", "ti", ")", "]", "\n", "}" ]
// Add adds ts to the TemplateInfo uniq'ly.
[ "Add", "adds", "ts", "to", "the", "TemplateInfo", "uniq", "ly", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/model/template_info.go#L67-L71
8,861
luci/luci-go
gce/api/config/v1/duration.go
ToSeconds
func (d *TimePeriod_Duration) ToSeconds() (int64, error) { // Decompose the duration into a slice of [duration, <int64>, <unit>]. m := regexp.MustCompile(durationRegex).FindStringSubmatch(d.Duration) if len(m) != 3 { return 0, errors.Reason("duration must match regex %q", durationRegex).Err() } n, err := strconv.ParseInt(m[1], 10, 64) if err != nil { return 0, errors.Reason("duration must not exceed %q", int64(math.MaxInt64)).Err() } var mul int64 switch m[2] { case "s": // 1 second. mul = 1 case "m": // 60 seconds. mul = 60 case "h": // 60 minutes. mul = 3600 case "d": // 24 hours. mul = 86400 case "mo": // 30 days. mul = 2592000 } if n > math.MaxInt64/mul { n = math.MaxInt64 } else { n *= mul } return n, nil }
go
func (d *TimePeriod_Duration) ToSeconds() (int64, error) { // Decompose the duration into a slice of [duration, <int64>, <unit>]. m := regexp.MustCompile(durationRegex).FindStringSubmatch(d.Duration) if len(m) != 3 { return 0, errors.Reason("duration must match regex %q", durationRegex).Err() } n, err := strconv.ParseInt(m[1], 10, 64) if err != nil { return 0, errors.Reason("duration must not exceed %q", int64(math.MaxInt64)).Err() } var mul int64 switch m[2] { case "s": // 1 second. mul = 1 case "m": // 60 seconds. mul = 60 case "h": // 60 minutes. mul = 3600 case "d": // 24 hours. mul = 86400 case "mo": // 30 days. mul = 2592000 } if n > math.MaxInt64/mul { n = math.MaxInt64 } else { n *= mul } return n, nil }
[ "func", "(", "d", "*", "TimePeriod_Duration", ")", "ToSeconds", "(", ")", "(", "int64", ",", "error", ")", "{", "// Decompose the duration into a slice of [duration, <int64>, <unit>].", "m", ":=", "regexp", ".", "MustCompile", "(", "durationRegex", ")", ".", "FindStringSubmatch", "(", "d", ".", "Duration", ")", "\n", "if", "len", "(", "m", ")", "!=", "3", "{", "return", "0", ",", "errors", ".", "Reason", "(", "\"", "\"", ",", "durationRegex", ")", ".", "Err", "(", ")", "\n", "}", "\n", "n", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "m", "[", "1", "]", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "errors", ".", "Reason", "(", "\"", "\"", ",", "int64", "(", "math", ".", "MaxInt64", ")", ")", ".", "Err", "(", ")", "\n", "}", "\n", "var", "mul", "int64", "\n", "switch", "m", "[", "2", "]", "{", "case", "\"", "\"", ":", "// 1 second.", "mul", "=", "1", "\n", "case", "\"", "\"", ":", "// 60 seconds.", "mul", "=", "60", "\n", "case", "\"", "\"", ":", "// 60 minutes.", "mul", "=", "3600", "\n", "case", "\"", "\"", ":", "// 24 hours.", "mul", "=", "86400", "\n", "case", "\"", "\"", ":", "// 30 days.", "mul", "=", "2592000", "\n", "}", "\n", "if", "n", ">", "math", ".", "MaxInt64", "/", "mul", "{", "n", "=", "math", ".", "MaxInt64", "\n", "}", "else", "{", "n", "*=", "mul", "\n", "}", "\n", "return", "n", ",", "nil", "\n", "}" ]
// ToSeconds returns this duration in seconds. Clamps to math.MaxInt64.
[ "ToSeconds", "returns", "this", "duration", "in", "seconds", ".", "Clamps", "to", "math", ".", "MaxInt64", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/api/config/v1/duration.go#L30-L64
8,862
luci/luci-go
gce/api/config/v1/duration.go
Validate
func (d *TimePeriod_Duration) Validate(c *validation.Context) { if _, err := d.ToSeconds(); err != nil { c.Errorf("%s", err) } }
go
func (d *TimePeriod_Duration) Validate(c *validation.Context) { if _, err := d.ToSeconds(); err != nil { c.Errorf("%s", err) } }
[ "func", "(", "d", "*", "TimePeriod_Duration", ")", "Validate", "(", "c", "*", "validation", ".", "Context", ")", "{", "if", "_", ",", "err", ":=", "d", ".", "ToSeconds", "(", ")", ";", "err", "!=", "nil", "{", "c", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}" ]
// Validate validates this duration.
[ "Validate", "validates", "this", "duration", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/api/config/v1/duration.go#L67-L71
8,863
luci/luci-go
common/proto/milo/util.go
ExtractProperties
func ExtractProperties(s *Step) (*structpb.Struct, error) { finals := map[string]json.RawMessage{} var extract func(s *Step) extract = func(s *Step) { for _, p := range s.Property { finals[p.Name] = json.RawMessage(p.Value) } for _, substep := range s.GetSubstep() { if ss := substep.GetStep(); ss != nil { extract(ss) } } } extract(s) buf, err := json.Marshal(finals) if err != nil { panic("failed to marshal in-memory map to JSON") } ret := &structpb.Struct{} if err := jsonpb.Unmarshal(bytes.NewReader(buf), ret); err != nil { return nil, err } return ret, nil }
go
func ExtractProperties(s *Step) (*structpb.Struct, error) { finals := map[string]json.RawMessage{} var extract func(s *Step) extract = func(s *Step) { for _, p := range s.Property { finals[p.Name] = json.RawMessage(p.Value) } for _, substep := range s.GetSubstep() { if ss := substep.GetStep(); ss != nil { extract(ss) } } } extract(s) buf, err := json.Marshal(finals) if err != nil { panic("failed to marshal in-memory map to JSON") } ret := &structpb.Struct{} if err := jsonpb.Unmarshal(bytes.NewReader(buf), ret); err != nil { return nil, err } return ret, nil }
[ "func", "ExtractProperties", "(", "s", "*", "Step", ")", "(", "*", "structpb", ".", "Struct", ",", "error", ")", "{", "finals", ":=", "map", "[", "string", "]", "json", ".", "RawMessage", "{", "}", "\n\n", "var", "extract", "func", "(", "s", "*", "Step", ")", "\n", "extract", "=", "func", "(", "s", "*", "Step", ")", "{", "for", "_", ",", "p", ":=", "range", "s", ".", "Property", "{", "finals", "[", "p", ".", "Name", "]", "=", "json", ".", "RawMessage", "(", "p", ".", "Value", ")", "\n", "}", "\n", "for", "_", ",", "substep", ":=", "range", "s", ".", "GetSubstep", "(", ")", "{", "if", "ss", ":=", "substep", ".", "GetStep", "(", ")", ";", "ss", "!=", "nil", "{", "extract", "(", "ss", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "extract", "(", "s", ")", "\n\n", "buf", ",", "err", ":=", "json", ".", "Marshal", "(", "finals", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "ret", ":=", "&", "structpb", ".", "Struct", "{", "}", "\n", "if", "err", ":=", "jsonpb", ".", "Unmarshal", "(", "bytes", ".", "NewReader", "(", "buf", ")", ",", "ret", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "ret", ",", "nil", "\n", "}" ]
// ExtractProperties returns a flat list of properties from a tree of steps. // If multiple step nodes have a property of the same name, the last one in the // preorder traversal wins.
[ "ExtractProperties", "returns", "a", "flat", "list", "of", "properties", "from", "a", "tree", "of", "steps", ".", "If", "multiple", "step", "nodes", "have", "a", "property", "of", "the", "same", "name", "the", "last", "one", "in", "the", "preorder", "traversal", "wins", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/proto/milo/util.go#L31-L57
8,864
luci/luci-go
cipd/client/cipd/json_structs.go
Before
func (t UnixTime) Before(t2 UnixTime) bool { return time.Time(t).Before(time.Time(t2)) }
go
func (t UnixTime) Before(t2 UnixTime) bool { return time.Time(t).Before(time.Time(t2)) }
[ "func", "(", "t", "UnixTime", ")", "Before", "(", "t2", "UnixTime", ")", "bool", "{", "return", "time", ".", "Time", "(", "t", ")", ".", "Before", "(", "time", ".", "Time", "(", "t2", ")", ")", "\n", "}" ]
// Before is used to compare UnixTime objects.
[ "Before", "is", "used", "to", "compare", "UnixTime", "objects", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/json_structs.go#L46-L48
8,865
luci/luci-go
logdog/common/storage/memory/memory.go
Close
func (s *Storage) Close() { s.run(func() error { s.closed = true return nil }) }
go
func (s *Storage) Close() { s.run(func() error { s.closed = true return nil }) }
[ "func", "(", "s", "*", "Storage", ")", "Close", "(", ")", "{", "s", ".", "run", "(", "func", "(", ")", "error", "{", "s", ".", "closed", "=", "true", "\n", "return", "nil", "\n", "}", ")", "\n", "}" ]
// Close implements storage.Storage.
[ "Close", "implements", "storage", ".", "Storage", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/storage/memory/memory.go#L69-L74
8,866
luci/luci-go
logdog/common/storage/memory/memory.go
ResetClose
func (s *Storage) ResetClose() { s.stateMu.Lock() defer s.stateMu.Unlock() s.closed = false }
go
func (s *Storage) ResetClose() { s.stateMu.Lock() defer s.stateMu.Unlock() s.closed = false }
[ "func", "(", "s", "*", "Storage", ")", "ResetClose", "(", ")", "{", "s", ".", "stateMu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "stateMu", ".", "Unlock", "(", ")", "\n\n", "s", ".", "closed", "=", "false", "\n", "}" ]
// ResetClose resets the storage instance, allowing it to be used another time. // The data stored in this instance is not changed.
[ "ResetClose", "resets", "the", "storage", "instance", "allowing", "it", "to", "be", "used", "another", "time", ".", "The", "data", "stored", "in", "this", "instance", "is", "not", "changed", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/storage/memory/memory.go#L78-L83
8,867
luci/luci-go
logdog/common/storage/memory/memory.go
Count
func (s *Storage) Count(project types.ProjectName, path types.StreamPath) (c int) { s.run(func() error { if st := s.getLogStreamLocked(project, path, false); st != nil { c = len(st.logs) } return nil }) return }
go
func (s *Storage) Count(project types.ProjectName, path types.StreamPath) (c int) { s.run(func() error { if st := s.getLogStreamLocked(project, path, false); st != nil { c = len(st.logs) } return nil }) return }
[ "func", "(", "s", "*", "Storage", ")", "Count", "(", "project", "types", ".", "ProjectName", ",", "path", "types", ".", "StreamPath", ")", "(", "c", "int", ")", "{", "s", ".", "run", "(", "func", "(", ")", "error", "{", "if", "st", ":=", "s", ".", "getLogStreamLocked", "(", "project", ",", "path", ",", "false", ")", ";", "st", "!=", "nil", "{", "c", "=", "len", "(", "st", ".", "logs", ")", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "return", "\n", "}" ]
// Count returns the number of log records for the given stream.
[ "Count", "returns", "the", "number", "of", "log", "records", "for", "the", "given", "stream", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/storage/memory/memory.go#L192-L200
8,868
luci/luci-go
logdog/common/storage/memory/memory.go
SetErr
func (s *Storage) SetErr(err error) { s.stateMu.Lock() defer s.stateMu.Unlock() s.err = err }
go
func (s *Storage) SetErr(err error) { s.stateMu.Lock() defer s.stateMu.Unlock() s.err = err }
[ "func", "(", "s", "*", "Storage", ")", "SetErr", "(", "err", "error", ")", "{", "s", ".", "stateMu", ".", "Lock", "(", ")", "\n", "defer", "s", ".", "stateMu", ".", "Unlock", "(", ")", "\n", "s", ".", "err", "=", "err", "\n", "}" ]
// SetErr sets the storage's error value. If not nil, all operations will fail // with this error.
[ "SetErr", "sets", "the", "storage", "s", "error", "value", ".", "If", "not", "nil", "all", "operations", "will", "fail", "with", "this", "error", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/storage/memory/memory.go#L204-L208
8,869
luci/luci-go
logdog/common/storage/memory/memory.go
PutEntries
func (s *Storage) PutEntries(ctx context.Context, project types.ProjectName, path types.StreamPath, entries ...*logpb.LogEntry) { for _, ent := range entries { value, err := proto.Marshal(ent) if err != nil { panic(err) } s.Put(ctx, storage.PutRequest{ Project: project, Path: path, Index: types.MessageIndex(ent.StreamIndex), Values: [][]byte{value}, }) } }
go
func (s *Storage) PutEntries(ctx context.Context, project types.ProjectName, path types.StreamPath, entries ...*logpb.LogEntry) { for _, ent := range entries { value, err := proto.Marshal(ent) if err != nil { panic(err) } s.Put(ctx, storage.PutRequest{ Project: project, Path: path, Index: types.MessageIndex(ent.StreamIndex), Values: [][]byte{value}, }) } }
[ "func", "(", "s", "*", "Storage", ")", "PutEntries", "(", "ctx", "context", ".", "Context", ",", "project", "types", ".", "ProjectName", ",", "path", "types", ".", "StreamPath", ",", "entries", "...", "*", "logpb", ".", "LogEntry", ")", "{", "for", "_", ",", "ent", ":=", "range", "entries", "{", "value", ",", "err", ":=", "proto", ".", "Marshal", "(", "ent", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "s", ".", "Put", "(", "ctx", ",", "storage", ".", "PutRequest", "{", "Project", ":", "project", ",", "Path", ":", "path", ",", "Index", ":", "types", ".", "MessageIndex", "(", "ent", ".", "StreamIndex", ")", ",", "Values", ":", "[", "]", "[", "]", "byte", "{", "value", "}", ",", "}", ")", "\n", "}", "\n", "}" ]
// PutEntries is a convenience method for ingesting logpb.Entry's into this // Storage object.
[ "PutEntries", "is", "a", "convenience", "method", "for", "ingesting", "logpb", ".", "Entry", "s", "into", "this", "Storage", "object", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/storage/memory/memory.go#L247-L260
8,870
luci/luci-go
grpc/prpc/format.go
FormatFromContentType
func FormatFromContentType(v string) (Format, error) { if v == "" { return FormatBinary, nil } mediaType, mediaTypeParams, err := mime.ParseMediaType(v) if err != nil { return 0, err } return FormatFromMediaType(mediaType, mediaTypeParams) }
go
func FormatFromContentType(v string) (Format, error) { if v == "" { return FormatBinary, nil } mediaType, mediaTypeParams, err := mime.ParseMediaType(v) if err != nil { return 0, err } return FormatFromMediaType(mediaType, mediaTypeParams) }
[ "func", "FormatFromContentType", "(", "v", "string", ")", "(", "Format", ",", "error", ")", "{", "if", "v", "==", "\"", "\"", "{", "return", "FormatBinary", ",", "nil", "\n", "}", "\n", "mediaType", ",", "mediaTypeParams", ",", "err", ":=", "mime", ".", "ParseMediaType", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "return", "FormatFromMediaType", "(", "mediaType", ",", "mediaTypeParams", ")", "\n", "}" ]
// FormatFromContentType converts Content-Type header value from a request to a // format. // Can return only FormatBinary, FormatJSONPB or FormatText. // In case of an error, format is undefined.
[ "FormatFromContentType", "converts", "Content", "-", "Type", "header", "value", "from", "a", "request", "to", "a", "format", ".", "Can", "return", "only", "FormatBinary", "FormatJSONPB", "or", "FormatText", ".", "In", "case", "of", "an", "error", "format", "is", "undefined", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/prpc/format.go#L61-L70
8,871
luci/luci-go
grpc/prpc/format.go
FormatFromMediaType
func FormatFromMediaType(mt string, params map[string]string) (Format, error) { switch mt { case ContentTypePRPC: for k := range params { if k != mtPRPCEncoding { return 0, fmt.Errorf("unexpected parameter %q", k) } } return FormatFromEncoding(params[mtPRPCEncoding]) case ContentTypeJSON: return FormatJSONPB, nil case "", "*/*", "application/*", "application/grpc": return FormatBinary, nil default: return 0, fmt.Errorf("unknown content type: %q", mt) } }
go
func FormatFromMediaType(mt string, params map[string]string) (Format, error) { switch mt { case ContentTypePRPC: for k := range params { if k != mtPRPCEncoding { return 0, fmt.Errorf("unexpected parameter %q", k) } } return FormatFromEncoding(params[mtPRPCEncoding]) case ContentTypeJSON: return FormatJSONPB, nil case "", "*/*", "application/*", "application/grpc": return FormatBinary, nil default: return 0, fmt.Errorf("unknown content type: %q", mt) } }
[ "func", "FormatFromMediaType", "(", "mt", "string", ",", "params", "map", "[", "string", "]", "string", ")", "(", "Format", ",", "error", ")", "{", "switch", "mt", "{", "case", "ContentTypePRPC", ":", "for", "k", ":=", "range", "params", "{", "if", "k", "!=", "mtPRPCEncoding", "{", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "k", ")", "\n", "}", "\n", "}", "\n", "return", "FormatFromEncoding", "(", "params", "[", "mtPRPCEncoding", "]", ")", "\n\n", "case", "ContentTypeJSON", ":", "return", "FormatJSONPB", ",", "nil", "\n\n", "case", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ":", "return", "FormatBinary", ",", "nil", "\n\n", "default", ":", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "mt", ")", "\n", "}", "\n", "}" ]
// FormatFromMediaType converts a media type ContentType and its parameters // into a pRPC Format. // Can return only FormatBinary, FormatJSONPB or FormatText. // In case of an error, format is undefined.
[ "FormatFromMediaType", "converts", "a", "media", "type", "ContentType", "and", "its", "parameters", "into", "a", "pRPC", "Format", ".", "Can", "return", "only", "FormatBinary", "FormatJSONPB", "or", "FormatText", ".", "In", "case", "of", "an", "error", "format", "is", "undefined", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/prpc/format.go#L76-L95
8,872
luci/luci-go
grpc/prpc/format.go
FormatFromEncoding
func FormatFromEncoding(v string) (Format, error) { switch v { case "", mtPRPCEncodingBinary: return FormatBinary, nil case mtPRPCEncodingJSONPB: return FormatJSONPB, nil case mtPRPCEncodingText: return FormatText, nil default: return 0, fmt.Errorf(`invalid encoding parameter: %q. Valid values: `+ `"`+mtPRPCEncodingBinary+`", `+ `"`+mtPRPCEncodingJSONPB+`", `+ `"`+mtPRPCEncodingText+`"`, v) } }
go
func FormatFromEncoding(v string) (Format, error) { switch v { case "", mtPRPCEncodingBinary: return FormatBinary, nil case mtPRPCEncodingJSONPB: return FormatJSONPB, nil case mtPRPCEncodingText: return FormatText, nil default: return 0, fmt.Errorf(`invalid encoding parameter: %q. Valid values: `+ `"`+mtPRPCEncodingBinary+`", `+ `"`+mtPRPCEncodingJSONPB+`", `+ `"`+mtPRPCEncodingText+`"`, v) } }
[ "func", "FormatFromEncoding", "(", "v", "string", ")", "(", "Format", ",", "error", ")", "{", "switch", "v", "{", "case", "\"", "\"", ",", "mtPRPCEncodingBinary", ":", "return", "FormatBinary", ",", "nil", "\n", "case", "mtPRPCEncodingJSONPB", ":", "return", "FormatJSONPB", ",", "nil", "\n", "case", "mtPRPCEncodingText", ":", "return", "FormatText", ",", "nil", "\n", "default", ":", "return", "0", ",", "fmt", ".", "Errorf", "(", "`invalid encoding parameter: %q. Valid values: `", "+", "`\"`", "+", "mtPRPCEncodingBinary", "+", "`\", `", "+", "`\"`", "+", "mtPRPCEncodingJSONPB", "+", "`\", `", "+", "`\"`", "+", "mtPRPCEncodingText", "+", "`\"`", ",", "v", ")", "\n", "}", "\n", "}" ]
// FormatFromEncoding converts a media type encoding parameter into a pRPC // Format. // Can return only FormatBinary, FormatJSONPB or FormatText. // In case of an error, format is undefined.
[ "FormatFromEncoding", "converts", "a", "media", "type", "encoding", "parameter", "into", "a", "pRPC", "Format", ".", "Can", "return", "only", "FormatBinary", "FormatJSONPB", "or", "FormatText", ".", "In", "case", "of", "an", "error", "format", "is", "undefined", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/prpc/format.go#L101-L115
8,873
luci/luci-go
grpc/prpc/format.go
MediaType
func (f Format) MediaType() string { switch f { case FormatJSONPB: return mtPRPCJSONPB case FormatText: return mtPRPCText case FormatBinary: fallthrough default: return mtPRPCBinary } }
go
func (f Format) MediaType() string { switch f { case FormatJSONPB: return mtPRPCJSONPB case FormatText: return mtPRPCText case FormatBinary: fallthrough default: return mtPRPCBinary } }
[ "func", "(", "f", "Format", ")", "MediaType", "(", ")", "string", "{", "switch", "f", "{", "case", "FormatJSONPB", ":", "return", "mtPRPCJSONPB", "\n", "case", "FormatText", ":", "return", "mtPRPCText", "\n", "case", "FormatBinary", ":", "fallthrough", "\n", "default", ":", "return", "mtPRPCBinary", "\n", "}", "\n", "}" ]
// MediaType returns a full media type for f.
[ "MediaType", "returns", "a", "full", "media", "type", "for", "f", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/prpc/format.go#L118-L129
8,874
luci/luci-go
grpc/cmd/prpc/call.go
call
func call(c context.Context, client *prpc.Client, req *request, out io.Writer) error { var inf, outf prpc.Format var message []byte switch req.format { default: var buf bytes.Buffer if _, err := buf.ReadFrom(req.message); err != nil { return err } message = buf.Bytes() inf = req.format.Format() outf = inf } // Send the request. var hmd, tmd metadata.MD res, err := client.CallRaw(c, req.service, req.method, message, inf, outf, prpc.Header(&hmd), prpc.Trailer(&tmd)) if err != nil { return &exitCode{err, int(grpc.Code(err))} } // Read response. if _, err := out.Write(res); err != nil { return fmt.Errorf("failed to write response: %s", err) } return err }
go
func call(c context.Context, client *prpc.Client, req *request, out io.Writer) error { var inf, outf prpc.Format var message []byte switch req.format { default: var buf bytes.Buffer if _, err := buf.ReadFrom(req.message); err != nil { return err } message = buf.Bytes() inf = req.format.Format() outf = inf } // Send the request. var hmd, tmd metadata.MD res, err := client.CallRaw(c, req.service, req.method, message, inf, outf, prpc.Header(&hmd), prpc.Trailer(&tmd)) if err != nil { return &exitCode{err, int(grpc.Code(err))} } // Read response. if _, err := out.Write(res); err != nil { return fmt.Errorf("failed to write response: %s", err) } return err }
[ "func", "call", "(", "c", "context", ".", "Context", ",", "client", "*", "prpc", ".", "Client", ",", "req", "*", "request", ",", "out", "io", ".", "Writer", ")", "error", "{", "var", "inf", ",", "outf", "prpc", ".", "Format", "\n", "var", "message", "[", "]", "byte", "\n", "switch", "req", ".", "format", "{", "default", ":", "var", "buf", "bytes", ".", "Buffer", "\n", "if", "_", ",", "err", ":=", "buf", ".", "ReadFrom", "(", "req", ".", "message", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "message", "=", "buf", ".", "Bytes", "(", ")", "\n", "inf", "=", "req", ".", "format", ".", "Format", "(", ")", "\n", "outf", "=", "inf", "\n", "}", "\n\n", "// Send the request.", "var", "hmd", ",", "tmd", "metadata", ".", "MD", "\n", "res", ",", "err", ":=", "client", ".", "CallRaw", "(", "c", ",", "req", ".", "service", ",", "req", ".", "method", ",", "message", ",", "inf", ",", "outf", ",", "prpc", ".", "Header", "(", "&", "hmd", ")", ",", "prpc", ".", "Trailer", "(", "&", "tmd", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "exitCode", "{", "err", ",", "int", "(", "grpc", ".", "Code", "(", "err", ")", ")", "}", "\n", "}", "\n\n", "// Read response.", "if", "_", ",", "err", ":=", "out", ".", "Write", "(", "res", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// call makes an RPC and writes response to out.
[ "call", "makes", "an", "RPC", "and", "writes", "response", "to", "out", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/cmd/prpc/call.go#L119-L146
8,875
luci/luci-go
logdog/appengine/coordinator/endpoints/services.go
Base
func (svc *ProdService) Base(c *router.Context, next router.Handler) { services := prodServicesInst{ ProdService: svc, } c.Context = coordinator.WithConfigProvider(c.Context, &services) c.Context = WithServices(c.Context, &services) next(c) }
go
func (svc *ProdService) Base(c *router.Context, next router.Handler) { services := prodServicesInst{ ProdService: svc, } c.Context = coordinator.WithConfigProvider(c.Context, &services) c.Context = WithServices(c.Context, &services) next(c) }
[ "func", "(", "svc", "*", "ProdService", ")", "Base", "(", "c", "*", "router", ".", "Context", ",", "next", "router", ".", "Handler", ")", "{", "services", ":=", "prodServicesInst", "{", "ProdService", ":", "svc", ",", "}", "\n\n", "c", ".", "Context", "=", "coordinator", ".", "WithConfigProvider", "(", "c", ".", "Context", ",", "&", "services", ")", "\n", "c", ".", "Context", "=", "WithServices", "(", "c", ".", "Context", ",", "&", "services", ")", "\n", "next", "(", "c", ")", "\n", "}" ]
// Base is Middleware used by Coordinator services. // // It installs a production Services instance into the Context.
[ "Base", "is", "Middleware", "used", "by", "Coordinator", "services", ".", "It", "installs", "a", "production", "Services", "instance", "into", "the", "Context", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/endpoints/services.go#L48-L56
8,876
luci/luci-go
cipd/appengine/impl/admin/admin.go
init
func (impl *adminImpl) init() { impl.ctl = &mapper.Controller{ MapperQueue: "mappers", // see queue.yaml ControlQueue: "default", } for _, m := range mappers { // see mappers.go impl.ctl.RegisterFactory(m.mapperID(), m.newMapper) } impl.ctl.Install(impl.tq) }
go
func (impl *adminImpl) init() { impl.ctl = &mapper.Controller{ MapperQueue: "mappers", // see queue.yaml ControlQueue: "default", } for _, m := range mappers { // see mappers.go impl.ctl.RegisterFactory(m.mapperID(), m.newMapper) } impl.ctl.Install(impl.tq) }
[ "func", "(", "impl", "*", "adminImpl", ")", "init", "(", ")", "{", "impl", ".", "ctl", "=", "&", "mapper", ".", "Controller", "{", "MapperQueue", ":", "\"", "\"", ",", "// see queue.yaml", "ControlQueue", ":", "\"", "\"", ",", "}", "\n", "for", "_", ",", "m", ":=", "range", "mappers", "{", "// see mappers.go", "impl", ".", "ctl", ".", "RegisterFactory", "(", "m", ".", "mapperID", "(", ")", ",", "m", ".", "newMapper", ")", "\n", "}", "\n", "impl", ".", "ctl", ".", "Install", "(", "impl", ".", "tq", ")", "\n", "}" ]
// init initializes mapper controller and registers mapping tasks.
[ "init", "initializes", "mapper", "controller", "and", "registers", "mapping", "tasks", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/admin/admin.go#L42-L51
8,877
luci/luci-go
cipd/appengine/impl/admin/admin.go
toStatus
func toStatus(err error) error { switch { case err == mapper.ErrNoSuchJob: return status.Errorf(codes.NotFound, "no such mapping job") case transient.Tag.In(err): return status.Errorf(codes.Internal, err.Error()) case err != nil: return status.Errorf(codes.InvalidArgument, err.Error()) default: return nil } }
go
func toStatus(err error) error { switch { case err == mapper.ErrNoSuchJob: return status.Errorf(codes.NotFound, "no such mapping job") case transient.Tag.In(err): return status.Errorf(codes.Internal, err.Error()) case err != nil: return status.Errorf(codes.InvalidArgument, err.Error()) default: return nil } }
[ "func", "toStatus", "(", "err", "error", ")", "error", "{", "switch", "{", "case", "err", "==", "mapper", ".", "ErrNoSuchJob", ":", "return", "status", ".", "Errorf", "(", "codes", ".", "NotFound", ",", "\"", "\"", ")", "\n", "case", "transient", ".", "Tag", ".", "In", "(", "err", ")", ":", "return", "status", ".", "Errorf", "(", "codes", ".", "Internal", ",", "err", ".", "Error", "(", ")", ")", "\n", "case", "err", "!=", "nil", ":", "return", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "err", ".", "Error", "(", ")", ")", "\n", "default", ":", "return", "nil", "\n", "}", "\n", "}" ]
// toStatus converts an error from mapper.Controller to an grpc status. // // Passes nil as is.
[ "toStatus", "converts", "an", "error", "from", "mapper", ".", "Controller", "to", "an", "grpc", "status", ".", "Passes", "nil", "as", "is", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/admin/admin.go#L56-L67
8,878
luci/luci-go
cipd/appengine/impl/admin/admin.go
LaunchJob
func (impl *adminImpl) LaunchJob(c context.Context, cfg *api.JobConfig) (*api.JobID, error) { def, ok := mappers[cfg.Kind] // see mappers.go if !ok { return nil, status.Errorf(codes.InvalidArgument, "unknown mapper kind") } cfgBlob, err := proto.Marshal(cfg) if err != nil { return nil, status.Errorf(codes.Internal, "failed to marshal JobConfig - %s", err) } launchCfg := def.Config launchCfg.Mapper = def.mapperID() launchCfg.Params = cfgBlob jid, err := impl.ctl.LaunchJob(c, &launchCfg) if err != nil { return nil, toStatus(err) } return &api.JobID{JobId: int64(jid)}, nil }
go
func (impl *adminImpl) LaunchJob(c context.Context, cfg *api.JobConfig) (*api.JobID, error) { def, ok := mappers[cfg.Kind] // see mappers.go if !ok { return nil, status.Errorf(codes.InvalidArgument, "unknown mapper kind") } cfgBlob, err := proto.Marshal(cfg) if err != nil { return nil, status.Errorf(codes.Internal, "failed to marshal JobConfig - %s", err) } launchCfg := def.Config launchCfg.Mapper = def.mapperID() launchCfg.Params = cfgBlob jid, err := impl.ctl.LaunchJob(c, &launchCfg) if err != nil { return nil, toStatus(err) } return &api.JobID{JobId: int64(jid)}, nil }
[ "func", "(", "impl", "*", "adminImpl", ")", "LaunchJob", "(", "c", "context", ".", "Context", ",", "cfg", "*", "api", ".", "JobConfig", ")", "(", "*", "api", ".", "JobID", ",", "error", ")", "{", "def", ",", "ok", ":=", "mappers", "[", "cfg", ".", "Kind", "]", "// see mappers.go", "\n", "if", "!", "ok", "{", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n\n", "cfgBlob", ",", "err", ":=", "proto", ".", "Marshal", "(", "cfg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "Internal", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "launchCfg", ":=", "def", ".", "Config", "\n", "launchCfg", ".", "Mapper", "=", "def", ".", "mapperID", "(", ")", "\n", "launchCfg", ".", "Params", "=", "cfgBlob", "\n\n", "jid", ",", "err", ":=", "impl", ".", "ctl", ".", "LaunchJob", "(", "c", ",", "&", "launchCfg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "toStatus", "(", "err", ")", "\n", "}", "\n\n", "return", "&", "api", ".", "JobID", "{", "JobId", ":", "int64", "(", "jid", ")", "}", ",", "nil", "\n", "}" ]
// LaunchJob implements the corresponding RPC method, see the proto doc.
[ "LaunchJob", "implements", "the", "corresponding", "RPC", "method", "see", "the", "proto", "doc", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/admin/admin.go#L70-L91
8,879
luci/luci-go
cipd/appengine/impl/admin/admin.go
AbortJob
func (impl *adminImpl) AbortJob(c context.Context, id *api.JobID) (*empty.Empty, error) { _, err := impl.ctl.AbortJob(c, mapper.JobID(id.JobId)) if err != nil { return nil, toStatus(err) } return &empty.Empty{}, nil }
go
func (impl *adminImpl) AbortJob(c context.Context, id *api.JobID) (*empty.Empty, error) { _, err := impl.ctl.AbortJob(c, mapper.JobID(id.JobId)) if err != nil { return nil, toStatus(err) } return &empty.Empty{}, nil }
[ "func", "(", "impl", "*", "adminImpl", ")", "AbortJob", "(", "c", "context", ".", "Context", ",", "id", "*", "api", ".", "JobID", ")", "(", "*", "empty", ".", "Empty", ",", "error", ")", "{", "_", ",", "err", ":=", "impl", ".", "ctl", ".", "AbortJob", "(", "c", ",", "mapper", ".", "JobID", "(", "id", ".", "JobId", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "toStatus", "(", "err", ")", "\n", "}", "\n", "return", "&", "empty", ".", "Empty", "{", "}", ",", "nil", "\n", "}" ]
// AbortJob implements the corresponding RPC method, see the proto doc.
[ "AbortJob", "implements", "the", "corresponding", "RPC", "method", "see", "the", "proto", "doc", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/admin/admin.go#L94-L100
8,880
luci/luci-go
common/data/chunkstream/view.go
ReadByte
func (r *View) ReadByte() (byte, error) { chunk := r.chunkBytes() if len(chunk) == 0 { return 0, io.EOF } r.Skip(1) return chunk[0], nil }
go
func (r *View) ReadByte() (byte, error) { chunk := r.chunkBytes() if len(chunk) == 0 { return 0, io.EOF } r.Skip(1) return chunk[0], nil }
[ "func", "(", "r", "*", "View", ")", "ReadByte", "(", ")", "(", "byte", ",", "error", ")", "{", "chunk", ":=", "r", ".", "chunkBytes", "(", ")", "\n", "if", "len", "(", "chunk", ")", "==", "0", "{", "return", "0", ",", "io", ".", "EOF", "\n", "}", "\n", "r", ".", "Skip", "(", "1", ")", "\n", "return", "chunk", "[", "0", "]", ",", "nil", "\n", "}" ]
// ReadByte implements io.ByteReader, reading a single byte from the buffer.
[ "ReadByte", "implements", "io", ".", "ByteReader", "reading", "a", "single", "byte", "from", "the", "buffer", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/chunkstream/view.go#L70-L77
8,881
luci/luci-go
common/data/chunkstream/view.go
Skip
func (r *View) Skip(count int64) { for count > 0 { if r.cur == nil { panic(errors.New("cannot skip past end buffer")) } amount := r.chunkRemaining() if count < int64(amount) { amount = int(count) r.cidx += amount } else { // Finished consuming this chunk, move on to the next. r.cur = r.cur.next r.cidx = 0 } count -= int64(amount) r.consumed += int64(amount) r.size -= int64(amount) } }
go
func (r *View) Skip(count int64) { for count > 0 { if r.cur == nil { panic(errors.New("cannot skip past end buffer")) } amount := r.chunkRemaining() if count < int64(amount) { amount = int(count) r.cidx += amount } else { // Finished consuming this chunk, move on to the next. r.cur = r.cur.next r.cidx = 0 } count -= int64(amount) r.consumed += int64(amount) r.size -= int64(amount) } }
[ "func", "(", "r", "*", "View", ")", "Skip", "(", "count", "int64", ")", "{", "for", "count", ">", "0", "{", "if", "r", ".", "cur", "==", "nil", "{", "panic", "(", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n\n", "amount", ":=", "r", ".", "chunkRemaining", "(", ")", "\n", "if", "count", "<", "int64", "(", "amount", ")", "{", "amount", "=", "int", "(", "count", ")", "\n", "r", ".", "cidx", "+=", "amount", "\n", "}", "else", "{", "// Finished consuming this chunk, move on to the next.", "r", ".", "cur", "=", "r", ".", "cur", ".", "next", "\n", "r", ".", "cidx", "=", "0", "\n", "}", "\n\n", "count", "-=", "int64", "(", "amount", ")", "\n", "r", ".", "consumed", "+=", "int64", "(", "amount", ")", "\n", "r", ".", "size", "-=", "int64", "(", "amount", ")", "\n", "}", "\n", "}" ]
// Skip advances the View forwards a fixed number of bytes.
[ "Skip", "advances", "the", "View", "forwards", "a", "fixed", "number", "of", "bytes", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/chunkstream/view.go#L91-L111
8,882
luci/luci-go
common/data/chunkstream/view.go
Index
func (r *View) Index(needle []byte) int64 { if r.Remaining() == 0 { return -1 } if len(needle) == 0 { return 0 } rc := r.Clone() if !rc.indexDestructive(needle) { return -1 } return rc.consumed - r.consumed }
go
func (r *View) Index(needle []byte) int64 { if r.Remaining() == 0 { return -1 } if len(needle) == 0 { return 0 } rc := r.Clone() if !rc.indexDestructive(needle) { return -1 } return rc.consumed - r.consumed }
[ "func", "(", "r", "*", "View", ")", "Index", "(", "needle", "[", "]", "byte", ")", "int64", "{", "if", "r", ".", "Remaining", "(", ")", "==", "0", "{", "return", "-", "1", "\n", "}", "\n", "if", "len", "(", "needle", ")", "==", "0", "{", "return", "0", "\n", "}", "\n\n", "rc", ":=", "r", ".", "Clone", "(", ")", "\n", "if", "!", "rc", ".", "indexDestructive", "(", "needle", ")", "{", "return", "-", "1", "\n", "}", "\n", "return", "rc", ".", "consumed", "-", "r", ".", "consumed", "\n", "}" ]
// Index scans the View for the specified needle bytes. If they are // found, their index in the View is returned. Otherwise, Index returns // -1. // // The View is not modified during the search.
[ "Index", "scans", "the", "View", "for", "the", "specified", "needle", "bytes", ".", "If", "they", "are", "found", "their", "index", "in", "the", "View", "is", "returned", ".", "Otherwise", "Index", "returns", "-", "1", ".", "The", "View", "is", "not", "modified", "during", "the", "search", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/chunkstream/view.go#L118-L131
8,883
luci/luci-go
common/data/chunkstream/view.go
indexDestructive
func (r *View) indexDestructive(needle []byte) bool { tbuf := make([]byte, 2*len(needle)) idx := int64(0) for { data := r.chunkBytes() if len(data) == 0 { return false } // Scan the current chunk for needle. Note that if the current chunk is too // small to hold needle, this is a no-op. if idx = int64(bytes.Index(data, needle)); idx >= 0 { r.Skip(idx) return true } if len(data) > len(needle) { // The needle is definitely not in this space. r.Skip(int64(len(data) - len(needle))) } // needle isn't in the current chunk; however, it may begin at the end of // the current chunk and complete in future chunks. // // We will scan a space twice the size of the needle, as otherwise, this // would end up scanning for one possibility, incrementing by one, and // repeating via 'for' loop iterations. // // Afterwards, we advance only the size of the needle, as we don't want to // preclude the needle starting after our last scan range. // // For example, to find needle "NDL": // // AAAAND|L|AAAA // |------|^- [NDLAAA], 0 // // AAAAN|D|NDL|AAAA // |------| [ANDNDL], 3 // // AAAA|A|A|NDL // |-------| [AAAAND], -1, consume 3 => A|NDL| // // // Note that we perform the read with a cloned View so we don't // actually consume this data. pr := r.Clone() amt, _ := pr.Read(tbuf) if amt < len(needle) { // All remaining buffers cannot hold the needle. return false } if idx = int64(bytes.Index(tbuf[:amt], needle)); idx >= 0 { r.Skip(idx) return true } r.Skip(int64(len(needle))) } }
go
func (r *View) indexDestructive(needle []byte) bool { tbuf := make([]byte, 2*len(needle)) idx := int64(0) for { data := r.chunkBytes() if len(data) == 0 { return false } // Scan the current chunk for needle. Note that if the current chunk is too // small to hold needle, this is a no-op. if idx = int64(bytes.Index(data, needle)); idx >= 0 { r.Skip(idx) return true } if len(data) > len(needle) { // The needle is definitely not in this space. r.Skip(int64(len(data) - len(needle))) } // needle isn't in the current chunk; however, it may begin at the end of // the current chunk and complete in future chunks. // // We will scan a space twice the size of the needle, as otherwise, this // would end up scanning for one possibility, incrementing by one, and // repeating via 'for' loop iterations. // // Afterwards, we advance only the size of the needle, as we don't want to // preclude the needle starting after our last scan range. // // For example, to find needle "NDL": // // AAAAND|L|AAAA // |------|^- [NDLAAA], 0 // // AAAAN|D|NDL|AAAA // |------| [ANDNDL], 3 // // AAAA|A|A|NDL // |-------| [AAAAND], -1, consume 3 => A|NDL| // // // Note that we perform the read with a cloned View so we don't // actually consume this data. pr := r.Clone() amt, _ := pr.Read(tbuf) if amt < len(needle) { // All remaining buffers cannot hold the needle. return false } if idx = int64(bytes.Index(tbuf[:amt], needle)); idx >= 0 { r.Skip(idx) return true } r.Skip(int64(len(needle))) } }
[ "func", "(", "r", "*", "View", ")", "indexDestructive", "(", "needle", "[", "]", "byte", ")", "bool", "{", "tbuf", ":=", "make", "(", "[", "]", "byte", ",", "2", "*", "len", "(", "needle", ")", ")", "\n", "idx", ":=", "int64", "(", "0", ")", "\n", "for", "{", "data", ":=", "r", ".", "chunkBytes", "(", ")", "\n", "if", "len", "(", "data", ")", "==", "0", "{", "return", "false", "\n", "}", "\n\n", "// Scan the current chunk for needle. Note that if the current chunk is too", "// small to hold needle, this is a no-op.", "if", "idx", "=", "int64", "(", "bytes", ".", "Index", "(", "data", ",", "needle", ")", ")", ";", "idx", ">=", "0", "{", "r", ".", "Skip", "(", "idx", ")", "\n", "return", "true", "\n", "}", "\n", "if", "len", "(", "data", ")", ">", "len", "(", "needle", ")", "{", "// The needle is definitely not in this space.", "r", ".", "Skip", "(", "int64", "(", "len", "(", "data", ")", "-", "len", "(", "needle", ")", ")", ")", "\n", "}", "\n\n", "// needle isn't in the current chunk; however, it may begin at the end of", "// the current chunk and complete in future chunks.", "//", "// We will scan a space twice the size of the needle, as otherwise, this", "// would end up scanning for one possibility, incrementing by one, and", "// repeating via 'for' loop iterations.", "//", "// Afterwards, we advance only the size of the needle, as we don't want to", "// preclude the needle starting after our last scan range.", "//", "// For example, to find needle \"NDL\":", "//", "// AAAAND|L|AAAA", "// |------|^- [NDLAAA], 0", "//", "// AAAAN|D|NDL|AAAA", "// |------| [ANDNDL], 3", "//", "// AAAA|A|A|NDL", "// |-------| [AAAAND], -1, consume 3 => A|NDL|", "//", "//", "// Note that we perform the read with a cloned View so we don't", "// actually consume this data.", "pr", ":=", "r", ".", "Clone", "(", ")", "\n", "amt", ",", "_", ":=", "pr", ".", "Read", "(", "tbuf", ")", "\n", "if", "amt", "<", "len", "(", "needle", ")", "{", "// All remaining buffers cannot hold the needle.", "return", "false", "\n", "}", "\n\n", "if", "idx", "=", "int64", "(", "bytes", ".", "Index", "(", "tbuf", "[", ":", "amt", "]", ",", "needle", ")", ")", ";", "idx", ">=", "0", "{", "r", ".", "Skip", "(", "idx", ")", "\n", "return", "true", "\n", "}", "\n", "r", ".", "Skip", "(", "int64", "(", "len", "(", "needle", ")", ")", ")", "\n", "}", "\n", "}" ]
// indexDestructive implements Index by actively mutating the View. // // It returns true if the needle was found, and false if not. The view will be // mutated regardless.
[ "indexDestructive", "implements", "Index", "by", "actively", "mutating", "the", "View", ".", "It", "returns", "true", "if", "the", "needle", "was", "found", "and", "false", "if", "not", ".", "The", "view", "will", "be", "mutated", "regardless", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/chunkstream/view.go#L137-L194
8,884
luci/luci-go
common/data/chunkstream/view.go
CloneLimit
func (r *View) CloneLimit(limit int64) *View { c := *r if c.size > limit { c.size = limit } return &c }
go
func (r *View) CloneLimit(limit int64) *View { c := *r if c.size > limit { c.size = limit } return &c }
[ "func", "(", "r", "*", "View", ")", "CloneLimit", "(", "limit", "int64", ")", "*", "View", "{", "c", ":=", "*", "r", "\n", "if", "c", ".", "size", ">", "limit", "{", "c", ".", "size", "=", "limit", "\n", "}", "\n", "return", "&", "c", "\n", "}" ]
// CloneLimit returns a copy of the View view, optionally truncating it. // // The clone is bound to the same underlying Buffer as the source.
[ "CloneLimit", "returns", "a", "copy", "of", "the", "View", "view", "optionally", "truncating", "it", ".", "The", "clone", "is", "bound", "to", "the", "same", "underlying", "Buffer", "as", "the", "source", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/chunkstream/view.go#L206-L212
8,885
luci/luci-go
appengine/gaesettings/gaesettings.go
GetConsistencyTime
func (s Storage) GetConsistencyTime(c context.Context) (time.Time, error) { c = defaultContext(c) latest := latestSettings() switch err := ds.Get(c, &latest); err { case nil: return latest.When.Add(s.expirationDuration(c)), nil case ds.ErrNoSuchEntity: return time.Time{}, nil default: return time.Time{}, transient.Tag.Apply(err) } }
go
func (s Storage) GetConsistencyTime(c context.Context) (time.Time, error) { c = defaultContext(c) latest := latestSettings() switch err := ds.Get(c, &latest); err { case nil: return latest.When.Add(s.expirationDuration(c)), nil case ds.ErrNoSuchEntity: return time.Time{}, nil default: return time.Time{}, transient.Tag.Apply(err) } }
[ "func", "(", "s", "Storage", ")", "GetConsistencyTime", "(", "c", "context", ".", "Context", ")", "(", "time", ".", "Time", ",", "error", ")", "{", "c", "=", "defaultContext", "(", "c", ")", "\n", "latest", ":=", "latestSettings", "(", ")", "\n", "switch", "err", ":=", "ds", ".", "Get", "(", "c", ",", "&", "latest", ")", ";", "err", "{", "case", "nil", ":", "return", "latest", ".", "When", ".", "Add", "(", "s", ".", "expirationDuration", "(", "c", ")", ")", ",", "nil", "\n", "case", "ds", ".", "ErrNoSuchEntity", ":", "return", "time", ".", "Time", "{", "}", ",", "nil", "\n", "default", ":", "return", "time", ".", "Time", "{", "}", ",", "transient", ".", "Tag", ".", "Apply", "(", "err", ")", "\n", "}", "\n", "}" ]
// GetConsistencyTime returns "last modification time" + "expiration period". // // It indicates moment in time when last setting change is fully propagated to // all instances. // // Returns zero time if there are no settings stored.
[ "GetConsistencyTime", "returns", "last", "modification", "time", "+", "expiration", "period", ".", "It", "indicates", "moment", "in", "time", "when", "last", "setting", "change", "is", "fully", "propagated", "to", "all", "instances", ".", "Returns", "zero", "time", "if", "there", "are", "no", "settings", "stored", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaesettings/gaesettings.go#L174-L185
8,886
luci/luci-go
starlark/starlarkproto/type.go
onAlternativePicked
func (g *oneofGroup) onAlternativePicked(alt *oneofAlternative, dict starlark.StringDict) { for _, a := range g.alternatives { if a != alt { delete(dict, a.name) } } }
go
func (g *oneofGroup) onAlternativePicked(alt *oneofAlternative, dict starlark.StringDict) { for _, a := range g.alternatives { if a != alt { delete(dict, a.name) } } }
[ "func", "(", "g", "*", "oneofGroup", ")", "onAlternativePicked", "(", "alt", "*", "oneofAlternative", ",", "dict", "starlark", ".", "StringDict", ")", "{", "for", "_", ",", "a", ":=", "range", "g", ".", "alternatives", "{", "if", "a", "!=", "alt", "{", "delete", "(", "dict", ",", "a", ".", "name", ")", "\n", "}", "\n", "}", "\n", "}" ]
// onAlternativePicked is called when one oneof alternative was set to. // // It clears all others.
[ "onAlternativePicked", "is", "called", "when", "one", "oneof", "alternative", "was", "set", "to", ".", "It", "clears", "all", "others", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/starlarkproto/type.go#L302-L308
8,887
luci/luci-go
starlark/starlarkproto/type.go
onReadingAlternative
func (g *oneofGroup) onReadingAlternative(alt *oneofAlternative, msg reflect.Value) reflect.Value { switch wrap := msg.Field(g.fieldIdx); { case wrap.IsNil(): return reflect.Value{} // no alternatives are set case wrap.Elem().Type() != alt.outerTyp: return reflect.Value{} // some other alternative is set default: return wrap.Elem().Elem().Field(0) // ~ (*msg.Wrapper).A } }
go
func (g *oneofGroup) onReadingAlternative(alt *oneofAlternative, msg reflect.Value) reflect.Value { switch wrap := msg.Field(g.fieldIdx); { case wrap.IsNil(): return reflect.Value{} // no alternatives are set case wrap.Elem().Type() != alt.outerTyp: return reflect.Value{} // some other alternative is set default: return wrap.Elem().Elem().Field(0) // ~ (*msg.Wrapper).A } }
[ "func", "(", "g", "*", "oneofGroup", ")", "onReadingAlternative", "(", "alt", "*", "oneofAlternative", ",", "msg", "reflect", ".", "Value", ")", "reflect", ".", "Value", "{", "switch", "wrap", ":=", "msg", ".", "Field", "(", "g", ".", "fieldIdx", ")", ";", "{", "case", "wrap", ".", "IsNil", "(", ")", ":", "return", "reflect", ".", "Value", "{", "}", "// no alternatives are set", "\n", "case", "wrap", ".", "Elem", "(", ")", ".", "Type", "(", ")", "!=", "alt", ".", "outerTyp", ":", "return", "reflect", ".", "Value", "{", "}", "// some other alternative is set", "\n", "default", ":", "return", "wrap", ".", "Elem", "(", ")", ".", "Elem", "(", ")", ".", "Field", "(", "0", ")", "// ~ (*msg.Wrapper).A", "\n", "}", "\n", "}" ]
// onReadingAlternative is called when reading a value from the proto message. // // If returns a valid reflect.Value if the given alternative is realized in // the 'msg' or an invalid zero reflect.Value otherwise.
[ "onReadingAlternative", "is", "called", "when", "reading", "a", "value", "from", "the", "proto", "message", ".", "If", "returns", "a", "valid", "reflect", ".", "Value", "if", "the", "given", "alternative", "is", "realized", "in", "the", "msg", "or", "an", "invalid", "zero", "reflect", ".", "Value", "otherwise", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/starlarkproto/type.go#L324-L333
8,888
luci/luci-go
lucictx/lucictx.go
Get
func Get(ctx context.Context, section string, out interface{}) error { _, err := Lookup(ctx, section, out) return err }
go
func Get(ctx context.Context, section string, out interface{}) error { _, err := Lookup(ctx, section, out) return err }
[ "func", "Get", "(", "ctx", "context", ".", "Context", ",", "section", "string", ",", "out", "interface", "{", "}", ")", "error", "{", "_", ",", "err", ":=", "Lookup", "(", "ctx", ",", "section", ",", "out", ")", "\n", "return", "err", "\n", "}" ]
// Get retrieves the current section from the current LUCI_CONTEXT, and // deserializes it into out. Out may be any target for json.Unmarshal. If the // section exists, it deserializes it into the provided out object. If not, then // out is unmodified.
[ "Get", "retrieves", "the", "current", "section", "from", "the", "current", "LUCI_CONTEXT", "and", "deserializes", "it", "into", "out", ".", "Out", "may", "be", "any", "target", "for", "json", ".", "Unmarshal", ".", "If", "the", "section", "exists", "it", "deserializes", "it", "into", "the", "provided", "out", "object", ".", "If", "not", "then", "out", "is", "unmodified", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucictx/lucictx.go#L126-L129
8,889
luci/luci-go
lucictx/lucictx.go
Set
func Set(ctx context.Context, section string, in interface{}) (context.Context, error) { var err error var data json.RawMessage if in != nil { if data, err = json.Marshal(in); err != nil { return ctx, err } if data[0] != '{' { return ctx, errors.New("LUCI_CONTEXT sections must always be JSON Objects") } } cur := getCurrent(ctx) if _, alreadyHas := cur.sections[section]; data == nil && !alreadyHas { // Removing a section which is already missing is a no-op return ctx, nil } newLctx := cur.clone() if data == nil { delete(newLctx.sections, section) } else { newLctx.sections[section] = &data } return context.WithValue(ctx, &lctxKey, newLctx), nil }
go
func Set(ctx context.Context, section string, in interface{}) (context.Context, error) { var err error var data json.RawMessage if in != nil { if data, err = json.Marshal(in); err != nil { return ctx, err } if data[0] != '{' { return ctx, errors.New("LUCI_CONTEXT sections must always be JSON Objects") } } cur := getCurrent(ctx) if _, alreadyHas := cur.sections[section]; data == nil && !alreadyHas { // Removing a section which is already missing is a no-op return ctx, nil } newLctx := cur.clone() if data == nil { delete(newLctx.sections, section) } else { newLctx.sections[section] = &data } return context.WithValue(ctx, &lctxKey, newLctx), nil }
[ "func", "Set", "(", "ctx", "context", ".", "Context", ",", "section", "string", ",", "in", "interface", "{", "}", ")", "(", "context", ".", "Context", ",", "error", ")", "{", "var", "err", "error", "\n", "var", "data", "json", ".", "RawMessage", "\n", "if", "in", "!=", "nil", "{", "if", "data", ",", "err", "=", "json", ".", "Marshal", "(", "in", ")", ";", "err", "!=", "nil", "{", "return", "ctx", ",", "err", "\n", "}", "\n", "if", "data", "[", "0", "]", "!=", "'{'", "{", "return", "ctx", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "cur", ":=", "getCurrent", "(", "ctx", ")", "\n", "if", "_", ",", "alreadyHas", ":=", "cur", ".", "sections", "[", "section", "]", ";", "data", "==", "nil", "&&", "!", "alreadyHas", "{", "// Removing a section which is already missing is a no-op", "return", "ctx", ",", "nil", "\n", "}", "\n", "newLctx", ":=", "cur", ".", "clone", "(", ")", "\n", "if", "data", "==", "nil", "{", "delete", "(", "newLctx", ".", "sections", ",", "section", ")", "\n", "}", "else", "{", "newLctx", ".", "sections", "[", "section", "]", "=", "&", "data", "\n", "}", "\n", "return", "context", ".", "WithValue", "(", "ctx", ",", "&", "lctxKey", ",", "newLctx", ")", ",", "nil", "\n", "}" ]
// Set writes the json serialization of `in` as the given section into the // LUCI_CONTEXT, returning the new ctx object containing it. This ctx can be // passed to Export to serialize it to disk. // // If in is nil, it will clear that section of the LUCI_CONTEXT. // // The returned context is always safe to use, even if this returns an error. // This only returns an error if `in` cannot be marshalled to a JSON Object.
[ "Set", "writes", "the", "json", "serialization", "of", "in", "as", "the", "given", "section", "into", "the", "LUCI_CONTEXT", "returning", "the", "new", "ctx", "object", "containing", "it", ".", "This", "ctx", "can", "be", "passed", "to", "Export", "to", "serialize", "it", "to", "disk", ".", "If", "in", "is", "nil", "it", "will", "clear", "that", "section", "of", "the", "LUCI_CONTEXT", ".", "The", "returned", "context", "is", "always", "safe", "to", "use", "even", "if", "this", "returns", "an", "error", ".", "This", "only", "returns", "an", "error", "if", "in", "cannot", "be", "marshalled", "to", "a", "JSON", "Object", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucictx/lucictx.go#L151-L174
8,890
luci/luci-go
appengine/gaesecrets/gaesecrets.go
Use
func Use(c context.Context, cfg *Config) context.Context { config := Config{} if cfg != nil { config = *cfg } if strings.Contains(config.Prefix, ":") { panic("forbidden character ':' in Prefix") } if config.SecretLen == 0 { config.SecretLen = 32 } if config.Entropy == nil { config.Entropy = rand.Reader } return secrets.SetFactory(c, func(ic context.Context) secrets.Store { return &storeImpl{config, ic} }) }
go
func Use(c context.Context, cfg *Config) context.Context { config := Config{} if cfg != nil { config = *cfg } if strings.Contains(config.Prefix, ":") { panic("forbidden character ':' in Prefix") } if config.SecretLen == 0 { config.SecretLen = 32 } if config.Entropy == nil { config.Entropy = rand.Reader } return secrets.SetFactory(c, func(ic context.Context) secrets.Store { return &storeImpl{config, ic} }) }
[ "func", "Use", "(", "c", "context", ".", "Context", ",", "cfg", "*", "Config", ")", "context", ".", "Context", "{", "config", ":=", "Config", "{", "}", "\n", "if", "cfg", "!=", "nil", "{", "config", "=", "*", "cfg", "\n", "}", "\n", "if", "strings", ".", "Contains", "(", "config", ".", "Prefix", ",", "\"", "\"", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "config", ".", "SecretLen", "==", "0", "{", "config", ".", "SecretLen", "=", "32", "\n", "}", "\n", "if", "config", ".", "Entropy", "==", "nil", "{", "config", ".", "Entropy", "=", "rand", ".", "Reader", "\n", "}", "\n", "return", "secrets", ".", "SetFactory", "(", "c", ",", "func", "(", "ic", "context", ".", "Context", ")", "secrets", ".", "Store", "{", "return", "&", "storeImpl", "{", "config", ",", "ic", "}", "\n", "}", ")", "\n", "}" ]
// Use injects the GAE implementation of secrets.Store into the context. // The context must be configured with GAE datastore implementation already.
[ "Use", "injects", "the", "GAE", "implementation", "of", "secrets", ".", "Store", "into", "the", "context", ".", "The", "context", "must", "be", "configured", "with", "GAE", "datastore", "implementation", "already", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaesecrets/gaesecrets.go#L55-L72
8,891
luci/luci-go
appengine/gaesecrets/gaesecrets.go
GetSecret
func (s *storeImpl) GetSecret(k secrets.Key) (secrets.Secret, error) { secret, err := secretsCache.LRU(s.ctx).GetOrCreate(s.ctx, s.cfg.Prefix+":"+string(k), func() (interface{}, time.Duration, error) { secret, err := s.getSecretFromDatastore(k) if err != nil { return nil, 0, err } return secret, cacheExp, nil }) if err != nil { return secrets.Secret{}, err } return secret.(secrets.Secret).Clone(), nil }
go
func (s *storeImpl) GetSecret(k secrets.Key) (secrets.Secret, error) { secret, err := secretsCache.LRU(s.ctx).GetOrCreate(s.ctx, s.cfg.Prefix+":"+string(k), func() (interface{}, time.Duration, error) { secret, err := s.getSecretFromDatastore(k) if err != nil { return nil, 0, err } return secret, cacheExp, nil }) if err != nil { return secrets.Secret{}, err } return secret.(secrets.Secret).Clone(), nil }
[ "func", "(", "s", "*", "storeImpl", ")", "GetSecret", "(", "k", "secrets", ".", "Key", ")", "(", "secrets", ".", "Secret", ",", "error", ")", "{", "secret", ",", "err", ":=", "secretsCache", ".", "LRU", "(", "s", ".", "ctx", ")", ".", "GetOrCreate", "(", "s", ".", "ctx", ",", "s", ".", "cfg", ".", "Prefix", "+", "\"", "\"", "+", "string", "(", "k", ")", ",", "func", "(", ")", "(", "interface", "{", "}", ",", "time", ".", "Duration", ",", "error", ")", "{", "secret", ",", "err", ":=", "s", ".", "getSecretFromDatastore", "(", "k", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "err", "\n", "}", "\n", "return", "secret", ",", "cacheExp", ",", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "secrets", ".", "Secret", "{", "}", ",", "err", "\n", "}", "\n", "return", "secret", ".", "(", "secrets", ".", "Secret", ")", ".", "Clone", "(", ")", ",", "nil", "\n", "}" ]
// GetSecret returns a secret by its key.
[ "GetSecret", "returns", "a", "secret", "by", "its", "key", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaesecrets/gaesecrets.go#L84-L96
8,892
luci/luci-go
client/cmd/swarming/trigger.go
mapToArray
func mapToArray(m stringmapflag.Value) []*swarming.SwarmingRpcsStringPair { a := make([]*swarming.SwarmingRpcsStringPair, 0, len(m)) for k, v := range m { a = append(a, &swarming.SwarmingRpcsStringPair{Key: k, Value: v}) } sort.Sort(array(a)) return a }
go
func mapToArray(m stringmapflag.Value) []*swarming.SwarmingRpcsStringPair { a := make([]*swarming.SwarmingRpcsStringPair, 0, len(m)) for k, v := range m { a = append(a, &swarming.SwarmingRpcsStringPair{Key: k, Value: v}) } sort.Sort(array(a)) return a }
[ "func", "mapToArray", "(", "m", "stringmapflag", ".", "Value", ")", "[", "]", "*", "swarming", ".", "SwarmingRpcsStringPair", "{", "a", ":=", "make", "(", "[", "]", "*", "swarming", ".", "SwarmingRpcsStringPair", ",", "0", ",", "len", "(", "m", ")", ")", "\n", "for", "k", ",", "v", ":=", "range", "m", "{", "a", "=", "append", "(", "a", ",", "&", "swarming", ".", "SwarmingRpcsStringPair", "{", "Key", ":", "k", ",", "Value", ":", "v", "}", ")", "\n", "}", "\n\n", "sort", ".", "Sort", "(", "array", "(", "a", ")", ")", "\n", "return", "a", "\n", "}" ]
// mapToArray converts a stringmapflag.Value into an array of // swarming.SwarmingRpcsStringPair, sorted by key and then value.
[ "mapToArray", "converts", "a", "stringmapflag", ".", "Value", "into", "an", "array", "of", "swarming", ".", "SwarmingRpcsStringPair", "sorted", "by", "key", "and", "then", "value", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/cmd/swarming/trigger.go#L62-L70
8,893
luci/luci-go
appengine/gaeauth/server/internal/authdbimpl/helpers.go
setAuthService
func setAuthService(c context.Context, s authService) context.Context { return context.WithValue(c, contextKey(0), s) }
go
func setAuthService(c context.Context, s authService) context.Context { return context.WithValue(c, contextKey(0), s) }
[ "func", "setAuthService", "(", "c", "context", ".", "Context", ",", "s", "authService", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "c", ",", "contextKey", "(", "0", ")", ",", "s", ")", "\n", "}" ]
// setAuthService injects authService implementation into the context. // // Used in unit tests.
[ "setAuthService", "injects", "authService", "implementation", "into", "the", "context", ".", "Used", "in", "unit", "tests", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaeauth/server/internal/authdbimpl/helpers.go#L41-L43
8,894
luci/luci-go
lucicfg/vars/vars.go
OpenScope
func (v *Vars) OpenScope(th *starlark.Thread) { v.scopes = append(v.scopes, &scope{thread: th}) }
go
func (v *Vars) OpenScope(th *starlark.Thread) { v.scopes = append(v.scopes, &scope{thread: th}) }
[ "func", "(", "v", "*", "Vars", ")", "OpenScope", "(", "th", "*", "starlark", ".", "Thread", ")", "{", "v", ".", "scopes", "=", "append", "(", "v", ".", "scopes", ",", "&", "scope", "{", "thread", ":", "th", "}", ")", "\n", "}" ]
// OpenScope opens a new scope for variables. // // All changes to variables' values made within this scope are discarded when it // is closed.
[ "OpenScope", "opens", "a", "new", "scope", "for", "variables", ".", "All", "changes", "to", "variables", "values", "made", "within", "this", "scope", "are", "discarded", "when", "it", "is", "closed", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/vars/vars.go#L73-L75
8,895
luci/luci-go
lucicfg/vars/vars.go
CloseScope
func (v *Vars) CloseScope(th *starlark.Thread) { switch { case len(v.scopes) == 0: panic("unexpected CloseScope call without matching OpenScope") case v.scopes[len(v.scopes)-1].thread != th: // This check may fail if Interpreter is using multiple goroutines to // execute 'exec's. It shouldn't. If this ever happens, we'll need to move // 'v.scopes' to Starlark's TLS. OpenScope will need a way to access TLS // of a thread that called 'exec', not only TLS of a new thread, as it does // now. panic("unexpected starlark thread") default: v.scopes = v.scopes[:len(v.scopes)-1] } }
go
func (v *Vars) CloseScope(th *starlark.Thread) { switch { case len(v.scopes) == 0: panic("unexpected CloseScope call without matching OpenScope") case v.scopes[len(v.scopes)-1].thread != th: // This check may fail if Interpreter is using multiple goroutines to // execute 'exec's. It shouldn't. If this ever happens, we'll need to move // 'v.scopes' to Starlark's TLS. OpenScope will need a way to access TLS // of a thread that called 'exec', not only TLS of a new thread, as it does // now. panic("unexpected starlark thread") default: v.scopes = v.scopes[:len(v.scopes)-1] } }
[ "func", "(", "v", "*", "Vars", ")", "CloseScope", "(", "th", "*", "starlark", ".", "Thread", ")", "{", "switch", "{", "case", "len", "(", "v", ".", "scopes", ")", "==", "0", ":", "panic", "(", "\"", "\"", ")", "\n", "case", "v", ".", "scopes", "[", "len", "(", "v", ".", "scopes", ")", "-", "1", "]", ".", "thread", "!=", "th", ":", "// This check may fail if Interpreter is using multiple goroutines to", "// execute 'exec's. It shouldn't. If this ever happens, we'll need to move", "// 'v.scopes' to Starlark's TLS. OpenScope will need a way to access TLS", "// of a thread that called 'exec', not only TLS of a new thread, as it does", "// now.", "panic", "(", "\"", "\"", ")", "\n", "default", ":", "v", ".", "scopes", "=", "v", ".", "scopes", "[", ":", "len", "(", "v", ".", "scopes", ")", "-", "1", "]", "\n", "}", "\n", "}" ]
// CloseScope discards changes made to variables since the matching OpenScope.
[ "CloseScope", "discards", "changes", "made", "to", "variables", "since", "the", "matching", "OpenScope", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/vars/vars.go#L78-L92
8,896
luci/luci-go
lucicfg/vars/vars.go
ClearValues
func (v *Vars) ClearValues() { for _, s := range v.scopes { s.values = nil } }
go
func (v *Vars) ClearValues() { for _, s := range v.scopes { s.values = nil } }
[ "func", "(", "v", "*", "Vars", ")", "ClearValues", "(", ")", "{", "for", "_", ",", "s", ":=", "range", "v", ".", "scopes", "{", "s", ".", "values", "=", "nil", "\n", "}", "\n", "}" ]
// ClearValues resets values of all variables, in all scopes. // // Should be used only from tests that want a clean slate.
[ "ClearValues", "resets", "values", "of", "all", "variables", "in", "all", "scopes", ".", "Should", "be", "used", "only", "from", "tests", "that", "want", "a", "clean", "slate", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/vars/vars.go#L97-L101
8,897
luci/luci-go
lucicfg/vars/vars.go
checkVarsAccess
func (v *Vars) checkVarsAccess(th *starlark.Thread, id ID) error { switch { case interpreter.GetThreadKind(th) != interpreter.ThreadExecing: return fmt.Errorf("only code that is being exec'ed is allowed to get or set variables") case len(v.scopes) == 0: return fmt.Errorf("not inside an exec scope") // shouldn't be possible case id >= v.next: return fmt.Errorf("unknown variable") // shouldn't be possible default: return nil } }
go
func (v *Vars) checkVarsAccess(th *starlark.Thread, id ID) error { switch { case interpreter.GetThreadKind(th) != interpreter.ThreadExecing: return fmt.Errorf("only code that is being exec'ed is allowed to get or set variables") case len(v.scopes) == 0: return fmt.Errorf("not inside an exec scope") // shouldn't be possible case id >= v.next: return fmt.Errorf("unknown variable") // shouldn't be possible default: return nil } }
[ "func", "(", "v", "*", "Vars", ")", "checkVarsAccess", "(", "th", "*", "starlark", ".", "Thread", ",", "id", "ID", ")", "error", "{", "switch", "{", "case", "interpreter", ".", "GetThreadKind", "(", "th", ")", "!=", "interpreter", ".", "ThreadExecing", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "case", "len", "(", "v", ".", "scopes", ")", "==", "0", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "// shouldn't be possible", "\n", "case", "id", ">=", "v", ".", "next", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "// shouldn't be possible", "\n", "default", ":", "return", "nil", "\n", "}", "\n", "}" ]
// checkVarsAccess verifies the variable is being used in an allowed context.
[ "checkVarsAccess", "verifies", "the", "variable", "is", "being", "used", "in", "an", "allowed", "context", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/vars/vars.go#L157-L168
8,898
luci/luci-go
lucicfg/vars/vars.go
lookup
func (v *Vars) lookup(id ID) *varValue { for idx := len(v.scopes) - 1; idx >= 0; idx-- { if val, ok := v.scopes[idx].values[id]; ok { return &val } } return nil }
go
func (v *Vars) lookup(id ID) *varValue { for idx := len(v.scopes) - 1; idx >= 0; idx-- { if val, ok := v.scopes[idx].values[id]; ok { return &val } } return nil }
[ "func", "(", "v", "*", "Vars", ")", "lookup", "(", "id", "ID", ")", "*", "varValue", "{", "for", "idx", ":=", "len", "(", "v", ".", "scopes", ")", "-", "1", ";", "idx", ">=", "0", ";", "idx", "--", "{", "if", "val", ",", "ok", ":=", "v", ".", "scopes", "[", "idx", "]", ".", "values", "[", "id", "]", ";", "ok", "{", "return", "&", "val", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// lookup finds the variable's value in the current scope or any of parent // scopes.
[ "lookup", "finds", "the", "variable", "s", "value", "in", "the", "current", "scope", "or", "any", "of", "parent", "scopes", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/vars/vars.go#L172-L179
8,899
luci/luci-go
lucicfg/vars/vars.go
assign
func (v *Vars) assign(th *starlark.Thread, id ID, value starlark.Value, auto bool) error { // Forbid sneaky cross-scope communication through in-place mutations of the // variable's value. value.Freeze() // Remember where assignment happened, for the error message in Set(). trace, err := builtins.CaptureStacktrace(th, 0) if err != nil { return err } // Set in the innermost scope. scope := v.scopes[len(v.scopes)-1] if scope.values == nil { scope.values = make(map[ID]varValue, 1) } scope.values[id] = varValue{value, trace, auto} return nil }
go
func (v *Vars) assign(th *starlark.Thread, id ID, value starlark.Value, auto bool) error { // Forbid sneaky cross-scope communication through in-place mutations of the // variable's value. value.Freeze() // Remember where assignment happened, for the error message in Set(). trace, err := builtins.CaptureStacktrace(th, 0) if err != nil { return err } // Set in the innermost scope. scope := v.scopes[len(v.scopes)-1] if scope.values == nil { scope.values = make(map[ID]varValue, 1) } scope.values[id] = varValue{value, trace, auto} return nil }
[ "func", "(", "v", "*", "Vars", ")", "assign", "(", "th", "*", "starlark", ".", "Thread", ",", "id", "ID", ",", "value", "starlark", ".", "Value", ",", "auto", "bool", ")", "error", "{", "// Forbid sneaky cross-scope communication through in-place mutations of the", "// variable's value.", "value", ".", "Freeze", "(", ")", "\n\n", "// Remember where assignment happened, for the error message in Set().", "trace", ",", "err", ":=", "builtins", ".", "CaptureStacktrace", "(", "th", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Set in the innermost scope.", "scope", ":=", "v", ".", "scopes", "[", "len", "(", "v", ".", "scopes", ")", "-", "1", "]", "\n", "if", "scope", ".", "values", "==", "nil", "{", "scope", ".", "values", "=", "make", "(", "map", "[", "ID", "]", "varValue", ",", "1", ")", "\n", "}", "\n", "scope", ".", "values", "[", "id", "]", "=", "varValue", "{", "value", ",", "trace", ",", "auto", "}", "\n", "return", "nil", "\n", "}" ]
// assign sets the variable's value in the innermost scope.
[ "assign", "sets", "the", "variable", "s", "value", "in", "the", "innermost", "scope", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/vars/vars.go#L182-L200