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
|
---|---|---|---|---|---|---|---|---|---|---|---|
9,000 | luci/luci-go | milo/api/buildbot/structs.go | Experimental | func (b *Build) Experimental() bool {
v, _ := b.PropertyValue("$recipe_engine/runtime").(map[string]interface{})
return v["is_experimental"] == true
} | go | func (b *Build) Experimental() bool {
v, _ := b.PropertyValue("$recipe_engine/runtime").(map[string]interface{})
return v["is_experimental"] == true
} | [
"func",
"(",
"b",
"*",
"Build",
")",
"Experimental",
"(",
")",
"bool",
"{",
"v",
",",
"_",
":=",
"b",
".",
"PropertyValue",
"(",
"\"",
"\"",
")",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"return",
"v",
"[",
"\"",
"\"",
"]",
"==",
"true",
"\n",
"}"
] | // Experimental returns true if b is experimental. | [
"Experimental",
"returns",
"true",
"if",
"b",
"is",
"experimental",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/api/buildbot/structs.go#L198-L201 |
9,001 | luci/luci-go | lucicfg/graph/graph.go | backtrace | func backtrace(err error, t *builtins.CapturedStacktrace) string {
return t.String() + "Error: " + err.Error()
} | go | func backtrace(err error, t *builtins.CapturedStacktrace) string {
return t.String() + "Error: " + err.Error()
} | [
"func",
"backtrace",
"(",
"err",
"error",
",",
"t",
"*",
"builtins",
".",
"CapturedStacktrace",
")",
"string",
"{",
"return",
"t",
".",
"String",
"(",
")",
"+",
"\"",
"\"",
"+",
"err",
".",
"Error",
"(",
")",
"\n",
"}"
] | // backtrace returns an error message annotated with a backtrace. | [
"backtrace",
"returns",
"an",
"error",
"message",
"annotated",
"with",
"a",
"backtrace",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/graph/graph.go#L40-L42 |
9,002 | luci/luci-go | lucicfg/graph/graph.go | validateOrder | func validateOrder(orderBy string) error {
if orderBy != "key" && orderBy != "def" {
return fmt.Errorf("unknown order %q, expecting either \"key\" or \"def\"", orderBy)
}
return nil
} | go | func validateOrder(orderBy string) error {
if orderBy != "key" && orderBy != "def" {
return fmt.Errorf("unknown order %q, expecting either \"key\" or \"def\"", orderBy)
}
return nil
} | [
"func",
"validateOrder",
"(",
"orderBy",
"string",
")",
"error",
"{",
"if",
"orderBy",
"!=",
"\"",
"\"",
"&&",
"orderBy",
"!=",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\\"",
"\\\"",
"\\\"",
"\\\"",
"\"",
",",
"orderBy",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // validateOrder returns an error if the edge traversal order is unrecognized. | [
"validateOrder",
"returns",
"an",
"error",
"if",
"the",
"edge",
"traversal",
"order",
"is",
"unrecognized",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/graph/graph.go#L157-L162 |
9,003 | luci/luci-go | lucicfg/graph/graph.go | validateKey | func (g *Graph) validateKey(title string, k *Key) error {
if k.set != &g.KeySet {
return fmt.Errorf("bad %s: %s is from another graph", title, k)
}
return nil
} | go | func (g *Graph) validateKey(title string, k *Key) error {
if k.set != &g.KeySet {
return fmt.Errorf("bad %s: %s is from another graph", title, k)
}
return nil
} | [
"func",
"(",
"g",
"*",
"Graph",
")",
"validateKey",
"(",
"title",
"string",
",",
"k",
"*",
"Key",
")",
"error",
"{",
"if",
"k",
".",
"set",
"!=",
"&",
"g",
".",
"KeySet",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"title",
",",
"k",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // validateKey returns an error if the key is not from this graph. | [
"validateKey",
"returns",
"an",
"error",
"if",
"the",
"key",
"is",
"not",
"from",
"this",
"graph",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/graph/graph.go#L165-L170 |
9,004 | luci/luci-go | lucicfg/graph/graph.go | orderedRelatives | func (g *Graph) orderedRelatives(key *Key, attr, orderBy string, cb func(n *Node) []*Node) ([]*Node, error) {
if !g.finalized {
return nil, ErrNotFinalized
}
if err := g.validateKey(attr, key); err != nil {
return nil, err
}
if err := validateOrder(orderBy); err != nil {
return nil, err
}
if n := g.nodes[key]; n != nil {
return sortByEdgeOrder(cb(n), orderBy), nil
}
return nil, nil // no node at all -> no related nodes
} | go | func (g *Graph) orderedRelatives(key *Key, attr, orderBy string, cb func(n *Node) []*Node) ([]*Node, error) {
if !g.finalized {
return nil, ErrNotFinalized
}
if err := g.validateKey(attr, key); err != nil {
return nil, err
}
if err := validateOrder(orderBy); err != nil {
return nil, err
}
if n := g.nodes[key]; n != nil {
return sortByEdgeOrder(cb(n), orderBy), nil
}
return nil, nil // no node at all -> no related nodes
} | [
"func",
"(",
"g",
"*",
"Graph",
")",
"orderedRelatives",
"(",
"key",
"*",
"Key",
",",
"attr",
",",
"orderBy",
"string",
",",
"cb",
"func",
"(",
"n",
"*",
"Node",
")",
"[",
"]",
"*",
"Node",
")",
"(",
"[",
"]",
"*",
"Node",
",",
"error",
")",
"{",
"if",
"!",
"g",
".",
"finalized",
"{",
"return",
"nil",
",",
"ErrNotFinalized",
"\n",
"}",
"\n",
"if",
"err",
":=",
"g",
".",
"validateKey",
"(",
"attr",
",",
"key",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"validateOrder",
"(",
"orderBy",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"n",
":=",
"g",
".",
"nodes",
"[",
"key",
"]",
";",
"n",
"!=",
"nil",
"{",
"return",
"sortByEdgeOrder",
"(",
"cb",
"(",
"n",
")",
",",
"orderBy",
")",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"nil",
"// no node at all -> no related nodes",
"\n",
"}"
] | // orderedRelatives is a common implementation of Children and Parents. | [
"orderedRelatives",
"is",
"a",
"common",
"implementation",
"of",
"Children",
"and",
"Parents",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/graph/graph.go#L500-L514 |
9,005 | luci/luci-go | lucicfg/graph/graph.go | AttrNames | func (g *Graph) AttrNames() []string {
names := make([]string, 0, len(graphAttrs))
for k := range graphAttrs {
names = append(names, k)
}
sort.Strings(names)
return names
} | go | func (g *Graph) AttrNames() []string {
names := make([]string, 0, len(graphAttrs))
for k := range graphAttrs {
names = append(names, k)
}
sort.Strings(names)
return names
} | [
"func",
"(",
"g",
"*",
"Graph",
")",
"AttrNames",
"(",
")",
"[",
"]",
"string",
"{",
"names",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"graphAttrs",
")",
")",
"\n",
"for",
"k",
":=",
"range",
"graphAttrs",
"{",
"names",
"=",
"append",
"(",
"names",
",",
"k",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"names",
")",
"\n",
"return",
"names",
"\n",
"}"
] | // AttrNames is a part of starlark.HasAttrs interface. | [
"AttrNames",
"is",
"a",
"part",
"of",
"starlark",
".",
"HasAttrs",
"interface",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/graph/graph.go#L564-L571 |
9,006 | luci/luci-go | common/data/caching/cache/cache.go | NewMemory | func NewMemory(policies Policies, namespace string) Cache {
return &memory{
policies: policies,
h: isolated.GetHash(namespace),
data: map[isolated.HexDigest][]byte{},
lru: makeLRUDict(namespace),
}
} | go | func NewMemory(policies Policies, namespace string) Cache {
return &memory{
policies: policies,
h: isolated.GetHash(namespace),
data: map[isolated.HexDigest][]byte{},
lru: makeLRUDict(namespace),
}
} | [
"func",
"NewMemory",
"(",
"policies",
"Policies",
",",
"namespace",
"string",
")",
"Cache",
"{",
"return",
"&",
"memory",
"{",
"policies",
":",
"policies",
",",
"h",
":",
"isolated",
".",
"GetHash",
"(",
"namespace",
")",
",",
"data",
":",
"map",
"[",
"isolated",
".",
"HexDigest",
"]",
"[",
"]",
"byte",
"{",
"}",
",",
"lru",
":",
"makeLRUDict",
"(",
"namespace",
")",
",",
"}",
"\n",
"}"
] | // NewMemory creates a purely in-memory cache. | [
"NewMemory",
"creates",
"a",
"purely",
"in",
"-",
"memory",
"cache",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/caching/cache/cache.go#L84-L91 |
9,007 | luci/luci-go | common/data/caching/cache/cache.go | NewDisk | func NewDisk(policies Policies, path, namespace string) (Cache, error) {
if !filepath.IsAbs(path) {
return nil, errors.New("must use absolute path")
}
d := &disk{
policies: policies,
path: path,
h: isolated.GetHash(namespace),
lru: makeLRUDict(namespace),
}
p := d.statePath()
f, err := os.Open(p)
if err == nil {
defer f.Close()
err = json.NewDecoder(f).Decode(&d.lru)
} else if os.IsNotExist(err) {
// The fact that the cache is new is not an error.
err = nil
}
return d, err
} | go | func NewDisk(policies Policies, path, namespace string) (Cache, error) {
if !filepath.IsAbs(path) {
return nil, errors.New("must use absolute path")
}
d := &disk{
policies: policies,
path: path,
h: isolated.GetHash(namespace),
lru: makeLRUDict(namespace),
}
p := d.statePath()
f, err := os.Open(p)
if err == nil {
defer f.Close()
err = json.NewDecoder(f).Decode(&d.lru)
} else if os.IsNotExist(err) {
// The fact that the cache is new is not an error.
err = nil
}
return d, err
} | [
"func",
"NewDisk",
"(",
"policies",
"Policies",
",",
"path",
",",
"namespace",
"string",
")",
"(",
"Cache",
",",
"error",
")",
"{",
"if",
"!",
"filepath",
".",
"IsAbs",
"(",
"path",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"d",
":=",
"&",
"disk",
"{",
"policies",
":",
"policies",
",",
"path",
":",
"path",
",",
"h",
":",
"isolated",
".",
"GetHash",
"(",
"namespace",
")",
",",
"lru",
":",
"makeLRUDict",
"(",
"namespace",
")",
",",
"}",
"\n",
"p",
":=",
"d",
".",
"statePath",
"(",
")",
"\n",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"p",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"defer",
"f",
".",
"Close",
"(",
")",
"\n",
"err",
"=",
"json",
".",
"NewDecoder",
"(",
"f",
")",
".",
"Decode",
"(",
"&",
"d",
".",
"lru",
")",
"\n",
"}",
"else",
"if",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"// The fact that the cache is new is not an error.",
"err",
"=",
"nil",
"\n",
"}",
"\n",
"return",
"d",
",",
"err",
"\n",
"}"
] | // NewDisk creates a disk based cache.
//
// It may return both a valid Cache and an error if it failed to load the
// previous cache metadata. It is safe to ignore this error. | [
"NewDisk",
"creates",
"a",
"disk",
"based",
"cache",
".",
"It",
"may",
"return",
"both",
"a",
"valid",
"Cache",
"and",
"an",
"error",
"if",
"it",
"failed",
"to",
"load",
"the",
"previous",
"cache",
"metadata",
".",
"It",
"is",
"safe",
"to",
"ignore",
"this",
"error",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/caching/cache/cache.go#L97-L117 |
9,008 | luci/luci-go | dm/api/service/v1/graph_data_abnormal_finish.go | CouldRetry | func (s AbnormalFinish_Status) CouldRetry() bool {
switch s {
case AbnormalFinish_FAILED, AbnormalFinish_CRASHED,
AbnormalFinish_EXPIRED, AbnormalFinish_TIMED_OUT:
return true
}
return false
} | go | func (s AbnormalFinish_Status) CouldRetry() bool {
switch s {
case AbnormalFinish_FAILED, AbnormalFinish_CRASHED,
AbnormalFinish_EXPIRED, AbnormalFinish_TIMED_OUT:
return true
}
return false
} | [
"func",
"(",
"s",
"AbnormalFinish_Status",
")",
"CouldRetry",
"(",
")",
"bool",
"{",
"switch",
"s",
"{",
"case",
"AbnormalFinish_FAILED",
",",
"AbnormalFinish_CRASHED",
",",
"AbnormalFinish_EXPIRED",
",",
"AbnormalFinish_TIMED_OUT",
":",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // CouldRetry returns true iff this status code is retryable. | [
"CouldRetry",
"returns",
"true",
"iff",
"this",
"status",
"code",
"is",
"retryable",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/graph_data_abnormal_finish.go#L18-L26 |
9,009 | luci/luci-go | tokenserver/appengine/impl/projectscope/config.go | SetupConfigValidation | func SetupConfigValidation(rules *validation.RuleSet) {
rules.Add("services/${config_service_appid}", projectsCfg, func(ctx *validation.Context, configSet, path string, content []byte) error {
ctx.SetFile(projectsCfg)
cfg := &config.ProjectsCfg{}
if err := proto.UnmarshalText(string(content), cfg); err != nil {
ctx.Errorf("not a valid ProjectsCfg proto message - %s", err)
} else {
validateProjectsCfg(ctx, cfg)
}
return nil
})
} | go | func SetupConfigValidation(rules *validation.RuleSet) {
rules.Add("services/${config_service_appid}", projectsCfg, func(ctx *validation.Context, configSet, path string, content []byte) error {
ctx.SetFile(projectsCfg)
cfg := &config.ProjectsCfg{}
if err := proto.UnmarshalText(string(content), cfg); err != nil {
ctx.Errorf("not a valid ProjectsCfg proto message - %s", err)
} else {
validateProjectsCfg(ctx, cfg)
}
return nil
})
} | [
"func",
"SetupConfigValidation",
"(",
"rules",
"*",
"validation",
".",
"RuleSet",
")",
"{",
"rules",
".",
"Add",
"(",
"\"",
"\"",
",",
"projectsCfg",
",",
"func",
"(",
"ctx",
"*",
"validation",
".",
"Context",
",",
"configSet",
",",
"path",
"string",
",",
"content",
"[",
"]",
"byte",
")",
"error",
"{",
"ctx",
".",
"SetFile",
"(",
"projectsCfg",
")",
"\n",
"cfg",
":=",
"&",
"config",
".",
"ProjectsCfg",
"{",
"}",
"\n",
"if",
"err",
":=",
"proto",
".",
"UnmarshalText",
"(",
"string",
"(",
"content",
")",
",",
"cfg",
")",
";",
"err",
"!=",
"nil",
"{",
"ctx",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"validateProjectsCfg",
"(",
"ctx",
",",
"cfg",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"}"
] | // SetupConfigValidation registers the tokenserver custom projects.cfg validator. | [
"SetupConfigValidation",
"registers",
"the",
"tokenserver",
"custom",
"projects",
".",
"cfg",
"validator",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/projectscope/config.go#L36-L47 |
9,010 | luci/luci-go | tokenserver/appengine/impl/projectscope/config.go | importIdentities | func importIdentities(c context.Context, cfg *config.ProjectsCfg) error {
storage := projectidentity.ProjectIdentities(c)
// TODO (fmatenaar): Make this transactional and provide some guarantees around cleanup
// but do this after we have a stronger story for warning about config changes which are
// about to remove an identity config from a project since this can cause an outage.
for _, project := range cfg.Projects {
if project.IdentityConfig != nil && project.IdentityConfig.ServiceAccountEmail != "" {
identity := &projectidentity.ProjectIdentity{
Project: project.Id,
Email: project.IdentityConfig.ServiceAccountEmail,
}
logging.Infof(c, "updating project scoped account: %v", identity)
if _, err := storage.Update(c, identity); err != nil {
logging.Errorf(c, "failed to update project scoped account: %v", identity)
return err
}
}
}
return nil
} | go | func importIdentities(c context.Context, cfg *config.ProjectsCfg) error {
storage := projectidentity.ProjectIdentities(c)
// TODO (fmatenaar): Make this transactional and provide some guarantees around cleanup
// but do this after we have a stronger story for warning about config changes which are
// about to remove an identity config from a project since this can cause an outage.
for _, project := range cfg.Projects {
if project.IdentityConfig != nil && project.IdentityConfig.ServiceAccountEmail != "" {
identity := &projectidentity.ProjectIdentity{
Project: project.Id,
Email: project.IdentityConfig.ServiceAccountEmail,
}
logging.Infof(c, "updating project scoped account: %v", identity)
if _, err := storage.Update(c, identity); err != nil {
logging.Errorf(c, "failed to update project scoped account: %v", identity)
return err
}
}
}
return nil
} | [
"func",
"importIdentities",
"(",
"c",
"context",
".",
"Context",
",",
"cfg",
"*",
"config",
".",
"ProjectsCfg",
")",
"error",
"{",
"storage",
":=",
"projectidentity",
".",
"ProjectIdentities",
"(",
"c",
")",
"\n\n",
"// TODO (fmatenaar): Make this transactional and provide some guarantees around cleanup",
"// but do this after we have a stronger story for warning about config changes which are",
"// about to remove an identity config from a project since this can cause an outage.",
"for",
"_",
",",
"project",
":=",
"range",
"cfg",
".",
"Projects",
"{",
"if",
"project",
".",
"IdentityConfig",
"!=",
"nil",
"&&",
"project",
".",
"IdentityConfig",
".",
"ServiceAccountEmail",
"!=",
"\"",
"\"",
"{",
"identity",
":=",
"&",
"projectidentity",
".",
"ProjectIdentity",
"{",
"Project",
":",
"project",
".",
"Id",
",",
"Email",
":",
"project",
".",
"IdentityConfig",
".",
"ServiceAccountEmail",
",",
"}",
"\n",
"logging",
".",
"Infof",
"(",
"c",
",",
"\"",
"\"",
",",
"identity",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"storage",
".",
"Update",
"(",
"c",
",",
"identity",
")",
";",
"err",
"!=",
"nil",
"{",
"logging",
".",
"Errorf",
"(",
"c",
",",
"\"",
"\"",
",",
"identity",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // importIdentities analyzes projects.cfg to import or update project scoped service accounts. | [
"importIdentities",
"analyzes",
"projects",
".",
"cfg",
"to",
"import",
"or",
"update",
"project",
"scoped",
"service",
"accounts",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/projectscope/config.go#L50-L70 |
9,011 | luci/luci-go | tokenserver/appengine/impl/projectscope/config.go | ImportConfigs | func ImportConfigs(c context.Context) (string, error) {
cfg, rev, err := fetchConfigs(c)
if err != nil {
return "", errors.Annotate(err, "failed to fetch project configs").Err()
}
if err := importIdentities(c, cfg); err != nil {
return "", errors.Annotate(err, "failed to import project configs").Err()
}
return rev, nil
} | go | func ImportConfigs(c context.Context) (string, error) {
cfg, rev, err := fetchConfigs(c)
if err != nil {
return "", errors.Annotate(err, "failed to fetch project configs").Err()
}
if err := importIdentities(c, cfg); err != nil {
return "", errors.Annotate(err, "failed to import project configs").Err()
}
return rev, nil
} | [
"func",
"ImportConfigs",
"(",
"c",
"context",
".",
"Context",
")",
"(",
"string",
",",
"error",
")",
"{",
"cfg",
",",
"rev",
",",
"err",
":=",
"fetchConfigs",
"(",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"importIdentities",
"(",
"c",
",",
"cfg",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"return",
"rev",
",",
"nil",
"\n",
"}"
] | // ImportConfigs fetches projects.cfg and updates datastore copy of it.
//
// Called from cron. | [
"ImportConfigs",
"fetches",
"projects",
".",
"cfg",
"and",
"updates",
"datastore",
"copy",
"of",
"it",
".",
"Called",
"from",
"cron",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/projectscope/config.go#L96-L105 |
9,012 | luci/luci-go | logdog/client/butlerlib/streamclient/registry.go | Register | func (r *Registry) Register(name string, f ClientFactory) {
r.lock.Lock()
defer r.lock.Unlock()
if _, ok := r.protocols[name]; ok {
panic(fmt.Errorf("streamclient: protocol already registered for [%s]", name))
}
if r.protocols == nil {
r.protocols = make(map[string]ClientFactory)
}
r.protocols[name] = f
} | go | func (r *Registry) Register(name string, f ClientFactory) {
r.lock.Lock()
defer r.lock.Unlock()
if _, ok := r.protocols[name]; ok {
panic(fmt.Errorf("streamclient: protocol already registered for [%s]", name))
}
if r.protocols == nil {
r.protocols = make(map[string]ClientFactory)
}
r.protocols[name] = f
} | [
"func",
"(",
"r",
"*",
"Registry",
")",
"Register",
"(",
"name",
"string",
",",
"f",
"ClientFactory",
")",
"{",
"r",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"r",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"_",
",",
"ok",
":=",
"r",
".",
"protocols",
"[",
"name",
"]",
";",
"ok",
"{",
"panic",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"name",
")",
")",
"\n",
"}",
"\n",
"if",
"r",
".",
"protocols",
"==",
"nil",
"{",
"r",
".",
"protocols",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"ClientFactory",
")",
"\n",
"}",
"\n",
"r",
".",
"protocols",
"[",
"name",
"]",
"=",
"f",
"\n",
"}"
] | // Register registers a new protocol and its ClientFactory.
//
// This can be invoked by calling NewClient with a path spec referencing that
// protocol. | [
"Register",
"registers",
"a",
"new",
"protocol",
"and",
"its",
"ClientFactory",
".",
"This",
"can",
"be",
"invoked",
"by",
"calling",
"NewClient",
"with",
"a",
"path",
"spec",
"referencing",
"that",
"protocol",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butlerlib/streamclient/registry.go#L46-L57 |
9,013 | luci/luci-go | logdog/client/butlerlib/streamclient/registry.go | RegisterDefaultProtocols | func RegisterDefaultProtocols(r *Registry) {
registerPlatformProtocols(r)
// Register common protocols.
r.Register("tcp4", tcpProtocolClientFactory("tcp4"))
r.Register("tcp6", tcpProtocolClientFactory("tcp6"))
} | go | func RegisterDefaultProtocols(r *Registry) {
registerPlatformProtocols(r)
// Register common protocols.
r.Register("tcp4", tcpProtocolClientFactory("tcp4"))
r.Register("tcp6", tcpProtocolClientFactory("tcp6"))
} | [
"func",
"RegisterDefaultProtocols",
"(",
"r",
"*",
"Registry",
")",
"{",
"registerPlatformProtocols",
"(",
"r",
")",
"\n\n",
"// Register common protocols.",
"r",
".",
"Register",
"(",
"\"",
"\"",
",",
"tcpProtocolClientFactory",
"(",
"\"",
"\"",
")",
")",
"\n",
"r",
".",
"Register",
"(",
"\"",
"\"",
",",
"tcpProtocolClientFactory",
"(",
"\"",
"\"",
")",
")",
"\n",
"}"
] | // RegisterDefaultProtocols registers the default set of protocols with a
// Registry. | [
"RegisterDefaultProtocols",
"registers",
"the",
"default",
"set",
"of",
"protocols",
"with",
"a",
"Registry",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butlerlib/streamclient/registry.go#L96-L102 |
9,014 | luci/luci-go | config/impl/remote/remote.go | service | func (r *remoteImpl) service(ctx context.Context) (*configApi.Service, error) {
client, err := r.clients(ctx)
if err != nil {
return nil, err
}
service, err := configApi.New(client)
if err != nil {
return nil, err
}
service.BasePath = r.serviceURL
return service, nil
} | go | func (r *remoteImpl) service(ctx context.Context) (*configApi.Service, error) {
client, err := r.clients(ctx)
if err != nil {
return nil, err
}
service, err := configApi.New(client)
if err != nil {
return nil, err
}
service.BasePath = r.serviceURL
return service, nil
} | [
"func",
"(",
"r",
"*",
"remoteImpl",
")",
"service",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"*",
"configApi",
".",
"Service",
",",
"error",
")",
"{",
"client",
",",
"err",
":=",
"r",
".",
"clients",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"service",
",",
"err",
":=",
"configApi",
".",
"New",
"(",
"client",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"service",
".",
"BasePath",
"=",
"r",
".",
"serviceURL",
"\n",
"return",
"service",
",",
"nil",
"\n",
"}"
] | // service returns Cloud Endpoints API client bound to the given context.
//
// It inherits context's deadline and transport. | [
"service",
"returns",
"Cloud",
"Endpoints",
"API",
"client",
"bound",
"to",
"the",
"given",
"context",
".",
"It",
"inherits",
"context",
"s",
"deadline",
"and",
"transport",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/impl/remote/remote.go#L78-L90 |
9,015 | luci/luci-go | config/impl/remote/remote.go | convertMultiWireConfigs | func convertMultiWireConfigs(ctx context.Context, path string, wireConfigs *configApi.LuciConfigGetConfigMultiResponseMessage, metaOnly bool) ([]config.Config, error) {
configs := make([]config.Config, len(wireConfigs.Configs))
for i, c := range wireConfigs.Configs {
var decoded []byte
var err error
if !metaOnly {
decoded, err = base64.StdEncoding.DecodeString(c.Content)
if err != nil {
lc := logging.SetField(ctx, "configSet", c.ConfigSet)
logging.Warningf(lc, "Failed to base64 decode config: %s", err)
}
}
configs[i] = config.Config{
Meta: config.Meta{
ConfigSet: config.Set(c.ConfigSet),
Path: path,
ContentHash: c.ContentHash,
Revision: c.Revision,
ViewURL: c.Url,
},
Content: string(decoded),
Error: err,
}
}
return configs, nil
} | go | func convertMultiWireConfigs(ctx context.Context, path string, wireConfigs *configApi.LuciConfigGetConfigMultiResponseMessage, metaOnly bool) ([]config.Config, error) {
configs := make([]config.Config, len(wireConfigs.Configs))
for i, c := range wireConfigs.Configs {
var decoded []byte
var err error
if !metaOnly {
decoded, err = base64.StdEncoding.DecodeString(c.Content)
if err != nil {
lc := logging.SetField(ctx, "configSet", c.ConfigSet)
logging.Warningf(lc, "Failed to base64 decode config: %s", err)
}
}
configs[i] = config.Config{
Meta: config.Meta{
ConfigSet: config.Set(c.ConfigSet),
Path: path,
ContentHash: c.ContentHash,
Revision: c.Revision,
ViewURL: c.Url,
},
Content: string(decoded),
Error: err,
}
}
return configs, nil
} | [
"func",
"convertMultiWireConfigs",
"(",
"ctx",
"context",
".",
"Context",
",",
"path",
"string",
",",
"wireConfigs",
"*",
"configApi",
".",
"LuciConfigGetConfigMultiResponseMessage",
",",
"metaOnly",
"bool",
")",
"(",
"[",
"]",
"config",
".",
"Config",
",",
"error",
")",
"{",
"configs",
":=",
"make",
"(",
"[",
"]",
"config",
".",
"Config",
",",
"len",
"(",
"wireConfigs",
".",
"Configs",
")",
")",
"\n",
"for",
"i",
",",
"c",
":=",
"range",
"wireConfigs",
".",
"Configs",
"{",
"var",
"decoded",
"[",
"]",
"byte",
"\n",
"var",
"err",
"error",
"\n\n",
"if",
"!",
"metaOnly",
"{",
"decoded",
",",
"err",
"=",
"base64",
".",
"StdEncoding",
".",
"DecodeString",
"(",
"c",
".",
"Content",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"lc",
":=",
"logging",
".",
"SetField",
"(",
"ctx",
",",
"\"",
"\"",
",",
"c",
".",
"ConfigSet",
")",
"\n",
"logging",
".",
"Warningf",
"(",
"lc",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"configs",
"[",
"i",
"]",
"=",
"config",
".",
"Config",
"{",
"Meta",
":",
"config",
".",
"Meta",
"{",
"ConfigSet",
":",
"config",
".",
"Set",
"(",
"c",
".",
"ConfigSet",
")",
",",
"Path",
":",
"path",
",",
"ContentHash",
":",
"c",
".",
"ContentHash",
",",
"Revision",
":",
"c",
".",
"Revision",
",",
"ViewURL",
":",
"c",
".",
"Url",
",",
"}",
",",
"Content",
":",
"string",
"(",
"decoded",
")",
",",
"Error",
":",
"err",
",",
"}",
"\n",
"}",
"\n\n",
"return",
"configs",
",",
"nil",
"\n",
"}"
] | // convertMultiWireConfigs is a utility to convert what we get over the wire
// into the structs we use in the config package. | [
"convertMultiWireConfigs",
"is",
"a",
"utility",
"to",
"convert",
"what",
"we",
"get",
"over",
"the",
"wire",
"into",
"the",
"structs",
"we",
"use",
"in",
"the",
"config",
"package",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/impl/remote/remote.go#L283-L311 |
9,016 | luci/luci-go | config/impl/remote/remote.go | parseWireRepoType | func parseWireRepoType(s string) config.RepoType {
if s == string(config.GitilesRepo) {
return config.GitilesRepo
}
return config.UnknownRepo
} | go | func parseWireRepoType(s string) config.RepoType {
if s == string(config.GitilesRepo) {
return config.GitilesRepo
}
return config.UnknownRepo
} | [
"func",
"parseWireRepoType",
"(",
"s",
"string",
")",
"config",
".",
"RepoType",
"{",
"if",
"s",
"==",
"string",
"(",
"config",
".",
"GitilesRepo",
")",
"{",
"return",
"config",
".",
"GitilesRepo",
"\n",
"}",
"\n\n",
"return",
"config",
".",
"UnknownRepo",
"\n",
"}"
] | // parseWireRepoType parses the string received over the wire from
// the luci-config service that represents the repo type. | [
"parseWireRepoType",
"parses",
"the",
"string",
"received",
"over",
"the",
"wire",
"from",
"the",
"luci",
"-",
"config",
"service",
"that",
"represents",
"the",
"repo",
"type",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/impl/remote/remote.go#L315-L321 |
9,017 | luci/luci-go | config/impl/remote/remote.go | apiErr | func apiErr(e error) error {
err, ok := e.(*googleapi.Error)
if !ok {
return e
}
if err.Code == 404 {
return config.ErrNoConfig
}
if err.Code >= 500 {
return transient.Tag.Apply(err)
}
return err
} | go | func apiErr(e error) error {
err, ok := e.(*googleapi.Error)
if !ok {
return e
}
if err.Code == 404 {
return config.ErrNoConfig
}
if err.Code >= 500 {
return transient.Tag.Apply(err)
}
return err
} | [
"func",
"apiErr",
"(",
"e",
"error",
")",
"error",
"{",
"err",
",",
"ok",
":=",
"e",
".",
"(",
"*",
"googleapi",
".",
"Error",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"e",
"\n",
"}",
"\n",
"if",
"err",
".",
"Code",
"==",
"404",
"{",
"return",
"config",
".",
"ErrNoConfig",
"\n",
"}",
"\n",
"if",
"err",
".",
"Code",
">=",
"500",
"{",
"return",
"transient",
".",
"Tag",
".",
"Apply",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // apiErr converts googleapi.Error to an appropriate type. | [
"apiErr",
"converts",
"googleapi",
".",
"Error",
"to",
"an",
"appropriate",
"type",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/impl/remote/remote.go#L324-L336 |
9,018 | luci/luci-go | tokenserver/appengine/impl/serviceaccounts/config.go | makeRule | func makeRule(c context.Context, ruleProto *admin.ServiceAccountRule, defaults *admin.ServiceAccountRuleDefaults, rev string) (*Rule, error) {
ctx := &validation.Context{Context: c}
validateRule(ctx, ruleProto.Name, ruleProto)
if err := ctx.Finalize(); err != nil {
return nil, err
}
allowedScopes := stringset.New(len(ruleProto.AllowedScope) + len(defaults.AllowedScope))
for _, scope := range ruleProto.AllowedScope {
allowedScopes.Add(scope)
}
for _, scope := range defaults.AllowedScope {
allowedScopes.Add(scope)
}
endUsers, err := identityset.FromStrings(ruleProto.EndUser, nil)
if err != nil {
return nil, fmt.Errorf("bad 'end_user' set - %s", err)
}
proxies, err := identityset.FromStrings(ruleProto.Proxy, nil)
if err != nil {
return nil, fmt.Errorf("bad 'proxy' set - %s", err)
}
trustedProxies, err := identityset.FromStrings(ruleProto.TrustedProxy, nil)
if err != nil {
return nil, fmt.Errorf("bad 'trusted_proxy' set - %s", err)
}
if ruleProto.MaxGrantValidityDuration == 0 {
ruleProto.MaxGrantValidityDuration = defaults.MaxGrantValidityDuration
}
return &Rule{
Rule: ruleProto,
Revision: rev,
AllowedScopes: allowedScopes,
EndUsers: endUsers,
Proxies: proxies,
TrustedProxies: trustedProxies,
AllProxies: identityset.Union(proxies, trustedProxies),
}, nil
} | go | func makeRule(c context.Context, ruleProto *admin.ServiceAccountRule, defaults *admin.ServiceAccountRuleDefaults, rev string) (*Rule, error) {
ctx := &validation.Context{Context: c}
validateRule(ctx, ruleProto.Name, ruleProto)
if err := ctx.Finalize(); err != nil {
return nil, err
}
allowedScopes := stringset.New(len(ruleProto.AllowedScope) + len(defaults.AllowedScope))
for _, scope := range ruleProto.AllowedScope {
allowedScopes.Add(scope)
}
for _, scope := range defaults.AllowedScope {
allowedScopes.Add(scope)
}
endUsers, err := identityset.FromStrings(ruleProto.EndUser, nil)
if err != nil {
return nil, fmt.Errorf("bad 'end_user' set - %s", err)
}
proxies, err := identityset.FromStrings(ruleProto.Proxy, nil)
if err != nil {
return nil, fmt.Errorf("bad 'proxy' set - %s", err)
}
trustedProxies, err := identityset.FromStrings(ruleProto.TrustedProxy, nil)
if err != nil {
return nil, fmt.Errorf("bad 'trusted_proxy' set - %s", err)
}
if ruleProto.MaxGrantValidityDuration == 0 {
ruleProto.MaxGrantValidityDuration = defaults.MaxGrantValidityDuration
}
return &Rule{
Rule: ruleProto,
Revision: rev,
AllowedScopes: allowedScopes,
EndUsers: endUsers,
Proxies: proxies,
TrustedProxies: trustedProxies,
AllProxies: identityset.Union(proxies, trustedProxies),
}, nil
} | [
"func",
"makeRule",
"(",
"c",
"context",
".",
"Context",
",",
"ruleProto",
"*",
"admin",
".",
"ServiceAccountRule",
",",
"defaults",
"*",
"admin",
".",
"ServiceAccountRuleDefaults",
",",
"rev",
"string",
")",
"(",
"*",
"Rule",
",",
"error",
")",
"{",
"ctx",
":=",
"&",
"validation",
".",
"Context",
"{",
"Context",
":",
"c",
"}",
"\n",
"validateRule",
"(",
"ctx",
",",
"ruleProto",
".",
"Name",
",",
"ruleProto",
")",
"\n",
"if",
"err",
":=",
"ctx",
".",
"Finalize",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"allowedScopes",
":=",
"stringset",
".",
"New",
"(",
"len",
"(",
"ruleProto",
".",
"AllowedScope",
")",
"+",
"len",
"(",
"defaults",
".",
"AllowedScope",
")",
")",
"\n",
"for",
"_",
",",
"scope",
":=",
"range",
"ruleProto",
".",
"AllowedScope",
"{",
"allowedScopes",
".",
"Add",
"(",
"scope",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"scope",
":=",
"range",
"defaults",
".",
"AllowedScope",
"{",
"allowedScopes",
".",
"Add",
"(",
"scope",
")",
"\n",
"}",
"\n\n",
"endUsers",
",",
"err",
":=",
"identityset",
".",
"FromStrings",
"(",
"ruleProto",
".",
"EndUser",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"proxies",
",",
"err",
":=",
"identityset",
".",
"FromStrings",
"(",
"ruleProto",
".",
"Proxy",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"trustedProxies",
",",
"err",
":=",
"identityset",
".",
"FromStrings",
"(",
"ruleProto",
".",
"TrustedProxy",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"if",
"ruleProto",
".",
"MaxGrantValidityDuration",
"==",
"0",
"{",
"ruleProto",
".",
"MaxGrantValidityDuration",
"=",
"defaults",
".",
"MaxGrantValidityDuration",
"\n",
"}",
"\n\n",
"return",
"&",
"Rule",
"{",
"Rule",
":",
"ruleProto",
",",
"Revision",
":",
"rev",
",",
"AllowedScopes",
":",
"allowedScopes",
",",
"EndUsers",
":",
"endUsers",
",",
"Proxies",
":",
"proxies",
",",
"TrustedProxies",
":",
"trustedProxies",
",",
"AllProxies",
":",
"identityset",
".",
"Union",
"(",
"proxies",
",",
"trustedProxies",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] | // makeRule converts ServiceAccountRule into queriable Rule.
//
// Mutates 'ruleProto' in-place filling in defaults. | [
"makeRule",
"converts",
"ServiceAccountRule",
"into",
"queriable",
"Rule",
".",
"Mutates",
"ruleProto",
"in",
"-",
"place",
"filling",
"in",
"defaults",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/serviceaccounts/config.go#L411-L454 |
9,019 | luci/luci-go | tokenserver/appengine/impl/serviceaccounts/config.go | CheckScopes | func (r *Rule) CheckScopes(scopes []string) error {
var notAllowed []string
for _, scope := range scopes {
if !r.AllowedScopes.Has(scope) {
notAllowed = append(notAllowed, scope)
}
}
if len(notAllowed) != 0 {
return fmt.Errorf("following scopes are not allowed by the rule %q - %q", r.Rule.Name, notAllowed)
}
return nil
} | go | func (r *Rule) CheckScopes(scopes []string) error {
var notAllowed []string
for _, scope := range scopes {
if !r.AllowedScopes.Has(scope) {
notAllowed = append(notAllowed, scope)
}
}
if len(notAllowed) != 0 {
return fmt.Errorf("following scopes are not allowed by the rule %q - %q", r.Rule.Name, notAllowed)
}
return nil
} | [
"func",
"(",
"r",
"*",
"Rule",
")",
"CheckScopes",
"(",
"scopes",
"[",
"]",
"string",
")",
"error",
"{",
"var",
"notAllowed",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"scope",
":=",
"range",
"scopes",
"{",
"if",
"!",
"r",
".",
"AllowedScopes",
".",
"Has",
"(",
"scope",
")",
"{",
"notAllowed",
"=",
"append",
"(",
"notAllowed",
",",
"scope",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"len",
"(",
"notAllowed",
")",
"!=",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"r",
".",
"Rule",
".",
"Name",
",",
"notAllowed",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // CheckScopes returns no errors if all passed scopes are allowed. | [
"CheckScopes",
"returns",
"no",
"errors",
"if",
"all",
"passed",
"scopes",
"are",
"allowed",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/serviceaccounts/config.go#L457-L468 |
9,020 | luci/luci-go | grpc/grpcmon/server.go | NewUnaryServerInterceptor | func NewUnaryServerInterceptor(next grpc.UnaryServerInterceptor) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
started := clock.Now(ctx)
panicing := true
defer func() {
// We don't want to recover anything, but we want to log Internal error
// in case of a panic. We pray here reportServerRPCMetrics is very
// lightweight and it doesn't panic itself.
code := codes.OK
switch {
case err != nil:
code = grpc.Code(err)
case panicing:
code = codes.Internal
}
reportServerRPCMetrics(ctx, info.FullMethod, code, clock.Now(ctx).Sub(started))
}()
if next != nil {
resp, err = next(ctx, req, info, handler)
} else {
resp, err = handler(ctx, req)
}
panicing = false // normal exit, no panic happened, disarms defer
return
}
} | go | func NewUnaryServerInterceptor(next grpc.UnaryServerInterceptor) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
started := clock.Now(ctx)
panicing := true
defer func() {
// We don't want to recover anything, but we want to log Internal error
// in case of a panic. We pray here reportServerRPCMetrics is very
// lightweight and it doesn't panic itself.
code := codes.OK
switch {
case err != nil:
code = grpc.Code(err)
case panicing:
code = codes.Internal
}
reportServerRPCMetrics(ctx, info.FullMethod, code, clock.Now(ctx).Sub(started))
}()
if next != nil {
resp, err = next(ctx, req, info, handler)
} else {
resp, err = handler(ctx, req)
}
panicing = false // normal exit, no panic happened, disarms defer
return
}
} | [
"func",
"NewUnaryServerInterceptor",
"(",
"next",
"grpc",
".",
"UnaryServerInterceptor",
")",
"grpc",
".",
"UnaryServerInterceptor",
"{",
"return",
"func",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"interface",
"{",
"}",
",",
"info",
"*",
"grpc",
".",
"UnaryServerInfo",
",",
"handler",
"grpc",
".",
"UnaryHandler",
")",
"(",
"resp",
"interface",
"{",
"}",
",",
"err",
"error",
")",
"{",
"started",
":=",
"clock",
".",
"Now",
"(",
"ctx",
")",
"\n",
"panicing",
":=",
"true",
"\n",
"defer",
"func",
"(",
")",
"{",
"// We don't want to recover anything, but we want to log Internal error",
"// in case of a panic. We pray here reportServerRPCMetrics is very",
"// lightweight and it doesn't panic itself.",
"code",
":=",
"codes",
".",
"OK",
"\n",
"switch",
"{",
"case",
"err",
"!=",
"nil",
":",
"code",
"=",
"grpc",
".",
"Code",
"(",
"err",
")",
"\n",
"case",
"panicing",
":",
"code",
"=",
"codes",
".",
"Internal",
"\n",
"}",
"\n",
"reportServerRPCMetrics",
"(",
"ctx",
",",
"info",
".",
"FullMethod",
",",
"code",
",",
"clock",
".",
"Now",
"(",
"ctx",
")",
".",
"Sub",
"(",
"started",
")",
")",
"\n",
"}",
"(",
")",
"\n",
"if",
"next",
"!=",
"nil",
"{",
"resp",
",",
"err",
"=",
"next",
"(",
"ctx",
",",
"req",
",",
"info",
",",
"handler",
")",
"\n",
"}",
"else",
"{",
"resp",
",",
"err",
"=",
"handler",
"(",
"ctx",
",",
"req",
")",
"\n",
"}",
"\n",
"panicing",
"=",
"false",
"// normal exit, no panic happened, disarms defer",
"\n",
"return",
"\n",
"}",
"\n",
"}"
] | // NewUnaryServerInterceptor returns an interceptor that gathers RPC handler
// metrics and sends them to tsmon.
//
// It can be optionally chained with other interceptor. The reported metrics
// include time spent in this other interceptor too.
//
// It assumes the RPC context has tsmon initialized already. | [
"NewUnaryServerInterceptor",
"returns",
"an",
"interceptor",
"that",
"gathers",
"RPC",
"handler",
"metrics",
"and",
"sends",
"them",
"to",
"tsmon",
".",
"It",
"can",
"be",
"optionally",
"chained",
"with",
"other",
"interceptor",
".",
"The",
"reported",
"metrics",
"include",
"time",
"spent",
"in",
"this",
"other",
"interceptor",
"too",
".",
"It",
"assumes",
"the",
"RPC",
"context",
"has",
"tsmon",
"initialized",
"already",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/grpcmon/server.go#L55-L80 |
9,021 | luci/luci-go | grpc/grpcmon/server.go | reportServerRPCMetrics | func reportServerRPCMetrics(ctx context.Context, method string, code codes.Code, dur time.Duration) {
grpcServerCount.Add(ctx, 1, method, int(code))
grpcServerDuration.Add(ctx, float64(dur.Nanoseconds()/1e6), method, int(code))
} | go | func reportServerRPCMetrics(ctx context.Context, method string, code codes.Code, dur time.Duration) {
grpcServerCount.Add(ctx, 1, method, int(code))
grpcServerDuration.Add(ctx, float64(dur.Nanoseconds()/1e6), method, int(code))
} | [
"func",
"reportServerRPCMetrics",
"(",
"ctx",
"context",
".",
"Context",
",",
"method",
"string",
",",
"code",
"codes",
".",
"Code",
",",
"dur",
"time",
".",
"Duration",
")",
"{",
"grpcServerCount",
".",
"Add",
"(",
"ctx",
",",
"1",
",",
"method",
",",
"int",
"(",
"code",
")",
")",
"\n",
"grpcServerDuration",
".",
"Add",
"(",
"ctx",
",",
"float64",
"(",
"dur",
".",
"Nanoseconds",
"(",
")",
"/",
"1e6",
")",
",",
"method",
",",
"int",
"(",
"code",
")",
")",
"\n",
"}"
] | // reportServerRPCMetrics sends metrics after RPC handler has finished. | [
"reportServerRPCMetrics",
"sends",
"metrics",
"after",
"RPC",
"handler",
"has",
"finished",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/grpcmon/server.go#L83-L86 |
9,022 | luci/luci-go | grpc/grpcutil/errors.go | WrapIfTransient | func WrapIfTransient(err error) error {
if err == nil {
return nil
}
if IsTransientCode(Code(err)) {
err = transient.Tag.Apply(err)
}
return err
} | go | func WrapIfTransient(err error) error {
if err == nil {
return nil
}
if IsTransientCode(Code(err)) {
err = transient.Tag.Apply(err)
}
return err
} | [
"func",
"WrapIfTransient",
"(",
"err",
"error",
")",
"error",
"{",
"if",
"err",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"if",
"IsTransientCode",
"(",
"Code",
"(",
"err",
")",
")",
"{",
"err",
"=",
"transient",
".",
"Tag",
".",
"Apply",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // WrapIfTransient wraps the supplied gRPC error with a transient wrapper if
// it has a transient gRPC code, as determined by IsTransientCode.
//
// If the supplied error is nil, nil will be returned.
//
// Note that non-gRPC errors will have code grpc.Unknown, which is considered
// transient, and be wrapped. This function should only be used on gRPC errors. | [
"WrapIfTransient",
"wraps",
"the",
"supplied",
"gRPC",
"error",
"with",
"a",
"transient",
"wrapper",
"if",
"it",
"has",
"a",
"transient",
"gRPC",
"code",
"as",
"determined",
"by",
"IsTransientCode",
".",
"If",
"the",
"supplied",
"error",
"is",
"nil",
"nil",
"will",
"be",
"returned",
".",
"Note",
"that",
"non",
"-",
"gRPC",
"errors",
"will",
"have",
"code",
"grpc",
".",
"Unknown",
"which",
"is",
"considered",
"transient",
"and",
"be",
"wrapped",
".",
"This",
"function",
"should",
"only",
"be",
"used",
"on",
"gRPC",
"errors",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/grpcutil/errors.go#L93-L102 |
9,023 | luci/luci-go | grpc/grpcutil/errors.go | CodeStatus | func CodeStatus(code codes.Code) int {
if status, ok := codeToStatus[code]; ok {
return status
}
return http.StatusInternalServerError
} | go | func CodeStatus(code codes.Code) int {
if status, ok := codeToStatus[code]; ok {
return status
}
return http.StatusInternalServerError
} | [
"func",
"CodeStatus",
"(",
"code",
"codes",
".",
"Code",
")",
"int",
"{",
"if",
"status",
",",
"ok",
":=",
"codeToStatus",
"[",
"code",
"]",
";",
"ok",
"{",
"return",
"status",
"\n",
"}",
"\n",
"return",
"http",
".",
"StatusInternalServerError",
"\n",
"}"
] | // CodeStatus maps gRPC codes to HTTP status codes.
// Falls back to http.StatusInternalServerError. | [
"CodeStatus",
"maps",
"gRPC",
"codes",
"to",
"HTTP",
"status",
"codes",
".",
"Falls",
"back",
"to",
"http",
".",
"StatusInternalServerError",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/grpcutil/errors.go#L169-L174 |
9,024 | luci/luci-go | grpc/grpcutil/errors.go | Code | func Code(err error) codes.Code {
if code, ok := Tag.In(err); ok {
return code
}
// TODO(nodir): use status.FromError
return grpc.Code(errors.Unwrap(err))
} | go | func Code(err error) codes.Code {
if code, ok := Tag.In(err); ok {
return code
}
// TODO(nodir): use status.FromError
return grpc.Code(errors.Unwrap(err))
} | [
"func",
"Code",
"(",
"err",
"error",
")",
"codes",
".",
"Code",
"{",
"if",
"code",
",",
"ok",
":=",
"Tag",
".",
"In",
"(",
"err",
")",
";",
"ok",
"{",
"return",
"code",
"\n",
"}",
"\n",
"// TODO(nodir): use status.FromError",
"return",
"grpc",
".",
"Code",
"(",
"errors",
".",
"Unwrap",
"(",
"err",
")",
")",
"\n",
"}"
] | // Code returns the gRPC code for a given error.
//
// In addition to the functionality of grpc.Code, this will unwrap any wrapped
// errors before asking for its code. | [
"Code",
"returns",
"the",
"gRPC",
"code",
"for",
"a",
"given",
"error",
".",
"In",
"addition",
"to",
"the",
"functionality",
"of",
"grpc",
".",
"Code",
"this",
"will",
"unwrap",
"any",
"wrapped",
"errors",
"before",
"asking",
"for",
"its",
"code",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/grpcutil/errors.go#L180-L186 |
9,025 | luci/luci-go | grpc/grpcutil/errors.go | IsTransientCode | func IsTransientCode(code codes.Code) bool {
switch code {
case codes.Internal, codes.Unknown, codes.Unavailable:
return true
default:
return false
}
} | go | func IsTransientCode(code codes.Code) bool {
switch code {
case codes.Internal, codes.Unknown, codes.Unavailable:
return true
default:
return false
}
} | [
"func",
"IsTransientCode",
"(",
"code",
"codes",
".",
"Code",
")",
"bool",
"{",
"switch",
"code",
"{",
"case",
"codes",
".",
"Internal",
",",
"codes",
".",
"Unknown",
",",
"codes",
".",
"Unavailable",
":",
"return",
"true",
"\n\n",
"default",
":",
"return",
"false",
"\n",
"}",
"\n",
"}"
] | // IsTransientCode returns true if a given gRPC code is associated with a
// transient gRPC error type. | [
"IsTransientCode",
"returns",
"true",
"if",
"a",
"given",
"gRPC",
"code",
"is",
"associated",
"with",
"a",
"transient",
"gRPC",
"error",
"type",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/grpcutil/errors.go#L195-L203 |
9,026 | luci/luci-go | tumble/add_to_journal.go | AddToJournal | func AddToJournal(c context.Context, m ...Mutation) error {
(logging.Fields{"count": len(m)}).Infof(c, "tumble.AddToJournal")
if len(m) == 0 {
return nil
}
return RunMutation(c, addToJournalMutation(m))
} | go | func AddToJournal(c context.Context, m ...Mutation) error {
(logging.Fields{"count": len(m)}).Infof(c, "tumble.AddToJournal")
if len(m) == 0 {
return nil
}
return RunMutation(c, addToJournalMutation(m))
} | [
"func",
"AddToJournal",
"(",
"c",
"context",
".",
"Context",
",",
"m",
"...",
"Mutation",
")",
"error",
"{",
"(",
"logging",
".",
"Fields",
"{",
"\"",
"\"",
":",
"len",
"(",
"m",
")",
"}",
")",
".",
"Infof",
"(",
"c",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"m",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"RunMutation",
"(",
"c",
",",
"addToJournalMutation",
"(",
"m",
")",
")",
"\n",
"}"
] | // AddToJournal records one or more Mutation to the tumble journal, but does not
// execute any of them. This does so by running a transaction on a pseudo-random
// entity group, and journaling the mutations there. | [
"AddToJournal",
"records",
"one",
"or",
"more",
"Mutation",
"to",
"the",
"tumble",
"journal",
"but",
"does",
"not",
"execute",
"any",
"of",
"them",
".",
"This",
"does",
"so",
"by",
"running",
"a",
"transaction",
"on",
"a",
"pseudo",
"-",
"random",
"entity",
"group",
"and",
"journaling",
"the",
"mutations",
"there",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tumble/add_to_journal.go#L30-L36 |
9,027 | luci/luci-go | client/flagpb/marshal.go | MarshalUntyped | func MarshalUntyped(msg map[string]interface{}) ([]string, error) {
return appendFlags(nil, nil, reflect.ValueOf(msg))
} | go | func MarshalUntyped(msg map[string]interface{}) ([]string, error) {
return appendFlags(nil, nil, reflect.ValueOf(msg))
} | [
"func",
"MarshalUntyped",
"(",
"msg",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"return",
"appendFlags",
"(",
"nil",
",",
"nil",
",",
"reflect",
".",
"ValueOf",
"(",
"msg",
")",
")",
"\n",
"}"
] | // MarshalUntyped marshals a key-value map to flags. | [
"MarshalUntyped",
"marshals",
"a",
"key",
"-",
"value",
"map",
"to",
"flags",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/flagpb/marshal.go#L24-L26 |
9,028 | luci/luci-go | server/pprof/token.go | generateToken | func generateToken(c context.Context) (string, error) {
logging.Warningf(c, "%q is generating pprof token", auth.CurrentIdentity(c))
return pprofToken.Generate(c, nil, nil, 0)
} | go | func generateToken(c context.Context) (string, error) {
logging.Warningf(c, "%q is generating pprof token", auth.CurrentIdentity(c))
return pprofToken.Generate(c, nil, nil, 0)
} | [
"func",
"generateToken",
"(",
"c",
"context",
".",
"Context",
")",
"(",
"string",
",",
"error",
")",
"{",
"logging",
".",
"Warningf",
"(",
"c",
",",
"\"",
"\"",
",",
"auth",
".",
"CurrentIdentity",
"(",
"c",
")",
")",
"\n",
"return",
"pprofToken",
".",
"Generate",
"(",
"c",
",",
"nil",
",",
"nil",
",",
"0",
")",
"\n",
"}"
] | // generateToken generates new pprof token.
//
// The token is URL safe base64 encoded string. Possession of such token allows
// to call pprof endpoints.
//
// The token expires after 12 hours. | [
"generateToken",
"generates",
"new",
"pprof",
"token",
".",
"The",
"token",
"is",
"URL",
"safe",
"base64",
"encoded",
"string",
".",
"Possession",
"of",
"such",
"token",
"allows",
"to",
"call",
"pprof",
"endpoints",
".",
"The",
"token",
"expires",
"after",
"12",
"hours",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/pprof/token.go#L40-L43 |
9,029 | luci/luci-go | server/pprof/token.go | checkToken | func checkToken(c context.Context, tok string) error {
_, err := pprofToken.Validate(c, tok, nil)
return err
} | go | func checkToken(c context.Context, tok string) error {
_, err := pprofToken.Validate(c, tok, nil)
return err
} | [
"func",
"checkToken",
"(",
"c",
"context",
".",
"Context",
",",
"tok",
"string",
")",
"error",
"{",
"_",
",",
"err",
":=",
"pprofToken",
".",
"Validate",
"(",
"c",
",",
"tok",
",",
"nil",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // checkToken succeeds if the given pprof token is valid and non-expired. | [
"checkToken",
"succeeds",
"if",
"the",
"given",
"pprof",
"token",
"is",
"valid",
"and",
"non",
"-",
"expired",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/pprof/token.go#L46-L49 |
9,030 | luci/luci-go | milo/frontend/middleware.go | replaceAllInChunks | func replaceAllInChunks(chunks []formatChunk, re *regexp.Regexp, repl func(string) template.HTML) []formatChunk {
var ret []formatChunk
for _, chunk := range chunks {
if len(chunk.html) != 0 {
ret = append(ret, chunk)
continue
}
s := chunk.str
for len(s) != 0 {
loc := re.FindStringIndex(s)
if loc == nil {
ret = append(ret, formatChunk{str: s})
break
}
if loc[0] > 0 {
ret = append(ret, formatChunk{str: s[:loc[0]]})
}
html := repl(s[loc[0]:loc[1]])
ret = append(ret, formatChunk{html: html})
s = s[loc[1]:]
}
}
return ret
} | go | func replaceAllInChunks(chunks []formatChunk, re *regexp.Regexp, repl func(string) template.HTML) []formatChunk {
var ret []formatChunk
for _, chunk := range chunks {
if len(chunk.html) != 0 {
ret = append(ret, chunk)
continue
}
s := chunk.str
for len(s) != 0 {
loc := re.FindStringIndex(s)
if loc == nil {
ret = append(ret, formatChunk{str: s})
break
}
if loc[0] > 0 {
ret = append(ret, formatChunk{str: s[:loc[0]]})
}
html := repl(s[loc[0]:loc[1]])
ret = append(ret, formatChunk{html: html})
s = s[loc[1]:]
}
}
return ret
} | [
"func",
"replaceAllInChunks",
"(",
"chunks",
"[",
"]",
"formatChunk",
",",
"re",
"*",
"regexp",
".",
"Regexp",
",",
"repl",
"func",
"(",
"string",
")",
"template",
".",
"HTML",
")",
"[",
"]",
"formatChunk",
"{",
"var",
"ret",
"[",
"]",
"formatChunk",
"\n",
"for",
"_",
",",
"chunk",
":=",
"range",
"chunks",
"{",
"if",
"len",
"(",
"chunk",
".",
"html",
")",
"!=",
"0",
"{",
"ret",
"=",
"append",
"(",
"ret",
",",
"chunk",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"s",
":=",
"chunk",
".",
"str",
"\n",
"for",
"len",
"(",
"s",
")",
"!=",
"0",
"{",
"loc",
":=",
"re",
".",
"FindStringIndex",
"(",
"s",
")",
"\n",
"if",
"loc",
"==",
"nil",
"{",
"ret",
"=",
"append",
"(",
"ret",
",",
"formatChunk",
"{",
"str",
":",
"s",
"}",
")",
"\n",
"break",
"\n",
"}",
"\n",
"if",
"loc",
"[",
"0",
"]",
">",
"0",
"{",
"ret",
"=",
"append",
"(",
"ret",
",",
"formatChunk",
"{",
"str",
":",
"s",
"[",
":",
"loc",
"[",
"0",
"]",
"]",
"}",
")",
"\n",
"}",
"\n",
"html",
":=",
"repl",
"(",
"s",
"[",
"loc",
"[",
"0",
"]",
":",
"loc",
"[",
"1",
"]",
"]",
")",
"\n",
"ret",
"=",
"append",
"(",
"ret",
",",
"formatChunk",
"{",
"html",
":",
"html",
"}",
")",
"\n",
"s",
"=",
"s",
"[",
"loc",
"[",
"1",
"]",
":",
"]",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"ret",
"\n",
"}"
] | // replaceAllInChunks behaves like Regexp.ReplaceAllStringFunc, but it only
// acts on unprocessed elements of chunks. Already-processed elements are left
// as-is. repl returns trusted HTML, performing any necessary escaping. | [
"replaceAllInChunks",
"behaves",
"like",
"Regexp",
".",
"ReplaceAllStringFunc",
"but",
"it",
"only",
"acts",
"on",
"unprocessed",
"elements",
"of",
"chunks",
".",
"Already",
"-",
"processed",
"elements",
"are",
"left",
"as",
"-",
"is",
".",
"repl",
"returns",
"trusted",
"HTML",
"performing",
"any",
"necessary",
"escaping",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/middleware.go#L163-L186 |
9,031 | luci/luci-go | milo/frontend/middleware.go | chunksToHTML | func chunksToHTML(chunks []formatChunk) template.HTML {
buf := bytes.Buffer{}
for _, chunk := range chunks {
if len(chunk.html) != 0 {
buf.WriteString(string(chunk.html))
} else {
buf.WriteString(template.HTMLEscapeString(chunk.str))
}
}
return template.HTML(buf.String())
} | go | func chunksToHTML(chunks []formatChunk) template.HTML {
buf := bytes.Buffer{}
for _, chunk := range chunks {
if len(chunk.html) != 0 {
buf.WriteString(string(chunk.html))
} else {
buf.WriteString(template.HTMLEscapeString(chunk.str))
}
}
return template.HTML(buf.String())
} | [
"func",
"chunksToHTML",
"(",
"chunks",
"[",
"]",
"formatChunk",
")",
"template",
".",
"HTML",
"{",
"buf",
":=",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"for",
"_",
",",
"chunk",
":=",
"range",
"chunks",
"{",
"if",
"len",
"(",
"chunk",
".",
"html",
")",
"!=",
"0",
"{",
"buf",
".",
"WriteString",
"(",
"string",
"(",
"chunk",
".",
"html",
")",
")",
"\n",
"}",
"else",
"{",
"buf",
".",
"WriteString",
"(",
"template",
".",
"HTMLEscapeString",
"(",
"chunk",
".",
"str",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"template",
".",
"HTML",
"(",
"buf",
".",
"String",
"(",
")",
")",
"\n",
"}"
] | // chunksToHTML concatenates chunks together, escaping as needed, to return a
// final completed HTML string. | [
"chunksToHTML",
"concatenates",
"chunks",
"together",
"escaping",
"as",
"needed",
"to",
"return",
"a",
"final",
"completed",
"HTML",
"string",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/middleware.go#L190-L200 |
9,032 | luci/luci-go | milo/frontend/middleware.go | recipeLink | func recipeLink(r *buildbucketpb.BuildInfra_Recipe) (result template.HTML) {
if r == nil {
return
}
// We don't know location of recipes within the repo and getting that
// information is not trivial, so use code search, which is precise enough.
csHost := "cs.chromium.org"
if strings.HasPrefix(r.CipdPackage, "infra_internal") {
csHost = "cs.corp.google.com"
}
recipeURL := fmt.Sprintf("https://%s/search/?q=file:recipes/%s.py", csHost, r.Name)
return ui.NewLink(r.Name, recipeURL, fmt.Sprintf("recipe %s", r.Name)).HTML()
} | go | func recipeLink(r *buildbucketpb.BuildInfra_Recipe) (result template.HTML) {
if r == nil {
return
}
// We don't know location of recipes within the repo and getting that
// information is not trivial, so use code search, which is precise enough.
csHost := "cs.chromium.org"
if strings.HasPrefix(r.CipdPackage, "infra_internal") {
csHost = "cs.corp.google.com"
}
recipeURL := fmt.Sprintf("https://%s/search/?q=file:recipes/%s.py", csHost, r.Name)
return ui.NewLink(r.Name, recipeURL, fmt.Sprintf("recipe %s", r.Name)).HTML()
} | [
"func",
"recipeLink",
"(",
"r",
"*",
"buildbucketpb",
".",
"BuildInfra_Recipe",
")",
"(",
"result",
"template",
".",
"HTML",
")",
"{",
"if",
"r",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"// We don't know location of recipes within the repo and getting that",
"// information is not trivial, so use code search, which is precise enough.",
"csHost",
":=",
"\"",
"\"",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"r",
".",
"CipdPackage",
",",
"\"",
"\"",
")",
"{",
"csHost",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"recipeURL",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"csHost",
",",
"r",
".",
"Name",
")",
"\n",
"return",
"ui",
".",
"NewLink",
"(",
"r",
".",
"Name",
",",
"recipeURL",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"r",
".",
"Name",
")",
")",
".",
"HTML",
"(",
")",
"\n",
"}"
] | // recipeLink generates a link to codesearch given a recipe bundle. | [
"recipeLink",
"generates",
"a",
"link",
"to",
"codesearch",
"given",
"a",
"recipe",
"bundle",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/middleware.go#L235-L247 |
9,033 | luci/luci-go | milo/frontend/middleware.go | botLink | func botLink(s *buildbucketpb.BuildInfra_Swarming) (result template.HTML) {
for _, d := range s.GetBotDimensions() {
if d.Key == "id" {
return ui.NewLink(
d.Value,
fmt.Sprintf("https://%s/bot?id=%s", s.Hostname, d.Value),
fmt.Sprintf("swarming bot %s", d.Value)).HTML()
}
}
return "N/A"
} | go | func botLink(s *buildbucketpb.BuildInfra_Swarming) (result template.HTML) {
for _, d := range s.GetBotDimensions() {
if d.Key == "id" {
return ui.NewLink(
d.Value,
fmt.Sprintf("https://%s/bot?id=%s", s.Hostname, d.Value),
fmt.Sprintf("swarming bot %s", d.Value)).HTML()
}
}
return "N/A"
} | [
"func",
"botLink",
"(",
"s",
"*",
"buildbucketpb",
".",
"BuildInfra_Swarming",
")",
"(",
"result",
"template",
".",
"HTML",
")",
"{",
"for",
"_",
",",
"d",
":=",
"range",
"s",
".",
"GetBotDimensions",
"(",
")",
"{",
"if",
"d",
".",
"Key",
"==",
"\"",
"\"",
"{",
"return",
"ui",
".",
"NewLink",
"(",
"d",
".",
"Value",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"s",
".",
"Hostname",
",",
"d",
".",
"Value",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"d",
".",
"Value",
")",
")",
".",
"HTML",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // botLink generates a link to a swarming bot given a buildbucketpb.BuildInfra_Swarming struct. | [
"botLink",
"generates",
"a",
"link",
"to",
"a",
"swarming",
"bot",
"given",
"a",
"buildbucketpb",
".",
"BuildInfra_Swarming",
"struct",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/middleware.go#L250-L260 |
9,034 | luci/luci-go | milo/frontend/middleware.go | toTime | func toTime(ts *timestamp.Timestamp) (result time.Time) {
// We want a zero-ed out time.Time, not one set to the epoch.
if t, err := ptypes.Timestamp(ts); err == nil {
result = t
}
return
} | go | func toTime(ts *timestamp.Timestamp) (result time.Time) {
// We want a zero-ed out time.Time, not one set to the epoch.
if t, err := ptypes.Timestamp(ts); err == nil {
result = t
}
return
} | [
"func",
"toTime",
"(",
"ts",
"*",
"timestamp",
".",
"Timestamp",
")",
"(",
"result",
"time",
".",
"Time",
")",
"{",
"// We want a zero-ed out time.Time, not one set to the epoch.",
"if",
"t",
",",
"err",
":=",
"ptypes",
".",
"Timestamp",
"(",
"ts",
")",
";",
"err",
"==",
"nil",
"{",
"result",
"=",
"t",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // toTime returns the time.Time format for the proto timestamp.
// If the proto timestamp is invalid, we return a zero-ed out time.Time. | [
"toTime",
"returns",
"the",
"time",
".",
"Time",
"format",
"for",
"the",
"proto",
"timestamp",
".",
"If",
"the",
"proto",
"timestamp",
"is",
"invalid",
"we",
"return",
"a",
"zero",
"-",
"ed",
"out",
"time",
".",
"Time",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/middleware.go#L291-L297 |
9,035 | luci/luci-go | milo/frontend/middleware.go | obfuscateEmail | func obfuscateEmail(email string) template.HTML {
email = template.HTMLEscapeString(email)
return template.HTML(strings.Replace(
email, "@", "<span style=\"display:none\">ohnoyoudont</span>@", -1))
} | go | func obfuscateEmail(email string) template.HTML {
email = template.HTMLEscapeString(email)
return template.HTML(strings.Replace(
email, "@", "<span style=\"display:none\">ohnoyoudont</span>@", -1))
} | [
"func",
"obfuscateEmail",
"(",
"email",
"string",
")",
"template",
".",
"HTML",
"{",
"email",
"=",
"template",
".",
"HTMLEscapeString",
"(",
"email",
")",
"\n",
"return",
"template",
".",
"HTML",
"(",
"strings",
".",
"Replace",
"(",
"email",
",",
"\"",
"\"",
",",
"\"",
"\\\"",
"\\\"",
"\"",
",",
"-",
"1",
")",
")",
"\n",
"}"
] | // obfuscateEmail converts a string containing email adddress [email protected]
// into email<junk>@address.com. | [
"obfuscateEmail",
"converts",
"a",
"string",
"containing",
"email",
"adddress",
"email"
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/middleware.go#L301-L305 |
9,036 | luci/luci-go | milo/frontend/middleware.go | parseRFC3339 | func parseRFC3339(s string) time.Time {
t, err := time.Parse(time.RFC3339, s)
if err == nil {
return t
}
t, err = time.Parse(time.RFC3339Nano, s)
if err == nil {
return t
}
return time.Time{}
} | go | func parseRFC3339(s string) time.Time {
t, err := time.Parse(time.RFC3339, s)
if err == nil {
return t
}
t, err = time.Parse(time.RFC3339Nano, s)
if err == nil {
return t
}
return time.Time{}
} | [
"func",
"parseRFC3339",
"(",
"s",
"string",
")",
"time",
".",
"Time",
"{",
"t",
",",
"err",
":=",
"time",
".",
"Parse",
"(",
"time",
".",
"RFC3339",
",",
"s",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"t",
"\n",
"}",
"\n",
"t",
",",
"err",
"=",
"time",
".",
"Parse",
"(",
"time",
".",
"RFC3339Nano",
",",
"s",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"t",
"\n",
"}",
"\n",
"return",
"time",
".",
"Time",
"{",
"}",
"\n",
"}"
] | // parseRFC3339 parses time represented as a RFC3339 or RFC3339Nano string.
// If cannot parse, returns zero time. | [
"parseRFC3339",
"parses",
"time",
"represented",
"as",
"a",
"RFC3339",
"or",
"RFC3339Nano",
"string",
".",
"If",
"cannot",
"parse",
"returns",
"zero",
"time",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/middleware.go#L309-L319 |
9,037 | luci/luci-go | milo/frontend/middleware.go | GetLimit | func GetLimit(r *http.Request, def int) int {
sLimit := r.FormValue("limit")
if sLimit == "" {
sLimit = r.FormValue("numbuilds")
if sLimit == "" {
sLimit = r.FormValue("num_builds")
if sLimit == "" {
return def
}
}
}
limit, err := strconv.Atoi(sLimit)
if err != nil || limit < 0 {
return def
}
return limit
} | go | func GetLimit(r *http.Request, def int) int {
sLimit := r.FormValue("limit")
if sLimit == "" {
sLimit = r.FormValue("numbuilds")
if sLimit == "" {
sLimit = r.FormValue("num_builds")
if sLimit == "" {
return def
}
}
}
limit, err := strconv.Atoi(sLimit)
if err != nil || limit < 0 {
return def
}
return limit
} | [
"func",
"GetLimit",
"(",
"r",
"*",
"http",
".",
"Request",
",",
"def",
"int",
")",
"int",
"{",
"sLimit",
":=",
"r",
".",
"FormValue",
"(",
"\"",
"\"",
")",
"\n",
"if",
"sLimit",
"==",
"\"",
"\"",
"{",
"sLimit",
"=",
"r",
".",
"FormValue",
"(",
"\"",
"\"",
")",
"\n",
"if",
"sLimit",
"==",
"\"",
"\"",
"{",
"sLimit",
"=",
"r",
".",
"FormValue",
"(",
"\"",
"\"",
")",
"\n",
"if",
"sLimit",
"==",
"\"",
"\"",
"{",
"return",
"def",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"limit",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"sLimit",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"limit",
"<",
"0",
"{",
"return",
"def",
"\n",
"}",
"\n",
"return",
"limit",
"\n",
"}"
] | // GetLimit extracts the "limit", "numbuilds", or "num_builds" http param from
// the request, or returns def implying no limit was specified. | [
"GetLimit",
"extracts",
"the",
"limit",
"numbuilds",
"or",
"num_builds",
"http",
"param",
"from",
"the",
"request",
"or",
"returns",
"def",
"implying",
"no",
"limit",
"was",
"specified",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/middleware.go#L348-L364 |
9,038 | luci/luci-go | milo/frontend/middleware.go | GetReload | func GetReload(r *http.Request, def int) int {
sReload := r.FormValue("reload")
if sReload == "" {
return def
}
refresh, err := strconv.Atoi(sReload)
if err != nil || refresh < 0 {
return def
}
return refresh
} | go | func GetReload(r *http.Request, def int) int {
sReload := r.FormValue("reload")
if sReload == "" {
return def
}
refresh, err := strconv.Atoi(sReload)
if err != nil || refresh < 0 {
return def
}
return refresh
} | [
"func",
"GetReload",
"(",
"r",
"*",
"http",
".",
"Request",
",",
"def",
"int",
")",
"int",
"{",
"sReload",
":=",
"r",
".",
"FormValue",
"(",
"\"",
"\"",
")",
"\n",
"if",
"sReload",
"==",
"\"",
"\"",
"{",
"return",
"def",
"\n",
"}",
"\n",
"refresh",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"sReload",
")",
"\n",
"if",
"err",
"!=",
"nil",
"||",
"refresh",
"<",
"0",
"{",
"return",
"def",
"\n",
"}",
"\n",
"return",
"refresh",
"\n",
"}"
] | // GetReload extracts the "reload" http param from the request,
// or returns def implying no limit was specified. | [
"GetReload",
"extracts",
"the",
"reload",
"http",
"param",
"from",
"the",
"request",
"or",
"returns",
"def",
"implying",
"no",
"limit",
"was",
"specified",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/middleware.go#L368-L378 |
9,039 | luci/luci-go | milo/frontend/middleware.go | renderMarkdown | func renderMarkdown(t string) (results template.HTML) {
// We don't want auto punctuation, which changes "foo" into “foo”
r := blackfriday.NewHTMLRenderer(blackfriday.HTMLRendererParameters{
Flags: blackfriday.CommonHTMLFlags &^ blackfriday.Smartypants,
})
buf := bytes.NewBuffer(blackfriday.Run(
[]byte(t),
blackfriday.WithRenderer(r),
blackfriday.WithExtensions(blackfriday.CommonExtensions)))
out := bytes.NewBuffer(nil)
if err := sanitizehtml.Sanitize(out, buf); err != nil {
return template.HTML(fmt.Sprintf("Failed to render markdown: %s", template.HTMLEscapeString(err.Error())))
}
return template.HTML(out.String())
} | go | func renderMarkdown(t string) (results template.HTML) {
// We don't want auto punctuation, which changes "foo" into “foo”
r := blackfriday.NewHTMLRenderer(blackfriday.HTMLRendererParameters{
Flags: blackfriday.CommonHTMLFlags &^ blackfriday.Smartypants,
})
buf := bytes.NewBuffer(blackfriday.Run(
[]byte(t),
blackfriday.WithRenderer(r),
blackfriday.WithExtensions(blackfriday.CommonExtensions)))
out := bytes.NewBuffer(nil)
if err := sanitizehtml.Sanitize(out, buf); err != nil {
return template.HTML(fmt.Sprintf("Failed to render markdown: %s", template.HTMLEscapeString(err.Error())))
}
return template.HTML(out.String())
} | [
"func",
"renderMarkdown",
"(",
"t",
"string",
")",
"(",
"results",
"template",
".",
"HTML",
")",
"{",
"// We don't want auto punctuation, which changes \"foo\" into “foo”",
"r",
":=",
"blackfriday",
".",
"NewHTMLRenderer",
"(",
"blackfriday",
".",
"HTMLRendererParameters",
"{",
"Flags",
":",
"blackfriday",
".",
"CommonHTMLFlags",
"&^",
"blackfriday",
".",
"Smartypants",
",",
"}",
")",
"\n",
"buf",
":=",
"bytes",
".",
"NewBuffer",
"(",
"blackfriday",
".",
"Run",
"(",
"[",
"]",
"byte",
"(",
"t",
")",
",",
"blackfriday",
".",
"WithRenderer",
"(",
"r",
")",
",",
"blackfriday",
".",
"WithExtensions",
"(",
"blackfriday",
".",
"CommonExtensions",
")",
")",
")",
"\n",
"out",
":=",
"bytes",
".",
"NewBuffer",
"(",
"nil",
")",
"\n",
"if",
"err",
":=",
"sanitizehtml",
".",
"Sanitize",
"(",
"out",
",",
"buf",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"template",
".",
"HTML",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"template",
".",
"HTMLEscapeString",
"(",
"err",
".",
"Error",
"(",
")",
")",
")",
")",
"\n",
"}",
"\n",
"return",
"template",
".",
"HTML",
"(",
"out",
".",
"String",
"(",
")",
")",
"\n",
"}"
] | // renderMarkdown renders the given text as markdown HTML.
// This uses blackfriday to convert from markdown to HTML,
// and sanitizehtml to allow only a small subset of HTML through. | [
"renderMarkdown",
"renders",
"the",
"given",
"text",
"as",
"markdown",
"HTML",
".",
"This",
"uses",
"blackfriday",
"to",
"convert",
"from",
"markdown",
"to",
"HTML",
"and",
"sanitizehtml",
"to",
"allow",
"only",
"a",
"small",
"subset",
"of",
"HTML",
"through",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/middleware.go#L385-L399 |
9,040 | luci/luci-go | milo/frontend/middleware.go | pagedURL | func pagedURL(r *http.Request, limit int, cursor string) string {
if limit == 0 {
limit = GetLimit(r, -1)
if limit < 0 {
limit = 0
}
}
values := r.URL.Query()
switch cursor {
case "EMPTY":
values.Del("cursor")
case "":
// Do nothing, just leave the cursor in.
default:
values.Set("cursor", cursor)
}
switch {
case limit < 0:
values.Del("limit")
case limit > 0:
values.Set("limit", fmt.Sprintf("%d", limit))
}
result := *r.URL
result.RawQuery = values.Encode()
return result.String()
} | go | func pagedURL(r *http.Request, limit int, cursor string) string {
if limit == 0 {
limit = GetLimit(r, -1)
if limit < 0 {
limit = 0
}
}
values := r.URL.Query()
switch cursor {
case "EMPTY":
values.Del("cursor")
case "":
// Do nothing, just leave the cursor in.
default:
values.Set("cursor", cursor)
}
switch {
case limit < 0:
values.Del("limit")
case limit > 0:
values.Set("limit", fmt.Sprintf("%d", limit))
}
result := *r.URL
result.RawQuery = values.Encode()
return result.String()
} | [
"func",
"pagedURL",
"(",
"r",
"*",
"http",
".",
"Request",
",",
"limit",
"int",
",",
"cursor",
"string",
")",
"string",
"{",
"if",
"limit",
"==",
"0",
"{",
"limit",
"=",
"GetLimit",
"(",
"r",
",",
"-",
"1",
")",
"\n",
"if",
"limit",
"<",
"0",
"{",
"limit",
"=",
"0",
"\n",
"}",
"\n",
"}",
"\n",
"values",
":=",
"r",
".",
"URL",
".",
"Query",
"(",
")",
"\n",
"switch",
"cursor",
"{",
"case",
"\"",
"\"",
":",
"values",
".",
"Del",
"(",
"\"",
"\"",
")",
"\n",
"case",
"\"",
"\"",
":",
"// Do nothing, just leave the cursor in.",
"default",
":",
"values",
".",
"Set",
"(",
"\"",
"\"",
",",
"cursor",
")",
"\n",
"}",
"\n",
"switch",
"{",
"case",
"limit",
"<",
"0",
":",
"values",
".",
"Del",
"(",
"\"",
"\"",
")",
"\n",
"case",
"limit",
">",
"0",
":",
"values",
".",
"Set",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"limit",
")",
")",
"\n",
"}",
"\n",
"result",
":=",
"*",
"r",
".",
"URL",
"\n",
"result",
".",
"RawQuery",
"=",
"values",
".",
"Encode",
"(",
")",
"\n",
"return",
"result",
".",
"String",
"(",
")",
"\n",
"}"
] | // pagedURL returns a self URL with the given cursor and limit paging options.
// if limit is set to 0, then inherit whatever limit is set in request. If
// both are unspecified, then limit is omitted. | [
"pagedURL",
"returns",
"a",
"self",
"URL",
"with",
"the",
"given",
"cursor",
"and",
"limit",
"paging",
"options",
".",
"if",
"limit",
"is",
"set",
"to",
"0",
"then",
"inherit",
"whatever",
"limit",
"is",
"set",
"in",
"request",
".",
"If",
"both",
"are",
"unspecified",
"then",
"limit",
"is",
"omitted",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/middleware.go#L404-L429 |
9,041 | luci/luci-go | milo/frontend/middleware.go | percent | func percent(numerator, divisor int) string {
p := float64(numerator) * 100.0 / float64(divisor)
return fmt.Sprintf("%.1f", p)
} | go | func percent(numerator, divisor int) string {
p := float64(numerator) * 100.0 / float64(divisor)
return fmt.Sprintf("%.1f", p)
} | [
"func",
"percent",
"(",
"numerator",
",",
"divisor",
"int",
")",
"string",
"{",
"p",
":=",
"float64",
"(",
"numerator",
")",
"*",
"100.0",
"/",
"float64",
"(",
"divisor",
")",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"p",
")",
"\n",
"}"
] | // percent divides one number by a divisor and returns the percentage in string form. | [
"percent",
"divides",
"one",
"number",
"by",
"a",
"divisor",
"and",
"returns",
"the",
"percentage",
"in",
"string",
"form",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/middleware.go#L432-L435 |
9,042 | luci/luci-go | milo/frontend/middleware.go | faviconMIMEType | func faviconMIMEType(fileURL string) string {
switch {
case strings.HasSuffix(fileURL, ".png"):
return "image/png"
case strings.HasSuffix(fileURL, ".ico"):
return "image/ico"
case strings.HasSuffix(fileURL, ".jpeg"):
fallthrough
case strings.HasSuffix(fileURL, ".jpg"):
return "image/jpeg"
case strings.HasSuffix(fileURL, ".gif"):
return "image/gif"
}
return ""
} | go | func faviconMIMEType(fileURL string) string {
switch {
case strings.HasSuffix(fileURL, ".png"):
return "image/png"
case strings.HasSuffix(fileURL, ".ico"):
return "image/ico"
case strings.HasSuffix(fileURL, ".jpeg"):
fallthrough
case strings.HasSuffix(fileURL, ".jpg"):
return "image/jpeg"
case strings.HasSuffix(fileURL, ".gif"):
return "image/gif"
}
return ""
} | [
"func",
"faviconMIMEType",
"(",
"fileURL",
"string",
")",
"string",
"{",
"switch",
"{",
"case",
"strings",
".",
"HasSuffix",
"(",
"fileURL",
",",
"\"",
"\"",
")",
":",
"return",
"\"",
"\"",
"\n",
"case",
"strings",
".",
"HasSuffix",
"(",
"fileURL",
",",
"\"",
"\"",
")",
":",
"return",
"\"",
"\"",
"\n",
"case",
"strings",
".",
"HasSuffix",
"(",
"fileURL",
",",
"\"",
"\"",
")",
":",
"fallthrough",
"\n",
"case",
"strings",
".",
"HasSuffix",
"(",
"fileURL",
",",
"\"",
"\"",
")",
":",
"return",
"\"",
"\"",
"\n",
"case",
"strings",
".",
"HasSuffix",
"(",
"fileURL",
",",
"\"",
"\"",
")",
":",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // faviconMIMEType derives the MIME type from a URL's file extension. Only valid
// favicon image formats are supported. | [
"faviconMIMEType",
"derives",
"the",
"MIME",
"type",
"from",
"a",
"URL",
"s",
"file",
"extension",
".",
"Only",
"valid",
"favicon",
"image",
"formats",
"are",
"supported",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/middleware.go#L439-L453 |
9,043 | luci/luci-go | milo/frontend/middleware.go | getTemplateBundle | func getTemplateBundle(templatePath string) *templates.Bundle {
return &templates.Bundle{
Loader: templates.FileSystemLoader(templatePath),
DebugMode: info.IsDevAppServer,
DefaultTemplate: "base",
DefaultArgs: func(c context.Context, e *templates.Extra) (templates.Args, error) {
loginURL, err := auth.LoginURL(c, e.Request.URL.RequestURI())
if err != nil {
return nil, err
}
logoutURL, err := auth.LogoutURL(c, e.Request.URL.RequestURI())
if err != nil {
return nil, err
}
project := e.Params.ByName("project")
group := e.Params.ByName("group")
return templates.Args{
"AppVersion": strings.Split(info.VersionID(c), ".")[0],
"IsAnonymous": auth.CurrentIdentity(c) == identity.AnonymousIdentity,
"User": auth.CurrentUser(c),
"LoginURL": loginURL,
"LogoutURL": logoutURL,
"CurrentTime": clock.Now(c),
"Analytics": analytics.Snippet(c),
"RequestID": info.RequestID(c),
"Request": e.Request,
"Navi": ProjectLinks(c, project, group),
"ProjectID": project,
}, nil
},
FuncMap: funcMap,
}
} | go | func getTemplateBundle(templatePath string) *templates.Bundle {
return &templates.Bundle{
Loader: templates.FileSystemLoader(templatePath),
DebugMode: info.IsDevAppServer,
DefaultTemplate: "base",
DefaultArgs: func(c context.Context, e *templates.Extra) (templates.Args, error) {
loginURL, err := auth.LoginURL(c, e.Request.URL.RequestURI())
if err != nil {
return nil, err
}
logoutURL, err := auth.LogoutURL(c, e.Request.URL.RequestURI())
if err != nil {
return nil, err
}
project := e.Params.ByName("project")
group := e.Params.ByName("group")
return templates.Args{
"AppVersion": strings.Split(info.VersionID(c), ".")[0],
"IsAnonymous": auth.CurrentIdentity(c) == identity.AnonymousIdentity,
"User": auth.CurrentUser(c),
"LoginURL": loginURL,
"LogoutURL": logoutURL,
"CurrentTime": clock.Now(c),
"Analytics": analytics.Snippet(c),
"RequestID": info.RequestID(c),
"Request": e.Request,
"Navi": ProjectLinks(c, project, group),
"ProjectID": project,
}, nil
},
FuncMap: funcMap,
}
} | [
"func",
"getTemplateBundle",
"(",
"templatePath",
"string",
")",
"*",
"templates",
".",
"Bundle",
"{",
"return",
"&",
"templates",
".",
"Bundle",
"{",
"Loader",
":",
"templates",
".",
"FileSystemLoader",
"(",
"templatePath",
")",
",",
"DebugMode",
":",
"info",
".",
"IsDevAppServer",
",",
"DefaultTemplate",
":",
"\"",
"\"",
",",
"DefaultArgs",
":",
"func",
"(",
"c",
"context",
".",
"Context",
",",
"e",
"*",
"templates",
".",
"Extra",
")",
"(",
"templates",
".",
"Args",
",",
"error",
")",
"{",
"loginURL",
",",
"err",
":=",
"auth",
".",
"LoginURL",
"(",
"c",
",",
"e",
".",
"Request",
".",
"URL",
".",
"RequestURI",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"logoutURL",
",",
"err",
":=",
"auth",
".",
"LogoutURL",
"(",
"c",
",",
"e",
".",
"Request",
".",
"URL",
".",
"RequestURI",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"project",
":=",
"e",
".",
"Params",
".",
"ByName",
"(",
"\"",
"\"",
")",
"\n",
"group",
":=",
"e",
".",
"Params",
".",
"ByName",
"(",
"\"",
"\"",
")",
"\n\n",
"return",
"templates",
".",
"Args",
"{",
"\"",
"\"",
":",
"strings",
".",
"Split",
"(",
"info",
".",
"VersionID",
"(",
"c",
")",
",",
"\"",
"\"",
")",
"[",
"0",
"]",
",",
"\"",
"\"",
":",
"auth",
".",
"CurrentIdentity",
"(",
"c",
")",
"==",
"identity",
".",
"AnonymousIdentity",
",",
"\"",
"\"",
":",
"auth",
".",
"CurrentUser",
"(",
"c",
")",
",",
"\"",
"\"",
":",
"loginURL",
",",
"\"",
"\"",
":",
"logoutURL",
",",
"\"",
"\"",
":",
"clock",
".",
"Now",
"(",
"c",
")",
",",
"\"",
"\"",
":",
"analytics",
".",
"Snippet",
"(",
"c",
")",
",",
"\"",
"\"",
":",
"info",
".",
"RequestID",
"(",
"c",
")",
",",
"\"",
"\"",
":",
"e",
".",
"Request",
",",
"\"",
"\"",
":",
"ProjectLinks",
"(",
"c",
",",
"project",
",",
"group",
")",
",",
"\"",
"\"",
":",
"project",
",",
"}",
",",
"nil",
"\n",
"}",
",",
"FuncMap",
":",
"funcMap",
",",
"}",
"\n",
"}"
] | // getTemplateBundles is used to render HTML templates. It provides base args
// passed to all templates. It takes a path to the template folder, relative
// to the path of the binary during runtime. | [
"getTemplateBundles",
"is",
"used",
"to",
"render",
"HTML",
"templates",
".",
"It",
"provides",
"base",
"args",
"passed",
"to",
"all",
"templates",
".",
"It",
"takes",
"a",
"path",
"to",
"the",
"template",
"folder",
"relative",
"to",
"the",
"path",
"of",
"the",
"binary",
"during",
"runtime",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/middleware.go#L458-L492 |
9,044 | luci/luci-go | milo/frontend/middleware.go | withBuildbucketClient | func withBuildbucketClient(c *router.Context, next router.Handler) {
c.Context = buildbucket.WithClientFactory(c.Context, buildbucket.ProdClientFactory)
next(c)
} | go | func withBuildbucketClient(c *router.Context, next router.Handler) {
c.Context = buildbucket.WithClientFactory(c.Context, buildbucket.ProdClientFactory)
next(c)
} | [
"func",
"withBuildbucketClient",
"(",
"c",
"*",
"router",
".",
"Context",
",",
"next",
"router",
".",
"Handler",
")",
"{",
"c",
".",
"Context",
"=",
"buildbucket",
".",
"WithClientFactory",
"(",
"c",
".",
"Context",
",",
"buildbucket",
".",
"ProdClientFactory",
")",
"\n",
"next",
"(",
"c",
")",
"\n",
"}"
] | // withBuildbucketClient is a middleware that installs a production buildbucket RPC client into the context. | [
"withBuildbucketClient",
"is",
"a",
"middleware",
"that",
"installs",
"a",
"production",
"buildbucket",
"RPC",
"client",
"into",
"the",
"context",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/middleware.go#L495-L498 |
9,045 | luci/luci-go | milo/frontend/middleware.go | withGitMiddleware | func withGitMiddleware(c *router.Context, next router.Handler) {
acls, err := gitacls.FromConfig(c.Context, common.GetSettings(c.Context).SourceAcls)
if err != nil {
ErrorHandler(c, err)
return
}
c.Context = git.UseACLs(c.Context, acls)
next(c)
} | go | func withGitMiddleware(c *router.Context, next router.Handler) {
acls, err := gitacls.FromConfig(c.Context, common.GetSettings(c.Context).SourceAcls)
if err != nil {
ErrorHandler(c, err)
return
}
c.Context = git.UseACLs(c.Context, acls)
next(c)
} | [
"func",
"withGitMiddleware",
"(",
"c",
"*",
"router",
".",
"Context",
",",
"next",
"router",
".",
"Handler",
")",
"{",
"acls",
",",
"err",
":=",
"gitacls",
".",
"FromConfig",
"(",
"c",
".",
"Context",
",",
"common",
".",
"GetSettings",
"(",
"c",
".",
"Context",
")",
".",
"SourceAcls",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"ErrorHandler",
"(",
"c",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"c",
".",
"Context",
"=",
"git",
".",
"UseACLs",
"(",
"c",
".",
"Context",
",",
"acls",
")",
"\n",
"next",
"(",
"c",
")",
"\n",
"}"
] | // withGitMiddleware is a middleware that installs a prod Gerrit and Gitiles client
// factory into the context. Both use Milo's credentials if current user is
// has been granted read access in settings.cfg.
//
// This middleware must be installed after the auth middleware. | [
"withGitMiddleware",
"is",
"a",
"middleware",
"that",
"installs",
"a",
"prod",
"Gerrit",
"and",
"Gitiles",
"client",
"factory",
"into",
"the",
"context",
".",
"Both",
"use",
"Milo",
"s",
"credentials",
"if",
"current",
"user",
"is",
"has",
"been",
"granted",
"read",
"access",
"in",
"settings",
".",
"cfg",
".",
"This",
"middleware",
"must",
"be",
"installed",
"after",
"the",
"auth",
"middleware",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/middleware.go#L505-L513 |
9,046 | luci/luci-go | milo/frontend/middleware.go | withAccessClientMiddleware | func withAccessClientMiddleware(c *router.Context, next router.Handler) {
client, err := common.NewAccessClient(c.Context)
if err != nil {
ErrorHandler(c, err)
return
}
c.Context = common.WithAccessClient(c.Context, client)
next(c)
} | go | func withAccessClientMiddleware(c *router.Context, next router.Handler) {
client, err := common.NewAccessClient(c.Context)
if err != nil {
ErrorHandler(c, err)
return
}
c.Context = common.WithAccessClient(c.Context, client)
next(c)
} | [
"func",
"withAccessClientMiddleware",
"(",
"c",
"*",
"router",
".",
"Context",
",",
"next",
"router",
".",
"Handler",
")",
"{",
"client",
",",
"err",
":=",
"common",
".",
"NewAccessClient",
"(",
"c",
".",
"Context",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"ErrorHandler",
"(",
"c",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"c",
".",
"Context",
"=",
"common",
".",
"WithAccessClient",
"(",
"c",
".",
"Context",
",",
"client",
")",
"\n",
"next",
"(",
"c",
")",
"\n",
"}"
] | // withAccessClientMiddleware is a middleware that installs a prod buildbucket
// access API client into the context.
//
// This middleware depends on auth middleware in order to generate the access
// client, so it must be called after the auth middleware is installed. | [
"withAccessClientMiddleware",
"is",
"a",
"middleware",
"that",
"installs",
"a",
"prod",
"buildbucket",
"access",
"API",
"client",
"into",
"the",
"context",
".",
"This",
"middleware",
"depends",
"on",
"auth",
"middleware",
"in",
"order",
"to",
"generate",
"the",
"access",
"client",
"so",
"it",
"must",
"be",
"called",
"after",
"the",
"auth",
"middleware",
"is",
"installed",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/middleware.go#L520-L528 |
9,047 | luci/luci-go | milo/frontend/middleware.go | projectACLMiddleware | func projectACLMiddleware(c *router.Context, next router.Handler) {
luciProject := c.Params.ByName("project")
switch allowed, err := common.IsAllowed(c.Context, luciProject); {
case err != nil:
ErrorHandler(c, err)
case !allowed:
if auth.CurrentIdentity(c.Context) == identity.AnonymousIdentity {
ErrorHandler(c, errors.New("not logged in", grpcutil.UnauthenticatedTag))
} else {
ErrorHandler(c, errors.New("no access to project", grpcutil.PermissionDeniedTag))
}
default:
c.Context = git.WithProject(c.Context, luciProject)
next(c)
}
} | go | func projectACLMiddleware(c *router.Context, next router.Handler) {
luciProject := c.Params.ByName("project")
switch allowed, err := common.IsAllowed(c.Context, luciProject); {
case err != nil:
ErrorHandler(c, err)
case !allowed:
if auth.CurrentIdentity(c.Context) == identity.AnonymousIdentity {
ErrorHandler(c, errors.New("not logged in", grpcutil.UnauthenticatedTag))
} else {
ErrorHandler(c, errors.New("no access to project", grpcutil.PermissionDeniedTag))
}
default:
c.Context = git.WithProject(c.Context, luciProject)
next(c)
}
} | [
"func",
"projectACLMiddleware",
"(",
"c",
"*",
"router",
".",
"Context",
",",
"next",
"router",
".",
"Handler",
")",
"{",
"luciProject",
":=",
"c",
".",
"Params",
".",
"ByName",
"(",
"\"",
"\"",
")",
"\n",
"switch",
"allowed",
",",
"err",
":=",
"common",
".",
"IsAllowed",
"(",
"c",
".",
"Context",
",",
"luciProject",
")",
";",
"{",
"case",
"err",
"!=",
"nil",
":",
"ErrorHandler",
"(",
"c",
",",
"err",
")",
"\n",
"case",
"!",
"allowed",
":",
"if",
"auth",
".",
"CurrentIdentity",
"(",
"c",
".",
"Context",
")",
"==",
"identity",
".",
"AnonymousIdentity",
"{",
"ErrorHandler",
"(",
"c",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
",",
"grpcutil",
".",
"UnauthenticatedTag",
")",
")",
"\n",
"}",
"else",
"{",
"ErrorHandler",
"(",
"c",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
",",
"grpcutil",
".",
"PermissionDeniedTag",
")",
")",
"\n",
"}",
"\n",
"default",
":",
"c",
".",
"Context",
"=",
"git",
".",
"WithProject",
"(",
"c",
".",
"Context",
",",
"luciProject",
")",
"\n",
"next",
"(",
"c",
")",
"\n",
"}",
"\n",
"}"
] | // projectACLMiddleware adds ACL checks on a per-project basis.
// Expects c.Params to have project parameter. | [
"projectACLMiddleware",
"adds",
"ACL",
"checks",
"on",
"a",
"per",
"-",
"project",
"basis",
".",
"Expects",
"c",
".",
"Params",
"to",
"have",
"project",
"parameter",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/middleware.go#L532-L547 |
9,048 | luci/luci-go | milo/frontend/middleware.go | emulationMiddleware | func emulationMiddleware(c *router.Context, next router.Handler) {
c.Context = buildstore.WithEmulation(c.Context, c.Request.FormValue("emulation") != "")
next(c)
} | go | func emulationMiddleware(c *router.Context, next router.Handler) {
c.Context = buildstore.WithEmulation(c.Context, c.Request.FormValue("emulation") != "")
next(c)
} | [
"func",
"emulationMiddleware",
"(",
"c",
"*",
"router",
".",
"Context",
",",
"next",
"router",
".",
"Handler",
")",
"{",
"c",
".",
"Context",
"=",
"buildstore",
".",
"WithEmulation",
"(",
"c",
".",
"Context",
",",
"c",
".",
"Request",
".",
"FormValue",
"(",
"\"",
"\"",
")",
"!=",
"\"",
"\"",
")",
"\n",
"next",
"(",
"c",
")",
"\n",
"}"
] | // emulationMiddleware enables buildstore emulation if "emulation" query
// string parameter is not empty. | [
"emulationMiddleware",
"enables",
"buildstore",
"emulation",
"if",
"emulation",
"query",
"string",
"parameter",
"is",
"not",
"empty",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/middleware.go#L551-L554 |
9,049 | luci/luci-go | milo/frontend/middleware.go | ProjectLinks | func ProjectLinks(c context.Context, project, group string) []ui.LinkGroup {
if project == "" {
return nil
}
projLinks := []*ui.Link{
ui.NewLink(
"Builders",
fmt.Sprintf("/p/%s/builders", project),
fmt.Sprintf("All builders for project %s", project))}
links := []ui.LinkGroup{
{
Name: ui.NewLink(
project,
fmt.Sprintf("/p/%s", project),
fmt.Sprintf("Project page for %s", project)),
Links: projLinks,
},
}
if group != "" {
groupLinks := []*ui.Link{}
con, err := common.GetConsole(c, project, group)
if err != nil {
logging.WithError(err).Warningf(c, "error getting console")
} else if !con.Def.BuilderViewOnly {
groupLinks = append(groupLinks, ui.NewLink(
"Console",
fmt.Sprintf("/p/%s/g/%s/console", project, group),
fmt.Sprintf("Console for group %s in project %s", group, project)))
}
groupLinks = append(groupLinks, ui.NewLink(
"Builders",
fmt.Sprintf("/p/%s/g/%s/builders", project, group),
fmt.Sprintf("Builders for group %s in project %s", group, project)))
links = append(links, ui.LinkGroup{
Name: ui.NewLink(group, "", ""),
Links: groupLinks,
})
}
return links
} | go | func ProjectLinks(c context.Context, project, group string) []ui.LinkGroup {
if project == "" {
return nil
}
projLinks := []*ui.Link{
ui.NewLink(
"Builders",
fmt.Sprintf("/p/%s/builders", project),
fmt.Sprintf("All builders for project %s", project))}
links := []ui.LinkGroup{
{
Name: ui.NewLink(
project,
fmt.Sprintf("/p/%s", project),
fmt.Sprintf("Project page for %s", project)),
Links: projLinks,
},
}
if group != "" {
groupLinks := []*ui.Link{}
con, err := common.GetConsole(c, project, group)
if err != nil {
logging.WithError(err).Warningf(c, "error getting console")
} else if !con.Def.BuilderViewOnly {
groupLinks = append(groupLinks, ui.NewLink(
"Console",
fmt.Sprintf("/p/%s/g/%s/console", project, group),
fmt.Sprintf("Console for group %s in project %s", group, project)))
}
groupLinks = append(groupLinks, ui.NewLink(
"Builders",
fmt.Sprintf("/p/%s/g/%s/builders", project, group),
fmt.Sprintf("Builders for group %s in project %s", group, project)))
links = append(links, ui.LinkGroup{
Name: ui.NewLink(group, "", ""),
Links: groupLinks,
})
}
return links
} | [
"func",
"ProjectLinks",
"(",
"c",
"context",
".",
"Context",
",",
"project",
",",
"group",
"string",
")",
"[",
"]",
"ui",
".",
"LinkGroup",
"{",
"if",
"project",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"projLinks",
":=",
"[",
"]",
"*",
"ui",
".",
"Link",
"{",
"ui",
".",
"NewLink",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"project",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"project",
")",
")",
"}",
"\n",
"links",
":=",
"[",
"]",
"ui",
".",
"LinkGroup",
"{",
"{",
"Name",
":",
"ui",
".",
"NewLink",
"(",
"project",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"project",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"project",
")",
")",
",",
"Links",
":",
"projLinks",
",",
"}",
",",
"}",
"\n",
"if",
"group",
"!=",
"\"",
"\"",
"{",
"groupLinks",
":=",
"[",
"]",
"*",
"ui",
".",
"Link",
"{",
"}",
"\n",
"con",
",",
"err",
":=",
"common",
".",
"GetConsole",
"(",
"c",
",",
"project",
",",
"group",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logging",
".",
"WithError",
"(",
"err",
")",
".",
"Warningf",
"(",
"c",
",",
"\"",
"\"",
")",
"\n",
"}",
"else",
"if",
"!",
"con",
".",
"Def",
".",
"BuilderViewOnly",
"{",
"groupLinks",
"=",
"append",
"(",
"groupLinks",
",",
"ui",
".",
"NewLink",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"project",
",",
"group",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"group",
",",
"project",
")",
")",
")",
"\n",
"}",
"\n\n",
"groupLinks",
"=",
"append",
"(",
"groupLinks",
",",
"ui",
".",
"NewLink",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"project",
",",
"group",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"group",
",",
"project",
")",
")",
")",
"\n\n",
"links",
"=",
"append",
"(",
"links",
",",
"ui",
".",
"LinkGroup",
"{",
"Name",
":",
"ui",
".",
"NewLink",
"(",
"group",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"Links",
":",
"groupLinks",
",",
"}",
")",
"\n",
"}",
"\n",
"return",
"links",
"\n",
"}"
] | // ProjectLinks returns the navigation list surrounding a project and optionally group. | [
"ProjectLinks",
"returns",
"the",
"navigation",
"list",
"surrounding",
"a",
"project",
"and",
"optionally",
"group",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/middleware.go#L557-L598 |
9,050 | luci/luci-go | milo/buildsource/buildbucket/client.go | WithClientFactory | func WithClientFactory(c context.Context, factory clientFactory) context.Context {
return context.WithValue(c, &clientContextKey, factory)
} | go | func WithClientFactory(c context.Context, factory clientFactory) context.Context {
return context.WithValue(c, &clientContextKey, factory)
} | [
"func",
"WithClientFactory",
"(",
"c",
"context",
".",
"Context",
",",
"factory",
"clientFactory",
")",
"context",
".",
"Context",
"{",
"return",
"context",
".",
"WithValue",
"(",
"c",
",",
"&",
"clientContextKey",
",",
"factory",
")",
"\n",
"}"
] | // WithClientFactory installs a buildbucket rpc client in the context. | [
"WithClientFactory",
"installs",
"a",
"buildbucket",
"rpc",
"client",
"in",
"the",
"context",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbucket/client.go#L44-L46 |
9,051 | luci/luci-go | buildbucket/cli/baserun.go | initClients | func (r *baseCommandRun) initClients(ctx context.Context) error {
// Create HTTP Client.
authOpts, err := r.authFlags.Options()
if err != nil {
return err
}
r.httpClient, err = auth.NewAuthenticator(ctx, auth.SilentLogin, authOpts).Client()
if err != nil {
return err
}
// Validate -host
if r.host == "" {
return fmt.Errorf("a host for the buildbucket service must be provided")
}
if strings.ContainsRune(r.host, '/') {
return fmt.Errorf("invalid host %q", r.host)
}
// Create Buildbucket client.
rpcOpts := prpc.DefaultOptions()
rpcOpts.Insecure = lhttp.IsLocalHost(r.host)
info, err := version.GetCurrentVersion()
if err != nil {
return err
}
rpcOpts.UserAgent = fmt.Sprintf("buildbucket CLI, instanceID=%q", info.InstanceID)
r.client = pb.NewBuildsPRPCClient(&prpc.Client{
C: r.httpClient,
Host: r.host,
Options: rpcOpts,
})
return nil
} | go | func (r *baseCommandRun) initClients(ctx context.Context) error {
// Create HTTP Client.
authOpts, err := r.authFlags.Options()
if err != nil {
return err
}
r.httpClient, err = auth.NewAuthenticator(ctx, auth.SilentLogin, authOpts).Client()
if err != nil {
return err
}
// Validate -host
if r.host == "" {
return fmt.Errorf("a host for the buildbucket service must be provided")
}
if strings.ContainsRune(r.host, '/') {
return fmt.Errorf("invalid host %q", r.host)
}
// Create Buildbucket client.
rpcOpts := prpc.DefaultOptions()
rpcOpts.Insecure = lhttp.IsLocalHost(r.host)
info, err := version.GetCurrentVersion()
if err != nil {
return err
}
rpcOpts.UserAgent = fmt.Sprintf("buildbucket CLI, instanceID=%q", info.InstanceID)
r.client = pb.NewBuildsPRPCClient(&prpc.Client{
C: r.httpClient,
Host: r.host,
Options: rpcOpts,
})
return nil
} | [
"func",
"(",
"r",
"*",
"baseCommandRun",
")",
"initClients",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"// Create HTTP Client.",
"authOpts",
",",
"err",
":=",
"r",
".",
"authFlags",
".",
"Options",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"r",
".",
"httpClient",
",",
"err",
"=",
"auth",
".",
"NewAuthenticator",
"(",
"ctx",
",",
"auth",
".",
"SilentLogin",
",",
"authOpts",
")",
".",
"Client",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Validate -host",
"if",
"r",
".",
"host",
"==",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"strings",
".",
"ContainsRune",
"(",
"r",
".",
"host",
",",
"'/'",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"r",
".",
"host",
")",
"\n",
"}",
"\n\n",
"// Create Buildbucket client.",
"rpcOpts",
":=",
"prpc",
".",
"DefaultOptions",
"(",
")",
"\n",
"rpcOpts",
".",
"Insecure",
"=",
"lhttp",
".",
"IsLocalHost",
"(",
"r",
".",
"host",
")",
"\n",
"info",
",",
"err",
":=",
"version",
".",
"GetCurrentVersion",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"rpcOpts",
".",
"UserAgent",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"info",
".",
"InstanceID",
")",
"\n",
"r",
".",
"client",
"=",
"pb",
".",
"NewBuildsPRPCClient",
"(",
"&",
"prpc",
".",
"Client",
"{",
"C",
":",
"r",
".",
"httpClient",
",",
"Host",
":",
"r",
".",
"host",
",",
"Options",
":",
"rpcOpts",
",",
"}",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // initClients validates -host flag and initializes r.httpClient and r.client. | [
"initClients",
"validates",
"-",
"host",
"flag",
"and",
"initializes",
"r",
".",
"httpClient",
"and",
"r",
".",
"client",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/cli/baserun.go#L78-L111 |
9,052 | luci/luci-go | buildbucket/cli/baserun.go | retrieveBuildID | func (r *baseCommandRun) retrieveBuildID(ctx context.Context, build string) (int64, error) {
getBuild, err := protoutil.ParseGetBuildRequest(build)
if err != nil {
return 0, err
}
if getBuild.Id != 0 {
return getBuild.Id, nil
}
res, err := r.client.GetBuild(ctx, getBuild)
if err != nil {
return 0, err
}
return res.Id, nil
} | go | func (r *baseCommandRun) retrieveBuildID(ctx context.Context, build string) (int64, error) {
getBuild, err := protoutil.ParseGetBuildRequest(build)
if err != nil {
return 0, err
}
if getBuild.Id != 0 {
return getBuild.Id, nil
}
res, err := r.client.GetBuild(ctx, getBuild)
if err != nil {
return 0, err
}
return res.Id, nil
} | [
"func",
"(",
"r",
"*",
"baseCommandRun",
")",
"retrieveBuildID",
"(",
"ctx",
"context",
".",
"Context",
",",
"build",
"string",
")",
"(",
"int64",
",",
"error",
")",
"{",
"getBuild",
",",
"err",
":=",
"protoutil",
".",
"ParseGetBuildRequest",
"(",
"build",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n\n",
"if",
"getBuild",
".",
"Id",
"!=",
"0",
"{",
"return",
"getBuild",
".",
"Id",
",",
"nil",
"\n",
"}",
"\n\n",
"res",
",",
"err",
":=",
"r",
".",
"client",
".",
"GetBuild",
"(",
"ctx",
",",
"getBuild",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"return",
"res",
".",
"Id",
",",
"nil",
"\n",
"}"
] | // retrieveBuildID converts a build string into a build id.
// May make a GetBuild RPC. | [
"retrieveBuildID",
"converts",
"a",
"build",
"string",
"into",
"a",
"build",
"id",
".",
"May",
"make",
"a",
"GetBuild",
"RPC",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/cli/baserun.go#L174-L189 |
9,053 | luci/luci-go | gce/api/config/v1/configs.go | Validate | func (cfgs *Configs) Validate(c *validation.Context) {
prefixes := make([]string, 0, len(cfgs.GetVms()))
for i, cfg := range cfgs.GetVms() {
c.Enter("vms config %d", i)
if cfg.Prefix == "" {
c.Errorf("prefix is required")
}
// Ensure no prefix is a prefix of any other prefix. Building a prefix tree
// and waiting until the end to check this is faster, but config validation
// isn't particularly time sensitive since configs are processed asynchronously.
for _, p := range prefixes {
switch {
case strings.HasPrefix(p, cfg.Prefix):
c.Errorf("prefix %q is a prefix of %q", cfg.Prefix, p)
case strings.HasPrefix(cfg.Prefix, p):
c.Errorf("prefix %q is a prefix of %q", p, cfg.Prefix)
}
}
prefixes = append(prefixes, cfg.Prefix)
cfg.Validate(c)
c.Exit()
}
} | go | func (cfgs *Configs) Validate(c *validation.Context) {
prefixes := make([]string, 0, len(cfgs.GetVms()))
for i, cfg := range cfgs.GetVms() {
c.Enter("vms config %d", i)
if cfg.Prefix == "" {
c.Errorf("prefix is required")
}
// Ensure no prefix is a prefix of any other prefix. Building a prefix tree
// and waiting until the end to check this is faster, but config validation
// isn't particularly time sensitive since configs are processed asynchronously.
for _, p := range prefixes {
switch {
case strings.HasPrefix(p, cfg.Prefix):
c.Errorf("prefix %q is a prefix of %q", cfg.Prefix, p)
case strings.HasPrefix(cfg.Prefix, p):
c.Errorf("prefix %q is a prefix of %q", p, cfg.Prefix)
}
}
prefixes = append(prefixes, cfg.Prefix)
cfg.Validate(c)
c.Exit()
}
} | [
"func",
"(",
"cfgs",
"*",
"Configs",
")",
"Validate",
"(",
"c",
"*",
"validation",
".",
"Context",
")",
"{",
"prefixes",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"cfgs",
".",
"GetVms",
"(",
")",
")",
")",
"\n",
"for",
"i",
",",
"cfg",
":=",
"range",
"cfgs",
".",
"GetVms",
"(",
")",
"{",
"c",
".",
"Enter",
"(",
"\"",
"\"",
",",
"i",
")",
"\n",
"if",
"cfg",
".",
"Prefix",
"==",
"\"",
"\"",
"{",
"c",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// Ensure no prefix is a prefix of any other prefix. Building a prefix tree",
"// and waiting until the end to check this is faster, but config validation",
"// isn't particularly time sensitive since configs are processed asynchronously.",
"for",
"_",
",",
"p",
":=",
"range",
"prefixes",
"{",
"switch",
"{",
"case",
"strings",
".",
"HasPrefix",
"(",
"p",
",",
"cfg",
".",
"Prefix",
")",
":",
"c",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"cfg",
".",
"Prefix",
",",
"p",
")",
"\n",
"case",
"strings",
".",
"HasPrefix",
"(",
"cfg",
".",
"Prefix",
",",
"p",
")",
":",
"c",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"p",
",",
"cfg",
".",
"Prefix",
")",
"\n",
"}",
"\n",
"}",
"\n",
"prefixes",
"=",
"append",
"(",
"prefixes",
",",
"cfg",
".",
"Prefix",
")",
"\n",
"cfg",
".",
"Validate",
"(",
"c",
")",
"\n",
"c",
".",
"Exit",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // Validate validates these configs. Kinds must already be applied. | [
"Validate",
"validates",
"these",
"configs",
".",
"Kinds",
"must",
"already",
"be",
"applied",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/api/config/v1/configs.go#L24-L46 |
9,054 | luci/luci-go | common/proto/gerrit/gerrit.mock.pb.go | NewMockGerritClient | func NewMockGerritClient(ctrl *gomock.Controller) *MockGerritClient {
mock := &MockGerritClient{ctrl: ctrl}
mock.recorder = &MockGerritClientMockRecorder{mock}
return mock
} | go | func NewMockGerritClient(ctrl *gomock.Controller) *MockGerritClient {
mock := &MockGerritClient{ctrl: ctrl}
mock.recorder = &MockGerritClientMockRecorder{mock}
return mock
} | [
"func",
"NewMockGerritClient",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockGerritClient",
"{",
"mock",
":=",
"&",
"MockGerritClient",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockGerritClientMockRecorder",
"{",
"mock",
"}",
"\n",
"return",
"mock",
"\n",
"}"
] | // NewMockGerritClient creates a new mock instance | [
"NewMockGerritClient",
"creates",
"a",
"new",
"mock",
"instance"
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/proto/gerrit/gerrit.mock.pb.go#L27-L31 |
9,055 | luci/luci-go | common/proto/gerrit/gerrit.mock.pb.go | ChangeEditPublish | func (mr *MockGerritClientMockRecorder) ChangeEditPublish(ctx, in interface{}, opts ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{ctx, in}, opts...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ChangeEditPublish", reflect.TypeOf((*MockGerritClient)(nil).ChangeEditPublish), varargs...)
} | go | func (mr *MockGerritClientMockRecorder) ChangeEditPublish(ctx, in interface{}, opts ...interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
varargs := append([]interface{}{ctx, in}, opts...)
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ChangeEditPublish", reflect.TypeOf((*MockGerritClient)(nil).ChangeEditPublish), varargs...)
} | [
"func",
"(",
"mr",
"*",
"MockGerritClientMockRecorder",
")",
"ChangeEditPublish",
"(",
"ctx",
",",
"in",
"interface",
"{",
"}",
",",
"opts",
"...",
"interface",
"{",
"}",
")",
"*",
"gomock",
".",
"Call",
"{",
"mr",
".",
"mock",
".",
"ctrl",
".",
"T",
".",
"Helper",
"(",
")",
"\n",
"varargs",
":=",
"append",
"(",
"[",
"]",
"interface",
"{",
"}",
"{",
"ctx",
",",
"in",
"}",
",",
"opts",
"...",
")",
"\n",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
"reflect",
".",
"TypeOf",
"(",
"(",
"*",
"MockGerritClient",
")",
"(",
"nil",
")",
".",
"ChangeEditPublish",
")",
",",
"varargs",
"...",
")",
"\n",
"}"
] | // ChangeEditPublish indicates an expected call of ChangeEditPublish | [
"ChangeEditPublish",
"indicates",
"an",
"expected",
"call",
"of",
"ChangeEditPublish"
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/proto/gerrit/gerrit.mock.pb.go#L112-L116 |
9,056 | luci/luci-go | common/proto/gerrit/gerrit.mock.pb.go | NewMockGerritServer | func NewMockGerritServer(ctrl *gomock.Controller) *MockGerritServer {
mock := &MockGerritServer{ctrl: ctrl}
mock.recorder = &MockGerritServerMockRecorder{mock}
return mock
} | go | func NewMockGerritServer(ctrl *gomock.Controller) *MockGerritServer {
mock := &MockGerritServer{ctrl: ctrl}
mock.recorder = &MockGerritServerMockRecorder{mock}
return mock
} | [
"func",
"NewMockGerritServer",
"(",
"ctrl",
"*",
"gomock",
".",
"Controller",
")",
"*",
"MockGerritServer",
"{",
"mock",
":=",
"&",
"MockGerritServer",
"{",
"ctrl",
":",
"ctrl",
"}",
"\n",
"mock",
".",
"recorder",
"=",
"&",
"MockGerritServerMockRecorder",
"{",
"mock",
"}",
"\n",
"return",
"mock",
"\n",
"}"
] | // NewMockGerritServer creates a new mock instance | [
"NewMockGerritServer",
"creates",
"a",
"new",
"mock",
"instance"
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/proto/gerrit/gerrit.mock.pb.go#L190-L194 |
9,057 | luci/luci-go | common/proto/gerrit/gerrit.mock.pb.go | GetChange | func (mr *MockGerritServerMockRecorder) GetChange(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetChange", reflect.TypeOf((*MockGerritServer)(nil).GetChange), arg0, arg1)
} | go | func (mr *MockGerritServerMockRecorder) GetChange(arg0, arg1 interface{}) *gomock.Call {
mr.mock.ctrl.T.Helper()
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetChange", reflect.TypeOf((*MockGerritServer)(nil).GetChange), arg0, arg1)
} | [
"func",
"(",
"mr",
"*",
"MockGerritServerMockRecorder",
")",
"GetChange",
"(",
"arg0",
",",
"arg1",
"interface",
"{",
"}",
")",
"*",
"gomock",
".",
"Call",
"{",
"mr",
".",
"mock",
".",
"ctrl",
".",
"T",
".",
"Helper",
"(",
")",
"\n",
"return",
"mr",
".",
"mock",
".",
"ctrl",
".",
"RecordCallWithMethodType",
"(",
"mr",
".",
"mock",
",",
"\"",
"\"",
",",
"reflect",
".",
"TypeOf",
"(",
"(",
"*",
"MockGerritServer",
")",
"(",
"nil",
")",
".",
"GetChange",
")",
",",
"arg0",
",",
"arg1",
")",
"\n",
"}"
] | // GetChange indicates an expected call of GetChange | [
"GetChange",
"indicates",
"an",
"expected",
"call",
"of",
"GetChange"
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/proto/gerrit/gerrit.mock.pb.go#L211-L214 |
9,058 | luci/luci-go | cipd/client/cipd/resolver.go | Resolve | func (r *Resolver) Resolve(ctx context.Context, file *ensure.File, expander template.Expander) (*ensure.ResolvedFile, error) {
return file.Resolve(func(pkg, ver string) (common.Pin, error) {
return r.ResolvePackage(ctx, pkg, ver)
}, expander)
} | go | func (r *Resolver) Resolve(ctx context.Context, file *ensure.File, expander template.Expander) (*ensure.ResolvedFile, error) {
return file.Resolve(func(pkg, ver string) (common.Pin, error) {
return r.ResolvePackage(ctx, pkg, ver)
}, expander)
} | [
"func",
"(",
"r",
"*",
"Resolver",
")",
"Resolve",
"(",
"ctx",
"context",
".",
"Context",
",",
"file",
"*",
"ensure",
".",
"File",
",",
"expander",
"template",
".",
"Expander",
")",
"(",
"*",
"ensure",
".",
"ResolvedFile",
",",
"error",
")",
"{",
"return",
"file",
".",
"Resolve",
"(",
"func",
"(",
"pkg",
",",
"ver",
"string",
")",
"(",
"common",
".",
"Pin",
",",
"error",
")",
"{",
"return",
"r",
".",
"ResolvePackage",
"(",
"ctx",
",",
"pkg",
",",
"ver",
")",
"\n",
"}",
",",
"expander",
")",
"\n",
"}"
] | // Resolve resolves versions of all packages in the ensure file using the
// given expander to expand templates.
//
// Succeeds only if all packages have been successfully resolved and verified.
//
// Names of packages that failed the resolution are returned as part of the
// multi-error. | [
"Resolve",
"resolves",
"versions",
"of",
"all",
"packages",
"in",
"the",
"ensure",
"file",
"using",
"the",
"given",
"expander",
"to",
"expand",
"templates",
".",
"Succeeds",
"only",
"if",
"all",
"packages",
"have",
"been",
"successfully",
"resolved",
"and",
"verified",
".",
"Names",
"of",
"packages",
"that",
"failed",
"the",
"resolution",
"are",
"returned",
"as",
"part",
"of",
"the",
"multi",
"-",
"error",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/resolver.go#L110-L114 |
9,059 | luci/luci-go | cipd/client/cipd/resolver.go | verifyPin | func (r *Resolver) verifyPin(ctx context.Context, pin common.Pin) error {
promise := r.verifying.Get(ctx, pin, func(ctx context.Context) (interface{}, error) {
logging.Debugf(ctx, "Validating pin %s...", pin)
_, err := r.Client.DescribeInstance(ctx, pin, nil)
if err == nil {
logging.Debugf(ctx, "Pin %s successfully validated", pin)
} else {
logging.Debugf(ctx, "Failed to resolve instance info for %s: %s", pin, err)
}
return nil, err
})
_, err := promise.Get(ctx)
return err
} | go | func (r *Resolver) verifyPin(ctx context.Context, pin common.Pin) error {
promise := r.verifying.Get(ctx, pin, func(ctx context.Context) (interface{}, error) {
logging.Debugf(ctx, "Validating pin %s...", pin)
_, err := r.Client.DescribeInstance(ctx, pin, nil)
if err == nil {
logging.Debugf(ctx, "Pin %s successfully validated", pin)
} else {
logging.Debugf(ctx, "Failed to resolve instance info for %s: %s", pin, err)
}
return nil, err
})
_, err := promise.Get(ctx)
return err
} | [
"func",
"(",
"r",
"*",
"Resolver",
")",
"verifyPin",
"(",
"ctx",
"context",
".",
"Context",
",",
"pin",
"common",
".",
"Pin",
")",
"error",
"{",
"promise",
":=",
"r",
".",
"verifying",
".",
"Get",
"(",
"ctx",
",",
"pin",
",",
"func",
"(",
"ctx",
"context",
".",
"Context",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"logging",
".",
"Debugf",
"(",
"ctx",
",",
"\"",
"\"",
",",
"pin",
")",
"\n",
"_",
",",
"err",
":=",
"r",
".",
"Client",
".",
"DescribeInstance",
"(",
"ctx",
",",
"pin",
",",
"nil",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"logging",
".",
"Debugf",
"(",
"ctx",
",",
"\"",
"\"",
",",
"pin",
")",
"\n",
"}",
"else",
"{",
"logging",
".",
"Debugf",
"(",
"ctx",
",",
"\"",
"\"",
",",
"pin",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
")",
"\n",
"_",
",",
"err",
":=",
"promise",
".",
"Get",
"(",
"ctx",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // verifyPin returns nil if the given pin exists on the backend. | [
"verifyPin",
"returns",
"nil",
"if",
"the",
"given",
"pin",
"exists",
"on",
"the",
"backend",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/resolver.go#L193-L206 |
9,060 | luci/luci-go | machine-db/appengine/rpc/machines.go | CreateMachine | func (*Service) CreateMachine(c context.Context, req *crimson.CreateMachineRequest) (*crimson.Machine, error) {
if err := createMachine(c, req.Machine); err != nil {
return nil, err
}
return req.Machine, nil
} | go | func (*Service) CreateMachine(c context.Context, req *crimson.CreateMachineRequest) (*crimson.Machine, error) {
if err := createMachine(c, req.Machine); err != nil {
return nil, err
}
return req.Machine, nil
} | [
"func",
"(",
"*",
"Service",
")",
"CreateMachine",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"crimson",
".",
"CreateMachineRequest",
")",
"(",
"*",
"crimson",
".",
"Machine",
",",
"error",
")",
"{",
"if",
"err",
":=",
"createMachine",
"(",
"c",
",",
"req",
".",
"Machine",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"req",
".",
"Machine",
",",
"nil",
"\n",
"}"
] | // CreateMachine handles a request to create a new machine. | [
"CreateMachine",
"handles",
"a",
"request",
"to",
"create",
"a",
"new",
"machine",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/machines.go#L39-L44 |
9,061 | luci/luci-go | machine-db/appengine/rpc/machines.go | DeleteMachine | func (*Service) DeleteMachine(c context.Context, req *crimson.DeleteMachineRequest) (*empty.Empty, error) {
if err := deleteMachine(c, req.Name); err != nil {
return nil, err
}
return &empty.Empty{}, nil
} | go | func (*Service) DeleteMachine(c context.Context, req *crimson.DeleteMachineRequest) (*empty.Empty, error) {
if err := deleteMachine(c, req.Name); err != nil {
return nil, err
}
return &empty.Empty{}, nil
} | [
"func",
"(",
"*",
"Service",
")",
"DeleteMachine",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"crimson",
".",
"DeleteMachineRequest",
")",
"(",
"*",
"empty",
".",
"Empty",
",",
"error",
")",
"{",
"if",
"err",
":=",
"deleteMachine",
"(",
"c",
",",
"req",
".",
"Name",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"empty",
".",
"Empty",
"{",
"}",
",",
"nil",
"\n",
"}"
] | // DeleteMachine handles a request to delete an existing machine. | [
"DeleteMachine",
"handles",
"a",
"request",
"to",
"delete",
"an",
"existing",
"machine",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/machines.go#L47-L52 |
9,062 | luci/luci-go | machine-db/appengine/rpc/machines.go | ListMachines | func (*Service) ListMachines(c context.Context, req *crimson.ListMachinesRequest) (*crimson.ListMachinesResponse, error) {
machines, err := listMachines(c, database.Get(c), req)
if err != nil {
return nil, err
}
return &crimson.ListMachinesResponse{
Machines: machines,
}, nil
} | go | func (*Service) ListMachines(c context.Context, req *crimson.ListMachinesRequest) (*crimson.ListMachinesResponse, error) {
machines, err := listMachines(c, database.Get(c), req)
if err != nil {
return nil, err
}
return &crimson.ListMachinesResponse{
Machines: machines,
}, nil
} | [
"func",
"(",
"*",
"Service",
")",
"ListMachines",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"crimson",
".",
"ListMachinesRequest",
")",
"(",
"*",
"crimson",
".",
"ListMachinesResponse",
",",
"error",
")",
"{",
"machines",
",",
"err",
":=",
"listMachines",
"(",
"c",
",",
"database",
".",
"Get",
"(",
"c",
")",
",",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"crimson",
".",
"ListMachinesResponse",
"{",
"Machines",
":",
"machines",
",",
"}",
",",
"nil",
"\n",
"}"
] | // ListMachines handles a request to list machines. | [
"ListMachines",
"handles",
"a",
"request",
"to",
"list",
"machines",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/machines.go#L55-L63 |
9,063 | luci/luci-go | machine-db/appengine/rpc/machines.go | RenameMachine | func (*Service) RenameMachine(c context.Context, req *crimson.RenameMachineRequest) (*crimson.Machine, error) {
return renameMachine(c, req.Name, req.NewName)
} | go | func (*Service) RenameMachine(c context.Context, req *crimson.RenameMachineRequest) (*crimson.Machine, error) {
return renameMachine(c, req.Name, req.NewName)
} | [
"func",
"(",
"*",
"Service",
")",
"RenameMachine",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"crimson",
".",
"RenameMachineRequest",
")",
"(",
"*",
"crimson",
".",
"Machine",
",",
"error",
")",
"{",
"return",
"renameMachine",
"(",
"c",
",",
"req",
".",
"Name",
",",
"req",
".",
"NewName",
")",
"\n",
"}"
] | // RenameMachine handles a request to rename an existing machine. | [
"RenameMachine",
"handles",
"a",
"request",
"to",
"rename",
"an",
"existing",
"machine",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/machines.go#L66-L68 |
9,064 | luci/luci-go | machine-db/appengine/rpc/machines.go | UpdateMachine | func (*Service) UpdateMachine(c context.Context, req *crimson.UpdateMachineRequest) (*crimson.Machine, error) {
return updateMachine(c, req.Machine, req.UpdateMask)
} | go | func (*Service) UpdateMachine(c context.Context, req *crimson.UpdateMachineRequest) (*crimson.Machine, error) {
return updateMachine(c, req.Machine, req.UpdateMask)
} | [
"func",
"(",
"*",
"Service",
")",
"UpdateMachine",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"crimson",
".",
"UpdateMachineRequest",
")",
"(",
"*",
"crimson",
".",
"Machine",
",",
"error",
")",
"{",
"return",
"updateMachine",
"(",
"c",
",",
"req",
".",
"Machine",
",",
"req",
".",
"UpdateMask",
")",
"\n",
"}"
] | // UpdateMachine handles a request to update an existing machine. | [
"UpdateMachine",
"handles",
"a",
"request",
"to",
"update",
"an",
"existing",
"machine",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/machines.go#L71-L73 |
9,065 | luci/luci-go | machine-db/appengine/rpc/machines.go | createMachine | func createMachine(c context.Context, m *crimson.Machine) error {
if err := validateMachineForCreation(m); err != nil {
return err
}
db := database.Get(c)
// By setting machines.platform_id and machines.rack_id NOT NULL when setting up the database, we can avoid checking if the given
// platform and rack are valid. MySQL will turn up NULL for their column values which will be rejected as an error.
_, err := db.ExecContext(c, `
INSERT INTO machines (name, platform_id, rack_id, description, asset_tag, service_tag, deployment_ticket, drac_password, state)
VALUES (?, (SELECT id FROM platforms WHERE name = ?), (SELECT id FROM racks WHERE name = ?), ?, ?, ?, ?, ?, ?)
`, m.Name, m.Platform, m.Rack, m.Description, m.AssetTag, m.ServiceTag, m.DeploymentTicket, m.DracPassword, m.State)
if err != nil {
switch e, ok := err.(*mysql.MySQLError); {
case !ok:
// Type assertion failed.
case e.Number == mysqlerr.ER_DUP_ENTRY:
// e.g. "Error 1062: Duplicate entry 'machine-name' for key 'name'".
// Name is the only required unique field (ID is required unique, but it's auto-incremented).
return status.Errorf(codes.AlreadyExists, "duplicate machine %q", m.Name)
case e.Number == mysqlerr.ER_BAD_NULL_ERROR && strings.Contains(e.Message, "'platform_id'"):
// e.g. "Error 1048: Column 'platform_id' cannot be null".
return status.Errorf(codes.NotFound, "platform %q does not exist", m.Platform)
case e.Number == mysqlerr.ER_BAD_NULL_ERROR && strings.Contains(e.Message, "'rack_id'"):
// e.g. "Error 1048: Column 'rack_id' cannot be null".
return status.Errorf(codes.NotFound, "rack %q does not exist", m.Rack)
}
return errors.Annotate(err, "failed to create machine").Err()
}
return nil
} | go | func createMachine(c context.Context, m *crimson.Machine) error {
if err := validateMachineForCreation(m); err != nil {
return err
}
db := database.Get(c)
// By setting machines.platform_id and machines.rack_id NOT NULL when setting up the database, we can avoid checking if the given
// platform and rack are valid. MySQL will turn up NULL for their column values which will be rejected as an error.
_, err := db.ExecContext(c, `
INSERT INTO machines (name, platform_id, rack_id, description, asset_tag, service_tag, deployment_ticket, drac_password, state)
VALUES (?, (SELECT id FROM platforms WHERE name = ?), (SELECT id FROM racks WHERE name = ?), ?, ?, ?, ?, ?, ?)
`, m.Name, m.Platform, m.Rack, m.Description, m.AssetTag, m.ServiceTag, m.DeploymentTicket, m.DracPassword, m.State)
if err != nil {
switch e, ok := err.(*mysql.MySQLError); {
case !ok:
// Type assertion failed.
case e.Number == mysqlerr.ER_DUP_ENTRY:
// e.g. "Error 1062: Duplicate entry 'machine-name' for key 'name'".
// Name is the only required unique field (ID is required unique, but it's auto-incremented).
return status.Errorf(codes.AlreadyExists, "duplicate machine %q", m.Name)
case e.Number == mysqlerr.ER_BAD_NULL_ERROR && strings.Contains(e.Message, "'platform_id'"):
// e.g. "Error 1048: Column 'platform_id' cannot be null".
return status.Errorf(codes.NotFound, "platform %q does not exist", m.Platform)
case e.Number == mysqlerr.ER_BAD_NULL_ERROR && strings.Contains(e.Message, "'rack_id'"):
// e.g. "Error 1048: Column 'rack_id' cannot be null".
return status.Errorf(codes.NotFound, "rack %q does not exist", m.Rack)
}
return errors.Annotate(err, "failed to create machine").Err()
}
return nil
} | [
"func",
"createMachine",
"(",
"c",
"context",
".",
"Context",
",",
"m",
"*",
"crimson",
".",
"Machine",
")",
"error",
"{",
"if",
"err",
":=",
"validateMachineForCreation",
"(",
"m",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"db",
":=",
"database",
".",
"Get",
"(",
"c",
")",
"\n",
"// By setting machines.platform_id and machines.rack_id NOT NULL when setting up the database, we can avoid checking if the given",
"// platform and rack are valid. MySQL will turn up NULL for their column values which will be rejected as an error.",
"_",
",",
"err",
":=",
"db",
".",
"ExecContext",
"(",
"c",
",",
"`\n\t\tINSERT INTO machines (name, platform_id, rack_id, description, asset_tag, service_tag, deployment_ticket, drac_password, state)\n\t\tVALUES (?, (SELECT id FROM platforms WHERE name = ?), (SELECT id FROM racks WHERE name = ?), ?, ?, ?, ?, ?, ?)\n\t`",
",",
"m",
".",
"Name",
",",
"m",
".",
"Platform",
",",
"m",
".",
"Rack",
",",
"m",
".",
"Description",
",",
"m",
".",
"AssetTag",
",",
"m",
".",
"ServiceTag",
",",
"m",
".",
"DeploymentTicket",
",",
"m",
".",
"DracPassword",
",",
"m",
".",
"State",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"switch",
"e",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"mysql",
".",
"MySQLError",
")",
";",
"{",
"case",
"!",
"ok",
":",
"// Type assertion failed.",
"case",
"e",
".",
"Number",
"==",
"mysqlerr",
".",
"ER_DUP_ENTRY",
":",
"// e.g. \"Error 1062: Duplicate entry 'machine-name' for key 'name'\".",
"// Name is the only required unique field (ID is required unique, but it's auto-incremented).",
"return",
"status",
".",
"Errorf",
"(",
"codes",
".",
"AlreadyExists",
",",
"\"",
"\"",
",",
"m",
".",
"Name",
")",
"\n",
"case",
"e",
".",
"Number",
"==",
"mysqlerr",
".",
"ER_BAD_NULL_ERROR",
"&&",
"strings",
".",
"Contains",
"(",
"e",
".",
"Message",
",",
"\"",
"\"",
")",
":",
"// e.g. \"Error 1048: Column 'platform_id' cannot be null\".",
"return",
"status",
".",
"Errorf",
"(",
"codes",
".",
"NotFound",
",",
"\"",
"\"",
",",
"m",
".",
"Platform",
")",
"\n",
"case",
"e",
".",
"Number",
"==",
"mysqlerr",
".",
"ER_BAD_NULL_ERROR",
"&&",
"strings",
".",
"Contains",
"(",
"e",
".",
"Message",
",",
"\"",
"\"",
")",
":",
"// e.g. \"Error 1048: Column 'rack_id' cannot be null\".",
"return",
"status",
".",
"Errorf",
"(",
"codes",
".",
"NotFound",
",",
"\"",
"\"",
",",
"m",
".",
"Rack",
")",
"\n",
"}",
"\n",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // createMachine creates a new machine in the database. | [
"createMachine",
"creates",
"a",
"new",
"machine",
"in",
"the",
"database",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/machines.go#L76-L106 |
9,066 | luci/luci-go | machine-db/appengine/rpc/machines.go | listMachines | func listMachines(c context.Context, q database.QueryerContext, req *crimson.ListMachinesRequest) ([]*crimson.Machine, error) {
stmt := squirrel.Select(
"m.name",
"p.name",
"r.name",
"d.name",
"m.description",
"m.asset_tag",
"m.service_tag",
"m.deployment_ticket",
"m.drac_password",
"m.state",
)
stmt = stmt.From("machines m, platforms p, racks r, datacenters d").
Where("m.platform_id = p.id").Where("m.rack_id = r.id").Where("r.datacenter_id = d.id")
stmt = selectInString(stmt, "m.name", req.Names)
stmt = selectInString(stmt, "p.name", req.Platforms)
stmt = selectInString(stmt, "r.name", req.Racks)
stmt = selectInString(stmt, "d.name", req.Datacenters)
stmt = selectInState(stmt, "m.state", req.States)
query, args, err := stmt.ToSql()
if err != nil {
return nil, errors.Annotate(err, "failed to generate statement").Err()
}
rows, err := q.QueryContext(c, query, args...)
if err != nil {
return nil, errors.Annotate(err, "failed to fetch machines").Err()
}
defer rows.Close()
var machines []*crimson.Machine
for rows.Next() {
m := &crimson.Machine{}
if err = rows.Scan(
&m.Name,
&m.Platform,
&m.Rack,
&m.Datacenter,
&m.Description,
&m.AssetTag,
&m.ServiceTag,
&m.DeploymentTicket,
&m.DracPassword,
&m.State,
); err != nil {
return nil, errors.Annotate(err, "failed to fetch machine").Err()
}
machines = append(machines, m)
}
return machines, nil
} | go | func listMachines(c context.Context, q database.QueryerContext, req *crimson.ListMachinesRequest) ([]*crimson.Machine, error) {
stmt := squirrel.Select(
"m.name",
"p.name",
"r.name",
"d.name",
"m.description",
"m.asset_tag",
"m.service_tag",
"m.deployment_ticket",
"m.drac_password",
"m.state",
)
stmt = stmt.From("machines m, platforms p, racks r, datacenters d").
Where("m.platform_id = p.id").Where("m.rack_id = r.id").Where("r.datacenter_id = d.id")
stmt = selectInString(stmt, "m.name", req.Names)
stmt = selectInString(stmt, "p.name", req.Platforms)
stmt = selectInString(stmt, "r.name", req.Racks)
stmt = selectInString(stmt, "d.name", req.Datacenters)
stmt = selectInState(stmt, "m.state", req.States)
query, args, err := stmt.ToSql()
if err != nil {
return nil, errors.Annotate(err, "failed to generate statement").Err()
}
rows, err := q.QueryContext(c, query, args...)
if err != nil {
return nil, errors.Annotate(err, "failed to fetch machines").Err()
}
defer rows.Close()
var machines []*crimson.Machine
for rows.Next() {
m := &crimson.Machine{}
if err = rows.Scan(
&m.Name,
&m.Platform,
&m.Rack,
&m.Datacenter,
&m.Description,
&m.AssetTag,
&m.ServiceTag,
&m.DeploymentTicket,
&m.DracPassword,
&m.State,
); err != nil {
return nil, errors.Annotate(err, "failed to fetch machine").Err()
}
machines = append(machines, m)
}
return machines, nil
} | [
"func",
"listMachines",
"(",
"c",
"context",
".",
"Context",
",",
"q",
"database",
".",
"QueryerContext",
",",
"req",
"*",
"crimson",
".",
"ListMachinesRequest",
")",
"(",
"[",
"]",
"*",
"crimson",
".",
"Machine",
",",
"error",
")",
"{",
"stmt",
":=",
"squirrel",
".",
"Select",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
")",
"\n",
"stmt",
"=",
"stmt",
".",
"From",
"(",
"\"",
"\"",
")",
".",
"Where",
"(",
"\"",
"\"",
")",
".",
"Where",
"(",
"\"",
"\"",
")",
".",
"Where",
"(",
"\"",
"\"",
")",
"\n",
"stmt",
"=",
"selectInString",
"(",
"stmt",
",",
"\"",
"\"",
",",
"req",
".",
"Names",
")",
"\n",
"stmt",
"=",
"selectInString",
"(",
"stmt",
",",
"\"",
"\"",
",",
"req",
".",
"Platforms",
")",
"\n",
"stmt",
"=",
"selectInString",
"(",
"stmt",
",",
"\"",
"\"",
",",
"req",
".",
"Racks",
")",
"\n",
"stmt",
"=",
"selectInString",
"(",
"stmt",
",",
"\"",
"\"",
",",
"req",
".",
"Datacenters",
")",
"\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",
"rows",
",",
"err",
":=",
"q",
".",
"QueryContext",
"(",
"c",
",",
"query",
",",
"args",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"defer",
"rows",
".",
"Close",
"(",
")",
"\n",
"var",
"machines",
"[",
"]",
"*",
"crimson",
".",
"Machine",
"\n",
"for",
"rows",
".",
"Next",
"(",
")",
"{",
"m",
":=",
"&",
"crimson",
".",
"Machine",
"{",
"}",
"\n",
"if",
"err",
"=",
"rows",
".",
"Scan",
"(",
"&",
"m",
".",
"Name",
",",
"&",
"m",
".",
"Platform",
",",
"&",
"m",
".",
"Rack",
",",
"&",
"m",
".",
"Datacenter",
",",
"&",
"m",
".",
"Description",
",",
"&",
"m",
".",
"AssetTag",
",",
"&",
"m",
".",
"ServiceTag",
",",
"&",
"m",
".",
"DeploymentTicket",
",",
"&",
"m",
".",
"DracPassword",
",",
"&",
"m",
".",
"State",
",",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"machines",
"=",
"append",
"(",
"machines",
",",
"m",
")",
"\n",
"}",
"\n",
"return",
"machines",
",",
"nil",
"\n",
"}"
] | // listMachines returns a slice of machines in the database. | [
"listMachines",
"returns",
"a",
"slice",
"of",
"machines",
"in",
"the",
"database",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/machines.go#L138-L188 |
9,067 | luci/luci-go | machine-db/appengine/rpc/machines.go | renameMachine | func renameMachine(c context.Context, name, newName string) (*crimson.Machine, error) {
switch {
case name == "":
return nil, status.Error(codes.InvalidArgument, "machine name is required and must be non-empty")
case newName == "":
return nil, status.Error(codes.InvalidArgument, "new name is required and must be non-empty")
case name == newName:
return nil, status.Error(codes.InvalidArgument, "new name must be different")
}
tx, err := database.Begin(c)
if err != nil {
return nil, errors.Annotate(err, "failed to begin transaction").Err()
}
defer tx.MaybeRollback(c)
res, err := tx.ExecContext(c, `
UPDATE machines
SET name = ?
WHERE name = ?
`, newName, name)
if err != nil {
switch e, ok := err.(*mysql.MySQLError); {
case !ok:
// Type assertion failed.
case e.Number == mysqlerr.ER_DUP_ENTRY:
// e.g. "Error 1062: Duplicate entry 'machine-name' for key 'name'".
return nil, status.Errorf(codes.AlreadyExists, "duplicate machine %q", newName)
}
return nil, errors.Annotate(err, "failed to rename machine").Err()
}
switch rows, err := res.RowsAffected(); {
case err != nil:
return nil, errors.Annotate(err, "failed to fetch affected rows").Err()
case rows == 0:
return nil, status.Errorf(codes.NotFound, "machine %q does not exist", name)
}
machines, err := listMachines(c, tx, &crimson.ListMachinesRequest{
Names: []string{newName},
})
if err != nil {
return nil, errors.Annotate(err, "failed to fetch renamed machine").Err()
}
if err := tx.Commit(); err != nil {
return nil, errors.Annotate(err, "failed to commit transaction").Err()
}
return machines[0], nil
} | go | func renameMachine(c context.Context, name, newName string) (*crimson.Machine, error) {
switch {
case name == "":
return nil, status.Error(codes.InvalidArgument, "machine name is required and must be non-empty")
case newName == "":
return nil, status.Error(codes.InvalidArgument, "new name is required and must be non-empty")
case name == newName:
return nil, status.Error(codes.InvalidArgument, "new name must be different")
}
tx, err := database.Begin(c)
if err != nil {
return nil, errors.Annotate(err, "failed to begin transaction").Err()
}
defer tx.MaybeRollback(c)
res, err := tx.ExecContext(c, `
UPDATE machines
SET name = ?
WHERE name = ?
`, newName, name)
if err != nil {
switch e, ok := err.(*mysql.MySQLError); {
case !ok:
// Type assertion failed.
case e.Number == mysqlerr.ER_DUP_ENTRY:
// e.g. "Error 1062: Duplicate entry 'machine-name' for key 'name'".
return nil, status.Errorf(codes.AlreadyExists, "duplicate machine %q", newName)
}
return nil, errors.Annotate(err, "failed to rename machine").Err()
}
switch rows, err := res.RowsAffected(); {
case err != nil:
return nil, errors.Annotate(err, "failed to fetch affected rows").Err()
case rows == 0:
return nil, status.Errorf(codes.NotFound, "machine %q does not exist", name)
}
machines, err := listMachines(c, tx, &crimson.ListMachinesRequest{
Names: []string{newName},
})
if err != nil {
return nil, errors.Annotate(err, "failed to fetch renamed machine").Err()
}
if err := tx.Commit(); err != nil {
return nil, errors.Annotate(err, "failed to commit transaction").Err()
}
return machines[0], nil
} | [
"func",
"renameMachine",
"(",
"c",
"context",
".",
"Context",
",",
"name",
",",
"newName",
"string",
")",
"(",
"*",
"crimson",
".",
"Machine",
",",
"error",
")",
"{",
"switch",
"{",
"case",
"name",
"==",
"\"",
"\"",
":",
"return",
"nil",
",",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"newName",
"==",
"\"",
"\"",
":",
"return",
"nil",
",",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"name",
"==",
"newName",
":",
"return",
"nil",
",",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"tx",
",",
"err",
":=",
"database",
".",
"Begin",
"(",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"defer",
"tx",
".",
"MaybeRollback",
"(",
"c",
")",
"\n\n",
"res",
",",
"err",
":=",
"tx",
".",
"ExecContext",
"(",
"c",
",",
"`\n\t\tUPDATE machines\n\t\tSET name = ?\n\t\tWHERE name = ?\n\t`",
",",
"newName",
",",
"name",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"switch",
"e",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"mysql",
".",
"MySQLError",
")",
";",
"{",
"case",
"!",
"ok",
":",
"// Type assertion failed.",
"case",
"e",
".",
"Number",
"==",
"mysqlerr",
".",
"ER_DUP_ENTRY",
":",
"// e.g. \"Error 1062: Duplicate entry 'machine-name' for key 'name'\".",
"return",
"nil",
",",
"status",
".",
"Errorf",
"(",
"codes",
".",
"AlreadyExists",
",",
"\"",
"\"",
",",
"newName",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"switch",
"rows",
",",
"err",
":=",
"res",
".",
"RowsAffected",
"(",
")",
";",
"{",
"case",
"err",
"!=",
"nil",
":",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"case",
"rows",
"==",
"0",
":",
"return",
"nil",
",",
"status",
".",
"Errorf",
"(",
"codes",
".",
"NotFound",
",",
"\"",
"\"",
",",
"name",
")",
"\n",
"}",
"\n\n",
"machines",
",",
"err",
":=",
"listMachines",
"(",
"c",
",",
"tx",
",",
"&",
"crimson",
".",
"ListMachinesRequest",
"{",
"Names",
":",
"[",
"]",
"string",
"{",
"newName",
"}",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"tx",
".",
"Commit",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"return",
"machines",
"[",
"0",
"]",
",",
"nil",
"\n",
"}"
] | // renameMachine renames an existing machine in the database. | [
"renameMachine",
"renames",
"an",
"existing",
"machine",
"in",
"the",
"database",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/machines.go#L191-L240 |
9,068 | luci/luci-go | machine-db/appengine/rpc/machines.go | validateMachineForCreation | func validateMachineForCreation(m *crimson.Machine) error {
switch {
case m == nil:
return status.Error(codes.InvalidArgument, "machine specification is required")
case m.Name == "":
return status.Error(codes.InvalidArgument, "machine name is required and must be non-empty")
case m.Platform == "":
return status.Error(codes.InvalidArgument, "platform is required and must be non-empty")
case m.Rack == "":
return status.Error(codes.InvalidArgument, "rack is required and must be non-empty")
case m.Datacenter != "":
return status.Error(codes.InvalidArgument, "datacenter must not be specified, use rack instead")
case m.State == common.State_STATE_UNSPECIFIED:
return status.Error(codes.InvalidArgument, "state is required")
default:
return nil
}
} | go | func validateMachineForCreation(m *crimson.Machine) error {
switch {
case m == nil:
return status.Error(codes.InvalidArgument, "machine specification is required")
case m.Name == "":
return status.Error(codes.InvalidArgument, "machine name is required and must be non-empty")
case m.Platform == "":
return status.Error(codes.InvalidArgument, "platform is required and must be non-empty")
case m.Rack == "":
return status.Error(codes.InvalidArgument, "rack is required and must be non-empty")
case m.Datacenter != "":
return status.Error(codes.InvalidArgument, "datacenter must not be specified, use rack instead")
case m.State == common.State_STATE_UNSPECIFIED:
return status.Error(codes.InvalidArgument, "state is required")
default:
return nil
}
} | [
"func",
"validateMachineForCreation",
"(",
"m",
"*",
"crimson",
".",
"Machine",
")",
"error",
"{",
"switch",
"{",
"case",
"m",
"==",
"nil",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"m",
".",
"Name",
"==",
"\"",
"\"",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"m",
".",
"Platform",
"==",
"\"",
"\"",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"m",
".",
"Rack",
"==",
"\"",
"\"",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"m",
".",
"Datacenter",
"!=",
"\"",
"\"",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"m",
".",
"State",
"==",
"common",
".",
"State_STATE_UNSPECIFIED",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"default",
":",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // validateMachineForCreation validates a machine for creation. | [
"validateMachineForCreation",
"validates",
"a",
"machine",
"for",
"creation",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/machines.go#L314-L331 |
9,069 | luci/luci-go | machine-db/appengine/rpc/machines.go | validateMachineForUpdate | func validateMachineForUpdate(m *crimson.Machine, mask *field_mask.FieldMask) error {
switch err := validateUpdateMask(mask); {
case m == nil:
return status.Error(codes.InvalidArgument, "machine specification is required")
case m.Name == "":
return status.Error(codes.InvalidArgument, "machine name is required and must be non-empty")
case err != nil:
return err
}
for _, path := range mask.Paths {
switch path {
case "name":
return status.Error(codes.InvalidArgument, "machine name cannot be updated, delete and create a new machine instead")
case "platform":
if m.Platform == "" {
return status.Error(codes.InvalidArgument, "platform is required and must be non-empty")
}
case "rack":
if m.Rack == "" {
return status.Error(codes.InvalidArgument, "rack is required and must be non-empty")
}
case "datacenter":
return status.Error(codes.InvalidArgument, "datacenter cannot be updated, update rack instead")
case "state":
if m.State == common.State_STATE_UNSPECIFIED {
return status.Error(codes.InvalidArgument, "state is required")
}
case "description":
// Empty description is allowed, nothing to validate.
case "asset_tag":
// Empty asset tag is allowed, nothing to validate.
case "service_tag":
// Empty service tag is allowed, nothing to validate.
case "deployment_ticket":
// Empty deployment ticket is allowed, nothing to validate.
case "drac_password":
// Empty DRAC password is allowed, nothing to validate.
default:
return status.Errorf(codes.InvalidArgument, "unsupported update mask path %q", path)
}
}
return nil
} | go | func validateMachineForUpdate(m *crimson.Machine, mask *field_mask.FieldMask) error {
switch err := validateUpdateMask(mask); {
case m == nil:
return status.Error(codes.InvalidArgument, "machine specification is required")
case m.Name == "":
return status.Error(codes.InvalidArgument, "machine name is required and must be non-empty")
case err != nil:
return err
}
for _, path := range mask.Paths {
switch path {
case "name":
return status.Error(codes.InvalidArgument, "machine name cannot be updated, delete and create a new machine instead")
case "platform":
if m.Platform == "" {
return status.Error(codes.InvalidArgument, "platform is required and must be non-empty")
}
case "rack":
if m.Rack == "" {
return status.Error(codes.InvalidArgument, "rack is required and must be non-empty")
}
case "datacenter":
return status.Error(codes.InvalidArgument, "datacenter cannot be updated, update rack instead")
case "state":
if m.State == common.State_STATE_UNSPECIFIED {
return status.Error(codes.InvalidArgument, "state is required")
}
case "description":
// Empty description is allowed, nothing to validate.
case "asset_tag":
// Empty asset tag is allowed, nothing to validate.
case "service_tag":
// Empty service tag is allowed, nothing to validate.
case "deployment_ticket":
// Empty deployment ticket is allowed, nothing to validate.
case "drac_password":
// Empty DRAC password is allowed, nothing to validate.
default:
return status.Errorf(codes.InvalidArgument, "unsupported update mask path %q", path)
}
}
return nil
} | [
"func",
"validateMachineForUpdate",
"(",
"m",
"*",
"crimson",
".",
"Machine",
",",
"mask",
"*",
"field_mask",
".",
"FieldMask",
")",
"error",
"{",
"switch",
"err",
":=",
"validateUpdateMask",
"(",
"mask",
")",
";",
"{",
"case",
"m",
"==",
"nil",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"m",
".",
"Name",
"==",
"\"",
"\"",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"err",
"!=",
"nil",
":",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"path",
":=",
"range",
"mask",
".",
"Paths",
"{",
"switch",
"path",
"{",
"case",
"\"",
"\"",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"\"",
"\"",
":",
"if",
"m",
".",
"Platform",
"==",
"\"",
"\"",
"{",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"case",
"\"",
"\"",
":",
"if",
"m",
".",
"Rack",
"==",
"\"",
"\"",
"{",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"case",
"\"",
"\"",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"\"",
"\"",
":",
"if",
"m",
".",
"State",
"==",
"common",
".",
"State_STATE_UNSPECIFIED",
"{",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"case",
"\"",
"\"",
":",
"// Empty description is allowed, nothing to validate.",
"case",
"\"",
"\"",
":",
"// Empty asset tag is allowed, nothing to validate.",
"case",
"\"",
"\"",
":",
"// Empty service tag is allowed, nothing to validate.",
"case",
"\"",
"\"",
":",
"// Empty deployment ticket is allowed, nothing to validate.",
"case",
"\"",
"\"",
":",
"// Empty DRAC password is allowed, nothing to validate.",
"default",
":",
"return",
"status",
".",
"Errorf",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
",",
"path",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // validateMachineForUpdate validates a machine for update. | [
"validateMachineForUpdate",
"validates",
"a",
"machine",
"for",
"update",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/machines.go#L334-L376 |
9,070 | luci/luci-go | mmutex/lib/shared.go | RunShared | func RunShared(ctx context.Context, env subcommands.Env, command func(context.Context) error) error {
lockFilePath, drainFilePath, err := computeMutexPaths(env)
if err != nil {
return err
}
if len(lockFilePath) == 0 {
return command(ctx)
}
blocker := createLockBlocker(ctx)
// Use the same retry mechanism for checking if the drain file still exists
// as we use to request the file lock.
if err = blockWhileFileExists(drainFilePath, blocker); err != nil {
return err
}
return fslock.WithSharedBlocking(lockFilePath, blocker, func() error {
return command(ctx)
})
} | go | func RunShared(ctx context.Context, env subcommands.Env, command func(context.Context) error) error {
lockFilePath, drainFilePath, err := computeMutexPaths(env)
if err != nil {
return err
}
if len(lockFilePath) == 0 {
return command(ctx)
}
blocker := createLockBlocker(ctx)
// Use the same retry mechanism for checking if the drain file still exists
// as we use to request the file lock.
if err = blockWhileFileExists(drainFilePath, blocker); err != nil {
return err
}
return fslock.WithSharedBlocking(lockFilePath, blocker, func() error {
return command(ctx)
})
} | [
"func",
"RunShared",
"(",
"ctx",
"context",
".",
"Context",
",",
"env",
"subcommands",
".",
"Env",
",",
"command",
"func",
"(",
"context",
".",
"Context",
")",
"error",
")",
"error",
"{",
"lockFilePath",
",",
"drainFilePath",
",",
"err",
":=",
"computeMutexPaths",
"(",
"env",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"lockFilePath",
")",
"==",
"0",
"{",
"return",
"command",
"(",
"ctx",
")",
"\n",
"}",
"\n\n",
"blocker",
":=",
"createLockBlocker",
"(",
"ctx",
")",
"\n\n",
"// Use the same retry mechanism for checking if the drain file still exists",
"// as we use to request the file lock.",
"if",
"err",
"=",
"blockWhileFileExists",
"(",
"drainFilePath",
",",
"blocker",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"fslock",
".",
"WithSharedBlocking",
"(",
"lockFilePath",
",",
"blocker",
",",
"func",
"(",
")",
"error",
"{",
"return",
"command",
"(",
"ctx",
")",
"\n",
"}",
")",
"\n",
"}"
] | // RunShared runs the command with the specified context and environment while
// holding a shared mmutex lock. | [
"RunShared",
"runs",
"the",
"command",
"with",
"the",
"specified",
"context",
"and",
"environment",
"while",
"holding",
"a",
"shared",
"mmutex",
"lock",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mmutex/lib/shared.go#L26-L46 |
9,071 | luci/luci-go | common/gcloud/pubsub/publisher.go | Publish | func (up *UnbufferedPublisher) Publish(c context.Context, msgs ...*pubsub.Message) ([]string, error) {
if len(msgs) == 0 {
return nil, nil
}
messages := make([]*pb.PubsubMessage, len(msgs))
for i, msg := range msgs {
messages[i] = &pb.PubsubMessage{
Data: msg.Data,
Attributes: msg.Attributes,
}
}
client, err := up.ClientFactory.Client(up.AECtx)
if err != nil {
return nil, err
}
resp, err := client.Publish(c, &pb.PublishRequest{
Topic: string(up.Topic),
Messages: messages,
}, up.CallOpts...)
if err != nil {
// Optimistically recreate the client.
up.ClientFactory.RecreateClient()
logging.Debugf(c, "Recreating a new PubSub client due to error")
return nil, err
}
return resp.MessageIds, nil
} | go | func (up *UnbufferedPublisher) Publish(c context.Context, msgs ...*pubsub.Message) ([]string, error) {
if len(msgs) == 0 {
return nil, nil
}
messages := make([]*pb.PubsubMessage, len(msgs))
for i, msg := range msgs {
messages[i] = &pb.PubsubMessage{
Data: msg.Data,
Attributes: msg.Attributes,
}
}
client, err := up.ClientFactory.Client(up.AECtx)
if err != nil {
return nil, err
}
resp, err := client.Publish(c, &pb.PublishRequest{
Topic: string(up.Topic),
Messages: messages,
}, up.CallOpts...)
if err != nil {
// Optimistically recreate the client.
up.ClientFactory.RecreateClient()
logging.Debugf(c, "Recreating a new PubSub client due to error")
return nil, err
}
return resp.MessageIds, nil
} | [
"func",
"(",
"up",
"*",
"UnbufferedPublisher",
")",
"Publish",
"(",
"c",
"context",
".",
"Context",
",",
"msgs",
"...",
"*",
"pubsub",
".",
"Message",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"if",
"len",
"(",
"msgs",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"messages",
":=",
"make",
"(",
"[",
"]",
"*",
"pb",
".",
"PubsubMessage",
",",
"len",
"(",
"msgs",
")",
")",
"\n",
"for",
"i",
",",
"msg",
":=",
"range",
"msgs",
"{",
"messages",
"[",
"i",
"]",
"=",
"&",
"pb",
".",
"PubsubMessage",
"{",
"Data",
":",
"msg",
".",
"Data",
",",
"Attributes",
":",
"msg",
".",
"Attributes",
",",
"}",
"\n",
"}",
"\n\n",
"client",
",",
"err",
":=",
"up",
".",
"ClientFactory",
".",
"Client",
"(",
"up",
".",
"AECtx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"resp",
",",
"err",
":=",
"client",
".",
"Publish",
"(",
"c",
",",
"&",
"pb",
".",
"PublishRequest",
"{",
"Topic",
":",
"string",
"(",
"up",
".",
"Topic",
")",
",",
"Messages",
":",
"messages",
",",
"}",
",",
"up",
".",
"CallOpts",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Optimistically recreate the client.",
"up",
".",
"ClientFactory",
".",
"RecreateClient",
"(",
")",
"\n",
"logging",
".",
"Debugf",
"(",
"c",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"resp",
".",
"MessageIds",
",",
"nil",
"\n",
"}"
] | // Publish publishes a message immediately, blocking until it completes.
//
// "c" must be an AppEngine context. | [
"Publish",
"publishes",
"a",
"message",
"immediately",
"blocking",
"until",
"it",
"completes",
".",
"c",
"must",
"be",
"an",
"AppEngine",
"context",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/gcloud/pubsub/publisher.go#L76-L105 |
9,072 | luci/luci-go | common/gcloud/pubsub/publisher.go | Close | func (up *UnbufferedPublisher) Close() error {
client, err := up.ClientFactory.Client(up.AECtx)
if err != nil {
return err
}
return client.Close()
} | go | func (up *UnbufferedPublisher) Close() error {
client, err := up.ClientFactory.Client(up.AECtx)
if err != nil {
return err
}
return client.Close()
} | [
"func",
"(",
"up",
"*",
"UnbufferedPublisher",
")",
"Close",
"(",
")",
"error",
"{",
"client",
",",
"err",
":=",
"up",
".",
"ClientFactory",
".",
"Client",
"(",
"up",
".",
"AECtx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"client",
".",
"Close",
"(",
")",
"\n",
"}"
] | // Close closes the UnbufferedPublisher, notably its Client. | [
"Close",
"closes",
"the",
"UnbufferedPublisher",
"notably",
"its",
"Client",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/gcloud/pubsub/publisher.go#L108-L114 |
9,073 | luci/luci-go | dm/api/service/v1/execution_data.go | NewExecutionFinished | func NewExecutionFinished(result *JsonResult) *Execution {
return &Execution{
Data: &Execution_Data{
ExecutionType: &Execution_Data_Finished_{
&Execution_Data_Finished{Data: result}}}}
} | go | func NewExecutionFinished(result *JsonResult) *Execution {
return &Execution{
Data: &Execution_Data{
ExecutionType: &Execution_Data_Finished_{
&Execution_Data_Finished{Data: result}}}}
} | [
"func",
"NewExecutionFinished",
"(",
"result",
"*",
"JsonResult",
")",
"*",
"Execution",
"{",
"return",
"&",
"Execution",
"{",
"Data",
":",
"&",
"Execution_Data",
"{",
"ExecutionType",
":",
"&",
"Execution_Data_Finished_",
"{",
"&",
"Execution_Data_Finished",
"{",
"Data",
":",
"result",
"}",
"}",
"}",
"}",
"\n",
"}"
] | // NewExecutionFinished creates an Execution in the FINISHED state. | [
"NewExecutionFinished",
"creates",
"an",
"Execution",
"in",
"the",
"FINISHED",
"state",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/execution_data.go#L44-L49 |
9,074 | luci/luci-go | dm/api/service/v1/execution_data.go | NewExecutionAbnormalFinish | func NewExecutionAbnormalFinish(af *AbnormalFinish) *Execution {
return &Execution{
Data: &Execution_Data{
ExecutionType: &Execution_Data_AbnormalFinish{af}}}
} | go | func NewExecutionAbnormalFinish(af *AbnormalFinish) *Execution {
return &Execution{
Data: &Execution_Data{
ExecutionType: &Execution_Data_AbnormalFinish{af}}}
} | [
"func",
"NewExecutionAbnormalFinish",
"(",
"af",
"*",
"AbnormalFinish",
")",
"*",
"Execution",
"{",
"return",
"&",
"Execution",
"{",
"Data",
":",
"&",
"Execution_Data",
"{",
"ExecutionType",
":",
"&",
"Execution_Data_AbnormalFinish",
"{",
"af",
"}",
"}",
"}",
"\n",
"}"
] | // NewExecutionAbnormalFinish creates an Execution in the ABNORMAL_FINISH state. | [
"NewExecutionAbnormalFinish",
"creates",
"an",
"Execution",
"in",
"the",
"ABNORMAL_FINISH",
"state",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/execution_data.go#L52-L56 |
9,075 | luci/luci-go | dm/api/service/v1/execution_data.go | State | func (d *Execution_Data) State() Execution_State {
if d != nil {
switch d.ExecutionType.(type) {
case *Execution_Data_Scheduling_:
return Execution_SCHEDULING
case *Execution_Data_Running_:
return Execution_RUNNING
case *Execution_Data_Stopping_:
return Execution_STOPPING
case *Execution_Data_Finished_:
return Execution_FINISHED
case *Execution_Data_AbnormalFinish:
return Execution_ABNORMAL_FINISHED
}
}
return Execution_SCHEDULING
} | go | func (d *Execution_Data) State() Execution_State {
if d != nil {
switch d.ExecutionType.(type) {
case *Execution_Data_Scheduling_:
return Execution_SCHEDULING
case *Execution_Data_Running_:
return Execution_RUNNING
case *Execution_Data_Stopping_:
return Execution_STOPPING
case *Execution_Data_Finished_:
return Execution_FINISHED
case *Execution_Data_AbnormalFinish:
return Execution_ABNORMAL_FINISHED
}
}
return Execution_SCHEDULING
} | [
"func",
"(",
"d",
"*",
"Execution_Data",
")",
"State",
"(",
")",
"Execution_State",
"{",
"if",
"d",
"!=",
"nil",
"{",
"switch",
"d",
".",
"ExecutionType",
".",
"(",
"type",
")",
"{",
"case",
"*",
"Execution_Data_Scheduling_",
":",
"return",
"Execution_SCHEDULING",
"\n",
"case",
"*",
"Execution_Data_Running_",
":",
"return",
"Execution_RUNNING",
"\n",
"case",
"*",
"Execution_Data_Stopping_",
":",
"return",
"Execution_STOPPING",
"\n",
"case",
"*",
"Execution_Data_Finished_",
":",
"return",
"Execution_FINISHED",
"\n",
"case",
"*",
"Execution_Data_AbnormalFinish",
":",
"return",
"Execution_ABNORMAL_FINISHED",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"Execution_SCHEDULING",
"\n",
"}"
] | // State computes the Execution_State for the current Execution_Data | [
"State",
"computes",
"the",
"Execution_State",
"for",
"the",
"current",
"Execution_Data"
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/execution_data.go#L59-L75 |
9,076 | luci/luci-go | tokenserver/appengine/impl/certchecker/certchecker.go | CheckCertificate | func CheckCertificate(c context.Context, cert *x509.Certificate) (*certconfig.CA, error) {
checker, err := GetCertChecker(c, cert.Issuer.CommonName)
if err != nil {
return nil, err
}
return checker.CheckCertificate(c, cert)
} | go | func CheckCertificate(c context.Context, cert *x509.Certificate) (*certconfig.CA, error) {
checker, err := GetCertChecker(c, cert.Issuer.CommonName)
if err != nil {
return nil, err
}
return checker.CheckCertificate(c, cert)
} | [
"func",
"CheckCertificate",
"(",
"c",
"context",
".",
"Context",
",",
"cert",
"*",
"x509",
".",
"Certificate",
")",
"(",
"*",
"certconfig",
".",
"CA",
",",
"error",
")",
"{",
"checker",
",",
"err",
":=",
"GetCertChecker",
"(",
"c",
",",
"cert",
".",
"Issuer",
".",
"CommonName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"checker",
".",
"CheckCertificate",
"(",
"c",
",",
"cert",
")",
"\n",
"}"
] | // CheckCertificate checks validity of a given certificate.
//
// It looks at the cert issuer, loads corresponding CertChecker and calls its
// CheckCertificate method. See CertChecker.CheckCertificate documentation for
// explanation of return values. | [
"CheckCertificate",
"checks",
"validity",
"of",
"a",
"given",
"certificate",
".",
"It",
"looks",
"at",
"the",
"cert",
"issuer",
"loads",
"corresponding",
"CertChecker",
"and",
"calls",
"its",
"CheckCertificate",
"method",
".",
"See",
"CertChecker",
".",
"CheckCertificate",
"documentation",
"for",
"explanation",
"of",
"return",
"values",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/certchecker/certchecker.go#L134-L140 |
9,077 | luci/luci-go | tokenserver/appengine/impl/certchecker/certchecker.go | GetCertChecker | func GetCertChecker(c context.Context, cn string) (*CertChecker, error) {
checker, err := certCheckerCache.LRU(c).GetOrCreate(c, cn, func() (interface{}, time.Duration, error) {
// To avoid storing CertChecker for non-existent CAs in local memory forever,
// we do a datastore check when creating the checker. It happens once during
// the process lifetime.
switch exists, err := ds.Exists(c, ds.NewKey(c, "CA", cn, 0, nil)); {
case err != nil:
return nil, 0, transient.Tag.Apply(err)
case !exists.All():
return nil, 0, Error{
error: fmt.Errorf("no such CA %q", cn),
Reason: NoSuchCA,
}
}
return &CertChecker{
CN: cn,
CRL: certconfig.NewCRLChecker(cn, certconfig.CRLShardCount, refetchCRLPeriod(c)),
}, 0, nil
})
if err != nil {
return nil, err
}
return checker.(*CertChecker), nil
} | go | func GetCertChecker(c context.Context, cn string) (*CertChecker, error) {
checker, err := certCheckerCache.LRU(c).GetOrCreate(c, cn, func() (interface{}, time.Duration, error) {
// To avoid storing CertChecker for non-existent CAs in local memory forever,
// we do a datastore check when creating the checker. It happens once during
// the process lifetime.
switch exists, err := ds.Exists(c, ds.NewKey(c, "CA", cn, 0, nil)); {
case err != nil:
return nil, 0, transient.Tag.Apply(err)
case !exists.All():
return nil, 0, Error{
error: fmt.Errorf("no such CA %q", cn),
Reason: NoSuchCA,
}
}
return &CertChecker{
CN: cn,
CRL: certconfig.NewCRLChecker(cn, certconfig.CRLShardCount, refetchCRLPeriod(c)),
}, 0, nil
})
if err != nil {
return nil, err
}
return checker.(*CertChecker), nil
} | [
"func",
"GetCertChecker",
"(",
"c",
"context",
".",
"Context",
",",
"cn",
"string",
")",
"(",
"*",
"CertChecker",
",",
"error",
")",
"{",
"checker",
",",
"err",
":=",
"certCheckerCache",
".",
"LRU",
"(",
"c",
")",
".",
"GetOrCreate",
"(",
"c",
",",
"cn",
",",
"func",
"(",
")",
"(",
"interface",
"{",
"}",
",",
"time",
".",
"Duration",
",",
"error",
")",
"{",
"// To avoid storing CertChecker for non-existent CAs in local memory forever,",
"// we do a datastore check when creating the checker. It happens once during",
"// the process lifetime.",
"switch",
"exists",
",",
"err",
":=",
"ds",
".",
"Exists",
"(",
"c",
",",
"ds",
".",
"NewKey",
"(",
"c",
",",
"\"",
"\"",
",",
"cn",
",",
"0",
",",
"nil",
")",
")",
";",
"{",
"case",
"err",
"!=",
"nil",
":",
"return",
"nil",
",",
"0",
",",
"transient",
".",
"Tag",
".",
"Apply",
"(",
"err",
")",
"\n",
"case",
"!",
"exists",
".",
"All",
"(",
")",
":",
"return",
"nil",
",",
"0",
",",
"Error",
"{",
"error",
":",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"cn",
")",
",",
"Reason",
":",
"NoSuchCA",
",",
"}",
"\n",
"}",
"\n",
"return",
"&",
"CertChecker",
"{",
"CN",
":",
"cn",
",",
"CRL",
":",
"certconfig",
".",
"NewCRLChecker",
"(",
"cn",
",",
"certconfig",
".",
"CRLShardCount",
",",
"refetchCRLPeriod",
"(",
"c",
")",
")",
",",
"}",
",",
"0",
",",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"checker",
".",
"(",
"*",
"CertChecker",
")",
",",
"nil",
"\n",
"}"
] | // GetCertChecker returns an instance of CertChecker for given CA.
//
// It caches CertChecker objects in local memory and reuses them between
// requests. | [
"GetCertChecker",
"returns",
"an",
"instance",
"of",
"CertChecker",
"for",
"given",
"CA",
".",
"It",
"caches",
"CertChecker",
"objects",
"in",
"local",
"memory",
"and",
"reuses",
"them",
"between",
"requests",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/certchecker/certchecker.go#L146-L169 |
9,078 | luci/luci-go | tokenserver/appengine/impl/certchecker/certchecker.go | GetCA | func (ch *CertChecker) GetCA(c context.Context) (*certconfig.CA, error) {
value, err := ch.ca.Get(c, func(interface{}) (ca interface{}, exp time.Duration, err error) {
ca, err = ch.refetchCA(c)
if err == nil {
exp = refetchCAPeriod(c)
}
return
})
if err != nil {
return nil, err
}
ca, _ := value.(*certconfig.CA)
// nil 'ca' means 'refetchCA' could not find it in the datastore. May happen
// if CA entity was deleted after GetCertChecker call. It could have been also
// "soft-deleted" by setting Removed == true.
if ca == nil || ca.Removed {
return nil, Error{
error: fmt.Errorf("no such CA %q", ch.CN),
Reason: NoSuchCA,
}
}
return ca, nil
} | go | func (ch *CertChecker) GetCA(c context.Context) (*certconfig.CA, error) {
value, err := ch.ca.Get(c, func(interface{}) (ca interface{}, exp time.Duration, err error) {
ca, err = ch.refetchCA(c)
if err == nil {
exp = refetchCAPeriod(c)
}
return
})
if err != nil {
return nil, err
}
ca, _ := value.(*certconfig.CA)
// nil 'ca' means 'refetchCA' could not find it in the datastore. May happen
// if CA entity was deleted after GetCertChecker call. It could have been also
// "soft-deleted" by setting Removed == true.
if ca == nil || ca.Removed {
return nil, Error{
error: fmt.Errorf("no such CA %q", ch.CN),
Reason: NoSuchCA,
}
}
return ca, nil
} | [
"func",
"(",
"ch",
"*",
"CertChecker",
")",
"GetCA",
"(",
"c",
"context",
".",
"Context",
")",
"(",
"*",
"certconfig",
".",
"CA",
",",
"error",
")",
"{",
"value",
",",
"err",
":=",
"ch",
".",
"ca",
".",
"Get",
"(",
"c",
",",
"func",
"(",
"interface",
"{",
"}",
")",
"(",
"ca",
"interface",
"{",
"}",
",",
"exp",
"time",
".",
"Duration",
",",
"err",
"error",
")",
"{",
"ca",
",",
"err",
"=",
"ch",
".",
"refetchCA",
"(",
"c",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"exp",
"=",
"refetchCAPeriod",
"(",
"c",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"ca",
",",
"_",
":=",
"value",
".",
"(",
"*",
"certconfig",
".",
"CA",
")",
"\n",
"// nil 'ca' means 'refetchCA' could not find it in the datastore. May happen",
"// if CA entity was deleted after GetCertChecker call. It could have been also",
"// \"soft-deleted\" by setting Removed == true.",
"if",
"ca",
"==",
"nil",
"||",
"ca",
".",
"Removed",
"{",
"return",
"nil",
",",
"Error",
"{",
"error",
":",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"ch",
".",
"CN",
")",
",",
"Reason",
":",
"NoSuchCA",
",",
"}",
"\n",
"}",
"\n",
"return",
"ca",
",",
"nil",
"\n",
"}"
] | // GetCA returns CA entity with ParsedConfig and ParsedCert fields set. | [
"GetCA",
"returns",
"CA",
"entity",
"with",
"ParsedConfig",
"and",
"ParsedCert",
"fields",
"set",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/certchecker/certchecker.go#L172-L194 |
9,079 | luci/luci-go | tokenserver/appengine/impl/certchecker/certchecker.go | refetchCAPeriod | func refetchCAPeriod(c context.Context) time.Duration {
if info.IsDevAppServer(c) {
return 100 * time.Millisecond
}
return RefetchCAPeriod
} | go | func refetchCAPeriod(c context.Context) time.Duration {
if info.IsDevAppServer(c) {
return 100 * time.Millisecond
}
return RefetchCAPeriod
} | [
"func",
"refetchCAPeriod",
"(",
"c",
"context",
".",
"Context",
")",
"time",
".",
"Duration",
"{",
"if",
"info",
".",
"IsDevAppServer",
"(",
"c",
")",
"{",
"return",
"100",
"*",
"time",
".",
"Millisecond",
"\n",
"}",
"\n",
"return",
"RefetchCAPeriod",
"\n",
"}"
] | // refetchCAPeriod returns for how long to cache the CA in memory by default.
//
// On dev server we cache for a very short duration to simplify local testing. | [
"refetchCAPeriod",
"returns",
"for",
"how",
"long",
"to",
"cache",
"the",
"CA",
"in",
"memory",
"by",
"default",
".",
"On",
"dev",
"server",
"we",
"cache",
"for",
"a",
"very",
"short",
"duration",
"to",
"simplify",
"local",
"testing",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/certchecker/certchecker.go#L260-L265 |
9,080 | luci/luci-go | tokenserver/appengine/impl/certchecker/certchecker.go | refetchCRLPeriod | func refetchCRLPeriod(c context.Context) time.Duration {
if info.IsDevAppServer(c) {
return 100 * time.Millisecond
}
return RefetchCRLPeriod
} | go | func refetchCRLPeriod(c context.Context) time.Duration {
if info.IsDevAppServer(c) {
return 100 * time.Millisecond
}
return RefetchCRLPeriod
} | [
"func",
"refetchCRLPeriod",
"(",
"c",
"context",
".",
"Context",
")",
"time",
".",
"Duration",
"{",
"if",
"info",
".",
"IsDevAppServer",
"(",
"c",
")",
"{",
"return",
"100",
"*",
"time",
".",
"Millisecond",
"\n",
"}",
"\n",
"return",
"RefetchCRLPeriod",
"\n",
"}"
] | // refetchCRLPeriod returns for how long to cache the CRL in memory by default.
//
// On dev server we cache for a very short duration to simplify local testing. | [
"refetchCRLPeriod",
"returns",
"for",
"how",
"long",
"to",
"cache",
"the",
"CRL",
"in",
"memory",
"by",
"default",
".",
"On",
"dev",
"server",
"we",
"cache",
"for",
"a",
"very",
"short",
"duration",
"to",
"simplify",
"local",
"testing",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/certchecker/certchecker.go#L270-L275 |
9,081 | luci/luci-go | common/logging/logging.go | Get | func Get(c context.Context) Logger {
if f := GetFactory(c); f != nil {
return f(c)
}
return Null
} | go | func Get(c context.Context) Logger {
if f := GetFactory(c); f != nil {
return f(c)
}
return Null
} | [
"func",
"Get",
"(",
"c",
"context",
".",
"Context",
")",
"Logger",
"{",
"if",
"f",
":=",
"GetFactory",
"(",
"c",
")",
";",
"f",
"!=",
"nil",
"{",
"return",
"f",
"(",
"c",
")",
"\n",
"}",
"\n",
"return",
"Null",
"\n",
"}"
] | // Get the current Logger, or a logger that ignores all messages if none
// is defined. | [
"Get",
"the",
"current",
"Logger",
"or",
"a",
"logger",
"that",
"ignores",
"all",
"messages",
"if",
"none",
"is",
"defined",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/logging.go#L92-L97 |
9,082 | luci/luci-go | common/cli/profile.go | Run | func (r *wrappedCmdRun) Run(a subcommands.Application, args []string, env subcommands.Env) int {
ctx := GetContext(a, r, env)
r.prof.Logger = logging.Get(ctx)
r.prof.Clock = clock.Get(ctx)
if err := r.prof.Start(); err != nil {
logging.WithError(err).Errorf(ctx, "Failed to start profiling")
return 1
}
defer r.prof.Stop()
return r.CommandRun.Run(a, args, env)
} | go | func (r *wrappedCmdRun) Run(a subcommands.Application, args []string, env subcommands.Env) int {
ctx := GetContext(a, r, env)
r.prof.Logger = logging.Get(ctx)
r.prof.Clock = clock.Get(ctx)
if err := r.prof.Start(); err != nil {
logging.WithError(err).Errorf(ctx, "Failed to start profiling")
return 1
}
defer r.prof.Stop()
return r.CommandRun.Run(a, args, env)
} | [
"func",
"(",
"r",
"*",
"wrappedCmdRun",
")",
"Run",
"(",
"a",
"subcommands",
".",
"Application",
",",
"args",
"[",
"]",
"string",
",",
"env",
"subcommands",
".",
"Env",
")",
"int",
"{",
"ctx",
":=",
"GetContext",
"(",
"a",
",",
"r",
",",
"env",
")",
"\n",
"r",
".",
"prof",
".",
"Logger",
"=",
"logging",
".",
"Get",
"(",
"ctx",
")",
"\n",
"r",
".",
"prof",
".",
"Clock",
"=",
"clock",
".",
"Get",
"(",
"ctx",
")",
"\n\n",
"if",
"err",
":=",
"r",
".",
"prof",
".",
"Start",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"logging",
".",
"WithError",
"(",
"err",
")",
".",
"Errorf",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"return",
"1",
"\n",
"}",
"\n",
"defer",
"r",
".",
"prof",
".",
"Stop",
"(",
")",
"\n\n",
"return",
"r",
".",
"CommandRun",
".",
"Run",
"(",
"a",
",",
"args",
",",
"env",
")",
"\n",
"}"
] | // Run is part of CommandRun interface. | [
"Run",
"is",
"part",
"of",
"CommandRun",
"interface",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/cli/profile.go#L56-L68 |
9,083 | luci/luci-go | common/cli/profile.go | ModifyContext | func (r *wrappedCmdRun) ModifyContext(ctx context.Context) context.Context {
if m, _ := r.CommandRun.(ContextModificator); m != nil {
return m.ModifyContext(ctx)
}
return ctx
} | go | func (r *wrappedCmdRun) ModifyContext(ctx context.Context) context.Context {
if m, _ := r.CommandRun.(ContextModificator); m != nil {
return m.ModifyContext(ctx)
}
return ctx
} | [
"func",
"(",
"r",
"*",
"wrappedCmdRun",
")",
"ModifyContext",
"(",
"ctx",
"context",
".",
"Context",
")",
"context",
".",
"Context",
"{",
"if",
"m",
",",
"_",
":=",
"r",
".",
"CommandRun",
".",
"(",
"ContextModificator",
")",
";",
"m",
"!=",
"nil",
"{",
"return",
"m",
".",
"ModifyContext",
"(",
"ctx",
")",
"\n",
"}",
"\n",
"return",
"ctx",
"\n",
"}"
] | // ModifyContext is part of ContextModificator interface.
//
// Need to explicitly define it, since embedding original CommandRun in
// wrappedCmdRun "disables" the sniffing of ContextModificator in GetContext. | [
"ModifyContext",
"is",
"part",
"of",
"ContextModificator",
"interface",
".",
"Need",
"to",
"explicitly",
"define",
"it",
"since",
"embedding",
"original",
"CommandRun",
"in",
"wrappedCmdRun",
"disables",
"the",
"sniffing",
"of",
"ContextModificator",
"in",
"GetContext",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/cli/profile.go#L74-L79 |
9,084 | luci/luci-go | machine-db/appengine/rpc/dracs.go | CreateDRAC | func (*Service) CreateDRAC(c context.Context, req *crimson.CreateDRACRequest) (*crimson.DRAC, error) {
return createDRAC(c, req.Drac)
} | go | func (*Service) CreateDRAC(c context.Context, req *crimson.CreateDRACRequest) (*crimson.DRAC, error) {
return createDRAC(c, req.Drac)
} | [
"func",
"(",
"*",
"Service",
")",
"CreateDRAC",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"crimson",
".",
"CreateDRACRequest",
")",
"(",
"*",
"crimson",
".",
"DRAC",
",",
"error",
")",
"{",
"return",
"createDRAC",
"(",
"c",
",",
"req",
".",
"Drac",
")",
"\n",
"}"
] | // CreateDRAC handles a request to create a new DRAC. | [
"CreateDRAC",
"handles",
"a",
"request",
"to",
"create",
"a",
"new",
"DRAC",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/dracs.go#L38-L40 |
9,085 | luci/luci-go | machine-db/appengine/rpc/dracs.go | ListDRACs | func (*Service) ListDRACs(c context.Context, req *crimson.ListDRACsRequest) (*crimson.ListDRACsResponse, error) {
dracs, err := listDRACs(c, database.Get(c), req)
if err != nil {
return nil, err
}
return &crimson.ListDRACsResponse{
Dracs: dracs,
}, nil
} | go | func (*Service) ListDRACs(c context.Context, req *crimson.ListDRACsRequest) (*crimson.ListDRACsResponse, error) {
dracs, err := listDRACs(c, database.Get(c), req)
if err != nil {
return nil, err
}
return &crimson.ListDRACsResponse{
Dracs: dracs,
}, nil
} | [
"func",
"(",
"*",
"Service",
")",
"ListDRACs",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"crimson",
".",
"ListDRACsRequest",
")",
"(",
"*",
"crimson",
".",
"ListDRACsResponse",
",",
"error",
")",
"{",
"dracs",
",",
"err",
":=",
"listDRACs",
"(",
"c",
",",
"database",
".",
"Get",
"(",
"c",
")",
",",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"crimson",
".",
"ListDRACsResponse",
"{",
"Dracs",
":",
"dracs",
",",
"}",
",",
"nil",
"\n",
"}"
] | // ListDRACs handles a request to list DRACs. | [
"ListDRACs",
"handles",
"a",
"request",
"to",
"list",
"DRACs",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/dracs.go#L43-L51 |
9,086 | luci/luci-go | machine-db/appengine/rpc/dracs.go | UpdateDRAC | func (*Service) UpdateDRAC(c context.Context, req *crimson.UpdateDRACRequest) (*crimson.DRAC, error) {
return updateDRAC(c, req.Drac, req.UpdateMask)
} | go | func (*Service) UpdateDRAC(c context.Context, req *crimson.UpdateDRACRequest) (*crimson.DRAC, error) {
return updateDRAC(c, req.Drac, req.UpdateMask)
} | [
"func",
"(",
"*",
"Service",
")",
"UpdateDRAC",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"crimson",
".",
"UpdateDRACRequest",
")",
"(",
"*",
"crimson",
".",
"DRAC",
",",
"error",
")",
"{",
"return",
"updateDRAC",
"(",
"c",
",",
"req",
".",
"Drac",
",",
"req",
".",
"UpdateMask",
")",
"\n",
"}"
] | // UpdateDRAC handles a request to update an existing DRAC. | [
"UpdateDRAC",
"handles",
"a",
"request",
"to",
"update",
"an",
"existing",
"DRAC",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/dracs.go#L54-L56 |
9,087 | luci/luci-go | machine-db/appengine/rpc/dracs.go | createDRAC | func createDRAC(c context.Context, d *crimson.DRAC) (*crimson.DRAC, error) {
if err := validateDRACForCreation(d); err != nil {
return nil, err
}
ip, _ := common.ParseIPv4(d.Ipv4)
mac, _ := common.ParseMAC48(d.MacAddress)
tx, err := database.Begin(c)
if err != nil {
return nil, errors.Annotate(err, "failed to begin transaction").Err()
}
defer tx.MaybeRollback(c)
hostnameId, err := model.AssignHostnameAndIP(c, tx, d.Name, ip)
if err != nil {
return nil, err
}
_, err = tx.ExecContext(c, `
INSERT INTO dracs (hostname_id, machine_id, switch_id, switchport, mac_address)
VALUES (?, (SELECT id FROM machines WHERE name = ?), (SELECT id FROM switches WHERE name = ?), ?, ?)
`, hostnameId, d.Machine, d.Switch, d.Switchport, mac)
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, "'machine_id'"):
// e.g. "Error 1062: Duplicate entry '1' for key 'machine_id'".
return nil, status.Errorf(codes.AlreadyExists, "duplicate DRAC for machine %q", d.Machine)
case e.Number == mysqlerr.ER_DUP_ENTRY && strings.Contains(e.Message, "'mac_address'"):
// e.g. "Error 1062: Duplicate entry '1' for key 'mac_address'".
return nil, status.Errorf(codes.AlreadyExists, "duplicate MAC address %q", d.MacAddress)
case e.Number == mysqlerr.ER_BAD_NULL_ERROR && strings.Contains(e.Message, "'machine_id'"):
// e.g. "Error 1048: Column 'machine_id' cannot be null".
return nil, status.Errorf(codes.NotFound, "machine %q does not exist", d.Machine)
case e.Number == mysqlerr.ER_BAD_NULL_ERROR && strings.Contains(e.Message, "'switch_id'"):
// e.g. "Error 1048: Column 'switch_id' cannot be null".
return nil, status.Errorf(codes.NotFound, "switch %q does not exist", d.Switch)
}
return nil, errors.Annotate(err, "failed to create DRAC").Err()
}
dracs, err := listDRACs(c, tx, &crimson.ListDRACsRequest{
Names: []string{d.Name},
})
if err != nil {
return nil, errors.Annotate(err, "failed to fetch created DRAC").Err()
}
if err := tx.Commit(); err != nil {
return nil, errors.Annotate(err, "failed to commit transaction").Err()
}
return dracs[0], nil
} | go | func createDRAC(c context.Context, d *crimson.DRAC) (*crimson.DRAC, error) {
if err := validateDRACForCreation(d); err != nil {
return nil, err
}
ip, _ := common.ParseIPv4(d.Ipv4)
mac, _ := common.ParseMAC48(d.MacAddress)
tx, err := database.Begin(c)
if err != nil {
return nil, errors.Annotate(err, "failed to begin transaction").Err()
}
defer tx.MaybeRollback(c)
hostnameId, err := model.AssignHostnameAndIP(c, tx, d.Name, ip)
if err != nil {
return nil, err
}
_, err = tx.ExecContext(c, `
INSERT INTO dracs (hostname_id, machine_id, switch_id, switchport, mac_address)
VALUES (?, (SELECT id FROM machines WHERE name = ?), (SELECT id FROM switches WHERE name = ?), ?, ?)
`, hostnameId, d.Machine, d.Switch, d.Switchport, mac)
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, "'machine_id'"):
// e.g. "Error 1062: Duplicate entry '1' for key 'machine_id'".
return nil, status.Errorf(codes.AlreadyExists, "duplicate DRAC for machine %q", d.Machine)
case e.Number == mysqlerr.ER_DUP_ENTRY && strings.Contains(e.Message, "'mac_address'"):
// e.g. "Error 1062: Duplicate entry '1' for key 'mac_address'".
return nil, status.Errorf(codes.AlreadyExists, "duplicate MAC address %q", d.MacAddress)
case e.Number == mysqlerr.ER_BAD_NULL_ERROR && strings.Contains(e.Message, "'machine_id'"):
// e.g. "Error 1048: Column 'machine_id' cannot be null".
return nil, status.Errorf(codes.NotFound, "machine %q does not exist", d.Machine)
case e.Number == mysqlerr.ER_BAD_NULL_ERROR && strings.Contains(e.Message, "'switch_id'"):
// e.g. "Error 1048: Column 'switch_id' cannot be null".
return nil, status.Errorf(codes.NotFound, "switch %q does not exist", d.Switch)
}
return nil, errors.Annotate(err, "failed to create DRAC").Err()
}
dracs, err := listDRACs(c, tx, &crimson.ListDRACsRequest{
Names: []string{d.Name},
})
if err != nil {
return nil, errors.Annotate(err, "failed to fetch created DRAC").Err()
}
if err := tx.Commit(); err != nil {
return nil, errors.Annotate(err, "failed to commit transaction").Err()
}
return dracs[0], nil
} | [
"func",
"createDRAC",
"(",
"c",
"context",
".",
"Context",
",",
"d",
"*",
"crimson",
".",
"DRAC",
")",
"(",
"*",
"crimson",
".",
"DRAC",
",",
"error",
")",
"{",
"if",
"err",
":=",
"validateDRACForCreation",
"(",
"d",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"ip",
",",
"_",
":=",
"common",
".",
"ParseIPv4",
"(",
"d",
".",
"Ipv4",
")",
"\n",
"mac",
",",
"_",
":=",
"common",
".",
"ParseMAC48",
"(",
"d",
".",
"MacAddress",
")",
"\n",
"tx",
",",
"err",
":=",
"database",
".",
"Begin",
"(",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"defer",
"tx",
".",
"MaybeRollback",
"(",
"c",
")",
"\n\n",
"hostnameId",
",",
"err",
":=",
"model",
".",
"AssignHostnameAndIP",
"(",
"c",
",",
"tx",
",",
"d",
".",
"Name",
",",
"ip",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"_",
",",
"err",
"=",
"tx",
".",
"ExecContext",
"(",
"c",
",",
"`\n\t\tINSERT INTO dracs (hostname_id, machine_id, switch_id, switchport, mac_address)\n\t\tVALUES (?, (SELECT id FROM machines WHERE name = ?), (SELECT id FROM switches WHERE name = ?), ?, ?)\n\t`",
",",
"hostnameId",
",",
"d",
".",
"Machine",
",",
"d",
".",
"Switch",
",",
"d",
".",
"Switchport",
",",
"mac",
")",
"\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 '1' for key 'machine_id'\".",
"return",
"nil",
",",
"status",
".",
"Errorf",
"(",
"codes",
".",
"AlreadyExists",
",",
"\"",
"\"",
",",
"d",
".",
"Machine",
")",
"\n",
"case",
"e",
".",
"Number",
"==",
"mysqlerr",
".",
"ER_DUP_ENTRY",
"&&",
"strings",
".",
"Contains",
"(",
"e",
".",
"Message",
",",
"\"",
"\"",
")",
":",
"// e.g. \"Error 1062: Duplicate entry '1' for key 'mac_address'\".",
"return",
"nil",
",",
"status",
".",
"Errorf",
"(",
"codes",
".",
"AlreadyExists",
",",
"\"",
"\"",
",",
"d",
".",
"MacAddress",
")",
"\n",
"case",
"e",
".",
"Number",
"==",
"mysqlerr",
".",
"ER_BAD_NULL_ERROR",
"&&",
"strings",
".",
"Contains",
"(",
"e",
".",
"Message",
",",
"\"",
"\"",
")",
":",
"// e.g. \"Error 1048: Column 'machine_id' cannot be null\".",
"return",
"nil",
",",
"status",
".",
"Errorf",
"(",
"codes",
".",
"NotFound",
",",
"\"",
"\"",
",",
"d",
".",
"Machine",
")",
"\n",
"case",
"e",
".",
"Number",
"==",
"mysqlerr",
".",
"ER_BAD_NULL_ERROR",
"&&",
"strings",
".",
"Contains",
"(",
"e",
".",
"Message",
",",
"\"",
"\"",
")",
":",
"// e.g. \"Error 1048: Column 'switch_id' cannot be null\".",
"return",
"nil",
",",
"status",
".",
"Errorf",
"(",
"codes",
".",
"NotFound",
",",
"\"",
"\"",
",",
"d",
".",
"Switch",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n\n",
"dracs",
",",
"err",
":=",
"listDRACs",
"(",
"c",
",",
"tx",
",",
"&",
"crimson",
".",
"ListDRACsRequest",
"{",
"Names",
":",
"[",
"]",
"string",
"{",
"d",
".",
"Name",
"}",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"tx",
".",
"Commit",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"return",
"dracs",
"[",
"0",
"]",
",",
"nil",
"\n",
"}"
] | // createDRAC creates a new DRAC in the database. | [
"createDRAC",
"creates",
"a",
"new",
"DRAC",
"in",
"the",
"database",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/dracs.go#L59-L111 |
9,088 | luci/luci-go | machine-db/appengine/rpc/dracs.go | listDRACs | func listDRACs(c context.Context, q database.QueryerContext, req *crimson.ListDRACsRequest) ([]*crimson.DRAC, 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", "m.name", "s.name", "d.switchport", "d.mac_address", "i.ipv4").
From("dracs d, hostnames h, machines m, switches s, ips i").
Where("d.hostname_id = h.id").
Where("d.machine_id = m.id").
Where("d.switch_id = s.id").
Where("i.hostname_id = h.id")
stmt = selectInString(stmt, "h.name", req.Names)
stmt = selectInString(stmt, "m.name", req.Machines)
stmt = selectInInt64(stmt, "i.ipv4", ipv4s)
stmt = selectInInt64(stmt, "h.vlan_id", req.Vlans)
stmt = selectInString(stmt, "s.name", req.Switches)
stmt = selectInUint64(stmt, "d.mac_address", mac48s)
query, args, err := stmt.ToSql()
if err != nil {
return nil, errors.Annotate(err, "failed to generate statement").Err()
}
rows, err := q.QueryContext(c, query, args...)
if err != nil {
return nil, errors.Annotate(err, "failed to fetch DRACs").Err()
}
defer rows.Close()
var dracs []*crimson.DRAC
for rows.Next() {
d := &crimson.DRAC{}
var ipv4 common.IPv4
var mac48 common.MAC48
if err = rows.Scan(&d.Name, &d.Vlan, &d.Machine, &d.Switch, &d.Switchport, &mac48, &ipv4); err != nil {
return nil, errors.Annotate(err, "failed to fetch DRAC").Err()
}
d.Ipv4 = ipv4.String()
d.MacAddress = mac48.String()
dracs = append(dracs, d)
}
return dracs, nil
} | go | func listDRACs(c context.Context, q database.QueryerContext, req *crimson.ListDRACsRequest) ([]*crimson.DRAC, 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", "m.name", "s.name", "d.switchport", "d.mac_address", "i.ipv4").
From("dracs d, hostnames h, machines m, switches s, ips i").
Where("d.hostname_id = h.id").
Where("d.machine_id = m.id").
Where("d.switch_id = s.id").
Where("i.hostname_id = h.id")
stmt = selectInString(stmt, "h.name", req.Names)
stmt = selectInString(stmt, "m.name", req.Machines)
stmt = selectInInt64(stmt, "i.ipv4", ipv4s)
stmt = selectInInt64(stmt, "h.vlan_id", req.Vlans)
stmt = selectInString(stmt, "s.name", req.Switches)
stmt = selectInUint64(stmt, "d.mac_address", mac48s)
query, args, err := stmt.ToSql()
if err != nil {
return nil, errors.Annotate(err, "failed to generate statement").Err()
}
rows, err := q.QueryContext(c, query, args...)
if err != nil {
return nil, errors.Annotate(err, "failed to fetch DRACs").Err()
}
defer rows.Close()
var dracs []*crimson.DRAC
for rows.Next() {
d := &crimson.DRAC{}
var ipv4 common.IPv4
var mac48 common.MAC48
if err = rows.Scan(&d.Name, &d.Vlan, &d.Machine, &d.Switch, &d.Switchport, &mac48, &ipv4); err != nil {
return nil, errors.Annotate(err, "failed to fetch DRAC").Err()
}
d.Ipv4 = ipv4.String()
d.MacAddress = mac48.String()
dracs = append(dracs, d)
}
return dracs, nil
} | [
"func",
"listDRACs",
"(",
"c",
"context",
".",
"Context",
",",
"q",
"database",
".",
"QueryerContext",
",",
"req",
"*",
"crimson",
".",
"ListDRACsRequest",
")",
"(",
"[",
"]",
"*",
"crimson",
".",
"DRAC",
",",
"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",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
".",
"From",
"(",
"\"",
"\"",
")",
".",
"Where",
"(",
"\"",
"\"",
")",
".",
"Where",
"(",
"\"",
"\"",
")",
".",
"Where",
"(",
"\"",
"\"",
")",
".",
"Where",
"(",
"\"",
"\"",
")",
"\n",
"stmt",
"=",
"selectInString",
"(",
"stmt",
",",
"\"",
"\"",
",",
"req",
".",
"Names",
")",
"\n",
"stmt",
"=",
"selectInString",
"(",
"stmt",
",",
"\"",
"\"",
",",
"req",
".",
"Machines",
")",
"\n",
"stmt",
"=",
"selectInInt64",
"(",
"stmt",
",",
"\"",
"\"",
",",
"ipv4s",
")",
"\n",
"stmt",
"=",
"selectInInt64",
"(",
"stmt",
",",
"\"",
"\"",
",",
"req",
".",
"Vlans",
")",
"\n",
"stmt",
"=",
"selectInString",
"(",
"stmt",
",",
"\"",
"\"",
",",
"req",
".",
"Switches",
")",
"\n",
"stmt",
"=",
"selectInUint64",
"(",
"stmt",
",",
"\"",
"\"",
",",
"mac48s",
")",
"\n",
"query",
",",
"args",
",",
"err",
":=",
"stmt",
".",
"ToSql",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n\n",
"rows",
",",
"err",
":=",
"q",
".",
"QueryContext",
"(",
"c",
",",
"query",
",",
"args",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"defer",
"rows",
".",
"Close",
"(",
")",
"\n",
"var",
"dracs",
"[",
"]",
"*",
"crimson",
".",
"DRAC",
"\n",
"for",
"rows",
".",
"Next",
"(",
")",
"{",
"d",
":=",
"&",
"crimson",
".",
"DRAC",
"{",
"}",
"\n",
"var",
"ipv4",
"common",
".",
"IPv4",
"\n",
"var",
"mac48",
"common",
".",
"MAC48",
"\n",
"if",
"err",
"=",
"rows",
".",
"Scan",
"(",
"&",
"d",
".",
"Name",
",",
"&",
"d",
".",
"Vlan",
",",
"&",
"d",
".",
"Machine",
",",
"&",
"d",
".",
"Switch",
",",
"&",
"d",
".",
"Switchport",
",",
"&",
"mac48",
",",
"&",
"ipv4",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"d",
".",
"Ipv4",
"=",
"ipv4",
".",
"String",
"(",
")",
"\n",
"d",
".",
"MacAddress",
"=",
"mac48",
".",
"String",
"(",
")",
"\n",
"dracs",
"=",
"append",
"(",
"dracs",
",",
"d",
")",
"\n",
"}",
"\n",
"return",
"dracs",
",",
"nil",
"\n",
"}"
] | // listDRACs returns a slice of DRACs in the database. | [
"listDRACs",
"returns",
"a",
"slice",
"of",
"DRACs",
"in",
"the",
"database",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/dracs.go#L114-L159 |
9,089 | luci/luci-go | machine-db/appengine/rpc/dracs.go | validateDRACForCreation | func validateDRACForCreation(d *crimson.DRAC) error {
switch {
case d == nil:
return status.Error(codes.InvalidArgument, "DRAC specification is required")
case d.Name == "":
return status.Error(codes.InvalidArgument, "hostname is required and must be non-empty")
case d.Machine == "":
return status.Error(codes.InvalidArgument, "machine is required and must be non-empty")
case d.Switch == "":
return status.Error(codes.InvalidArgument, "switch is required and must be non-empty")
case d.Switchport < 1:
return status.Error(codes.InvalidArgument, "switchport must be positive")
case d.Vlan != 0:
return status.Error(codes.InvalidArgument, "VLAN must not be specified, use IP address instead")
default:
_, err := common.ParseIPv4(d.Ipv4)
if err != nil {
return status.Errorf(codes.InvalidArgument, "invalid IPv4 address %q", d.Ipv4)
}
_, err = common.ParseMAC48(d.MacAddress)
if err != nil {
return status.Errorf(codes.InvalidArgument, "invalid MAC-48 address %q", d.MacAddress)
}
return nil
}
} | go | func validateDRACForCreation(d *crimson.DRAC) error {
switch {
case d == nil:
return status.Error(codes.InvalidArgument, "DRAC specification is required")
case d.Name == "":
return status.Error(codes.InvalidArgument, "hostname is required and must be non-empty")
case d.Machine == "":
return status.Error(codes.InvalidArgument, "machine is required and must be non-empty")
case d.Switch == "":
return status.Error(codes.InvalidArgument, "switch is required and must be non-empty")
case d.Switchport < 1:
return status.Error(codes.InvalidArgument, "switchport must be positive")
case d.Vlan != 0:
return status.Error(codes.InvalidArgument, "VLAN must not be specified, use IP address instead")
default:
_, err := common.ParseIPv4(d.Ipv4)
if err != nil {
return status.Errorf(codes.InvalidArgument, "invalid IPv4 address %q", d.Ipv4)
}
_, err = common.ParseMAC48(d.MacAddress)
if err != nil {
return status.Errorf(codes.InvalidArgument, "invalid MAC-48 address %q", d.MacAddress)
}
return nil
}
} | [
"func",
"validateDRACForCreation",
"(",
"d",
"*",
"crimson",
".",
"DRAC",
")",
"error",
"{",
"switch",
"{",
"case",
"d",
"==",
"nil",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"d",
".",
"Name",
"==",
"\"",
"\"",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"d",
".",
"Machine",
"==",
"\"",
"\"",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"d",
".",
"Switch",
"==",
"\"",
"\"",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"d",
".",
"Switchport",
"<",
"1",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"d",
".",
"Vlan",
"!=",
"0",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"default",
":",
"_",
",",
"err",
":=",
"common",
".",
"ParseIPv4",
"(",
"d",
".",
"Ipv4",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"status",
".",
"Errorf",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
",",
"d",
".",
"Ipv4",
")",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"common",
".",
"ParseMAC48",
"(",
"d",
".",
"MacAddress",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"status",
".",
"Errorf",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
",",
"d",
".",
"MacAddress",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // validateDRACForCreation validates a DRAC for creation. | [
"validateDRACForCreation",
"validates",
"a",
"DRAC",
"for",
"creation",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/dracs.go#L232-L257 |
9,090 | luci/luci-go | machine-db/appengine/rpc/dracs.go | validateDRACForUpdate | func validateDRACForUpdate(d *crimson.DRAC, mask *field_mask.FieldMask) error {
switch err := validateUpdateMask(mask); {
case d == nil:
return status.Error(codes.InvalidArgument, "DRAC specification is required")
case d.Name == "":
return status.Error(codes.InvalidArgument, "DRAC name is required and must be non-empty")
case err != nil:
return err
}
for _, path := range mask.Paths {
// TODO(smut): Allow IPv4 address to be updated.
switch path {
case "name":
return status.Error(codes.InvalidArgument, "DRAC name cannot be updated, delete and create a new DRAC instead")
case "vlan":
return status.Error(codes.InvalidArgument, "VLAN cannot be updated, delete and create a new DRAC instead")
case "machine":
if d.Machine == "" {
return status.Error(codes.InvalidArgument, "machine is required and must be non-empty")
}
case "mac_address":
if d.MacAddress == "" {
return status.Error(codes.InvalidArgument, "MAC address is required and must be non-empty")
}
_, err := common.ParseMAC48(d.MacAddress)
if err != nil {
return status.Errorf(codes.InvalidArgument, "invalid MAC-48 address %q", d.MacAddress)
}
case "switch":
if d.Switch == "" {
return status.Error(codes.InvalidArgument, "switch is required and must be non-empty")
}
case "switchport":
if d.Switchport < 1 {
return status.Error(codes.InvalidArgument, "switchport must be positive")
}
default:
return status.Errorf(codes.InvalidArgument, "unsupported update mask path %q", path)
}
}
return nil
} | go | func validateDRACForUpdate(d *crimson.DRAC, mask *field_mask.FieldMask) error {
switch err := validateUpdateMask(mask); {
case d == nil:
return status.Error(codes.InvalidArgument, "DRAC specification is required")
case d.Name == "":
return status.Error(codes.InvalidArgument, "DRAC name is required and must be non-empty")
case err != nil:
return err
}
for _, path := range mask.Paths {
// TODO(smut): Allow IPv4 address to be updated.
switch path {
case "name":
return status.Error(codes.InvalidArgument, "DRAC name cannot be updated, delete and create a new DRAC instead")
case "vlan":
return status.Error(codes.InvalidArgument, "VLAN cannot be updated, delete and create a new DRAC instead")
case "machine":
if d.Machine == "" {
return status.Error(codes.InvalidArgument, "machine is required and must be non-empty")
}
case "mac_address":
if d.MacAddress == "" {
return status.Error(codes.InvalidArgument, "MAC address is required and must be non-empty")
}
_, err := common.ParseMAC48(d.MacAddress)
if err != nil {
return status.Errorf(codes.InvalidArgument, "invalid MAC-48 address %q", d.MacAddress)
}
case "switch":
if d.Switch == "" {
return status.Error(codes.InvalidArgument, "switch is required and must be non-empty")
}
case "switchport":
if d.Switchport < 1 {
return status.Error(codes.InvalidArgument, "switchport must be positive")
}
default:
return status.Errorf(codes.InvalidArgument, "unsupported update mask path %q", path)
}
}
return nil
} | [
"func",
"validateDRACForUpdate",
"(",
"d",
"*",
"crimson",
".",
"DRAC",
",",
"mask",
"*",
"field_mask",
".",
"FieldMask",
")",
"error",
"{",
"switch",
"err",
":=",
"validateUpdateMask",
"(",
"mask",
")",
";",
"{",
"case",
"d",
"==",
"nil",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"d",
".",
"Name",
"==",
"\"",
"\"",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"err",
"!=",
"nil",
":",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"path",
":=",
"range",
"mask",
".",
"Paths",
"{",
"// TODO(smut): Allow IPv4 address to be updated.",
"switch",
"path",
"{",
"case",
"\"",
"\"",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"\"",
"\"",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"\"",
"\"",
":",
"if",
"d",
".",
"Machine",
"==",
"\"",
"\"",
"{",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"case",
"\"",
"\"",
":",
"if",
"d",
".",
"MacAddress",
"==",
"\"",
"\"",
"{",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"common",
".",
"ParseMAC48",
"(",
"d",
".",
"MacAddress",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"status",
".",
"Errorf",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
",",
"d",
".",
"MacAddress",
")",
"\n",
"}",
"\n",
"case",
"\"",
"\"",
":",
"if",
"d",
".",
"Switch",
"==",
"\"",
"\"",
"{",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"case",
"\"",
"\"",
":",
"if",
"d",
".",
"Switchport",
"<",
"1",
"{",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"default",
":",
"return",
"status",
".",
"Errorf",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
",",
"path",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // validateDRACForUpdate validates a DRAC for update. | [
"validateDRACForUpdate",
"validates",
"a",
"DRAC",
"for",
"update",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/dracs.go#L260-L301 |
9,091 | luci/luci-go | grpc/prpc/accept.go | qParamSplit | func qParamSplit(v string) (mediaType string, qValue string, acceptParams string) {
rest := v
for {
semicolon := strings.IndexRune(rest, ';')
if semicolon < 0 {
mediaType = v
return
}
semicolonAbs := len(v) - len(rest) + semicolon // mark
rest = rest[semicolon:]
rest = rest[1:] // consume ;
rest = strings.TrimLeftFunc(rest, unicode.IsSpace)
if rest == "" || (rest[0] != 'q' && rest[0] != 'Q') {
continue
}
rest = rest[1:] // consume q
rest = strings.TrimLeftFunc(rest, unicode.IsSpace)
if rest == "" || rest[0] != '=' {
continue
}
rest = rest[1:] // consume =
rest = strings.TrimLeftFunc(rest, unicode.IsSpace)
if rest == "" {
continue
}
qValueStartAbs := len(v) - len(rest) // mark
semicolon2 := strings.IndexRune(rest, ';')
if semicolon2 >= 0 {
semicolon2Abs := len(v) - len(rest) + semicolon2
mediaType = v[:semicolonAbs]
qValue = v[qValueStartAbs:semicolon2Abs]
acceptParams = v[semicolon2Abs+1:]
acceptParams = strings.TrimLeftFunc(acceptParams, unicode.IsSpace)
} else {
mediaType = v[:semicolonAbs]
qValue = v[qValueStartAbs:]
}
qValue = strings.TrimRightFunc(qValue, unicode.IsSpace)
return
}
} | go | func qParamSplit(v string) (mediaType string, qValue string, acceptParams string) {
rest := v
for {
semicolon := strings.IndexRune(rest, ';')
if semicolon < 0 {
mediaType = v
return
}
semicolonAbs := len(v) - len(rest) + semicolon // mark
rest = rest[semicolon:]
rest = rest[1:] // consume ;
rest = strings.TrimLeftFunc(rest, unicode.IsSpace)
if rest == "" || (rest[0] != 'q' && rest[0] != 'Q') {
continue
}
rest = rest[1:] // consume q
rest = strings.TrimLeftFunc(rest, unicode.IsSpace)
if rest == "" || rest[0] != '=' {
continue
}
rest = rest[1:] // consume =
rest = strings.TrimLeftFunc(rest, unicode.IsSpace)
if rest == "" {
continue
}
qValueStartAbs := len(v) - len(rest) // mark
semicolon2 := strings.IndexRune(rest, ';')
if semicolon2 >= 0 {
semicolon2Abs := len(v) - len(rest) + semicolon2
mediaType = v[:semicolonAbs]
qValue = v[qValueStartAbs:semicolon2Abs]
acceptParams = v[semicolon2Abs+1:]
acceptParams = strings.TrimLeftFunc(acceptParams, unicode.IsSpace)
} else {
mediaType = v[:semicolonAbs]
qValue = v[qValueStartAbs:]
}
qValue = strings.TrimRightFunc(qValue, unicode.IsSpace)
return
}
} | [
"func",
"qParamSplit",
"(",
"v",
"string",
")",
"(",
"mediaType",
"string",
",",
"qValue",
"string",
",",
"acceptParams",
"string",
")",
"{",
"rest",
":=",
"v",
"\n",
"for",
"{",
"semicolon",
":=",
"strings",
".",
"IndexRune",
"(",
"rest",
",",
"';'",
")",
"\n",
"if",
"semicolon",
"<",
"0",
"{",
"mediaType",
"=",
"v",
"\n",
"return",
"\n",
"}",
"\n",
"semicolonAbs",
":=",
"len",
"(",
"v",
")",
"-",
"len",
"(",
"rest",
")",
"+",
"semicolon",
"// mark",
"\n",
"rest",
"=",
"rest",
"[",
"semicolon",
":",
"]",
"\n\n",
"rest",
"=",
"rest",
"[",
"1",
":",
"]",
"// consume ;",
"\n",
"rest",
"=",
"strings",
".",
"TrimLeftFunc",
"(",
"rest",
",",
"unicode",
".",
"IsSpace",
")",
"\n",
"if",
"rest",
"==",
"\"",
"\"",
"||",
"(",
"rest",
"[",
"0",
"]",
"!=",
"'q'",
"&&",
"rest",
"[",
"0",
"]",
"!=",
"'Q'",
")",
"{",
"continue",
"\n",
"}",
"\n\n",
"rest",
"=",
"rest",
"[",
"1",
":",
"]",
"// consume q",
"\n",
"rest",
"=",
"strings",
".",
"TrimLeftFunc",
"(",
"rest",
",",
"unicode",
".",
"IsSpace",
")",
"\n",
"if",
"rest",
"==",
"\"",
"\"",
"||",
"rest",
"[",
"0",
"]",
"!=",
"'='",
"{",
"continue",
"\n",
"}",
"\n\n",
"rest",
"=",
"rest",
"[",
"1",
":",
"]",
"// consume =",
"\n",
"rest",
"=",
"strings",
".",
"TrimLeftFunc",
"(",
"rest",
",",
"unicode",
".",
"IsSpace",
")",
"\n",
"if",
"rest",
"==",
"\"",
"\"",
"{",
"continue",
"\n",
"}",
"\n\n",
"qValueStartAbs",
":=",
"len",
"(",
"v",
")",
"-",
"len",
"(",
"rest",
")",
"// mark",
"\n",
"semicolon2",
":=",
"strings",
".",
"IndexRune",
"(",
"rest",
",",
"';'",
")",
"\n",
"if",
"semicolon2",
">=",
"0",
"{",
"semicolon2Abs",
":=",
"len",
"(",
"v",
")",
"-",
"len",
"(",
"rest",
")",
"+",
"semicolon2",
"\n",
"mediaType",
"=",
"v",
"[",
":",
"semicolonAbs",
"]",
"\n",
"qValue",
"=",
"v",
"[",
"qValueStartAbs",
":",
"semicolon2Abs",
"]",
"\n",
"acceptParams",
"=",
"v",
"[",
"semicolon2Abs",
"+",
"1",
":",
"]",
"\n",
"acceptParams",
"=",
"strings",
".",
"TrimLeftFunc",
"(",
"acceptParams",
",",
"unicode",
".",
"IsSpace",
")",
"\n",
"}",
"else",
"{",
"mediaType",
"=",
"v",
"[",
":",
"semicolonAbs",
"]",
"\n",
"qValue",
"=",
"v",
"[",
"qValueStartAbs",
":",
"]",
"\n",
"}",
"\n",
"qValue",
"=",
"strings",
".",
"TrimRightFunc",
"(",
"qValue",
",",
"unicode",
".",
"IsSpace",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}"
] | // qParamSplit splits media type and accept params by "q" parameter. | [
"qParamSplit",
"splits",
"media",
"type",
"and",
"accept",
"params",
"by",
"q",
"parameter",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/prpc/accept.go#L79-L123 |
9,092 | luci/luci-go | milo/buildsource/buildbot/pubsub.go | unmarshal | func unmarshal(
c context.Context, msg []byte) ([]*buildbot.Build, *buildbot.Master, error) {
bm := buildMasterMsg{}
if len(msg) == 0 {
return bm.Builds, bm.Master, nil
}
reader, err := zlib.NewReader(bytes.NewReader(msg))
if err != nil {
logging.WithError(err).Errorf(c, "gzip decompression error")
return nil, nil, err
}
defer reader.Close()
d := json.NewDecoder(reader)
if err = d.Decode(&bm); err != nil {
logging.WithError(err).Errorf(c, "could not unmarshal message")
return nil, nil, err
}
// Extract the builds out of master and append it onto builds.
if bm.Master != nil {
for _, slave := range bm.Master.Slaves {
if slave.RunningbuildsMap == nil {
slave.RunningbuildsMap = map[string][]int{}
}
for _, build := range slave.Runningbuilds {
build.Master = bm.Master.Name
bm.Builds = append(bm.Builds, build)
slave.RunningbuildsMap[build.Buildername] = append(
slave.RunningbuildsMap[build.Buildername], build.Number)
}
slave.Runningbuilds = nil
}
}
return bm.Builds, bm.Master, nil
} | go | func unmarshal(
c context.Context, msg []byte) ([]*buildbot.Build, *buildbot.Master, error) {
bm := buildMasterMsg{}
if len(msg) == 0 {
return bm.Builds, bm.Master, nil
}
reader, err := zlib.NewReader(bytes.NewReader(msg))
if err != nil {
logging.WithError(err).Errorf(c, "gzip decompression error")
return nil, nil, err
}
defer reader.Close()
d := json.NewDecoder(reader)
if err = d.Decode(&bm); err != nil {
logging.WithError(err).Errorf(c, "could not unmarshal message")
return nil, nil, err
}
// Extract the builds out of master and append it onto builds.
if bm.Master != nil {
for _, slave := range bm.Master.Slaves {
if slave.RunningbuildsMap == nil {
slave.RunningbuildsMap = map[string][]int{}
}
for _, build := range slave.Runningbuilds {
build.Master = bm.Master.Name
bm.Builds = append(bm.Builds, build)
slave.RunningbuildsMap[build.Buildername] = append(
slave.RunningbuildsMap[build.Buildername], build.Number)
}
slave.Runningbuilds = nil
}
}
return bm.Builds, bm.Master, nil
} | [
"func",
"unmarshal",
"(",
"c",
"context",
".",
"Context",
",",
"msg",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"*",
"buildbot",
".",
"Build",
",",
"*",
"buildbot",
".",
"Master",
",",
"error",
")",
"{",
"bm",
":=",
"buildMasterMsg",
"{",
"}",
"\n",
"if",
"len",
"(",
"msg",
")",
"==",
"0",
"{",
"return",
"bm",
".",
"Builds",
",",
"bm",
".",
"Master",
",",
"nil",
"\n",
"}",
"\n",
"reader",
",",
"err",
":=",
"zlib",
".",
"NewReader",
"(",
"bytes",
".",
"NewReader",
"(",
"msg",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logging",
".",
"WithError",
"(",
"err",
")",
".",
"Errorf",
"(",
"c",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"defer",
"reader",
".",
"Close",
"(",
")",
"\n",
"d",
":=",
"json",
".",
"NewDecoder",
"(",
"reader",
")",
"\n",
"if",
"err",
"=",
"d",
".",
"Decode",
"(",
"&",
"bm",
")",
";",
"err",
"!=",
"nil",
"{",
"logging",
".",
"WithError",
"(",
"err",
")",
".",
"Errorf",
"(",
"c",
",",
"\"",
"\"",
")",
"\n",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// Extract the builds out of master and append it onto builds.",
"if",
"bm",
".",
"Master",
"!=",
"nil",
"{",
"for",
"_",
",",
"slave",
":=",
"range",
"bm",
".",
"Master",
".",
"Slaves",
"{",
"if",
"slave",
".",
"RunningbuildsMap",
"==",
"nil",
"{",
"slave",
".",
"RunningbuildsMap",
"=",
"map",
"[",
"string",
"]",
"[",
"]",
"int",
"{",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"build",
":=",
"range",
"slave",
".",
"Runningbuilds",
"{",
"build",
".",
"Master",
"=",
"bm",
".",
"Master",
".",
"Name",
"\n",
"bm",
".",
"Builds",
"=",
"append",
"(",
"bm",
".",
"Builds",
",",
"build",
")",
"\n",
"slave",
".",
"RunningbuildsMap",
"[",
"build",
".",
"Buildername",
"]",
"=",
"append",
"(",
"slave",
".",
"RunningbuildsMap",
"[",
"build",
".",
"Buildername",
"]",
",",
"build",
".",
"Number",
")",
"\n",
"}",
"\n",
"slave",
".",
"Runningbuilds",
"=",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"bm",
".",
"Builds",
",",
"bm",
".",
"Master",
",",
"nil",
"\n",
"}"
] | // unmarshal a gzipped byte stream into a list of buildbot builds and masters. | [
"unmarshal",
"a",
"gzipped",
"byte",
"stream",
"into",
"a",
"list",
"of",
"buildbot",
"builds",
"and",
"masters",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/pubsub.go#L72-L105 |
9,093 | luci/luci-go | milo/buildsource/buildbot/pubsub.go | getOSInfo | func getOSInfo(c context.Context, b *buildbot.Build, m *buildstore.Master) (
family, version string) {
// Fetch the master info from datastore if not provided.
if m.Name == "" {
logging.Infof(c, "Fetching info for master %s", b.Master)
freshMaster, err := buildstore.GetMaster(c, b.Master, false)
if err != nil {
logging.WithError(err).Errorf(c, "fetching master %q", b.Master)
return
}
if freshMaster.Internal && !b.Internal {
logging.Errorf(c, "Build references an internal master, but build is not internal.")
return
}
*m = *freshMaster
}
s, ok := m.Slaves[b.Slave]
if !ok {
logging.Warningf(c, "Could not find slave %s in master %s", b.Slave, b.Master)
return
}
hostInfo := map[string]string{}
for _, v := range strings.Split(s.Host, "\n") {
if info := strings.SplitN(v, ":", 2); len(info) == 2 {
hostInfo[info[0]] = strings.TrimSpace(info[1])
}
}
// Extract OS and OS Family
if v, ok := hostInfo["os family"]; ok {
family = v
}
if v, ok := hostInfo["os version"]; ok {
version = v
}
return
} | go | func getOSInfo(c context.Context, b *buildbot.Build, m *buildstore.Master) (
family, version string) {
// Fetch the master info from datastore if not provided.
if m.Name == "" {
logging.Infof(c, "Fetching info for master %s", b.Master)
freshMaster, err := buildstore.GetMaster(c, b.Master, false)
if err != nil {
logging.WithError(err).Errorf(c, "fetching master %q", b.Master)
return
}
if freshMaster.Internal && !b.Internal {
logging.Errorf(c, "Build references an internal master, but build is not internal.")
return
}
*m = *freshMaster
}
s, ok := m.Slaves[b.Slave]
if !ok {
logging.Warningf(c, "Could not find slave %s in master %s", b.Slave, b.Master)
return
}
hostInfo := map[string]string{}
for _, v := range strings.Split(s.Host, "\n") {
if info := strings.SplitN(v, ":", 2); len(info) == 2 {
hostInfo[info[0]] = strings.TrimSpace(info[1])
}
}
// Extract OS and OS Family
if v, ok := hostInfo["os family"]; ok {
family = v
}
if v, ok := hostInfo["os version"]; ok {
version = v
}
return
} | [
"func",
"getOSInfo",
"(",
"c",
"context",
".",
"Context",
",",
"b",
"*",
"buildbot",
".",
"Build",
",",
"m",
"*",
"buildstore",
".",
"Master",
")",
"(",
"family",
",",
"version",
"string",
")",
"{",
"// Fetch the master info from datastore if not provided.",
"if",
"m",
".",
"Name",
"==",
"\"",
"\"",
"{",
"logging",
".",
"Infof",
"(",
"c",
",",
"\"",
"\"",
",",
"b",
".",
"Master",
")",
"\n",
"freshMaster",
",",
"err",
":=",
"buildstore",
".",
"GetMaster",
"(",
"c",
",",
"b",
".",
"Master",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logging",
".",
"WithError",
"(",
"err",
")",
".",
"Errorf",
"(",
"c",
",",
"\"",
"\"",
",",
"b",
".",
"Master",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"freshMaster",
".",
"Internal",
"&&",
"!",
"b",
".",
"Internal",
"{",
"logging",
".",
"Errorf",
"(",
"c",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"*",
"m",
"=",
"*",
"freshMaster",
"\n",
"}",
"\n\n",
"s",
",",
"ok",
":=",
"m",
".",
"Slaves",
"[",
"b",
".",
"Slave",
"]",
"\n",
"if",
"!",
"ok",
"{",
"logging",
".",
"Warningf",
"(",
"c",
",",
"\"",
"\"",
",",
"b",
".",
"Slave",
",",
"b",
".",
"Master",
")",
"\n",
"return",
"\n",
"}",
"\n",
"hostInfo",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"strings",
".",
"Split",
"(",
"s",
".",
"Host",
",",
"\"",
"\\n",
"\"",
")",
"{",
"if",
"info",
":=",
"strings",
".",
"SplitN",
"(",
"v",
",",
"\"",
"\"",
",",
"2",
")",
";",
"len",
"(",
"info",
")",
"==",
"2",
"{",
"hostInfo",
"[",
"info",
"[",
"0",
"]",
"]",
"=",
"strings",
".",
"TrimSpace",
"(",
"info",
"[",
"1",
"]",
")",
"\n",
"}",
"\n",
"}",
"\n",
"// Extract OS and OS Family",
"if",
"v",
",",
"ok",
":=",
"hostInfo",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"family",
"=",
"v",
"\n",
"}",
"\n",
"if",
"v",
",",
"ok",
":=",
"hostInfo",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"version",
"=",
"v",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // getOSInfo fetches the os family and version of the slave the build was
// running on from the master json on a best-effort basis. | [
"getOSInfo",
"fetches",
"the",
"os",
"family",
"and",
"version",
"of",
"the",
"slave",
"the",
"build",
"was",
"running",
"on",
"from",
"the",
"master",
"json",
"on",
"a",
"best",
"-",
"effort",
"basis",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/pubsub.go#L109-L145 |
9,094 | luci/luci-go | milo/buildsource/buildbot/pubsub.go | StatsHandler | func StatsHandler(c context.Context) error {
masters, err := buildstore.AllMasters(c, false)
if err != nil {
return errors.Annotate(err, "failed to fetch masters").Err()
}
now := clock.Now(c)
for _, m := range masters {
allMasterTimer.Set(c, now.Sub(m.Modified).Seconds(), m.Name)
}
return nil
} | go | func StatsHandler(c context.Context) error {
masters, err := buildstore.AllMasters(c, false)
if err != nil {
return errors.Annotate(err, "failed to fetch masters").Err()
}
now := clock.Now(c)
for _, m := range masters {
allMasterTimer.Set(c, now.Sub(m.Modified).Seconds(), m.Name)
}
return nil
} | [
"func",
"StatsHandler",
"(",
"c",
"context",
".",
"Context",
")",
"error",
"{",
"masters",
",",
"err",
":=",
"buildstore",
".",
"AllMasters",
"(",
"c",
",",
"false",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"now",
":=",
"clock",
".",
"Now",
"(",
"c",
")",
"\n",
"for",
"_",
",",
"m",
":=",
"range",
"masters",
"{",
"allMasterTimer",
".",
"Set",
"(",
"c",
",",
"now",
".",
"Sub",
"(",
"m",
".",
"Modified",
")",
".",
"Seconds",
"(",
")",
",",
"m",
".",
"Name",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // StatsHandler is a cron endpoint that sends stats periodically. | [
"StatsHandler",
"is",
"a",
"cron",
"endpoint",
"that",
"sends",
"stats",
"periodically",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/pubsub.go#L182-L192 |
9,095 | luci/luci-go | client/isolate/format.go | ToIsolated | func (r ReadOnlyValue) ToIsolated() (out *isolated.ReadOnlyValue) {
switch r {
case NotSet:
case Writeable:
out = new(isolated.ReadOnlyValue)
*out = isolated.Writeable
case FilesReadOnly:
out = new(isolated.ReadOnlyValue)
*out = isolated.FilesReadOnly
case DirsReadOnly:
out = new(isolated.ReadOnlyValue)
*out = isolated.DirsReadOnly
default:
log.Printf("invalid ReadOnlyValue %d", r)
}
return
} | go | func (r ReadOnlyValue) ToIsolated() (out *isolated.ReadOnlyValue) {
switch r {
case NotSet:
case Writeable:
out = new(isolated.ReadOnlyValue)
*out = isolated.Writeable
case FilesReadOnly:
out = new(isolated.ReadOnlyValue)
*out = isolated.FilesReadOnly
case DirsReadOnly:
out = new(isolated.ReadOnlyValue)
*out = isolated.DirsReadOnly
default:
log.Printf("invalid ReadOnlyValue %d", r)
}
return
} | [
"func",
"(",
"r",
"ReadOnlyValue",
")",
"ToIsolated",
"(",
")",
"(",
"out",
"*",
"isolated",
".",
"ReadOnlyValue",
")",
"{",
"switch",
"r",
"{",
"case",
"NotSet",
":",
"case",
"Writeable",
":",
"out",
"=",
"new",
"(",
"isolated",
".",
"ReadOnlyValue",
")",
"\n",
"*",
"out",
"=",
"isolated",
".",
"Writeable",
"\n",
"case",
"FilesReadOnly",
":",
"out",
"=",
"new",
"(",
"isolated",
".",
"ReadOnlyValue",
")",
"\n",
"*",
"out",
"=",
"isolated",
".",
"FilesReadOnly",
"\n",
"case",
"DirsReadOnly",
":",
"out",
"=",
"new",
"(",
"isolated",
".",
"ReadOnlyValue",
")",
"\n",
"*",
"out",
"=",
"isolated",
".",
"DirsReadOnly",
"\n",
"default",
":",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"r",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // ToIsolated can be used to convert ReadOnlyValue enum values to corresponding
// isolated.ReadOnlyValue enum values. It returns nil on errors. | [
"ToIsolated",
"can",
"be",
"used",
"to",
"convert",
"ReadOnlyValue",
"enum",
"values",
"to",
"corresponding",
"isolated",
".",
"ReadOnlyValue",
"enum",
"values",
".",
"It",
"returns",
"nil",
"on",
"errors",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/isolate/format.go#L57-L73 |
9,096 | luci/luci-go | client/isolate/format.go | GetConfig | func (c *Configs) GetConfig(configName configName) (*ConfigSettings, error) {
// Order byConfig according to configNames ordering function.
out := &ConfigSettings{}
for _, pair := range c.getSortedConfigPairs() {
ok := true
for i, confKey := range configName {
if pair.key[i].isBound() && pair.key[i].compare(confKey) != 0 {
ok = false
break
}
}
if ok {
var err error
if out, err = out.union(pair.value); err != nil {
return nil, err
}
}
}
return out, nil
} | go | func (c *Configs) GetConfig(configName configName) (*ConfigSettings, error) {
// Order byConfig according to configNames ordering function.
out := &ConfigSettings{}
for _, pair := range c.getSortedConfigPairs() {
ok := true
for i, confKey := range configName {
if pair.key[i].isBound() && pair.key[i].compare(confKey) != 0 {
ok = false
break
}
}
if ok {
var err error
if out, err = out.union(pair.value); err != nil {
return nil, err
}
}
}
return out, nil
} | [
"func",
"(",
"c",
"*",
"Configs",
")",
"GetConfig",
"(",
"configName",
"configName",
")",
"(",
"*",
"ConfigSettings",
",",
"error",
")",
"{",
"// Order byConfig according to configNames ordering function.",
"out",
":=",
"&",
"ConfigSettings",
"{",
"}",
"\n",
"for",
"_",
",",
"pair",
":=",
"range",
"c",
".",
"getSortedConfigPairs",
"(",
")",
"{",
"ok",
":=",
"true",
"\n",
"for",
"i",
",",
"confKey",
":=",
"range",
"configName",
"{",
"if",
"pair",
".",
"key",
"[",
"i",
"]",
".",
"isBound",
"(",
")",
"&&",
"pair",
".",
"key",
"[",
"i",
"]",
".",
"compare",
"(",
"confKey",
")",
"!=",
"0",
"{",
"ok",
"=",
"false",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"ok",
"{",
"var",
"err",
"error",
"\n",
"if",
"out",
",",
"err",
"=",
"out",
".",
"union",
"(",
"pair",
".",
"value",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"out",
",",
"nil",
"\n",
"}"
] | // GetConfig returns all configs that matches this config as a single ConfigSettings.
//
// Returns nil if none apply. | [
"GetConfig",
"returns",
"all",
"configs",
"that",
"matches",
"this",
"config",
"as",
"a",
"single",
"ConfigSettings",
".",
"Returns",
"nil",
"if",
"none",
"apply",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/isolate/format.go#L261-L280 |
9,097 | luci/luci-go | client/isolate/format.go | setConfig | func (c *Configs) setConfig(confName configName, value *ConfigSettings) {
assert(len(confName) == len(c.ConfigVariables))
assert(value != nil)
key := confName.key()
pair, ok := c.byConfig[key]
assert(!ok, "setConfig must not override existing keys (%s => %v)", key, pair.value)
c.byConfig[key] = configPair{confName, value}
} | go | func (c *Configs) setConfig(confName configName, value *ConfigSettings) {
assert(len(confName) == len(c.ConfigVariables))
assert(value != nil)
key := confName.key()
pair, ok := c.byConfig[key]
assert(!ok, "setConfig must not override existing keys (%s => %v)", key, pair.value)
c.byConfig[key] = configPair{confName, value}
} | [
"func",
"(",
"c",
"*",
"Configs",
")",
"setConfig",
"(",
"confName",
"configName",
",",
"value",
"*",
"ConfigSettings",
")",
"{",
"assert",
"(",
"len",
"(",
"confName",
")",
"==",
"len",
"(",
"c",
".",
"ConfigVariables",
")",
")",
"\n",
"assert",
"(",
"value",
"!=",
"nil",
")",
"\n",
"key",
":=",
"confName",
".",
"key",
"(",
")",
"\n",
"pair",
",",
"ok",
":=",
"c",
".",
"byConfig",
"[",
"key",
"]",
"\n",
"assert",
"(",
"!",
"ok",
",",
"\"",
"\"",
",",
"key",
",",
"pair",
".",
"value",
")",
"\n",
"c",
".",
"byConfig",
"[",
"key",
"]",
"=",
"configPair",
"{",
"confName",
",",
"value",
"}",
"\n",
"}"
] | // setConfig sets the ConfigSettings for this key.
//
// The key is a tuple of bounded or unbounded variables. The global variable
// is the key where all values are unbounded. | [
"setConfig",
"sets",
"the",
"ConfigSettings",
"for",
"this",
"key",
".",
"The",
"key",
"is",
"a",
"tuple",
"of",
"bounded",
"or",
"unbounded",
"variables",
".",
"The",
"global",
"variable",
"is",
"the",
"key",
"where",
"all",
"values",
"are",
"unbounded",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/isolate/format.go#L286-L293 |
9,098 | luci/luci-go | client/isolate/format.go | union | func (c *Configs) union(rhs *Configs) (*Configs, error) {
// Merge the keys of ConfigVariables for each Configs instances. All the new
// variables will become unbounded. This requires realigning the keys.
configVariables := uniqueMergeSortedStrings(
c.ConfigVariables, rhs.ConfigVariables)
out := newConfigs(configVariables)
byConfig := configPairs(append(
c.expandConfigVariables(configVariables),
rhs.expandConfigVariables(configVariables)...))
if len(byConfig) == 0 {
return out, nil
}
// Take union of ConfigSettings with the same configName (key),
// in order left, right.
// Thus, preserve the order between left, right while sorting.
sort.Stable(byConfig)
last := byConfig[0]
for _, curr := range byConfig[1:] {
if last.key.compare(curr.key) == 0 {
val, err := last.value.union(curr.value)
if err != nil {
return out, err
}
last.value = val
} else {
out.setConfig(last.key, last.value)
last = curr
}
}
out.setConfig(last.key, last.value)
return out, nil
} | go | func (c *Configs) union(rhs *Configs) (*Configs, error) {
// Merge the keys of ConfigVariables for each Configs instances. All the new
// variables will become unbounded. This requires realigning the keys.
configVariables := uniqueMergeSortedStrings(
c.ConfigVariables, rhs.ConfigVariables)
out := newConfigs(configVariables)
byConfig := configPairs(append(
c.expandConfigVariables(configVariables),
rhs.expandConfigVariables(configVariables)...))
if len(byConfig) == 0 {
return out, nil
}
// Take union of ConfigSettings with the same configName (key),
// in order left, right.
// Thus, preserve the order between left, right while sorting.
sort.Stable(byConfig)
last := byConfig[0]
for _, curr := range byConfig[1:] {
if last.key.compare(curr.key) == 0 {
val, err := last.value.union(curr.value)
if err != nil {
return out, err
}
last.value = val
} else {
out.setConfig(last.key, last.value)
last = curr
}
}
out.setConfig(last.key, last.value)
return out, nil
} | [
"func",
"(",
"c",
"*",
"Configs",
")",
"union",
"(",
"rhs",
"*",
"Configs",
")",
"(",
"*",
"Configs",
",",
"error",
")",
"{",
"// Merge the keys of ConfigVariables for each Configs instances. All the new",
"// variables will become unbounded. This requires realigning the keys.",
"configVariables",
":=",
"uniqueMergeSortedStrings",
"(",
"c",
".",
"ConfigVariables",
",",
"rhs",
".",
"ConfigVariables",
")",
"\n",
"out",
":=",
"newConfigs",
"(",
"configVariables",
")",
"\n",
"byConfig",
":=",
"configPairs",
"(",
"append",
"(",
"c",
".",
"expandConfigVariables",
"(",
"configVariables",
")",
",",
"rhs",
".",
"expandConfigVariables",
"(",
"configVariables",
")",
"...",
")",
")",
"\n",
"if",
"len",
"(",
"byConfig",
")",
"==",
"0",
"{",
"return",
"out",
",",
"nil",
"\n",
"}",
"\n",
"// Take union of ConfigSettings with the same configName (key),",
"// in order left, right.",
"// Thus, preserve the order between left, right while sorting.",
"sort",
".",
"Stable",
"(",
"byConfig",
")",
"\n",
"last",
":=",
"byConfig",
"[",
"0",
"]",
"\n",
"for",
"_",
",",
"curr",
":=",
"range",
"byConfig",
"[",
"1",
":",
"]",
"{",
"if",
"last",
".",
"key",
".",
"compare",
"(",
"curr",
".",
"key",
")",
"==",
"0",
"{",
"val",
",",
"err",
":=",
"last",
".",
"value",
".",
"union",
"(",
"curr",
".",
"value",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"out",
",",
"err",
"\n",
"}",
"\n",
"last",
".",
"value",
"=",
"val",
"\n",
"}",
"else",
"{",
"out",
".",
"setConfig",
"(",
"last",
".",
"key",
",",
"last",
".",
"value",
")",
"\n",
"last",
"=",
"curr",
"\n",
"}",
"\n",
"}",
"\n",
"out",
".",
"setConfig",
"(",
"last",
".",
"key",
",",
"last",
".",
"value",
")",
"\n",
"return",
"out",
",",
"nil",
"\n",
"}"
] | // union returns a new Configs instance, the union of variables from self and rhs.
//
// It keeps ConfigVariables sorted in the output. | [
"union",
"returns",
"a",
"new",
"Configs",
"instance",
"the",
"union",
"of",
"variables",
"from",
"self",
"and",
"rhs",
".",
"It",
"keeps",
"ConfigVariables",
"sorted",
"in",
"the",
"output",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/isolate/format.go#L298-L329 |
9,099 | luci/luci-go | client/isolate/format.go | expandConfigVariables | func (c *Configs) expandConfigVariables(newConfigVars []string) []configPair {
// Get mapping from old config vars list to new one.
mapping := make([]int, len(newConfigVars))
i := 0
for n, nk := range newConfigVars {
if i == len(c.ConfigVariables) || c.ConfigVariables[i] > nk {
mapping[n] = -1
} else if c.ConfigVariables[i] == nk {
mapping[n] = i
i++
} else {
// Must never happen because newConfigVars and c.configVariables are sorted ASC,
// and newConfigVars contain c.configVariables as a subset.
panic("unreachable code")
}
}
// Expands configName to match newConfigVars.
getNewconfigName := func(old configName) configName {
newConfig := make(configName, len(mapping))
for k, v := range mapping {
if v != -1 {
newConfig[k] = old[v]
}
}
return newConfig
}
// Compute new byConfig.
out := make([]configPair, 0, len(c.byConfig))
for _, pair := range c.byConfig {
out = append(out, configPair{getNewconfigName(pair.key), pair.value})
}
return out
} | go | func (c *Configs) expandConfigVariables(newConfigVars []string) []configPair {
// Get mapping from old config vars list to new one.
mapping := make([]int, len(newConfigVars))
i := 0
for n, nk := range newConfigVars {
if i == len(c.ConfigVariables) || c.ConfigVariables[i] > nk {
mapping[n] = -1
} else if c.ConfigVariables[i] == nk {
mapping[n] = i
i++
} else {
// Must never happen because newConfigVars and c.configVariables are sorted ASC,
// and newConfigVars contain c.configVariables as a subset.
panic("unreachable code")
}
}
// Expands configName to match newConfigVars.
getNewconfigName := func(old configName) configName {
newConfig := make(configName, len(mapping))
for k, v := range mapping {
if v != -1 {
newConfig[k] = old[v]
}
}
return newConfig
}
// Compute new byConfig.
out := make([]configPair, 0, len(c.byConfig))
for _, pair := range c.byConfig {
out = append(out, configPair{getNewconfigName(pair.key), pair.value})
}
return out
} | [
"func",
"(",
"c",
"*",
"Configs",
")",
"expandConfigVariables",
"(",
"newConfigVars",
"[",
"]",
"string",
")",
"[",
"]",
"configPair",
"{",
"// Get mapping from old config vars list to new one.",
"mapping",
":=",
"make",
"(",
"[",
"]",
"int",
",",
"len",
"(",
"newConfigVars",
")",
")",
"\n",
"i",
":=",
"0",
"\n",
"for",
"n",
",",
"nk",
":=",
"range",
"newConfigVars",
"{",
"if",
"i",
"==",
"len",
"(",
"c",
".",
"ConfigVariables",
")",
"||",
"c",
".",
"ConfigVariables",
"[",
"i",
"]",
">",
"nk",
"{",
"mapping",
"[",
"n",
"]",
"=",
"-",
"1",
"\n",
"}",
"else",
"if",
"c",
".",
"ConfigVariables",
"[",
"i",
"]",
"==",
"nk",
"{",
"mapping",
"[",
"n",
"]",
"=",
"i",
"\n",
"i",
"++",
"\n",
"}",
"else",
"{",
"// Must never happen because newConfigVars and c.configVariables are sorted ASC,",
"// and newConfigVars contain c.configVariables as a subset.",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"// Expands configName to match newConfigVars.",
"getNewconfigName",
":=",
"func",
"(",
"old",
"configName",
")",
"configName",
"{",
"newConfig",
":=",
"make",
"(",
"configName",
",",
"len",
"(",
"mapping",
")",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"mapping",
"{",
"if",
"v",
"!=",
"-",
"1",
"{",
"newConfig",
"[",
"k",
"]",
"=",
"old",
"[",
"v",
"]",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"newConfig",
"\n",
"}",
"\n",
"// Compute new byConfig.",
"out",
":=",
"make",
"(",
"[",
"]",
"configPair",
",",
"0",
",",
"len",
"(",
"c",
".",
"byConfig",
")",
")",
"\n",
"for",
"_",
",",
"pair",
":=",
"range",
"c",
".",
"byConfig",
"{",
"out",
"=",
"append",
"(",
"out",
",",
"configPair",
"{",
"getNewconfigName",
"(",
"pair",
".",
"key",
")",
",",
"pair",
".",
"value",
"}",
")",
"\n",
"}",
"\n",
"return",
"out",
"\n",
"}"
] | // expandConfigVariables returns new configPair list for newConfigVars. | [
"expandConfigVariables",
"returns",
"new",
"configPair",
"list",
"for",
"newConfigVars",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/isolate/format.go#L332-L364 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.