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 list | docstring stringlengths 6 2.61k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 85 252 |
|---|---|---|---|---|---|---|---|---|---|---|---|
7,800 | luci/luci-go | milo/api/config/util.go | AllBuilderIDs | func (c *Console) AllBuilderIDs() []string {
builders := make([]string, 0, len(c.Builders))
for _, b := range c.Builders {
builders = append(builders, b.Name...)
}
return builders
} | go | func (c *Console) AllBuilderIDs() []string {
builders := make([]string, 0, len(c.Builders))
for _, b := range c.Builders {
builders = append(builders, b.Name...)
}
return builders
} | [
"func",
"(",
"c",
"*",
"Console",
")",
"AllBuilderIDs",
"(",
")",
"[",
"]",
"string",
"{",
"builders",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"c",
".",
"Builders",
")",
")",
"\n",
"for",
"_",
",",
"b",
":=",
"range",
... | // AllBuilderIDs returns all BuilderIDs mentioned by this Console. | [
"AllBuilderIDs",
"returns",
"all",
"BuilderIDs",
"mentioned",
"by",
"this",
"Console",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/api/config/util.go#L26-L32 |
7,801 | luci/luci-go | machine-db/appengine/model/oses.go | fetch | func (t *OSesTable) fetch(c context.Context) error {
db := database.Get(c)
rows, err := db.QueryContext(c, `
SELECT id, name, description
FROM oses
`)
if err != nil {
return errors.Annotate(err, "failed to select operating systems").Err()
}
defer rows.Close()
for rows.Next() {
os := &OS{}
if err := rows.Scan(&os.Id, &os.Name, &os.Description); err != nil {
return errors.Annotate(err, "failed to scan operating system").Err()
}
t.current = append(t.current, os)
}
return nil
} | go | func (t *OSesTable) fetch(c context.Context) error {
db := database.Get(c)
rows, err := db.QueryContext(c, `
SELECT id, name, description
FROM oses
`)
if err != nil {
return errors.Annotate(err, "failed to select operating systems").Err()
}
defer rows.Close()
for rows.Next() {
os := &OS{}
if err := rows.Scan(&os.Id, &os.Name, &os.Description); err != nil {
return errors.Annotate(err, "failed to scan operating system").Err()
}
t.current = append(t.current, os)
}
return nil
} | [
"func",
"(",
"t",
"*",
"OSesTable",
")",
"fetch",
"(",
"c",
"context",
".",
"Context",
")",
"error",
"{",
"db",
":=",
"database",
".",
"Get",
"(",
"c",
")",
"\n",
"rows",
",",
"err",
":=",
"db",
".",
"QueryContext",
"(",
"c",
",",
"`\n\t\tSELECT id... | // fetch fetches the operating systems from the database. | [
"fetch",
"fetches",
"the",
"operating",
"systems",
"from",
"the",
"database",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/oses.go#L47-L65 |
7,802 | luci/luci-go | machine-db/appengine/model/oses.go | computeChanges | func (t *OSesTable) computeChanges(c context.Context, oses []*config.OS) {
cfgs := make(map[string]*OS, len(oses))
for _, cfg := range oses {
cfgs[cfg.Name] = &OS{
OS: config.OS{
Name: cfg.Name,
Description: cfg.Description,
},
}
}
for _, os := range t.current {
if cfg, ok := cfgs[os.Name]; ok {
// Operating system found in the config.
if t.needsUpdate(os, cfg) {
// Operating system doesn't match the config.
cfg.Id = os.Id
t.updates = append(t.updates, cfg)
}
// Record that the operating system config has been seen.
delete(cfgs, cfg.Name)
} else {
// Operating system not found in the config.
t.removals = append(t.removals, os)
}
}
// Operating systems remaining in the map are present in the config but not the database.
// Iterate deterministically over the slice to determine which operating systems need to be added.
for _, cfg := range oses {
if os, ok := cfgs[cfg.Name]; ok {
t.additions = append(t.additions, os)
}
}
} | go | func (t *OSesTable) computeChanges(c context.Context, oses []*config.OS) {
cfgs := make(map[string]*OS, len(oses))
for _, cfg := range oses {
cfgs[cfg.Name] = &OS{
OS: config.OS{
Name: cfg.Name,
Description: cfg.Description,
},
}
}
for _, os := range t.current {
if cfg, ok := cfgs[os.Name]; ok {
// Operating system found in the config.
if t.needsUpdate(os, cfg) {
// Operating system doesn't match the config.
cfg.Id = os.Id
t.updates = append(t.updates, cfg)
}
// Record that the operating system config has been seen.
delete(cfgs, cfg.Name)
} else {
// Operating system not found in the config.
t.removals = append(t.removals, os)
}
}
// Operating systems remaining in the map are present in the config but not the database.
// Iterate deterministically over the slice to determine which operating systems need to be added.
for _, cfg := range oses {
if os, ok := cfgs[cfg.Name]; ok {
t.additions = append(t.additions, os)
}
}
} | [
"func",
"(",
"t",
"*",
"OSesTable",
")",
"computeChanges",
"(",
"c",
"context",
".",
"Context",
",",
"oses",
"[",
"]",
"*",
"config",
".",
"OS",
")",
"{",
"cfgs",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"OS",
",",
"len",
"(",
"oses",
... | // computeChanges computes the changes that need to be made to the operating systems in the database. | [
"computeChanges",
"computes",
"the",
"changes",
"that",
"need",
"to",
"be",
"made",
"to",
"the",
"operating",
"systems",
"in",
"the",
"database",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/oses.go#L73-L107 |
7,803 | luci/luci-go | machine-db/appengine/model/oses.go | remove | func (t *OSesTable) remove(c context.Context) error {
// Avoid using the database connection to prepare unnecessary statements.
if len(t.removals) == 0 {
return nil
}
db := database.Get(c)
stmt, err := db.PrepareContext(c, `
DELETE FROM oses
WHERE id = ?
`)
if err != nil {
return errors.Annotate(err, "failed to prepare statement").Err()
}
defer stmt.Close()
// Remove each operating system from the table. It's more efficient to update the slice of
// operating systems once at the end rather than for each removal, so use a defer.
removed := make(map[int64]struct{}, len(t.removals))
defer func() {
var oses []*OS
for _, os := range t.current {
if _, ok := removed[os.Id]; !ok {
oses = append(oses, os)
}
}
t.current = oses
}()
for len(t.removals) > 0 {
os := t.removals[0]
if _, err := stmt.ExecContext(c, os.Id); err != nil {
// Defer ensures the slice of operating systems is updated even if we exit early.
return errors.Annotate(err, "failed to remove operating system %q", os.Name).Err()
}
removed[os.Id] = struct{}{}
t.removals = t.removals[1:]
logging.Infof(c, "Removed operating system %q", os.Name)
}
return nil
} | go | func (t *OSesTable) remove(c context.Context) error {
// Avoid using the database connection to prepare unnecessary statements.
if len(t.removals) == 0 {
return nil
}
db := database.Get(c)
stmt, err := db.PrepareContext(c, `
DELETE FROM oses
WHERE id = ?
`)
if err != nil {
return errors.Annotate(err, "failed to prepare statement").Err()
}
defer stmt.Close()
// Remove each operating system from the table. It's more efficient to update the slice of
// operating systems once at the end rather than for each removal, so use a defer.
removed := make(map[int64]struct{}, len(t.removals))
defer func() {
var oses []*OS
for _, os := range t.current {
if _, ok := removed[os.Id]; !ok {
oses = append(oses, os)
}
}
t.current = oses
}()
for len(t.removals) > 0 {
os := t.removals[0]
if _, err := stmt.ExecContext(c, os.Id); err != nil {
// Defer ensures the slice of operating systems is updated even if we exit early.
return errors.Annotate(err, "failed to remove operating system %q", os.Name).Err()
}
removed[os.Id] = struct{}{}
t.removals = t.removals[1:]
logging.Infof(c, "Removed operating system %q", os.Name)
}
return nil
} | [
"func",
"(",
"t",
"*",
"OSesTable",
")",
"remove",
"(",
"c",
"context",
".",
"Context",
")",
"error",
"{",
"// Avoid using the database connection to prepare unnecessary statements.",
"if",
"len",
"(",
"t",
".",
"removals",
")",
"==",
"0",
"{",
"return",
"nil",
... | // remove removes all operating systems pending removal from the database, clearing pending removals.
// No-op unless computeChanges was called first. Idempotent until computeChanges is called again. | [
"remove",
"removes",
"all",
"operating",
"systems",
"pending",
"removal",
"from",
"the",
"database",
"clearing",
"pending",
"removals",
".",
"No",
"-",
"op",
"unless",
"computeChanges",
"was",
"called",
"first",
".",
"Idempotent",
"until",
"computeChanges",
"is",
... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/oses.go#L147-L186 |
7,804 | luci/luci-go | machine-db/appengine/model/oses.go | ids | func (t *OSesTable) ids(c context.Context) map[string]int64 {
oses := make(map[string]int64, len(t.current))
for _, os := range t.current {
oses[os.Name] = os.Id
}
return oses
} | go | func (t *OSesTable) ids(c context.Context) map[string]int64 {
oses := make(map[string]int64, len(t.current))
for _, os := range t.current {
oses[os.Name] = os.Id
}
return oses
} | [
"func",
"(",
"t",
"*",
"OSesTable",
")",
"ids",
"(",
"c",
"context",
".",
"Context",
")",
"map",
"[",
"string",
"]",
"int64",
"{",
"oses",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"int64",
",",
"len",
"(",
"t",
".",
"current",
")",
")",
"\... | // ids returns a map of operating system names to IDs. | [
"ids",
"returns",
"a",
"map",
"of",
"operating",
"system",
"names",
"to",
"IDs",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/oses.go#L230-L236 |
7,805 | luci/luci-go | machine-db/appengine/model/oses.go | EnsureOSes | func EnsureOSes(c context.Context, cfgs []*config.OS) error {
t := &OSesTable{}
if err := t.fetch(c); err != nil {
return errors.Annotate(err, "failed to fetch operating systems").Err()
}
t.computeChanges(c, cfgs)
if err := t.add(c); err != nil {
return errors.Annotate(err, "failed to add operating systems").Err()
}
if err := t.remove(c); err != nil {
return errors.Annotate(err, "failed to remove operating systems").Err()
}
if err := t.update(c); err != nil {
return errors.Annotate(err, "failed to update operating systems").Err()
}
return nil
} | go | func EnsureOSes(c context.Context, cfgs []*config.OS) error {
t := &OSesTable{}
if err := t.fetch(c); err != nil {
return errors.Annotate(err, "failed to fetch operating systems").Err()
}
t.computeChanges(c, cfgs)
if err := t.add(c); err != nil {
return errors.Annotate(err, "failed to add operating systems").Err()
}
if err := t.remove(c); err != nil {
return errors.Annotate(err, "failed to remove operating systems").Err()
}
if err := t.update(c); err != nil {
return errors.Annotate(err, "failed to update operating systems").Err()
}
return nil
} | [
"func",
"EnsureOSes",
"(",
"c",
"context",
".",
"Context",
",",
"cfgs",
"[",
"]",
"*",
"config",
".",
"OS",
")",
"error",
"{",
"t",
":=",
"&",
"OSesTable",
"{",
"}",
"\n",
"if",
"err",
":=",
"t",
".",
"fetch",
"(",
"c",
")",
";",
"err",
"!=",
... | // EnsureOSes ensures the database contains exactly the given operating systems. | [
"EnsureOSes",
"ensures",
"the",
"database",
"contains",
"exactly",
"the",
"given",
"operating",
"systems",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/oses.go#L239-L255 |
7,806 | luci/luci-go | cipd/common/hash.go | NewHash | func NewHash(algo api.HashAlgo) (hash.Hash, error) {
if err := ValidateHashAlgo(algo); err != nil {
return nil, err
}
return supportedAlgos[algo].hash(), nil
} | go | func NewHash(algo api.HashAlgo) (hash.Hash, error) {
if err := ValidateHashAlgo(algo); err != nil {
return nil, err
}
return supportedAlgos[algo].hash(), nil
} | [
"func",
"NewHash",
"(",
"algo",
"api",
".",
"HashAlgo",
")",
"(",
"hash",
".",
"Hash",
",",
"error",
")",
"{",
"if",
"err",
":=",
"ValidateHashAlgo",
"(",
"algo",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"r... | // NewHash returns a hash implementation or an error if the algo is unknown. | [
"NewHash",
"returns",
"a",
"hash",
"implementation",
"or",
"an",
"error",
"if",
"the",
"algo",
"is",
"unknown",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/common/hash.go#L55-L60 |
7,807 | luci/luci-go | cipd/common/hash.go | MustNewHash | func MustNewHash(algo api.HashAlgo) hash.Hash {
h, err := NewHash(algo)
if err != nil {
panic(err)
}
return h
} | go | func MustNewHash(algo api.HashAlgo) hash.Hash {
h, err := NewHash(algo)
if err != nil {
panic(err)
}
return h
} | [
"func",
"MustNewHash",
"(",
"algo",
"api",
".",
"HashAlgo",
")",
"hash",
".",
"Hash",
"{",
"h",
",",
"err",
":=",
"NewHash",
"(",
"algo",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"h",
"\n",
... | // MustNewHash as like NewHash, but panics on errors.
//
// Appropriate for cases when the hash algo has already been validated. | [
"MustNewHash",
"as",
"like",
"NewHash",
"but",
"panics",
"on",
"errors",
".",
"Appropriate",
"for",
"cases",
"when",
"the",
"hash",
"algo",
"has",
"already",
"been",
"validated",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/common/hash.go#L65-L71 |
7,808 | luci/luci-go | gce/appengine/rpc/instances.go | Delete | func (*Instances) Delete(c context.Context, req *instances.DeleteRequest) (*empty.Empty, error) {
if req.GetId() == "" {
return nil, status.Errorf(codes.InvalidArgument, "ID is required")
}
vm := &model.VM{
ID: req.Id,
}
if err := datastore.RunInTransaction(c, func(c context.Context) error {
switch err := datastore.Get(c, vm); {
case err == datastore.ErrNoSuchEntity:
return nil
case err != nil:
return errors.Annotate(err, "failed to fetch VM").Err()
case vm.Drained:
return nil
}
vm.Drained = true
if err := datastore.Put(c, vm); err != nil {
return errors.Annotate(err, "failed to store VM").Err()
}
return nil
}, nil); err != nil {
return nil, err
}
return &empty.Empty{}, nil
} | go | func (*Instances) Delete(c context.Context, req *instances.DeleteRequest) (*empty.Empty, error) {
if req.GetId() == "" {
return nil, status.Errorf(codes.InvalidArgument, "ID is required")
}
vm := &model.VM{
ID: req.Id,
}
if err := datastore.RunInTransaction(c, func(c context.Context) error {
switch err := datastore.Get(c, vm); {
case err == datastore.ErrNoSuchEntity:
return nil
case err != nil:
return errors.Annotate(err, "failed to fetch VM").Err()
case vm.Drained:
return nil
}
vm.Drained = true
if err := datastore.Put(c, vm); err != nil {
return errors.Annotate(err, "failed to store VM").Err()
}
return nil
}, nil); err != nil {
return nil, err
}
return &empty.Empty{}, nil
} | [
"func",
"(",
"*",
"Instances",
")",
"Delete",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"instances",
".",
"DeleteRequest",
")",
"(",
"*",
"empty",
".",
"Empty",
",",
"error",
")",
"{",
"if",
"req",
".",
"GetId",
"(",
")",
"==",
"\"",
... | // Delete handles a request to delete an instance asynchronously. | [
"Delete",
"handles",
"a",
"request",
"to",
"delete",
"an",
"instance",
"asynchronously",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/rpc/instances.go#L42-L67 |
7,809 | luci/luci-go | gce/appengine/rpc/instances.go | Get | func (*Instances) Get(c context.Context, req *instances.GetRequest) (*instances.Instance, error) {
switch {
case req.GetId() == "" && req.GetHostname() == "":
return nil, status.Errorf(codes.InvalidArgument, "ID or hostname is required")
case req.Id != "" && req.Hostname != "":
return nil, status.Errorf(codes.InvalidArgument, "exactly one of ID or hostname is required")
case req.Id != "":
return getByID(c, req.Id)
default:
return getByHostname(c, req.Hostname)
}
} | go | func (*Instances) Get(c context.Context, req *instances.GetRequest) (*instances.Instance, error) {
switch {
case req.GetId() == "" && req.GetHostname() == "":
return nil, status.Errorf(codes.InvalidArgument, "ID or hostname is required")
case req.Id != "" && req.Hostname != "":
return nil, status.Errorf(codes.InvalidArgument, "exactly one of ID or hostname is required")
case req.Id != "":
return getByID(c, req.Id)
default:
return getByHostname(c, req.Hostname)
}
} | [
"func",
"(",
"*",
"Instances",
")",
"Get",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"instances",
".",
"GetRequest",
")",
"(",
"*",
"instances",
".",
"Instance",
",",
"error",
")",
"{",
"switch",
"{",
"case",
"req",
".",
"GetId",
"(",
"... | // Get handles a request to get an existing instance. | [
"Get",
"handles",
"a",
"request",
"to",
"get",
"an",
"existing",
"instance",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/rpc/instances.go#L148-L159 |
7,810 | luci/luci-go | gce/appengine/rpc/instances.go | List | func (*Instances) List(c context.Context, req *instances.ListRequest) (*instances.ListResponse, error) {
if req.GetPrefix() == "" {
return nil, status.Errorf(codes.InvalidArgument, "prefix is required")
}
rsp := &instances.ListResponse{}
// TODO(smut): Handle page tokens.
if req.GetPageToken() != "" {
return rsp, nil
}
q := datastore.NewQuery(model.VMKind).Eq("prefix", req.Prefix)
if err := datastore.Run(c, q, func(vm *model.VM, f datastore.CursorCB) error {
rsp.Instances = append(rsp.Instances, toInstance(vm))
return nil
}); err != nil {
return nil, errors.Annotate(err, "failed to fetch instances").Err()
}
return rsp, nil
} | go | func (*Instances) List(c context.Context, req *instances.ListRequest) (*instances.ListResponse, error) {
if req.GetPrefix() == "" {
return nil, status.Errorf(codes.InvalidArgument, "prefix is required")
}
rsp := &instances.ListResponse{}
// TODO(smut): Handle page tokens.
if req.GetPageToken() != "" {
return rsp, nil
}
q := datastore.NewQuery(model.VMKind).Eq("prefix", req.Prefix)
if err := datastore.Run(c, q, func(vm *model.VM, f datastore.CursorCB) error {
rsp.Instances = append(rsp.Instances, toInstance(vm))
return nil
}); err != nil {
return nil, errors.Annotate(err, "failed to fetch instances").Err()
}
return rsp, nil
} | [
"func",
"(",
"*",
"Instances",
")",
"List",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"instances",
".",
"ListRequest",
")",
"(",
"*",
"instances",
".",
"ListResponse",
",",
"error",
")",
"{",
"if",
"req",
".",
"GetPrefix",
"(",
")",
"==",... | // List handles a request to list instances. | [
"List",
"handles",
"a",
"request",
"to",
"list",
"instances",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/rpc/instances.go#L162-L179 |
7,811 | luci/luci-go | gce/appengine/rpc/instances.go | NewInstancesServer | func NewInstancesServer() instances.InstancesServer {
return &instances.DecoratedInstances{
Prelude: vmAccessPrelude,
Service: &Instances{},
Postlude: gRPCifyAndLogErr,
}
} | go | func NewInstancesServer() instances.InstancesServer {
return &instances.DecoratedInstances{
Prelude: vmAccessPrelude,
Service: &Instances{},
Postlude: gRPCifyAndLogErr,
}
} | [
"func",
"NewInstancesServer",
"(",
")",
"instances",
".",
"InstancesServer",
"{",
"return",
"&",
"instances",
".",
"DecoratedInstances",
"{",
"Prelude",
":",
"vmAccessPrelude",
",",
"Service",
":",
"&",
"Instances",
"{",
"}",
",",
"Postlude",
":",
"gRPCifyAndLog... | // NewInstancesServer returns a new instances server. | [
"NewInstancesServer",
"returns",
"a",
"new",
"instances",
"server",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/rpc/instances.go#L182-L188 |
7,812 | luci/luci-go | milo/git/client.go | UseACLs | func UseACLs(c context.Context, acls *gitacls.ACLs) context.Context {
return Use(c, &implementation{acls: acls})
} | go | func UseACLs(c context.Context, acls *gitacls.ACLs) context.Context {
return Use(c, &implementation{acls: acls})
} | [
"func",
"UseACLs",
"(",
"c",
"context",
".",
"Context",
",",
"acls",
"*",
"gitacls",
".",
"ACLs",
")",
"context",
".",
"Context",
"{",
"return",
"Use",
"(",
"c",
",",
"&",
"implementation",
"{",
"acls",
":",
"acls",
"}",
")",
"\n",
"}"
] | // UseACLs returns context with production implementation installed. | [
"UseACLs",
"returns",
"context",
"with",
"production",
"implementation",
"installed",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/git/client.go#L97-L99 |
7,813 | luci/luci-go | milo/git/client.go | Use | func Use(c context.Context, s Client) context.Context {
return context.WithValue(c, &contextKey, s)
} | go | func Use(c context.Context, s Client) context.Context {
return context.WithValue(c, &contextKey, s)
} | [
"func",
"Use",
"(",
"c",
"context",
".",
"Context",
",",
"s",
"Client",
")",
"context",
".",
"Context",
"{",
"return",
"context",
".",
"WithValue",
"(",
"c",
",",
"&",
"contextKey",
",",
"s",
")",
"\n",
"}"
] | // Use returns context with provided Client implementation.
//
// Useful in tests, see also gittest.MockClient | [
"Use",
"returns",
"context",
"with",
"provided",
"Client",
"implementation",
".",
"Useful",
"in",
"tests",
"see",
"also",
"gittest",
".",
"MockClient"
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/git/client.go#L104-L106 |
7,814 | luci/luci-go | milo/git/client.go | Get | func Get(c context.Context) Client {
s, ok := c.Value(&contextKey).(Client)
if !ok {
panic(errors.New("git.Client not installed in context"))
}
return s
} | go | func Get(c context.Context) Client {
s, ok := c.Value(&contextKey).(Client)
if !ok {
panic(errors.New("git.Client not installed in context"))
}
return s
} | [
"func",
"Get",
"(",
"c",
"context",
".",
"Context",
")",
"Client",
"{",
"s",
",",
"ok",
":=",
"c",
".",
"Value",
"(",
"&",
"contextKey",
")",
".",
"(",
"Client",
")",
"\n",
"if",
"!",
"ok",
"{",
"panic",
"(",
"errors",
".",
"New",
"(",
"\"",
... | // Get returns Client set in supplied context.
//
// panics if not set. | [
"Get",
"returns",
"Client",
"set",
"in",
"supplied",
"context",
".",
"panics",
"if",
"not",
"set",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/git/client.go#L111-L117 |
7,815 | luci/luci-go | milo/git/client.go | transport | func (p *implementation) transport(c context.Context) (transport http.RoundTripper, err error) {
luciProject, err := ProjectFromContext(c)
if err != nil {
return nil, err
}
opts := []auth.RPCOption{
auth.WithProject(luciProject),
auth.WithScopes(gitiles.OAuthScope),
}
return auth.GetRPCTransport(c, auth.AsProject, opts...)
} | go | func (p *implementation) transport(c context.Context) (transport http.RoundTripper, err error) {
luciProject, err := ProjectFromContext(c)
if err != nil {
return nil, err
}
opts := []auth.RPCOption{
auth.WithProject(luciProject),
auth.WithScopes(gitiles.OAuthScope),
}
return auth.GetRPCTransport(c, auth.AsProject, opts...)
} | [
"func",
"(",
"p",
"*",
"implementation",
")",
"transport",
"(",
"c",
"context",
".",
"Context",
")",
"(",
"transport",
"http",
".",
"RoundTripper",
",",
"err",
"error",
")",
"{",
"luciProject",
",",
"err",
":=",
"ProjectFromContext",
"(",
"c",
")",
"\n",... | // transport returns an authenticated RoundTripper for Gerrit or Gitiles RPCs. | [
"transport",
"returns",
"an",
"authenticated",
"RoundTripper",
"for",
"Gerrit",
"or",
"Gitiles",
"RPCs",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/git/client.go#L135-L145 |
7,816 | luci/luci-go | common/tsmon/flush.go | Flush | func Flush(c context.Context) error {
return GetState(c).Flush(c, nil)
} | go | func Flush(c context.Context) error {
return GetState(c).Flush(c, nil)
} | [
"func",
"Flush",
"(",
"c",
"context",
".",
"Context",
")",
"error",
"{",
"return",
"GetState",
"(",
"c",
")",
".",
"Flush",
"(",
"c",
",",
"nil",
")",
"\n",
"}"
] | // Flush sends all the metrics that are registered in the application. | [
"Flush",
"sends",
"all",
"the",
"metrics",
"that",
"are",
"registered",
"in",
"the",
"application",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/flush.go#L26-L28 |
7,817 | luci/luci-go | gce/appengine/config/config.go | withInterface | func withInterface(c context.Context, cfg config.Interface) context.Context {
return context.WithValue(c, &cfgKey, cfg)
} | go | func withInterface(c context.Context, cfg config.Interface) context.Context {
return context.WithValue(c, &cfgKey, cfg)
} | [
"func",
"withInterface",
"(",
"c",
"context",
".",
"Context",
",",
"cfg",
"config",
".",
"Interface",
")",
"context",
".",
"Context",
"{",
"return",
"context",
".",
"WithValue",
"(",
"c",
",",
"&",
"cfgKey",
",",
"cfg",
")",
"\n",
"}"
] | // withInterface returns a new context with the given config.Interface
// installed. | [
"withInterface",
"returns",
"a",
"new",
"context",
"with",
"the",
"given",
"config",
".",
"Interface",
"installed",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/config/config.go#L62-L64 |
7,818 | luci/luci-go | gce/appengine/config/config.go | getInterface | func getInterface(c context.Context) config.Interface {
return c.Value(&cfgKey).(config.Interface)
} | go | func getInterface(c context.Context) config.Interface {
return c.Value(&cfgKey).(config.Interface)
} | [
"func",
"getInterface",
"(",
"c",
"context",
".",
"Context",
")",
"config",
".",
"Interface",
"{",
"return",
"c",
".",
"Value",
"(",
"&",
"cfgKey",
")",
".",
"(",
"config",
".",
"Interface",
")",
"\n",
"}"
] | // getInterface returns the config.Interface installed in the current context. | [
"getInterface",
"returns",
"the",
"config",
".",
"Interface",
"installed",
"in",
"the",
"current",
"context",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/config/config.go#L67-L69 |
7,819 | luci/luci-go | gce/appengine/config/config.go | withProjServer | func withProjServer(c context.Context, srv projects.ProjectsServer) context.Context {
return context.WithValue(c, &prjKey, srv)
} | go | func withProjServer(c context.Context, srv projects.ProjectsServer) context.Context {
return context.WithValue(c, &prjKey, srv)
} | [
"func",
"withProjServer",
"(",
"c",
"context",
".",
"Context",
",",
"srv",
"projects",
".",
"ProjectsServer",
")",
"context",
".",
"Context",
"{",
"return",
"context",
".",
"WithValue",
"(",
"c",
",",
"&",
"prjKey",
",",
"srv",
")",
"\n",
"}"
] | // withProjServer returns a new context with the given projects.ProjectsServer
// installed. | [
"withProjServer",
"returns",
"a",
"new",
"context",
"with",
"the",
"given",
"projects",
".",
"ProjectsServer",
"installed",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/config/config.go#L76-L78 |
7,820 | luci/luci-go | gce/appengine/config/config.go | getProjServer | func getProjServer(c context.Context) projects.ProjectsServer {
return c.Value(&prjKey).(projects.ProjectsServer)
} | go | func getProjServer(c context.Context) projects.ProjectsServer {
return c.Value(&prjKey).(projects.ProjectsServer)
} | [
"func",
"getProjServer",
"(",
"c",
"context",
".",
"Context",
")",
"projects",
".",
"ProjectsServer",
"{",
"return",
"c",
".",
"Value",
"(",
"&",
"prjKey",
")",
".",
"(",
"projects",
".",
"ProjectsServer",
")",
"\n",
"}"
] | // getProjServer returns the projects.ProjectsServer installed in the current
// context. | [
"getProjServer",
"returns",
"the",
"projects",
".",
"ProjectsServer",
"installed",
"in",
"the",
"current",
"context",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/config/config.go#L82-L84 |
7,821 | luci/luci-go | gce/appengine/config/config.go | withVMsServer | func withVMsServer(c context.Context, srv gce.ConfigurationServer) context.Context {
return context.WithValue(c, &vmsKey, srv)
} | go | func withVMsServer(c context.Context, srv gce.ConfigurationServer) context.Context {
return context.WithValue(c, &vmsKey, srv)
} | [
"func",
"withVMsServer",
"(",
"c",
"context",
".",
"Context",
",",
"srv",
"gce",
".",
"ConfigurationServer",
")",
"context",
".",
"Context",
"{",
"return",
"context",
".",
"WithValue",
"(",
"c",
",",
"&",
"vmsKey",
",",
"srv",
")",
"\n",
"}"
] | // withVMsServer returns a new context with the given gce.ConfigurationServer
// installed. | [
"withVMsServer",
"returns",
"a",
"new",
"context",
"with",
"the",
"given",
"gce",
".",
"ConfigurationServer",
"installed",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/config/config.go#L91-L93 |
7,822 | luci/luci-go | gce/appengine/config/config.go | getVMsServer | func getVMsServer(c context.Context) gce.ConfigurationServer {
return c.Value(&vmsKey).(gce.ConfigurationServer)
} | go | func getVMsServer(c context.Context) gce.ConfigurationServer {
return c.Value(&vmsKey).(gce.ConfigurationServer)
} | [
"func",
"getVMsServer",
"(",
"c",
"context",
".",
"Context",
")",
"gce",
".",
"ConfigurationServer",
"{",
"return",
"c",
".",
"Value",
"(",
"&",
"vmsKey",
")",
".",
"(",
"gce",
".",
"ConfigurationServer",
")",
"\n",
"}"
] | // getVMsServer returns the gce.ConfigurationServer installed in the current
// context. | [
"getVMsServer",
"returns",
"the",
"gce",
".",
"ConfigurationServer",
"installed",
"in",
"the",
"current",
"context",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/config/config.go#L97-L99 |
7,823 | luci/luci-go | gce/appengine/config/config.go | newInterface | func newInterface(c context.Context) config.Interface {
s, err := gaeconfig.FetchCachedSettings(c)
if err != nil {
panic(err)
}
t, err := auth.GetRPCTransport(c, auth.AsSelf)
if err != nil {
panic(err)
}
return remote.New(s.ConfigServiceHost, false, func(c context.Context) (*http.Client, error) {
return &http.Client{Transport: t}, nil
})
} | go | func newInterface(c context.Context) config.Interface {
s, err := gaeconfig.FetchCachedSettings(c)
if err != nil {
panic(err)
}
t, err := auth.GetRPCTransport(c, auth.AsSelf)
if err != nil {
panic(err)
}
return remote.New(s.ConfigServiceHost, false, func(c context.Context) (*http.Client, error) {
return &http.Client{Transport: t}, nil
})
} | [
"func",
"newInterface",
"(",
"c",
"context",
".",
"Context",
")",
"config",
".",
"Interface",
"{",
"s",
",",
"err",
":=",
"gaeconfig",
".",
"FetchCachedSettings",
"(",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}"... | // newInterface returns a new config.Interface. Panics on error. | [
"newInterface",
"returns",
"a",
"new",
"config",
".",
"Interface",
".",
"Panics",
"on",
"error",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/config/config.go#L102-L114 |
7,824 | luci/luci-go | gce/appengine/config/config.go | fetch | func fetch(c context.Context) (*Config, error) {
cli := getInterface(c)
set := cfgclient.CurrentServiceConfigSet(c)
// If VMs and kinds are both non-empty, then their revisions must match
// because VMs may depend on kinds. If VMs is empty but kinds is not,
// then kinds are declared but unused (which is fine). If kinds is empty
// but VMs is not, this may or may not be fine. Validation will tell us.
rev := ""
vms := &gce.Configs{}
switch vmsCfg, err := cli.GetConfig(c, set, vmsFile, false); {
case err == config.ErrNoConfig:
logging.Debugf(c, "%q not found", vmsFile)
case err != nil:
return nil, errors.Annotate(err, "failed to fetch %q", vmsFile).Err()
default:
rev = vmsCfg.Revision
logging.Debugf(c, "found %q revision %s", vmsFile, vmsCfg.Revision)
if err := proto.UnmarshalText(vmsCfg.Content, vms); err != nil {
return nil, errors.Annotate(err, "failed to load %q", vmsFile).Err()
}
}
kinds := &gce.Kinds{}
switch kindsCfg, err := cli.GetConfig(c, set, kindsFile, false); {
case err == config.ErrNoConfig:
logging.Debugf(c, "%q not found", kindsFile)
case err != nil:
return nil, errors.Annotate(err, "failed to fetch %q", kindsFile).Err()
default:
logging.Debugf(c, "found %q revision %s", kindsFile, kindsCfg.Revision)
if rev != "" && kindsCfg.Revision != rev {
return nil, errors.Reason("config revision mismatch").Err()
}
if err := proto.UnmarshalText(kindsCfg.Content, kinds); err != nil {
return nil, errors.Annotate(err, "failed to load %q", kindsFile).Err()
}
}
prjs := &projects.Configs{}
switch prjsCfg, err := cli.GetConfig(c, set, projectsFile, false); {
case err == config.ErrNoConfig:
logging.Debugf(c, "%q not found", projectsFile)
case err != nil:
return nil, errors.Annotate(err, "failed to fetch %q", projectsFile).Err()
default:
logging.Debugf(c, "found %q revision %s", projectsFile, prjsCfg.Revision)
if rev != "" && prjsCfg.Revision != rev {
return nil, errors.Reason("config revision mismatch").Err()
}
if err := proto.UnmarshalText(prjsCfg.Content, prjs); err != nil {
return nil, errors.Annotate(err, "failed to load %q", projectsFile).Err()
}
}
return &Config{
revision: rev,
Kinds: kinds,
Projects: prjs,
VMs: vms,
}, nil
} | go | func fetch(c context.Context) (*Config, error) {
cli := getInterface(c)
set := cfgclient.CurrentServiceConfigSet(c)
// If VMs and kinds are both non-empty, then their revisions must match
// because VMs may depend on kinds. If VMs is empty but kinds is not,
// then kinds are declared but unused (which is fine). If kinds is empty
// but VMs is not, this may or may not be fine. Validation will tell us.
rev := ""
vms := &gce.Configs{}
switch vmsCfg, err := cli.GetConfig(c, set, vmsFile, false); {
case err == config.ErrNoConfig:
logging.Debugf(c, "%q not found", vmsFile)
case err != nil:
return nil, errors.Annotate(err, "failed to fetch %q", vmsFile).Err()
default:
rev = vmsCfg.Revision
logging.Debugf(c, "found %q revision %s", vmsFile, vmsCfg.Revision)
if err := proto.UnmarshalText(vmsCfg.Content, vms); err != nil {
return nil, errors.Annotate(err, "failed to load %q", vmsFile).Err()
}
}
kinds := &gce.Kinds{}
switch kindsCfg, err := cli.GetConfig(c, set, kindsFile, false); {
case err == config.ErrNoConfig:
logging.Debugf(c, "%q not found", kindsFile)
case err != nil:
return nil, errors.Annotate(err, "failed to fetch %q", kindsFile).Err()
default:
logging.Debugf(c, "found %q revision %s", kindsFile, kindsCfg.Revision)
if rev != "" && kindsCfg.Revision != rev {
return nil, errors.Reason("config revision mismatch").Err()
}
if err := proto.UnmarshalText(kindsCfg.Content, kinds); err != nil {
return nil, errors.Annotate(err, "failed to load %q", kindsFile).Err()
}
}
prjs := &projects.Configs{}
switch prjsCfg, err := cli.GetConfig(c, set, projectsFile, false); {
case err == config.ErrNoConfig:
logging.Debugf(c, "%q not found", projectsFile)
case err != nil:
return nil, errors.Annotate(err, "failed to fetch %q", projectsFile).Err()
default:
logging.Debugf(c, "found %q revision %s", projectsFile, prjsCfg.Revision)
if rev != "" && prjsCfg.Revision != rev {
return nil, errors.Reason("config revision mismatch").Err()
}
if err := proto.UnmarshalText(prjsCfg.Content, prjs); err != nil {
return nil, errors.Annotate(err, "failed to load %q", projectsFile).Err()
}
}
return &Config{
revision: rev,
Kinds: kinds,
Projects: prjs,
VMs: vms,
}, nil
} | [
"func",
"fetch",
"(",
"c",
"context",
".",
"Context",
")",
"(",
"*",
"Config",
",",
"error",
")",
"{",
"cli",
":=",
"getInterface",
"(",
"c",
")",
"\n",
"set",
":=",
"cfgclient",
".",
"CurrentServiceConfigSet",
"(",
"c",
")",
"\n\n",
"// If VMs and kinds... | // fetch fetches configs from the config service. | [
"fetch",
"fetches",
"configs",
"from",
"the",
"config",
"service",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/config/config.go#L117-L178 |
7,825 | luci/luci-go | gce/appengine/config/config.go | validate | func validate(c context.Context, cfg *Config) error {
v := &validation.Context{Context: c}
v.SetFile(kindsFile)
cfg.Kinds.Validate(v)
v.SetFile(projectsFile)
cfg.Projects.Validate(v)
v.SetFile(vmsFile)
cfg.VMs.Validate(v)
return v.Finalize()
} | go | func validate(c context.Context, cfg *Config) error {
v := &validation.Context{Context: c}
v.SetFile(kindsFile)
cfg.Kinds.Validate(v)
v.SetFile(projectsFile)
cfg.Projects.Validate(v)
v.SetFile(vmsFile)
cfg.VMs.Validate(v)
return v.Finalize()
} | [
"func",
"validate",
"(",
"c",
"context",
".",
"Context",
",",
"cfg",
"*",
"Config",
")",
"error",
"{",
"v",
":=",
"&",
"validation",
".",
"Context",
"{",
"Context",
":",
"c",
"}",
"\n",
"v",
".",
"SetFile",
"(",
"kindsFile",
")",
"\n",
"cfg",
".",
... | // validate validates configs. | [
"validate",
"validates",
"configs",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/config/config.go#L181-L190 |
7,826 | luci/luci-go | gce/appengine/config/config.go | merge | func merge(c context.Context, cfg *Config) error {
kindsMap := cfg.Kinds.Map()
for _, v := range cfg.VMs.GetVms() {
if v.Kind != "" {
k, ok := kindsMap[v.Kind]
if !ok {
return errors.Reason("unknown kind %q", v.Kind).Err()
}
// Merge the config's attributes into a copy of the kind's.
// This ensures the config's attributes overwrite the kind's.
attrs := proto.Clone(k.Attributes).(*gce.VM)
// By default, proto.Merge concatenates repeated field values.
// Instead, make repeated fields in the config override the kind.
if len(v.Attributes.Disk) > 0 {
attrs.Disk = nil
}
if len(v.Attributes.Metadata) > 0 {
attrs.Metadata = nil
}
if len(v.Attributes.NetworkInterface) > 0 {
attrs.NetworkInterface = nil
}
if len(v.Attributes.Tag) > 0 {
attrs.Tag = nil
}
proto.Merge(attrs, v.Attributes)
v.Attributes = attrs
}
}
return nil
} | go | func merge(c context.Context, cfg *Config) error {
kindsMap := cfg.Kinds.Map()
for _, v := range cfg.VMs.GetVms() {
if v.Kind != "" {
k, ok := kindsMap[v.Kind]
if !ok {
return errors.Reason("unknown kind %q", v.Kind).Err()
}
// Merge the config's attributes into a copy of the kind's.
// This ensures the config's attributes overwrite the kind's.
attrs := proto.Clone(k.Attributes).(*gce.VM)
// By default, proto.Merge concatenates repeated field values.
// Instead, make repeated fields in the config override the kind.
if len(v.Attributes.Disk) > 0 {
attrs.Disk = nil
}
if len(v.Attributes.Metadata) > 0 {
attrs.Metadata = nil
}
if len(v.Attributes.NetworkInterface) > 0 {
attrs.NetworkInterface = nil
}
if len(v.Attributes.Tag) > 0 {
attrs.Tag = nil
}
proto.Merge(attrs, v.Attributes)
v.Attributes = attrs
}
}
return nil
} | [
"func",
"merge",
"(",
"c",
"context",
".",
"Context",
",",
"cfg",
"*",
"Config",
")",
"error",
"{",
"kindsMap",
":=",
"cfg",
".",
"Kinds",
".",
"Map",
"(",
")",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"cfg",
".",
"VMs",
".",
"GetVms",
"(",
"... | // merge merges validated configs.
// Each config's referenced Kind is used to fill out unset values in its attributes. | [
"merge",
"merges",
"validated",
"configs",
".",
"Each",
"config",
"s",
"referenced",
"Kind",
"is",
"used",
"to",
"fill",
"out",
"unset",
"values",
"in",
"its",
"attributes",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/config/config.go#L194-L224 |
7,827 | luci/luci-go | gce/appengine/config/config.go | deref | func deref(c context.Context, cfg *Config) error {
// Cache fetched files.
fileMap := make(map[string]string)
cli := getInterface(c)
set := cfgclient.CurrentServiceConfigSet(c)
for _, v := range cfg.VMs.GetVms() {
for i, m := range v.GetAttributes().Metadata {
if m.GetFromFile() != "" {
parts := strings.SplitN(m.GetFromFile(), ":", 2)
if len(parts) < 2 {
return errors.Reason("metadata from file must be in key:value form").Err()
}
file := parts[1]
if _, ok := fileMap[file]; !ok {
fileCfg, err := cli.GetConfig(c, set, file, false)
if err != nil {
return errors.Annotate(err, "failed to fetch %q", file).Err()
}
logging.Debugf(c, "found %q revision %s", file, fileCfg.Revision)
if fileCfg.Revision != cfg.revision {
return errors.Reason("config revision mismatch %q", fileCfg.Revision).Err()
}
fileMap[file] = fileCfg.Content
}
// fileMap[file] definitely exists.
key := parts[0]
val := fileMap[file]
v.Attributes.Metadata[i].Metadata = &gce.Metadata_FromText{
FromText: fmt.Sprintf("%s:%s", key, val),
}
}
}
}
return nil
} | go | func deref(c context.Context, cfg *Config) error {
// Cache fetched files.
fileMap := make(map[string]string)
cli := getInterface(c)
set := cfgclient.CurrentServiceConfigSet(c)
for _, v := range cfg.VMs.GetVms() {
for i, m := range v.GetAttributes().Metadata {
if m.GetFromFile() != "" {
parts := strings.SplitN(m.GetFromFile(), ":", 2)
if len(parts) < 2 {
return errors.Reason("metadata from file must be in key:value form").Err()
}
file := parts[1]
if _, ok := fileMap[file]; !ok {
fileCfg, err := cli.GetConfig(c, set, file, false)
if err != nil {
return errors.Annotate(err, "failed to fetch %q", file).Err()
}
logging.Debugf(c, "found %q revision %s", file, fileCfg.Revision)
if fileCfg.Revision != cfg.revision {
return errors.Reason("config revision mismatch %q", fileCfg.Revision).Err()
}
fileMap[file] = fileCfg.Content
}
// fileMap[file] definitely exists.
key := parts[0]
val := fileMap[file]
v.Attributes.Metadata[i].Metadata = &gce.Metadata_FromText{
FromText: fmt.Sprintf("%s:%s", key, val),
}
}
}
}
return nil
} | [
"func",
"deref",
"(",
"c",
"context",
".",
"Context",
",",
"cfg",
"*",
"Config",
")",
"error",
"{",
"// Cache fetched files.",
"fileMap",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"cli",
":=",
"getInterface",
"(",
"c",
")",
"\n... | // deref dereferences VMs metadata by fetching referenced files. | [
"deref",
"dereferences",
"VMs",
"metadata",
"by",
"fetching",
"referenced",
"files",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/config/config.go#L227-L261 |
7,828 | luci/luci-go | gce/appengine/config/config.go | normalize | func normalize(c context.Context, cfg *Config) error {
for _, p := range cfg.Projects.GetProject() {
p.Revision = cfg.revision
}
for _, v := range cfg.VMs.GetVms() {
for _, ch := range v.Amount.GetChange() {
if err := ch.Length.Normalize(); err != nil {
return errors.Annotate(err, "failed to normalize %q", v.Prefix).Err()
}
}
if err := v.Lifetime.Normalize(); err != nil {
return errors.Annotate(err, "failed to normalize %q", v.Prefix).Err()
}
v.Revision = cfg.revision
if err := v.Timeout.Normalize(); err != nil {
return errors.Annotate(err, "failed to normalize %q", v.Prefix).Err()
}
}
return nil
} | go | func normalize(c context.Context, cfg *Config) error {
for _, p := range cfg.Projects.GetProject() {
p.Revision = cfg.revision
}
for _, v := range cfg.VMs.GetVms() {
for _, ch := range v.Amount.GetChange() {
if err := ch.Length.Normalize(); err != nil {
return errors.Annotate(err, "failed to normalize %q", v.Prefix).Err()
}
}
if err := v.Lifetime.Normalize(); err != nil {
return errors.Annotate(err, "failed to normalize %q", v.Prefix).Err()
}
v.Revision = cfg.revision
if err := v.Timeout.Normalize(); err != nil {
return errors.Annotate(err, "failed to normalize %q", v.Prefix).Err()
}
}
return nil
} | [
"func",
"normalize",
"(",
"c",
"context",
".",
"Context",
",",
"cfg",
"*",
"Config",
")",
"error",
"{",
"for",
"_",
",",
"p",
":=",
"range",
"cfg",
".",
"Projects",
".",
"GetProject",
"(",
")",
"{",
"p",
".",
"Revision",
"=",
"cfg",
".",
"revision"... | // normalize normalizes VMs durations by converting them to seconds, and sets
// output-only properties. | [
"normalize",
"normalizes",
"VMs",
"durations",
"by",
"converting",
"them",
"to",
"seconds",
"and",
"sets",
"output",
"-",
"only",
"properties",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/config/config.go#L265-L284 |
7,829 | luci/luci-go | gce/appengine/config/config.go | syncVMs | func syncVMs(c context.Context, vms []*gce.Config) error {
// Fetch existing configs.
srv := getVMsServer(c)
rsp, err := srv.List(c, &gce.ListRequest{})
if err != nil {
return errors.Annotate(err, "failed to fetch VMs configs").Err()
}
// Track the revision of each config.
revs := make(map[string]string, len(rsp.Configs))
for _, v := range rsp.Configs {
revs[v.Prefix] = v.Revision
}
logging.Debugf(c, "fetched %d VMs configs", len(rsp.Configs))
// Update configs to new revisions.
ens := &gce.EnsureRequest{}
for _, v := range vms {
rev, ok := revs[v.Prefix]
delete(revs, v.Prefix)
if ok && rev == v.Revision {
continue
}
ens.Id = v.Prefix
ens.Config = v
if _, err := srv.Ensure(c, ens); err != nil {
return errors.Annotate(err, "failed to ensure VMs config %q", ens.Id).Err()
}
}
// Delete unreferenced configs.
del := &gce.DeleteRequest{}
for id := range revs {
del.Id = id
if _, err := srv.Delete(c, del); err != nil {
return errors.Annotate(err, "failed to delete VMs config %q", del.Id).Err()
}
logging.Debugf(c, "deleted VMs config %q", del.Id)
}
return nil
} | go | func syncVMs(c context.Context, vms []*gce.Config) error {
// Fetch existing configs.
srv := getVMsServer(c)
rsp, err := srv.List(c, &gce.ListRequest{})
if err != nil {
return errors.Annotate(err, "failed to fetch VMs configs").Err()
}
// Track the revision of each config.
revs := make(map[string]string, len(rsp.Configs))
for _, v := range rsp.Configs {
revs[v.Prefix] = v.Revision
}
logging.Debugf(c, "fetched %d VMs configs", len(rsp.Configs))
// Update configs to new revisions.
ens := &gce.EnsureRequest{}
for _, v := range vms {
rev, ok := revs[v.Prefix]
delete(revs, v.Prefix)
if ok && rev == v.Revision {
continue
}
ens.Id = v.Prefix
ens.Config = v
if _, err := srv.Ensure(c, ens); err != nil {
return errors.Annotate(err, "failed to ensure VMs config %q", ens.Id).Err()
}
}
// Delete unreferenced configs.
del := &gce.DeleteRequest{}
for id := range revs {
del.Id = id
if _, err := srv.Delete(c, del); err != nil {
return errors.Annotate(err, "failed to delete VMs config %q", del.Id).Err()
}
logging.Debugf(c, "deleted VMs config %q", del.Id)
}
return nil
} | [
"func",
"syncVMs",
"(",
"c",
"context",
".",
"Context",
",",
"vms",
"[",
"]",
"*",
"gce",
".",
"Config",
")",
"error",
"{",
"// Fetch existing configs.",
"srv",
":=",
"getVMsServer",
"(",
"c",
")",
"\n",
"rsp",
",",
"err",
":=",
"srv",
".",
"List",
"... | // syncVMs synchronizes the given validated VM configs. | [
"syncVMs",
"synchronizes",
"the",
"given",
"validated",
"VM",
"configs",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/config/config.go#L287-L326 |
7,830 | luci/luci-go | gce/appengine/config/config.go | syncPrjs | func syncPrjs(c context.Context, prjs []*projects.Config) error {
// Fetch existing configs.
srv := getProjServer(c)
rsp, err := srv.List(c, &projects.ListRequest{})
if err != nil {
return errors.Annotate(err, "failed to fetch project configs").Err()
}
// Track the revision of each config.
revs := make(map[string]string, len(rsp.Projects))
for _, p := range rsp.Projects {
revs[p.Project] = p.Revision
}
logging.Debugf(c, "fetched %d project configs", len(rsp.Projects))
// Update configs to new revisions.
ens := &projects.EnsureRequest{}
for _, p := range prjs {
rev, ok := revs[p.Project]
delete(revs, p.Project)
if ok && rev == p.Revision {
continue
}
ens.Id = p.Project
ens.Project = p
if _, err := srv.Ensure(c, ens); err != nil {
return errors.Annotate(err, "failed to ensure project config %q", ens.Id).Err()
}
}
// Delete unreferenced configs.
del := &projects.DeleteRequest{}
for id := range revs {
del.Id = id
if _, err := srv.Delete(c, del); err != nil {
return errors.Annotate(err, "failed to delete project config %q", del.Id).Err()
}
logging.Debugf(c, "deleted project config %q", del.Id)
}
return nil
} | go | func syncPrjs(c context.Context, prjs []*projects.Config) error {
// Fetch existing configs.
srv := getProjServer(c)
rsp, err := srv.List(c, &projects.ListRequest{})
if err != nil {
return errors.Annotate(err, "failed to fetch project configs").Err()
}
// Track the revision of each config.
revs := make(map[string]string, len(rsp.Projects))
for _, p := range rsp.Projects {
revs[p.Project] = p.Revision
}
logging.Debugf(c, "fetched %d project configs", len(rsp.Projects))
// Update configs to new revisions.
ens := &projects.EnsureRequest{}
for _, p := range prjs {
rev, ok := revs[p.Project]
delete(revs, p.Project)
if ok && rev == p.Revision {
continue
}
ens.Id = p.Project
ens.Project = p
if _, err := srv.Ensure(c, ens); err != nil {
return errors.Annotate(err, "failed to ensure project config %q", ens.Id).Err()
}
}
// Delete unreferenced configs.
del := &projects.DeleteRequest{}
for id := range revs {
del.Id = id
if _, err := srv.Delete(c, del); err != nil {
return errors.Annotate(err, "failed to delete project config %q", del.Id).Err()
}
logging.Debugf(c, "deleted project config %q", del.Id)
}
return nil
} | [
"func",
"syncPrjs",
"(",
"c",
"context",
".",
"Context",
",",
"prjs",
"[",
"]",
"*",
"projects",
".",
"Config",
")",
"error",
"{",
"// Fetch existing configs.",
"srv",
":=",
"getProjServer",
"(",
"c",
")",
"\n",
"rsp",
",",
"err",
":=",
"srv",
".",
"Li... | // syncPrjs synchronizes the given validated project configs. | [
"syncPrjs",
"synchronizes",
"the",
"given",
"validated",
"project",
"configs",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/config/config.go#L329-L368 |
7,831 | luci/luci-go | gce/appengine/config/config.go | sync | func sync(c context.Context, cfg *Config) error {
if err := syncVMs(c, cfg.VMs.GetVms()); err != nil {
return errors.Annotate(err, "failed to sync VMs configs").Err()
}
if err := syncPrjs(c, cfg.Projects.GetProject()); err != nil {
return errors.Annotate(err, "failed to sync project configs").Err()
}
return nil
} | go | func sync(c context.Context, cfg *Config) error {
if err := syncVMs(c, cfg.VMs.GetVms()); err != nil {
return errors.Annotate(err, "failed to sync VMs configs").Err()
}
if err := syncPrjs(c, cfg.Projects.GetProject()); err != nil {
return errors.Annotate(err, "failed to sync project configs").Err()
}
return nil
} | [
"func",
"sync",
"(",
"c",
"context",
".",
"Context",
",",
"cfg",
"*",
"Config",
")",
"error",
"{",
"if",
"err",
":=",
"syncVMs",
"(",
"c",
",",
"cfg",
".",
"VMs",
".",
"GetVms",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
"... | // sync synchronizes the given validated configs. | [
"sync",
"synchronizes",
"the",
"given",
"validated",
"configs",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/config/config.go#L371-L379 |
7,832 | luci/luci-go | gce/appengine/config/config.go | Import | func Import(c context.Context) error {
cfg, err := fetch(c)
if err != nil {
return errors.Annotate(err, "failed to fetch configs").Err()
}
// Merge before validating. VMs may be invalid until referenced kinds are applied.
if err := merge(c, cfg); err != nil {
return errors.Annotate(err, "failed to merge kinds into configs").Err()
}
// Deref before validating. VMs may be invalid until metadata from file is imported.
if err := deref(c, cfg); err != nil {
return errors.Annotate(err, "failed to dereference files").Err()
}
if err := validate(c, cfg); err != nil {
return errors.Annotate(err, "invalid configs").Err()
}
if err := normalize(c, cfg); err != nil {
return errors.Annotate(err, "failed to normalize configs").Err()
}
if err := sync(c, cfg); err != nil {
return errors.Annotate(err, "failed to synchronize configs").Err()
}
return nil
} | go | func Import(c context.Context) error {
cfg, err := fetch(c)
if err != nil {
return errors.Annotate(err, "failed to fetch configs").Err()
}
// Merge before validating. VMs may be invalid until referenced kinds are applied.
if err := merge(c, cfg); err != nil {
return errors.Annotate(err, "failed to merge kinds into configs").Err()
}
// Deref before validating. VMs may be invalid until metadata from file is imported.
if err := deref(c, cfg); err != nil {
return errors.Annotate(err, "failed to dereference files").Err()
}
if err := validate(c, cfg); err != nil {
return errors.Annotate(err, "invalid configs").Err()
}
if err := normalize(c, cfg); err != nil {
return errors.Annotate(err, "failed to normalize configs").Err()
}
if err := sync(c, cfg); err != nil {
return errors.Annotate(err, "failed to synchronize configs").Err()
}
return nil
} | [
"func",
"Import",
"(",
"c",
"context",
".",
"Context",
")",
"error",
"{",
"cfg",
",",
"err",
":=",
"fetch",
"(",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"... | // Import fetches and validates configs from the config service. | [
"Import",
"fetches",
"and",
"validates",
"configs",
"from",
"the",
"config",
"service",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/config/config.go#L382-L410 |
7,833 | luci/luci-go | gce/appengine/config/config.go | importHandler | func importHandler(c *router.Context) {
c.Writer.Header().Set("Content-Type", "text/plain")
if err := Import(c.Context); err != nil {
errors.Log(c.Context, err)
c.Writer.WriteHeader(http.StatusInternalServerError)
return
}
c.Writer.WriteHeader(http.StatusOK)
} | go | func importHandler(c *router.Context) {
c.Writer.Header().Set("Content-Type", "text/plain")
if err := Import(c.Context); err != nil {
errors.Log(c.Context, err)
c.Writer.WriteHeader(http.StatusInternalServerError)
return
}
c.Writer.WriteHeader(http.StatusOK)
} | [
"func",
"importHandler",
"(",
"c",
"*",
"router",
".",
"Context",
")",
"{",
"c",
".",
"Writer",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n\n",
"if",
"err",
":=",
"Import",
"(",
"c",
".",
"Context",
")",
";",... | // importHandler imports the config from the config service. | [
"importHandler",
"imports",
"the",
"config",
"from",
"the",
"config",
"service",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/config/config.go#L413-L423 |
7,834 | luci/luci-go | cipd/client/cli/main.go | writeJSONOutput | func (c *cipdSubcommand) writeJSONOutput(result interface{}, err error) error {
// -json-output flag wasn't specified.
if c.jsonOutput == "" {
return err
}
// Prepare the body of the output file.
var body struct {
Error string `json:"error,omitempty"`
Result interface{} `json:"result,omitempty"`
}
if err != nil {
body.Error = err.Error()
}
body.Result = result
out, e := json.MarshalIndent(&body, "", " ")
if e != nil {
if err == nil {
err = e
} else {
fmt.Fprintf(os.Stderr, "Failed to serialize JSON output: %s\n", e)
}
return err
}
e = ioutil.WriteFile(c.jsonOutput, out, 0666)
if e != nil {
if err == nil {
err = e
} else {
fmt.Fprintf(os.Stderr, "Failed write JSON output to %s: %s\n", c.jsonOutput, e)
}
return err
}
return err
} | go | func (c *cipdSubcommand) writeJSONOutput(result interface{}, err error) error {
// -json-output flag wasn't specified.
if c.jsonOutput == "" {
return err
}
// Prepare the body of the output file.
var body struct {
Error string `json:"error,omitempty"`
Result interface{} `json:"result,omitempty"`
}
if err != nil {
body.Error = err.Error()
}
body.Result = result
out, e := json.MarshalIndent(&body, "", " ")
if e != nil {
if err == nil {
err = e
} else {
fmt.Fprintf(os.Stderr, "Failed to serialize JSON output: %s\n", e)
}
return err
}
e = ioutil.WriteFile(c.jsonOutput, out, 0666)
if e != nil {
if err == nil {
err = e
} else {
fmt.Fprintf(os.Stderr, "Failed write JSON output to %s: %s\n", c.jsonOutput, e)
}
return err
}
return err
} | [
"func",
"(",
"c",
"*",
"cipdSubcommand",
")",
"writeJSONOutput",
"(",
"result",
"interface",
"{",
"}",
",",
"err",
"error",
")",
"error",
"{",
"// -json-output flag wasn't specified.",
"if",
"c",
".",
"jsonOutput",
"==",
"\"",
"\"",
"{",
"return",
"err",
"\n... | // writeJSONOutput writes result to JSON output file. It returns original error
// if it is non-nil. | [
"writeJSONOutput",
"writes",
"result",
"to",
"JSON",
"output",
"file",
".",
"It",
"returns",
"original",
"error",
"if",
"it",
"is",
"non",
"-",
"nil",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cli/main.go#L213-L249 |
7,835 | luci/luci-go | cipd/client/cli/main.go | doneWithPins | func (c *cipdSubcommand) doneWithPins(pins []pinInfo, err error) int {
return c.doneWithPinMap(map[string][]pinInfo{"": pins}, err)
} | go | func (c *cipdSubcommand) doneWithPins(pins []pinInfo, err error) int {
return c.doneWithPinMap(map[string][]pinInfo{"": pins}, err)
} | [
"func",
"(",
"c",
"*",
"cipdSubcommand",
")",
"doneWithPins",
"(",
"pins",
"[",
"]",
"pinInfo",
",",
"err",
"error",
")",
"int",
"{",
"return",
"c",
".",
"doneWithPinMap",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"pinInfo",
"{",
"\"",
"\"",
":",
"... | // doneWithPins is a handy shortcut that prints a pinInfo slice and
// deduces process exit code based on presence of errors there.
//
// This just calls through to doneWithPinMap. | [
"doneWithPins",
"is",
"a",
"handy",
"shortcut",
"that",
"prints",
"a",
"pinInfo",
"slice",
"and",
"deduces",
"process",
"exit",
"code",
"based",
"on",
"presence",
"of",
"errors",
"there",
".",
"This",
"just",
"calls",
"through",
"to",
"doneWithPinMap",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cli/main.go#L267-L269 |
7,836 | luci/luci-go | cipd/client/cli/main.go | doneWithPinMap | func (c *cipdSubcommand) doneWithPinMap(pins map[string][]pinInfo, err error) int {
if len(pins) == 0 {
if err == nil { // this error will be printed in c.done(...)
fmt.Println("No packages.")
}
} else {
printPinsAndError(pins)
}
if ret := c.done(pins, err); ret != 0 {
return ret
}
for _, infos := range pins {
if hasErrors(infos) {
return 1
}
}
return 0
} | go | func (c *cipdSubcommand) doneWithPinMap(pins map[string][]pinInfo, err error) int {
if len(pins) == 0 {
if err == nil { // this error will be printed in c.done(...)
fmt.Println("No packages.")
}
} else {
printPinsAndError(pins)
}
if ret := c.done(pins, err); ret != 0 {
return ret
}
for _, infos := range pins {
if hasErrors(infos) {
return 1
}
}
return 0
} | [
"func",
"(",
"c",
"*",
"cipdSubcommand",
")",
"doneWithPinMap",
"(",
"pins",
"map",
"[",
"string",
"]",
"[",
"]",
"pinInfo",
",",
"err",
"error",
")",
"int",
"{",
"if",
"len",
"(",
"pins",
")",
"==",
"0",
"{",
"if",
"err",
"==",
"nil",
"{",
"// t... | // doneWithPinMap is a handy shortcut that prints the subdir->pinInfo map and
// deduces process exit code based on presence of errors there. | [
"doneWithPinMap",
"is",
"a",
"handy",
"shortcut",
"that",
"prints",
"the",
"subdir",
"-",
">",
"pinInfo",
"map",
"and",
"deduces",
"process",
"exit",
"code",
"based",
"on",
"presence",
"of",
"errors",
"there",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cli/main.go#L273-L290 |
7,837 | luci/luci-go | cipd/client/cli/main.go | makeCLIError | func makeCLIError(msg string, args ...interface{}) error {
return commandLineError{fmt.Errorf(msg, args...)}
} | go | func makeCLIError(msg string, args ...interface{}) error {
return commandLineError{fmt.Errorf(msg, args...)}
} | [
"func",
"makeCLIError",
"(",
"msg",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"error",
"{",
"return",
"commandLineError",
"{",
"fmt",
".",
"Errorf",
"(",
"msg",
",",
"args",
"...",
")",
"}",
"\n",
"}"
] | // makeCLIError returns new commandLineError. | [
"makeCLIError",
"returns",
"new",
"commandLineError",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cli/main.go#L298-L300 |
7,838 | luci/luci-go | cipd/client/cli/main.go | prepareInput | func (opts *inputOptions) prepareInput() (builder.Options, error) {
empty := builder.Options{}
if opts.compressionLevel < 0 || opts.compressionLevel > 9 {
return empty, makeCLIError("invalid -compression-level: must be in [0-9] set")
}
// Handle -name and -in if defined. Do not allow -pkg-def in that case, since
// it provides same information as -name and -in. Note that -pkg-var are
// ignored, even if defined. There's nothing to apply them to.
if opts.inputDir != "" {
if opts.packageName == "" {
return empty, makeCLIError("missing required flag: -name")
}
if opts.packageDef != "" {
return empty, makeCLIError("-pkg-def and -in can not be used together")
}
packageName, err := expandTemplate(opts.packageName)
if err != nil {
return empty, err
}
// Simply enumerate files in the directory.
files, err := fs.ScanFileSystem(opts.inputDir, opts.inputDir, nil, fs.ScanOptions{
PreserveModTime: opts.preserveModTime,
PreserveWritable: opts.preserveWritable,
})
if err != nil {
return empty, err
}
return builder.Options{
Input: files,
PackageName: packageName,
InstallMode: opts.installMode,
CompressionLevel: opts.compressionLevel,
}, nil
}
// Handle -pkg-def case. -in is "" (already checked), reject -name.
if opts.packageDef != "" {
if opts.packageName != "" {
return empty, makeCLIError("-pkg-def and -name can not be used together")
}
if opts.installMode != "" {
return empty, makeCLIError("-install-mode is ignored if -pkg-def is used")
}
if opts.preserveModTime {
return empty, makeCLIError("-preserve-mtime is ignored if -pkg-def is used")
}
if opts.preserveWritable {
return empty, makeCLIError("-preserve-writable is ignored if -pkg-def is used")
}
// Parse the file, perform variable substitution.
f, err := os.Open(opts.packageDef)
if err != nil {
return empty, err
}
defer f.Close()
pkgDef, err := builder.LoadPackageDef(f, opts.vars)
if err != nil {
return empty, err
}
// Scan the file system. Package definition may use path relative to the
// package definition file itself, so pass its location.
fmt.Println("Enumerating files to zip...")
files, err := pkgDef.FindFiles(filepath.Dir(opts.packageDef))
if err != nil {
return empty, err
}
return builder.Options{
Input: files,
PackageName: pkgDef.Package,
VersionFile: pkgDef.VersionFile(),
InstallMode: pkgDef.InstallMode,
CompressionLevel: opts.compressionLevel,
}, nil
}
// All command line options are missing.
return empty, makeCLIError("-pkg-def or -name/-in are required")
} | go | func (opts *inputOptions) prepareInput() (builder.Options, error) {
empty := builder.Options{}
if opts.compressionLevel < 0 || opts.compressionLevel > 9 {
return empty, makeCLIError("invalid -compression-level: must be in [0-9] set")
}
// Handle -name and -in if defined. Do not allow -pkg-def in that case, since
// it provides same information as -name and -in. Note that -pkg-var are
// ignored, even if defined. There's nothing to apply them to.
if opts.inputDir != "" {
if opts.packageName == "" {
return empty, makeCLIError("missing required flag: -name")
}
if opts.packageDef != "" {
return empty, makeCLIError("-pkg-def and -in can not be used together")
}
packageName, err := expandTemplate(opts.packageName)
if err != nil {
return empty, err
}
// Simply enumerate files in the directory.
files, err := fs.ScanFileSystem(opts.inputDir, opts.inputDir, nil, fs.ScanOptions{
PreserveModTime: opts.preserveModTime,
PreserveWritable: opts.preserveWritable,
})
if err != nil {
return empty, err
}
return builder.Options{
Input: files,
PackageName: packageName,
InstallMode: opts.installMode,
CompressionLevel: opts.compressionLevel,
}, nil
}
// Handle -pkg-def case. -in is "" (already checked), reject -name.
if opts.packageDef != "" {
if opts.packageName != "" {
return empty, makeCLIError("-pkg-def and -name can not be used together")
}
if opts.installMode != "" {
return empty, makeCLIError("-install-mode is ignored if -pkg-def is used")
}
if opts.preserveModTime {
return empty, makeCLIError("-preserve-mtime is ignored if -pkg-def is used")
}
if opts.preserveWritable {
return empty, makeCLIError("-preserve-writable is ignored if -pkg-def is used")
}
// Parse the file, perform variable substitution.
f, err := os.Open(opts.packageDef)
if err != nil {
return empty, err
}
defer f.Close()
pkgDef, err := builder.LoadPackageDef(f, opts.vars)
if err != nil {
return empty, err
}
// Scan the file system. Package definition may use path relative to the
// package definition file itself, so pass its location.
fmt.Println("Enumerating files to zip...")
files, err := pkgDef.FindFiles(filepath.Dir(opts.packageDef))
if err != nil {
return empty, err
}
return builder.Options{
Input: files,
PackageName: pkgDef.Package,
VersionFile: pkgDef.VersionFile(),
InstallMode: pkgDef.InstallMode,
CompressionLevel: opts.compressionLevel,
}, nil
}
// All command line options are missing.
return empty, makeCLIError("-pkg-def or -name/-in are required")
} | [
"func",
"(",
"opts",
"*",
"inputOptions",
")",
"prepareInput",
"(",
")",
"(",
"builder",
".",
"Options",
",",
"error",
")",
"{",
"empty",
":=",
"builder",
".",
"Options",
"{",
"}",
"\n\n",
"if",
"opts",
".",
"compressionLevel",
"<",
"0",
"||",
"opts",
... | // prepareInput processes inputOptions by collecting all files to be added to
// a package and populating builder.Options. Caller is still responsible to fill
// out Output field of Options. | [
"prepareInput",
"processes",
"inputOptions",
"by",
"collecting",
"all",
"files",
"to",
"be",
"added",
"to",
"a",
"package",
"and",
"populating",
"builder",
".",
"Options",
".",
"Caller",
"is",
"still",
"responsible",
"to",
"fill",
"out",
"Output",
"field",
"of... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cli/main.go#L462-L545 |
7,839 | luci/luci-go | cipd/client/cli/main.go | String | func (ha *hashAlgoFlag) String() string {
return strings.ToLower(api.HashAlgo(*ha).String())
} | go | func (ha *hashAlgoFlag) String() string {
return strings.ToLower(api.HashAlgo(*ha).String())
} | [
"func",
"(",
"ha",
"*",
"hashAlgoFlag",
")",
"String",
"(",
")",
"string",
"{",
"return",
"strings",
".",
"ToLower",
"(",
"api",
".",
"HashAlgo",
"(",
"*",
"ha",
")",
".",
"String",
"(",
")",
")",
"\n",
"}"
] | // String is called by 'flag' package when displaying default value of a flag. | [
"String",
"is",
"called",
"by",
"flag",
"package",
"when",
"displaying",
"default",
"value",
"of",
"a",
"flag",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cli/main.go#L647-L649 |
7,840 | luci/luci-go | cipd/client/cli/main.go | loadEnsureFile | func (opts *ensureFileOptions) loadEnsureFile(ctx context.Context, clientOpts *clientOptions, verifying verifyingEnsureFile, parseVers versionFileOpt) (*ensure.File, error) {
parsedFile, err := ensure.LoadEnsureFile(opts.ensureFile)
if err != nil {
return nil, err
}
// Prefer the ServiceURL from the file (if set), and log a warning if the user
// provided one on the command line that doesn't match the one in the file.
if parsedFile.ServiceURL != "" {
if clientOpts.serviceURL != "" && clientOpts.serviceURL != parsedFile.ServiceURL {
logging.Warningf(ctx, "serviceURL in ensure file != serviceURL on CLI (%q v %q). Using %q from file.",
parsedFile.ServiceURL, clientOpts.serviceURL, parsedFile.ServiceURL)
}
clientOpts.serviceURL = parsedFile.ServiceURL
}
if verifying && len(parsedFile.VerifyPlatforms) == 0 {
logging.Errorf(ctx,
"For this feature to work, verification platforms must be specified in "+
"the ensure file using one or more $VerifiedPlatform directives.")
return nil, errors.New("no verification platforms configured")
}
if parseVers && parsedFile.ResolvedVersions != "" {
clientOpts.versions, err = loadVersionsFile(parsedFile.ResolvedVersions, opts.ensureFile)
if err != nil {
return nil, err
}
logging.Debugf(ctx, "Using the resolved version file %q", filepath.Base(parsedFile.ResolvedVersions))
}
return parsedFile, nil
} | go | func (opts *ensureFileOptions) loadEnsureFile(ctx context.Context, clientOpts *clientOptions, verifying verifyingEnsureFile, parseVers versionFileOpt) (*ensure.File, error) {
parsedFile, err := ensure.LoadEnsureFile(opts.ensureFile)
if err != nil {
return nil, err
}
// Prefer the ServiceURL from the file (if set), and log a warning if the user
// provided one on the command line that doesn't match the one in the file.
if parsedFile.ServiceURL != "" {
if clientOpts.serviceURL != "" && clientOpts.serviceURL != parsedFile.ServiceURL {
logging.Warningf(ctx, "serviceURL in ensure file != serviceURL on CLI (%q v %q). Using %q from file.",
parsedFile.ServiceURL, clientOpts.serviceURL, parsedFile.ServiceURL)
}
clientOpts.serviceURL = parsedFile.ServiceURL
}
if verifying && len(parsedFile.VerifyPlatforms) == 0 {
logging.Errorf(ctx,
"For this feature to work, verification platforms must be specified in "+
"the ensure file using one or more $VerifiedPlatform directives.")
return nil, errors.New("no verification platforms configured")
}
if parseVers && parsedFile.ResolvedVersions != "" {
clientOpts.versions, err = loadVersionsFile(parsedFile.ResolvedVersions, opts.ensureFile)
if err != nil {
return nil, err
}
logging.Debugf(ctx, "Using the resolved version file %q", filepath.Base(parsedFile.ResolvedVersions))
}
return parsedFile, nil
} | [
"func",
"(",
"opts",
"*",
"ensureFileOptions",
")",
"loadEnsureFile",
"(",
"ctx",
"context",
".",
"Context",
",",
"clientOpts",
"*",
"clientOptions",
",",
"verifying",
"verifyingEnsureFile",
",",
"parseVers",
"versionFileOpt",
")",
"(",
"*",
"ensure",
".",
"File... | // loadEnsureFile parses the ensure file and mutates clientOpts to point to a
// service URL specified in the ensure file. | [
"loadEnsureFile",
"parses",
"the",
"ensure",
"file",
"and",
"mutates",
"clientOpts",
"to",
"point",
"to",
"a",
"service",
"URL",
"specified",
"in",
"the",
"ensure",
"file",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cli/main.go#L737-L769 |
7,841 | luci/luci-go | cipd/client/cli/main.go | loadClientVersion | func loadClientVersion(path string) (string, error) {
blob, err := ioutil.ReadFile(path)
if err != nil {
return "", err
}
version := strings.TrimSpace(string(blob))
if err := common.ValidateInstanceVersion(version); err != nil {
return "", err
}
return version, nil
} | go | func loadClientVersion(path string) (string, error) {
blob, err := ioutil.ReadFile(path)
if err != nil {
return "", err
}
version := strings.TrimSpace(string(blob))
if err := common.ValidateInstanceVersion(version); err != nil {
return "", err
}
return version, nil
} | [
"func",
"loadClientVersion",
"(",
"path",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"blob",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",... | // loadClientVersion reads a version string from a file. | [
"loadClientVersion",
"reads",
"a",
"version",
"string",
"from",
"a",
"file",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cli/main.go#L2731-L2741 |
7,842 | luci/luci-go | cipd/client/cli/main.go | assembleClientDigests | func assembleClientDigests(ctx context.Context, c cipd.Client, version string) (*digests.ClientDigestsFile, []pinInfo, error) {
if !strings.HasSuffix(cipd.ClientPackage, "/${platform}") {
panic(fmt.Sprintf("client package template (%q) is expected to end with '${platform}'", cipd.ClientPackage))
}
out := &digests.ClientDigestsFile{}
mu := sync.Mutex{}
// Ask the backend to give us hashes of the client binary for all platforms.
pins, err := performBatchOperation(ctx, batchOperation{
client: c,
packagePrefix: strings.TrimSuffix(cipd.ClientPackage, "${platform}"),
callback: func(pkg string) (common.Pin, error) {
pin, err := c.ResolveVersion(ctx, pkg, version)
if err != nil {
return common.Pin{}, err
}
desc, err := c.DescribeClient(ctx, pin)
if err != nil {
return common.Pin{}, err
}
mu.Lock()
defer mu.Unlock()
plat := pkg[strings.LastIndex(pkg, "/")+1:]
if err := out.AddClientRef(plat, desc.Digest); err != nil {
return common.Pin{}, err
}
return pin, nil
},
})
switch {
case err != nil:
return nil, pins, err
case hasErrors(pins):
return nil, pins, errors.New("failed to obtain the client binary digest for all platforms")
}
out.Sort()
return out, pins, nil
} | go | func assembleClientDigests(ctx context.Context, c cipd.Client, version string) (*digests.ClientDigestsFile, []pinInfo, error) {
if !strings.HasSuffix(cipd.ClientPackage, "/${platform}") {
panic(fmt.Sprintf("client package template (%q) is expected to end with '${platform}'", cipd.ClientPackage))
}
out := &digests.ClientDigestsFile{}
mu := sync.Mutex{}
// Ask the backend to give us hashes of the client binary for all platforms.
pins, err := performBatchOperation(ctx, batchOperation{
client: c,
packagePrefix: strings.TrimSuffix(cipd.ClientPackage, "${platform}"),
callback: func(pkg string) (common.Pin, error) {
pin, err := c.ResolveVersion(ctx, pkg, version)
if err != nil {
return common.Pin{}, err
}
desc, err := c.DescribeClient(ctx, pin)
if err != nil {
return common.Pin{}, err
}
mu.Lock()
defer mu.Unlock()
plat := pkg[strings.LastIndex(pkg, "/")+1:]
if err := out.AddClientRef(plat, desc.Digest); err != nil {
return common.Pin{}, err
}
return pin, nil
},
})
switch {
case err != nil:
return nil, pins, err
case hasErrors(pins):
return nil, pins, errors.New("failed to obtain the client binary digest for all platforms")
}
out.Sort()
return out, pins, nil
} | [
"func",
"assembleClientDigests",
"(",
"ctx",
"context",
".",
"Context",
",",
"c",
"cipd",
".",
"Client",
",",
"version",
"string",
")",
"(",
"*",
"digests",
".",
"ClientDigestsFile",
",",
"[",
"]",
"pinInfo",
",",
"error",
")",
"{",
"if",
"!",
"strings",... | // assembleClientDigests produces the digests file by making backend RPCs. | [
"assembleClientDigests",
"produces",
"the",
"digests",
"file",
"by",
"making",
"backend",
"RPCs",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cli/main.go#L2760-L2799 |
7,843 | luci/luci-go | cipd/client/cli/main.go | Main | func Main(params Parameters, args []string) int {
return subcommands.Run(GetApplication(params), fixflagpos.FixSubcommands(args))
} | go | func Main(params Parameters, args []string) int {
return subcommands.Run(GetApplication(params), fixflagpos.FixSubcommands(args))
} | [
"func",
"Main",
"(",
"params",
"Parameters",
",",
"args",
"[",
"]",
"string",
")",
"int",
"{",
"return",
"subcommands",
".",
"Run",
"(",
"GetApplication",
"(",
"params",
")",
",",
"fixflagpos",
".",
"FixSubcommands",
"(",
"args",
")",
")",
"\n",
"}"
] | // Main runs the CIPD CLI.
// | [
"Main",
"runs",
"the",
"CIPD",
"CLI",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cli/main.go#L2989-L2991 |
7,844 | luci/luci-go | common/isolated/utils.go | Sum | func Sum(h hash.Hash) HexDigest {
return HexDigest(hex.EncodeToString(h.Sum(nil)))
} | go | func Sum(h hash.Hash) HexDigest {
return HexDigest(hex.EncodeToString(h.Sum(nil)))
} | [
"func",
"Sum",
"(",
"h",
"hash",
".",
"Hash",
")",
"HexDigest",
"{",
"return",
"HexDigest",
"(",
"hex",
".",
"EncodeToString",
"(",
"h",
".",
"Sum",
"(",
"nil",
")",
")",
")",
"\n",
"}"
] | // Sum is a shortcut to get a HexDigest from a hash.Hash. | [
"Sum",
"is",
"a",
"shortcut",
"to",
"get",
"a",
"HexDigest",
"from",
"a",
"hash",
".",
"Hash",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/isolated/utils.go#L28-L30 |
7,845 | luci/luci-go | common/isolated/utils.go | Hash | func Hash(h crypto.Hash, src io.Reader) (HexDigest, error) {
a := h.New()
_, err := io.Copy(a, src)
if err != nil {
return HexDigest(""), err
}
return Sum(a), nil
} | go | func Hash(h crypto.Hash, src io.Reader) (HexDigest, error) {
a := h.New()
_, err := io.Copy(a, src)
if err != nil {
return HexDigest(""), err
}
return Sum(a), nil
} | [
"func",
"Hash",
"(",
"h",
"crypto",
".",
"Hash",
",",
"src",
"io",
".",
"Reader",
")",
"(",
"HexDigest",
",",
"error",
")",
"{",
"a",
":=",
"h",
".",
"New",
"(",
")",
"\n",
"_",
",",
"err",
":=",
"io",
".",
"Copy",
"(",
"a",
",",
"src",
")"... | // Hash hashes a reader and returns a HexDigest from it. | [
"Hash",
"hashes",
"a",
"reader",
"and",
"returns",
"a",
"HexDigest",
"from",
"it",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/isolated/utils.go#L33-L40 |
7,846 | luci/luci-go | common/isolated/utils.go | HashBytes | func HashBytes(h crypto.Hash, content []byte) HexDigest {
a := h.New()
_, _ = a.Write(content)
return Sum(a)
} | go | func HashBytes(h crypto.Hash, content []byte) HexDigest {
a := h.New()
_, _ = a.Write(content)
return Sum(a)
} | [
"func",
"HashBytes",
"(",
"h",
"crypto",
".",
"Hash",
",",
"content",
"[",
"]",
"byte",
")",
"HexDigest",
"{",
"a",
":=",
"h",
".",
"New",
"(",
")",
"\n",
"_",
",",
"_",
"=",
"a",
".",
"Write",
"(",
"content",
")",
"\n",
"return",
"Sum",
"(",
... | // HashBytes hashes content and returns a HexDigest from it. | [
"HashBytes",
"hashes",
"content",
"and",
"returns",
"a",
"HexDigest",
"from",
"it",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/isolated/utils.go#L43-L47 |
7,847 | luci/luci-go | common/isolated/utils.go | HashFile | func HashFile(h crypto.Hash, path string) (isolateservice.HandlersEndpointsV1Digest, error) {
f, err := os.Open(path)
if err != nil {
return isolateservice.HandlersEndpointsV1Digest{}, err
}
defer f.Close()
a := h.New()
size, err := io.Copy(a, f)
if err != nil {
return isolateservice.HandlersEndpointsV1Digest{}, err
}
return isolateservice.HandlersEndpointsV1Digest{Digest: string(Sum(a)), IsIsolated: false, Size: size}, nil
} | go | func HashFile(h crypto.Hash, path string) (isolateservice.HandlersEndpointsV1Digest, error) {
f, err := os.Open(path)
if err != nil {
return isolateservice.HandlersEndpointsV1Digest{}, err
}
defer f.Close()
a := h.New()
size, err := io.Copy(a, f)
if err != nil {
return isolateservice.HandlersEndpointsV1Digest{}, err
}
return isolateservice.HandlersEndpointsV1Digest{Digest: string(Sum(a)), IsIsolated: false, Size: size}, nil
} | [
"func",
"HashFile",
"(",
"h",
"crypto",
".",
"Hash",
",",
"path",
"string",
")",
"(",
"isolateservice",
".",
"HandlersEndpointsV1Digest",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"ni... | // HashFile hashes a file and returns a HandlersEndpointsV1Digest out of it. | [
"HashFile",
"hashes",
"a",
"file",
"and",
"returns",
"a",
"HandlersEndpointsV1Digest",
"out",
"of",
"it",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/isolated/utils.go#L50-L62 |
7,848 | luci/luci-go | common/tsmon/field/utils.go | Hash | func Hash(fieldVals []interface{}) uint64 {
if len(fieldVals) == 0 {
// Avoid allocating the hasher if there are no fieldVals
return 0
}
h := fnv.New64a()
for _, v := range fieldVals {
switch v := v.(type) {
case string:
h.Write([]byte(v))
case int64:
b := [8]byte{}
for i := 0; i < 8; i++ {
b[i] = byte(v & 0xFF)
v >>= 8
}
h.Write(b[:])
case bool:
if v {
h.Write([]byte{1})
} else {
h.Write([]byte{0})
}
}
}
return h.Sum64()
} | go | func Hash(fieldVals []interface{}) uint64 {
if len(fieldVals) == 0 {
// Avoid allocating the hasher if there are no fieldVals
return 0
}
h := fnv.New64a()
for _, v := range fieldVals {
switch v := v.(type) {
case string:
h.Write([]byte(v))
case int64:
b := [8]byte{}
for i := 0; i < 8; i++ {
b[i] = byte(v & 0xFF)
v >>= 8
}
h.Write(b[:])
case bool:
if v {
h.Write([]byte{1})
} else {
h.Write([]byte{0})
}
}
}
return h.Sum64()
} | [
"func",
"Hash",
"(",
"fieldVals",
"[",
"]",
"interface",
"{",
"}",
")",
"uint64",
"{",
"if",
"len",
"(",
"fieldVals",
")",
"==",
"0",
"{",
"// Avoid allocating the hasher if there are no fieldVals",
"return",
"0",
"\n",
"}",
"\n",
"h",
":=",
"fnv",
".",
"N... | // Hash returns a uint64 hash of fieldVals. | [
"Hash",
"returns",
"a",
"uint64",
"hash",
"of",
"fieldVals",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/field/utils.go#L60-L87 |
7,849 | luci/luci-go | logdog/appengine/coordinator/settings.go | validatePercent | func validatePercent(v string) error {
if v == "" {
return nil
}
i, err := strconv.Atoi(v)
if err != nil {
return fmt.Errorf("invalid integer %q - %s", v, err)
}
if i < 0 || i > 100 {
return fmt.Errorf("%d is out of range (0-100)", i)
}
return nil
} | go | func validatePercent(v string) error {
if v == "" {
return nil
}
i, err := strconv.Atoi(v)
if err != nil {
return fmt.Errorf("invalid integer %q - %s", v, err)
}
if i < 0 || i > 100 {
return fmt.Errorf("%d is out of range (0-100)", i)
}
return nil
} | [
"func",
"validatePercent",
"(",
"v",
"string",
")",
"error",
"{",
"if",
"v",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"i",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"v",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"... | // validatePercent validates a string is empty or an integer between 0-100. | [
"validatePercent",
"validates",
"a",
"string",
"is",
"empty",
"or",
"an",
"integer",
"between",
"0",
"-",
"100",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/settings.go#L202-L214 |
7,850 | luci/luci-go | logdog/appengine/coordinator/settings.go | validateInt | func validateInt(v string) error {
if v == "" {
return nil
}
_, err := strconv.Atoi(v)
return err
} | go | func validateInt(v string) error {
if v == "" {
return nil
}
_, err := strconv.Atoi(v)
return err
} | [
"func",
"validateInt",
"(",
"v",
"string",
")",
"error",
"{",
"if",
"v",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"v",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // validateInt validates that a string is empty or an integer. | [
"validateInt",
"validates",
"that",
"a",
"string",
"is",
"empty",
"or",
"an",
"integer",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/settings.go#L217-L223 |
7,851 | luci/luci-go | logdog/appengine/coordinator/settings.go | GetSettings | func GetSettings(c context.Context) *Settings {
set := Settings{}
switch err := settings.Get(c, baseName, &set); err {
case nil:
break
case settings.ErrNoSettings:
// Defaults.
set = defaultSettings
default:
panic(fmt.Errorf("could not fetch Archivist settings - %s", err))
}
return &set
} | go | func GetSettings(c context.Context) *Settings {
set := Settings{}
switch err := settings.Get(c, baseName, &set); err {
case nil:
break
case settings.ErrNoSettings:
// Defaults.
set = defaultSettings
default:
panic(fmt.Errorf("could not fetch Archivist settings - %s", err))
}
return &set
} | [
"func",
"GetSettings",
"(",
"c",
"context",
".",
"Context",
")",
"*",
"Settings",
"{",
"set",
":=",
"Settings",
"{",
"}",
"\n",
"switch",
"err",
":=",
"settings",
".",
"Get",
"(",
"c",
",",
"baseName",
",",
"&",
"set",
")",
";",
"err",
"{",
"case",... | // GetSettings returns the current settings.
//
// It first tries to load it from settings. If no settings is installed, or if
// there is no configuration in settings, defaultSettings is returned. | [
"GetSettings",
"returns",
"the",
"current",
"settings",
".",
"It",
"first",
"tries",
"to",
"load",
"it",
"from",
"settings",
".",
"If",
"no",
"settings",
"is",
"installed",
"or",
"if",
"there",
"is",
"no",
"configuration",
"in",
"settings",
"defaultSettings",
... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/settings.go#L244-L256 |
7,852 | luci/luci-go | vpython/api/vpython/util.go | Clone | func (e *Environment) Clone() *Environment {
if e == nil {
return &Environment{}
}
return proto.Clone(e).(*Environment)
} | go | func (e *Environment) Clone() *Environment {
if e == nil {
return &Environment{}
}
return proto.Clone(e).(*Environment)
} | [
"func",
"(",
"e",
"*",
"Environment",
")",
"Clone",
"(",
")",
"*",
"Environment",
"{",
"if",
"e",
"==",
"nil",
"{",
"return",
"&",
"Environment",
"{",
"}",
"\n",
"}",
"\n",
"return",
"proto",
".",
"Clone",
"(",
"e",
")",
".",
"(",
"*",
"Environme... | // Clone returns a deep clone of the supplied Environment.
//
// If e is nil, a non-nil empty Environment will be returned. | [
"Clone",
"returns",
"a",
"deep",
"clone",
"of",
"the",
"supplied",
"Environment",
".",
"If",
"e",
"is",
"nil",
"a",
"non",
"-",
"nil",
"empty",
"Environment",
"will",
"be",
"returned",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/api/vpython/util.go#L33-L38 |
7,853 | luci/luci-go | vpython/api/vpython/util.go | IsZero | func (t *PEP425Tag) IsZero() bool {
return t == nil || (t.Python == "" && t.Abi == "" && t.Platform == "")
} | go | func (t *PEP425Tag) IsZero() bool {
return t == nil || (t.Python == "" && t.Abi == "" && t.Platform == "")
} | [
"func",
"(",
"t",
"*",
"PEP425Tag",
")",
"IsZero",
"(",
")",
"bool",
"{",
"return",
"t",
"==",
"nil",
"||",
"(",
"t",
".",
"Python",
"==",
"\"",
"\"",
"&&",
"t",
".",
"Abi",
"==",
"\"",
"\"",
"&&",
"t",
".",
"Platform",
"==",
"\"",
"\"",
")",... | // IsZero returns true if this tag is a zero value. | [
"IsZero",
"returns",
"true",
"if",
"this",
"tag",
"is",
"a",
"zero",
"value",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/api/vpython/util.go#L41-L43 |
7,854 | luci/luci-go | vpython/api/vpython/util.go | TagString | func (t *PEP425Tag) TagString() string {
return strings.Join([]string{t.Python, t.Abi, t.Platform}, "-")
} | go | func (t *PEP425Tag) TagString() string {
return strings.Join([]string{t.Python, t.Abi, t.Platform}, "-")
} | [
"func",
"(",
"t",
"*",
"PEP425Tag",
")",
"TagString",
"(",
")",
"string",
"{",
"return",
"strings",
".",
"Join",
"(",
"[",
"]",
"string",
"{",
"t",
".",
"Python",
",",
"t",
".",
"Abi",
",",
"t",
".",
"Platform",
"}",
",",
"\"",
"\"",
")",
"\n",... | // TagString returns an underscore-separated string containing t's fields. | [
"TagString",
"returns",
"an",
"underscore",
"-",
"separated",
"string",
"containing",
"t",
"s",
"fields",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/api/vpython/util.go#L46-L48 |
7,855 | luci/luci-go | vpython/api/vpython/util.go | Count | func (t *PEP425Tag) Count() (v int) {
if t.HasABI() {
v++
}
if t.AnyPlatform() {
v++
}
return
} | go | func (t *PEP425Tag) Count() (v int) {
if t.HasABI() {
v++
}
if t.AnyPlatform() {
v++
}
return
} | [
"func",
"(",
"t",
"*",
"PEP425Tag",
")",
"Count",
"(",
")",
"(",
"v",
"int",
")",
"{",
"if",
"t",
".",
"HasABI",
"(",
")",
"{",
"v",
"++",
"\n",
"}",
"\n",
"if",
"t",
".",
"AnyPlatform",
"(",
")",
"{",
"v",
"++",
"\n",
"}",
"\n",
"return",
... | // Count returns the number of populated fields in this tag. | [
"Count",
"returns",
"the",
"number",
"of",
"populated",
"fields",
"in",
"this",
"tag",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/api/vpython/util.go#L57-L65 |
7,856 | luci/luci-go | vpython/api/vpython/util.go | Clone | func (s *Spec) Clone() *Spec {
if s == nil {
return &Spec{}
}
return proto.Clone(s).(*Spec)
} | go | func (s *Spec) Clone() *Spec {
if s == nil {
return &Spec{}
}
return proto.Clone(s).(*Spec)
} | [
"func",
"(",
"s",
"*",
"Spec",
")",
"Clone",
"(",
")",
"*",
"Spec",
"{",
"if",
"s",
"==",
"nil",
"{",
"return",
"&",
"Spec",
"{",
"}",
"\n",
"}",
"\n",
"return",
"proto",
".",
"Clone",
"(",
"s",
")",
".",
"(",
"*",
"Spec",
")",
"\n",
"}"
] | // Clone returns a deep clone of the supplied Spec.
//
// If e is nil, a non-nil empty Spec will be returned. | [
"Clone",
"returns",
"a",
"deep",
"clone",
"of",
"the",
"supplied",
"Spec",
".",
"If",
"e",
"is",
"nil",
"a",
"non",
"-",
"nil",
"empty",
"Spec",
"will",
"be",
"returned",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/api/vpython/util.go#L70-L75 |
7,857 | luci/luci-go | dm/api/service/v1/queries.go | AttemptRangeQuery | func AttemptRangeQuery(quest string, low, high uint32) *GraphQuery {
return &GraphQuery{
AttemptRange: []*GraphQuery_AttemptRange{{Quest: quest, Low: low, High: high}}}
} | go | func AttemptRangeQuery(quest string, low, high uint32) *GraphQuery {
return &GraphQuery{
AttemptRange: []*GraphQuery_AttemptRange{{Quest: quest, Low: low, High: high}}}
} | [
"func",
"AttemptRangeQuery",
"(",
"quest",
"string",
",",
"low",
",",
"high",
"uint32",
")",
"*",
"GraphQuery",
"{",
"return",
"&",
"GraphQuery",
"{",
"AttemptRange",
":",
"[",
"]",
"*",
"GraphQuery_AttemptRange",
"{",
"{",
"Quest",
":",
"quest",
",",
"Low... | // AttemptRangeQuery returns a new GraphQuery for the given AttemptRange
// specification. | [
"AttemptRangeQuery",
"returns",
"a",
"new",
"GraphQuery",
"for",
"the",
"given",
"AttemptRange",
"specification",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/queries.go#L30-L33 |
7,858 | luci/luci-go | logdog/client/annotee/link_generator.go | GetLink | func (g *CoordinatorLinkGenerator) GetLink(names ...types.StreamName) string {
paths := make([]types.StreamPath, len(names))
for i, name := range names {
paths[i] = g.Prefix.AsPathPrefix(name)
}
return viewer.GetURL(g.Host, g.Project, paths...)
} | go | func (g *CoordinatorLinkGenerator) GetLink(names ...types.StreamName) string {
paths := make([]types.StreamPath, len(names))
for i, name := range names {
paths[i] = g.Prefix.AsPathPrefix(name)
}
return viewer.GetURL(g.Host, g.Project, paths...)
} | [
"func",
"(",
"g",
"*",
"CoordinatorLinkGenerator",
")",
"GetLink",
"(",
"names",
"...",
"types",
".",
"StreamName",
")",
"string",
"{",
"paths",
":=",
"make",
"(",
"[",
"]",
"types",
".",
"StreamPath",
",",
"len",
"(",
"names",
")",
")",
"\n",
"for",
... | // GetLink implements LinkGenerator. | [
"GetLink",
"implements",
"LinkGenerator",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/annotee/link_generator.go#L44-L50 |
7,859 | luci/luci-go | server/router/handler.go | RunMiddleware | func RunMiddleware(c *Context, mc MiddlewareChain, h Handler) {
runChains(c, mc, MiddlewareChain{}, h)
} | go | func RunMiddleware(c *Context, mc MiddlewareChain, h Handler) {
runChains(c, mc, MiddlewareChain{}, h)
} | [
"func",
"RunMiddleware",
"(",
"c",
"*",
"Context",
",",
"mc",
"MiddlewareChain",
",",
"h",
"Handler",
")",
"{",
"runChains",
"(",
"c",
",",
"mc",
",",
"MiddlewareChain",
"{",
"}",
",",
"h",
")",
"\n",
"}"
] | // RunMiddleware executes the middleware chain and handlers with the given
// initial context. Useful to execute a chain of functions in tests. | [
"RunMiddleware",
"executes",
"the",
"middleware",
"chain",
"and",
"handlers",
"with",
"the",
"given",
"initial",
"context",
".",
"Useful",
"to",
"execute",
"a",
"chain",
"of",
"functions",
"in",
"tests",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/router/handler.go#L43-L45 |
7,860 | luci/luci-go | server/router/handler.go | NewMiddlewareChain | func NewMiddlewareChain(mw ...Middleware) (mc MiddlewareChain) {
if len(mw) > 0 {
mc = mc.Extend(mw...)
}
return
} | go | func NewMiddlewareChain(mw ...Middleware) (mc MiddlewareChain) {
if len(mw) > 0 {
mc = mc.Extend(mw...)
}
return
} | [
"func",
"NewMiddlewareChain",
"(",
"mw",
"...",
"Middleware",
")",
"(",
"mc",
"MiddlewareChain",
")",
"{",
"if",
"len",
"(",
"mw",
")",
">",
"0",
"{",
"mc",
"=",
"mc",
".",
"Extend",
"(",
"mw",
"...",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // NewMiddlewareChain creates a new MiddlewareChain with the supplied Middleware
// entries. | [
"NewMiddlewareChain",
"creates",
"a",
"new",
"MiddlewareChain",
"with",
"the",
"supplied",
"Middleware",
"entries",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/router/handler.go#L49-L54 |
7,861 | luci/luci-go | server/router/handler.go | Extend | func (mc MiddlewareChain) Extend(mw ...Middleware) MiddlewareChain {
if len(mw) == 0 {
return mc
}
ext := make([]Middleware, 0, len(mc.middleware)+len(mw))
return MiddlewareChain{append(append(ext, mc.middleware...), mw...)}
} | go | func (mc MiddlewareChain) Extend(mw ...Middleware) MiddlewareChain {
if len(mw) == 0 {
return mc
}
ext := make([]Middleware, 0, len(mc.middleware)+len(mw))
return MiddlewareChain{append(append(ext, mc.middleware...), mw...)}
} | [
"func",
"(",
"mc",
"MiddlewareChain",
")",
"Extend",
"(",
"mw",
"...",
"Middleware",
")",
"MiddlewareChain",
"{",
"if",
"len",
"(",
"mw",
")",
"==",
"0",
"{",
"return",
"mc",
"\n",
"}",
"\n\n",
"ext",
":=",
"make",
"(",
"[",
"]",
"Middleware",
",",
... | // Extend returns a new MiddlewareChain with the supplied Middleware appended to
// the end. | [
"Extend",
"returns",
"a",
"new",
"MiddlewareChain",
"with",
"the",
"supplied",
"Middleware",
"appended",
"to",
"the",
"end",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/router/handler.go#L58-L65 |
7,862 | luci/luci-go | server/router/handler.go | ExtendFrom | func (mc MiddlewareChain) ExtendFrom(other MiddlewareChain) MiddlewareChain {
return mc.Extend(other.middleware...)
} | go | func (mc MiddlewareChain) ExtendFrom(other MiddlewareChain) MiddlewareChain {
return mc.Extend(other.middleware...)
} | [
"func",
"(",
"mc",
"MiddlewareChain",
")",
"ExtendFrom",
"(",
"other",
"MiddlewareChain",
")",
"MiddlewareChain",
"{",
"return",
"mc",
".",
"Extend",
"(",
"other",
".",
"middleware",
"...",
")",
"\n",
"}"
] | // ExtendFrom returns a new MiddlewareChain with the supplied MiddlewareChain
// appended to the end. | [
"ExtendFrom",
"returns",
"a",
"new",
"MiddlewareChain",
"with",
"the",
"supplied",
"MiddlewareChain",
"appended",
"to",
"the",
"end",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/router/handler.go#L69-L71 |
7,863 | luci/luci-go | server/router/handler.go | run | func run(c *Context, m, n []Middleware, h Handler) {
switch {
case len(m) > 0:
if m[0] != nil {
m[0](c, func(ctx *Context) { run(ctx, m[1:], n, h) })
} else {
run(c, m[1:], n, h)
}
case len(n) > 0:
if n[0] != nil {
n[0](c, func(ctx *Context) { run(ctx, nil, n[1:], h) })
} else {
run(c, nil, n[1:], h)
}
case h != nil:
h(c)
}
} | go | func run(c *Context, m, n []Middleware, h Handler) {
switch {
case len(m) > 0:
if m[0] != nil {
m[0](c, func(ctx *Context) { run(ctx, m[1:], n, h) })
} else {
run(c, m[1:], n, h)
}
case len(n) > 0:
if n[0] != nil {
n[0](c, func(ctx *Context) { run(ctx, nil, n[1:], h) })
} else {
run(c, nil, n[1:], h)
}
case h != nil:
h(c)
}
} | [
"func",
"run",
"(",
"c",
"*",
"Context",
",",
"m",
",",
"n",
"[",
"]",
"Middleware",
",",
"h",
"Handler",
")",
"{",
"switch",
"{",
"case",
"len",
"(",
"m",
")",
">",
"0",
":",
"if",
"m",
"[",
"0",
"]",
"!=",
"nil",
"{",
"m",
"[",
"0",
"]"... | // run executes the middleware chains m and n and the handler h using
// c as the initial context. If a middleware or handler is nil, run
// simply advances to the next middleware or handler. | [
"run",
"executes",
"the",
"middleware",
"chains",
"m",
"and",
"n",
"and",
"the",
"handler",
"h",
"using",
"c",
"as",
"the",
"initial",
"context",
".",
"If",
"a",
"middleware",
"or",
"handler",
"is",
"nil",
"run",
"simply",
"advances",
"to",
"the",
"next"... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/router/handler.go#L80-L97 |
7,864 | luci/luci-go | dm/appengine/distributor/jobsim/run.go | getRandom | func getRandom(c context.Context, want int) ([]byte, error) {
ret := make([]byte, want)
_, err := cryptorand.Read(c, ret)
if err != nil {
logging.WithError(err).Errorf(c, "could not generate random data")
return nil, err
}
return ret, nil
} | go | func getRandom(c context.Context, want int) ([]byte, error) {
ret := make([]byte, want)
_, err := cryptorand.Read(c, ret)
if err != nil {
logging.WithError(err).Errorf(c, "could not generate random data")
return nil, err
}
return ret, nil
} | [
"func",
"getRandom",
"(",
"c",
"context",
".",
"Context",
",",
"want",
"int",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"ret",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"want",
")",
"\n",
"_",
",",
"err",
":=",
"cryptorand",
".",
"Rea... | // getRandom returns a random byte sequence of `want` length, or an error if
// that number of random bytes could not be generated.
//
// This uses cryptorand to generate cryptographically secure random numbers. | [
"getRandom",
"returns",
"a",
"random",
"byte",
"sequence",
"of",
"want",
"length",
"or",
"an",
"error",
"if",
"that",
"number",
"of",
"random",
"bytes",
"could",
"not",
"be",
"generated",
".",
"This",
"uses",
"cryptorand",
"to",
"generate",
"cryptographically"... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/distributor/jobsim/run.go#L96-L104 |
7,865 | luci/luci-go | dm/appengine/distributor/jobsim/run.go | doReturnStage | func (r *runner) doReturnStage(stg *jobsim.ReturnStage) error {
retval := int64(0)
if stg != nil {
retval += stg.Retval
}
if r.state != nil {
retval += r.state.Sum
}
_, err := r.dmc.FinishAttempt(r.c, &dm.FinishAttemptReq{
Auth: r.auth,
Data: executionResult(true, retval, google.TimeFromProto(stg.GetExpiration())),
})
if err != nil {
logging.WithError(err).Warningf(r.c, "got error on FinishAttempt")
}
return err
} | go | func (r *runner) doReturnStage(stg *jobsim.ReturnStage) error {
retval := int64(0)
if stg != nil {
retval += stg.Retval
}
if r.state != nil {
retval += r.state.Sum
}
_, err := r.dmc.FinishAttempt(r.c, &dm.FinishAttemptReq{
Auth: r.auth,
Data: executionResult(true, retval, google.TimeFromProto(stg.GetExpiration())),
})
if err != nil {
logging.WithError(err).Warningf(r.c, "got error on FinishAttempt")
}
return err
} | [
"func",
"(",
"r",
"*",
"runner",
")",
"doReturnStage",
"(",
"stg",
"*",
"jobsim",
".",
"ReturnStage",
")",
"error",
"{",
"retval",
":=",
"int64",
"(",
"0",
")",
"\n",
"if",
"stg",
"!=",
"nil",
"{",
"retval",
"+=",
"stg",
".",
"Retval",
"\n",
"}",
... | // doReturnStage implements the FinishAttempt portion of the DM Attempt
// lifecycle. This sets the final result for the Attempt, and will prevent any
// further executions of this Attempt. This is analogous to the recipe returning
// a final result. | [
"doReturnStage",
"implements",
"the",
"FinishAttempt",
"portion",
"of",
"the",
"DM",
"Attempt",
"lifecycle",
".",
"This",
"sets",
"the",
"final",
"result",
"for",
"the",
"Attempt",
"and",
"will",
"prevent",
"any",
"further",
"executions",
"of",
"this",
"Attempt"... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/distributor/jobsim/run.go#L143-L160 |
7,866 | luci/luci-go | common/data/strpair/pair.go | ParseMap | func ParseMap(raw []string) Map {
m := make(Map, len(raw))
for _, t := range raw {
m.Add(Parse(t))
}
return m
} | go | func ParseMap(raw []string) Map {
m := make(Map, len(raw))
for _, t := range raw {
m.Add(Parse(t))
}
return m
} | [
"func",
"ParseMap",
"(",
"raw",
"[",
"]",
"string",
")",
"Map",
"{",
"m",
":=",
"make",
"(",
"Map",
",",
"len",
"(",
"raw",
")",
")",
"\n",
"for",
"_",
",",
"t",
":=",
"range",
"raw",
"{",
"m",
".",
"Add",
"(",
"Parse",
"(",
"t",
")",
")",
... | // ParseMap parses a list of colon-delimited key-value pair strings. | [
"ParseMap",
"parses",
"a",
"list",
"of",
"colon",
"-",
"delimited",
"key",
"-",
"value",
"pair",
"strings",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/strpair/pair.go#L86-L92 |
7,867 | luci/luci-go | common/data/strpair/pair.go | Format | func (m Map) Format() []string {
res := make([]string, 0, len(m))
for k, values := range m {
for _, v := range values {
res = append(res, Format(k, v))
}
}
sort.Strings(res)
return res
} | go | func (m Map) Format() []string {
res := make([]string, 0, len(m))
for k, values := range m {
for _, v := range values {
res = append(res, Format(k, v))
}
}
sort.Strings(res)
return res
} | [
"func",
"(",
"m",
"Map",
")",
"Format",
"(",
")",
"[",
"]",
"string",
"{",
"res",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"m",
")",
")",
"\n",
"for",
"k",
",",
"values",
":=",
"range",
"m",
"{",
"for",
"_",
",",
... | // Format converts m to a sorted list of strings. | [
"Format",
"converts",
"m",
"to",
"a",
"sorted",
"list",
"of",
"strings",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/strpair/pair.go#L95-L104 |
7,868 | luci/luci-go | common/data/strpair/pair.go | Copy | func (m Map) Copy() Map {
cpy := make(Map, len(m))
for k, vs := range m {
cpy[k] = append([]string(nil), vs...)
}
return cpy
} | go | func (m Map) Copy() Map {
cpy := make(Map, len(m))
for k, vs := range m {
cpy[k] = append([]string(nil), vs...)
}
return cpy
} | [
"func",
"(",
"m",
"Map",
")",
"Copy",
"(",
")",
"Map",
"{",
"cpy",
":=",
"make",
"(",
"Map",
",",
"len",
"(",
"m",
")",
")",
"\n",
"for",
"k",
",",
"vs",
":=",
"range",
"m",
"{",
"cpy",
"[",
"k",
"]",
"=",
"append",
"(",
"[",
"]",
"string... | // Copy returns a deep copy of m. | [
"Copy",
"returns",
"a",
"deep",
"copy",
"of",
"m",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/strpair/pair.go#L107-L113 |
7,869 | luci/luci-go | common/data/strpair/pair.go | Contains | func (m Map) Contains(key, value string) bool {
for _, v := range m[key] {
if v == value {
return true
}
}
return false
} | go | func (m Map) Contains(key, value string) bool {
for _, v := range m[key] {
if v == value {
return true
}
}
return false
} | [
"func",
"(",
"m",
"Map",
")",
"Contains",
"(",
"key",
",",
"value",
"string",
")",
"bool",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"m",
"[",
"key",
"]",
"{",
"if",
"v",
"==",
"value",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"retu... | // Contains returns true if m contains the key-value pair. | [
"Contains",
"returns",
"true",
"if",
"m",
"contains",
"the",
"key",
"-",
"value",
"pair",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/strpair/pair.go#L116-L123 |
7,870 | luci/luci-go | milo/buildsource/swarming/buildLog.go | swarmingBuildLogImpl | func swarmingBuildLogImpl(c context.Context, svc SwarmingService, taskID, logname string) (string, bool, error) {
server := svc.GetHost()
cached, err := mc.GetKey(c, path.Join("swarmingLog", server, taskID, logname))
switch {
case err == mc.ErrCacheMiss:
case err != nil:
logging.WithError(err).Errorf(c, "failed to fetch log with key %s from memcache", cached.Key())
default:
logging.Debugf(c, "Cache hit for step log %s/%s/%s", server, taskID, logname)
return string(cached.Value()), false, nil
}
fr, err := swarmingFetch(c, svc, taskID, swarmingFetchParams{fetchLog: true})
if err != nil {
return "", false, err
}
// Decode the data using annotee.
s, err := streamsFromAnnotatedLog(c, fr.log)
if err != nil {
return "", false, err
}
k := fmt.Sprintf("steps%s", logname)
stream, ok := s.Streams[k]
if !ok {
var keys []string
for sk := range s.Streams {
keys = append(keys, sk)
}
sort.Strings(keys)
return "", false, fmt.Errorf("stream %q not found; available streams: %q", k, keys)
}
if stream.Closed {
cached.SetValue([]byte(stream.Text))
if err := mc.Set(c, cached); err != nil {
logging.Errorf(c, "Failed to write log with key %s to memcache: %s", cached.Key(), err)
}
}
return stream.Text, stream.Closed, nil
} | go | func swarmingBuildLogImpl(c context.Context, svc SwarmingService, taskID, logname string) (string, bool, error) {
server := svc.GetHost()
cached, err := mc.GetKey(c, path.Join("swarmingLog", server, taskID, logname))
switch {
case err == mc.ErrCacheMiss:
case err != nil:
logging.WithError(err).Errorf(c, "failed to fetch log with key %s from memcache", cached.Key())
default:
logging.Debugf(c, "Cache hit for step log %s/%s/%s", server, taskID, logname)
return string(cached.Value()), false, nil
}
fr, err := swarmingFetch(c, svc, taskID, swarmingFetchParams{fetchLog: true})
if err != nil {
return "", false, err
}
// Decode the data using annotee.
s, err := streamsFromAnnotatedLog(c, fr.log)
if err != nil {
return "", false, err
}
k := fmt.Sprintf("steps%s", logname)
stream, ok := s.Streams[k]
if !ok {
var keys []string
for sk := range s.Streams {
keys = append(keys, sk)
}
sort.Strings(keys)
return "", false, fmt.Errorf("stream %q not found; available streams: %q", k, keys)
}
if stream.Closed {
cached.SetValue([]byte(stream.Text))
if err := mc.Set(c, cached); err != nil {
logging.Errorf(c, "Failed to write log with key %s to memcache: %s", cached.Key(), err)
}
}
return stream.Text, stream.Closed, nil
} | [
"func",
"swarmingBuildLogImpl",
"(",
"c",
"context",
".",
"Context",
",",
"svc",
"SwarmingService",
",",
"taskID",
",",
"logname",
"string",
")",
"(",
"string",
",",
"bool",
",",
"error",
")",
"{",
"server",
":=",
"svc",
".",
"GetHost",
"(",
")",
"\n",
... | // swarmingBuildLogImpl is the implementation for getting a log name from
// a swarming build via annotee. It returns the full text of the specific log,
// and whether or not it has been closed. | [
"swarmingBuildLogImpl",
"is",
"the",
"implementation",
"for",
"getting",
"a",
"log",
"name",
"from",
"a",
"swarming",
"build",
"via",
"annotee",
".",
"It",
"returns",
"the",
"full",
"text",
"of",
"the",
"specific",
"log",
"and",
"whether",
"or",
"not",
"it",... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/swarming/buildLog.go#L30-L74 |
7,871 | luci/luci-go | tokenserver/appengine/impl/serviceaccounts/grant.go | SignGrant | func SignGrant(c context.Context, signer signing.Signer, tok *tokenserver.OAuthTokenGrantBody) (string, error) {
s := tokensigning.Signer{
Signer: signer,
SigningContext: tokenSigningContext,
Wrap: func(w *tokensigning.Unwrapped) proto.Message {
return &tokenserver.OAuthTokenGrantEnvelope{
TokenBody: w.Body,
Pkcs1Sha256Sig: w.RsaSHA256Sig,
KeyId: w.KeyID,
}
},
}
return s.SignToken(c, tok)
} | go | func SignGrant(c context.Context, signer signing.Signer, tok *tokenserver.OAuthTokenGrantBody) (string, error) {
s := tokensigning.Signer{
Signer: signer,
SigningContext: tokenSigningContext,
Wrap: func(w *tokensigning.Unwrapped) proto.Message {
return &tokenserver.OAuthTokenGrantEnvelope{
TokenBody: w.Body,
Pkcs1Sha256Sig: w.RsaSHA256Sig,
KeyId: w.KeyID,
}
},
}
return s.SignToken(c, tok)
} | [
"func",
"SignGrant",
"(",
"c",
"context",
".",
"Context",
",",
"signer",
"signing",
".",
"Signer",
",",
"tok",
"*",
"tokenserver",
".",
"OAuthTokenGrantBody",
")",
"(",
"string",
",",
"error",
")",
"{",
"s",
":=",
"tokensigning",
".",
"Signer",
"{",
"Sig... | // SignGrant signs and serializes the OAuth grant.
//
// It doesn't do any validation. Assumes the prepared body is valid.
//
// Produces base64 URL-safe token or a transient error. | [
"SignGrant",
"signs",
"and",
"serializes",
"the",
"OAuth",
"grant",
".",
"It",
"doesn",
"t",
"do",
"any",
"validation",
".",
"Assumes",
"the",
"prepared",
"body",
"is",
"valid",
".",
"Produces",
"base64",
"URL",
"-",
"safe",
"token",
"or",
"a",
"transient"... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/serviceaccounts/grant.go#L41-L54 |
7,872 | luci/luci-go | config/impl/filesystem/fs.go | setRevision | func (c *scannedConfigs) setRevision(revision string) {
newRevPathMap := make(map[lookupKey]*config.Config, len(c.contentRevPathMap))
for k, v := range c.contentRevPathMap {
k.revision = revision
v.Revision = revision
newRevPathMap[k] = v
}
c.contentRevPathMap = newRevPathMap
newRevProject := make(map[lookupKey]*config.Project, len(c.contentRevProject))
for k, v := range c.contentRevProject {
k.revision = revision
newRevProject[k] = v
}
c.contentRevProject = newRevProject
} | go | func (c *scannedConfigs) setRevision(revision string) {
newRevPathMap := make(map[lookupKey]*config.Config, len(c.contentRevPathMap))
for k, v := range c.contentRevPathMap {
k.revision = revision
v.Revision = revision
newRevPathMap[k] = v
}
c.contentRevPathMap = newRevPathMap
newRevProject := make(map[lookupKey]*config.Project, len(c.contentRevProject))
for k, v := range c.contentRevProject {
k.revision = revision
newRevProject[k] = v
}
c.contentRevProject = newRevProject
} | [
"func",
"(",
"c",
"*",
"scannedConfigs",
")",
"setRevision",
"(",
"revision",
"string",
")",
"{",
"newRevPathMap",
":=",
"make",
"(",
"map",
"[",
"lookupKey",
"]",
"*",
"config",
".",
"Config",
",",
"len",
"(",
"c",
".",
"contentRevPathMap",
")",
")",
... | // setRevision updates 'revision' fields of all objects owned by scannedConfigs. | [
"setRevision",
"updates",
"revision",
"fields",
"of",
"all",
"objects",
"owned",
"by",
"scannedConfigs",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/impl/filesystem/fs.go#L122-L137 |
7,873 | luci/luci-go | config/impl/filesystem/fs.go | deriveRevision | func deriveRevision(c *scannedConfigs) string {
keys := make([]string, 0, len(c.contentHashMap))
for k := range c.contentHashMap {
keys = append(keys, k)
}
sort.Strings(keys)
hsh := sha256.New()
for _, k := range keys {
fmt.Fprintf(hsh, "%s\n%s\n", k, c.contentHashMap[k])
}
digest := hsh.Sum(nil)
return hex.EncodeToString(digest[:])[:40]
} | go | func deriveRevision(c *scannedConfigs) string {
keys := make([]string, 0, len(c.contentHashMap))
for k := range c.contentHashMap {
keys = append(keys, k)
}
sort.Strings(keys)
hsh := sha256.New()
for _, k := range keys {
fmt.Fprintf(hsh, "%s\n%s\n", k, c.contentHashMap[k])
}
digest := hsh.Sum(nil)
return hex.EncodeToString(digest[:])[:40]
} | [
"func",
"deriveRevision",
"(",
"c",
"*",
"scannedConfigs",
")",
"string",
"{",
"keys",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"c",
".",
"contentHashMap",
")",
")",
"\n",
"for",
"k",
":=",
"range",
"c",
".",
"contentHashMap"... | // deriveRevision generates a revision string from data in contentHashMap. | [
"deriveRevision",
"generates",
"a",
"revision",
"string",
"from",
"data",
"in",
"contentHashMap",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/impl/filesystem/fs.go#L140-L152 |
7,874 | luci/luci-go | common/bq/eventupload.go | Save | func (r *Row) Save() (map[string]bigquery.Value, string, error) {
m, err := mapFromMessage(r.Message, nil)
return m, r.InsertID, err
} | go | func (r *Row) Save() (map[string]bigquery.Value, string, error) {
m, err := mapFromMessage(r.Message, nil)
return m, r.InsertID, err
} | [
"func",
"(",
"r",
"*",
"Row",
")",
"Save",
"(",
")",
"(",
"map",
"[",
"string",
"]",
"bigquery",
".",
"Value",
",",
"string",
",",
"error",
")",
"{",
"m",
",",
"err",
":=",
"mapFromMessage",
"(",
"r",
".",
"Message",
",",
"nil",
")",
"\n",
"ret... | // Save is used by bigquery.Uploader.Put when inserting values into a table. | [
"Save",
"is",
"used",
"by",
"bigquery",
".",
"Uploader",
".",
"Put",
"when",
"inserting",
"values",
"into",
"a",
"table",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/bq/eventupload.go#L102-L105 |
7,875 | luci/luci-go | common/bq/eventupload.go | getFieldInfos | func getFieldInfos(t reflect.Type) ([]fieldInfo, error) {
bqFieldsLock.RLock()
f := bqFields[t]
bqFieldsLock.RUnlock()
if f != nil {
return f, nil
}
bqFieldsLock.Lock()
defer bqFieldsLock.Unlock()
return getFieldInfosLocked(t)
} | go | func getFieldInfos(t reflect.Type) ([]fieldInfo, error) {
bqFieldsLock.RLock()
f := bqFields[t]
bqFieldsLock.RUnlock()
if f != nil {
return f, nil
}
bqFieldsLock.Lock()
defer bqFieldsLock.Unlock()
return getFieldInfosLocked(t)
} | [
"func",
"getFieldInfos",
"(",
"t",
"reflect",
".",
"Type",
")",
"(",
"[",
"]",
"fieldInfo",
",",
"error",
")",
"{",
"bqFieldsLock",
".",
"RLock",
"(",
")",
"\n",
"f",
":=",
"bqFields",
"[",
"t",
"]",
"\n",
"bqFieldsLock",
".",
"RUnlock",
"(",
")",
... | // getFieldInfos returns field metadata for a given proto go type.
// Caches results. | [
"getFieldInfos",
"returns",
"field",
"metadata",
"for",
"a",
"given",
"proto",
"go",
"type",
".",
"Caches",
"results",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/bq/eventupload.go#L193-L204 |
7,876 | luci/luci-go | common/bq/eventupload.go | NewUploader | func NewUploader(ctx context.Context, c *bigquery.Client, datasetID, tableID string) *Uploader {
return &Uploader{
DatasetID: datasetID,
TableID: tableID,
Uploader: c.Dataset(datasetID).Table(tableID).Uploader(),
}
} | go | func NewUploader(ctx context.Context, c *bigquery.Client, datasetID, tableID string) *Uploader {
return &Uploader{
DatasetID: datasetID,
TableID: tableID,
Uploader: c.Dataset(datasetID).Table(tableID).Uploader(),
}
} | [
"func",
"NewUploader",
"(",
"ctx",
"context",
".",
"Context",
",",
"c",
"*",
"bigquery",
".",
"Client",
",",
"datasetID",
",",
"tableID",
"string",
")",
"*",
"Uploader",
"{",
"return",
"&",
"Uploader",
"{",
"DatasetID",
":",
"datasetID",
",",
"TableID",
... | // NewUploader constructs a new Uploader struct.
//
// DatasetID and TableID are provided to the BigQuery client to
// gain access to a particular table.
//
// You may want to change the default configuration of the bigquery.Uploader.
// Check the documentation for more details.
//
// Set UploadsMetricName on the resulting Uploader to use the default counter
// metric.
//
// Set BatchSize to set a custom batch size. | [
"NewUploader",
"constructs",
"a",
"new",
"Uploader",
"struct",
".",
"DatasetID",
"and",
"TableID",
"are",
"provided",
"to",
"the",
"BigQuery",
"client",
"to",
"gain",
"access",
"to",
"a",
"particular",
"table",
".",
"You",
"may",
"want",
"to",
"change",
"the... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/bq/eventupload.go#L337-L343 |
7,877 | luci/luci-go | common/bq/eventupload.go | Put | func (u *Uploader) Put(ctx context.Context, messages ...proto.Message) error {
if _, ok := ctx.Deadline(); !ok {
var c context.CancelFunc
ctx, c = context.WithTimeout(ctx, time.Minute)
defer c()
}
rows := make([]*Row, len(messages))
for i, m := range messages {
rows[i] = &Row{
Message: m,
InsertID: ID.Generate(),
}
}
return parallel.WorkPool(16, func(workC chan<- func() error) {
for _, rowSet := range batch(rows, u.batchSize()) {
rowSet := rowSet
workC <- func() error {
var failed int
err := u.Uploader.Put(ctx, rowSet)
if err != nil {
logging.WithError(err).Errorf(ctx, "eventupload: Uploader.Put failed")
if merr, ok := err.(bigquery.PutMultiError); ok {
if failed = len(merr); failed > len(rowSet) {
logging.Errorf(ctx, "eventupload: %v failures trying to insert %v rows", failed, len(rowSet))
}
} else {
failed = len(rowSet)
}
u.updateUploads(ctx, int64(failed), "failure")
}
succeeded := len(rowSet) - failed
u.updateUploads(ctx, int64(succeeded), "success")
return err
}
}
})
} | go | func (u *Uploader) Put(ctx context.Context, messages ...proto.Message) error {
if _, ok := ctx.Deadline(); !ok {
var c context.CancelFunc
ctx, c = context.WithTimeout(ctx, time.Minute)
defer c()
}
rows := make([]*Row, len(messages))
for i, m := range messages {
rows[i] = &Row{
Message: m,
InsertID: ID.Generate(),
}
}
return parallel.WorkPool(16, func(workC chan<- func() error) {
for _, rowSet := range batch(rows, u.batchSize()) {
rowSet := rowSet
workC <- func() error {
var failed int
err := u.Uploader.Put(ctx, rowSet)
if err != nil {
logging.WithError(err).Errorf(ctx, "eventupload: Uploader.Put failed")
if merr, ok := err.(bigquery.PutMultiError); ok {
if failed = len(merr); failed > len(rowSet) {
logging.Errorf(ctx, "eventupload: %v failures trying to insert %v rows", failed, len(rowSet))
}
} else {
failed = len(rowSet)
}
u.updateUploads(ctx, int64(failed), "failure")
}
succeeded := len(rowSet) - failed
u.updateUploads(ctx, int64(succeeded), "success")
return err
}
}
})
} | [
"func",
"(",
"u",
"*",
"Uploader",
")",
"Put",
"(",
"ctx",
"context",
".",
"Context",
",",
"messages",
"...",
"proto",
".",
"Message",
")",
"error",
"{",
"if",
"_",
",",
"ok",
":=",
"ctx",
".",
"Deadline",
"(",
")",
";",
"!",
"ok",
"{",
"var",
... | // Put uploads one or more rows to the BigQuery service. Put takes care of
// adding InsertIDs, used by BigQuery to deduplicate rows.
//
// If any rows do now match one of the expected types, Put will not attempt to
// upload any rows and returns an InvalidTypeError.
//
// Put returns a PutMultiError if one or more rows failed to be uploaded.
// The PutMultiError contains a RowInsertionError for each failed row.
//
// Put will retry on temporary errors. If the error persists, the call will
// run indefinitely. Because of this, if ctx does not have a timeout, Put will
// add one.
//
// See bigquery documentation and source code for detailed information on how
// struct values are mapped to rows. | [
"Put",
"uploads",
"one",
"or",
"more",
"rows",
"to",
"the",
"BigQuery",
"service",
".",
"Put",
"takes",
"care",
"of",
"adding",
"InsertIDs",
"used",
"by",
"BigQuery",
"to",
"deduplicate",
"rows",
".",
"If",
"any",
"rows",
"do",
"now",
"match",
"one",
"of... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/bq/eventupload.go#L388-L425 |
7,878 | luci/luci-go | server/caching/global.go | WithGlobalCache | func WithGlobalCache(c context.Context, provider BlobCacheProvider) context.Context {
return context.WithValue(c, &globalCacheKey, provider)
} | go | func WithGlobalCache(c context.Context, provider BlobCacheProvider) context.Context {
return context.WithValue(c, &globalCacheKey, provider)
} | [
"func",
"WithGlobalCache",
"(",
"c",
"context",
".",
"Context",
",",
"provider",
"BlobCacheProvider",
")",
"context",
".",
"Context",
"{",
"return",
"context",
".",
"WithValue",
"(",
"c",
",",
"&",
"globalCacheKey",
",",
"provider",
")",
"\n",
"}"
] | // WithGlobalCache installs a global cache implementation into the supplied
// context. | [
"WithGlobalCache",
"installs",
"a",
"global",
"cache",
"implementation",
"into",
"the",
"supplied",
"context",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/caching/global.go#L61-L63 |
7,879 | luci/luci-go | appengine/gaeauth/client/client.go | GetAccessToken | func GetAccessToken(c context.Context, scopes []string) (*oauth2.Token, error) {
scopes, cacheKey := normalizeScopes(scopes)
// Try to find the token in the local memory first. If it expires soon,
// refresh it earlier with some probability. That avoids a situation when
// parallel requests that use access tokens suddenly see the cache expired
// and rush to refresh the token all at once.
lru := tokensCache.LRU(c)
if tokIface, ok := lru.Get(c, cacheKey); ok {
tok := tokIface.(*oauth2.Token)
if !closeToExpRandomized(c, tok.Expiry) {
return tok, nil
}
}
tokIface, err := lru.Create(c, cacheKey, func() (interface{}, time.Duration, error) {
// The token needs to be refreshed.
logging.Debugf(c, "Getting an access token for scopes %q", strings.Join(scopes, ", "))
accessToken, exp, err := info.AccessToken(c, scopes...)
if err != nil {
return nil, 0, transient.Tag.Apply(err)
}
now := clock.Now(c)
logging.Debugf(c, "The token expires in %s", exp.Sub(now))
// Prematurely expire it to guarantee all returned token live for at least
// 'expirationMinLifetime'.
tok := &oauth2.Token{
AccessToken: accessToken,
Expiry: exp.Add(-expirationMinLifetime),
TokenType: "Bearer",
}
return tok, now.Sub(tok.Expiry), nil
})
if err != nil {
return nil, err
}
return tokIface.(*oauth2.Token), nil
} | go | func GetAccessToken(c context.Context, scopes []string) (*oauth2.Token, error) {
scopes, cacheKey := normalizeScopes(scopes)
// Try to find the token in the local memory first. If it expires soon,
// refresh it earlier with some probability. That avoids a situation when
// parallel requests that use access tokens suddenly see the cache expired
// and rush to refresh the token all at once.
lru := tokensCache.LRU(c)
if tokIface, ok := lru.Get(c, cacheKey); ok {
tok := tokIface.(*oauth2.Token)
if !closeToExpRandomized(c, tok.Expiry) {
return tok, nil
}
}
tokIface, err := lru.Create(c, cacheKey, func() (interface{}, time.Duration, error) {
// The token needs to be refreshed.
logging.Debugf(c, "Getting an access token for scopes %q", strings.Join(scopes, ", "))
accessToken, exp, err := info.AccessToken(c, scopes...)
if err != nil {
return nil, 0, transient.Tag.Apply(err)
}
now := clock.Now(c)
logging.Debugf(c, "The token expires in %s", exp.Sub(now))
// Prematurely expire it to guarantee all returned token live for at least
// 'expirationMinLifetime'.
tok := &oauth2.Token{
AccessToken: accessToken,
Expiry: exp.Add(-expirationMinLifetime),
TokenType: "Bearer",
}
return tok, now.Sub(tok.Expiry), nil
})
if err != nil {
return nil, err
}
return tokIface.(*oauth2.Token), nil
} | [
"func",
"GetAccessToken",
"(",
"c",
"context",
".",
"Context",
",",
"scopes",
"[",
"]",
"string",
")",
"(",
"*",
"oauth2",
".",
"Token",
",",
"error",
")",
"{",
"scopes",
",",
"cacheKey",
":=",
"normalizeScopes",
"(",
"scopes",
")",
"\n\n",
"// Try to fi... | // GetAccessToken returns an OAuth access token representing app's service
// account.
//
// If scopes is empty, uses auth.OAuthScopeEmail scope.
//
// Implements a caching layer on top of GAE's GetAccessToken RPC. May return
// transient errors. | [
"GetAccessToken",
"returns",
"an",
"OAuth",
"access",
"token",
"representing",
"app",
"s",
"service",
"account",
".",
"If",
"scopes",
"is",
"empty",
"uses",
"auth",
".",
"OAuthScopeEmail",
"scope",
".",
"Implements",
"a",
"caching",
"layer",
"on",
"top",
"of",... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaeauth/client/client.go#L46-L85 |
7,880 | luci/luci-go | appengine/gaeauth/client/client.go | NewTokenSource | func NewTokenSource(ctx context.Context, scopes []string) oauth2.TokenSource {
return &tokenSource{ctx, scopes}
} | go | func NewTokenSource(ctx context.Context, scopes []string) oauth2.TokenSource {
return &tokenSource{ctx, scopes}
} | [
"func",
"NewTokenSource",
"(",
"ctx",
"context",
".",
"Context",
",",
"scopes",
"[",
"]",
"string",
")",
"oauth2",
".",
"TokenSource",
"{",
"return",
"&",
"tokenSource",
"{",
"ctx",
",",
"scopes",
"}",
"\n",
"}"
] | // NewTokenSource makes oauth2.TokenSource implemented on top of GetAccessToken.
//
// It is bound to the given context. | [
"NewTokenSource",
"makes",
"oauth2",
".",
"TokenSource",
"implemented",
"on",
"top",
"of",
"GetAccessToken",
".",
"It",
"is",
"bound",
"to",
"the",
"given",
"context",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaeauth/client/client.go#L90-L92 |
7,881 | luci/luci-go | common/clock/tags.go | Tag | func Tag(c context.Context, v string) context.Context {
return context.WithValue(c, &clockTagKey, append(Tags(c), v))
} | go | func Tag(c context.Context, v string) context.Context {
return context.WithValue(c, &clockTagKey, append(Tags(c), v))
} | [
"func",
"Tag",
"(",
"c",
"context",
".",
"Context",
",",
"v",
"string",
")",
"context",
".",
"Context",
"{",
"return",
"context",
".",
"WithValue",
"(",
"c",
",",
"&",
"clockTagKey",
",",
"append",
"(",
"Tags",
"(",
"c",
")",
",",
"v",
")",
")",
... | // Tag returns a derivative Context with the supplied Tag appended to it.
//
// Tag chains can be used by timers to identify themselves. | [
"Tag",
"returns",
"a",
"derivative",
"Context",
"with",
"the",
"supplied",
"Tag",
"appended",
"to",
"it",
".",
"Tag",
"chains",
"can",
"be",
"used",
"by",
"timers",
"to",
"identify",
"themselves",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/clock/tags.go#L24-L26 |
7,882 | luci/luci-go | common/clock/tags.go | Tags | func Tags(c context.Context) []string {
if tags, ok := c.Value(&clockTagKey).([]string); ok && len(tags) > 0 {
tclone := make([]string, len(tags))
copy(tclone, tags)
return tclone
}
return nil
} | go | func Tags(c context.Context) []string {
if tags, ok := c.Value(&clockTagKey).([]string); ok && len(tags) > 0 {
tclone := make([]string, len(tags))
copy(tclone, tags)
return tclone
}
return nil
} | [
"func",
"Tags",
"(",
"c",
"context",
".",
"Context",
")",
"[",
"]",
"string",
"{",
"if",
"tags",
",",
"ok",
":=",
"c",
".",
"Value",
"(",
"&",
"clockTagKey",
")",
".",
"(",
"[",
"]",
"string",
")",
";",
"ok",
"&&",
"len",
"(",
"tags",
")",
">... | // Tags returns a copy of the set of tags in the current Context. | [
"Tags",
"returns",
"a",
"copy",
"of",
"the",
"set",
"of",
"tags",
"in",
"the",
"current",
"Context",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/clock/tags.go#L29-L36 |
7,883 | luci/luci-go | machine-db/appengine/model/rack_kvms.go | fetch | func (t *RackKVMsTable) fetch(c context.Context) error {
db := database.Get(c)
rows, err := db.QueryContext(c, `
SELECT id, name, kvm_id
FROM racks
`)
if err != nil {
return errors.Annotate(err, "failed to select racks").Err()
}
defer rows.Close()
for rows.Next() {
rack := &RackKVM{}
if err := rows.Scan(&rack.Id, &rack.Name, &rack.KVMId); err != nil {
return errors.Annotate(err, "failed to scan racks").Err()
}
t.current = append(t.current, rack)
}
return nil
} | go | func (t *RackKVMsTable) fetch(c context.Context) error {
db := database.Get(c)
rows, err := db.QueryContext(c, `
SELECT id, name, kvm_id
FROM racks
`)
if err != nil {
return errors.Annotate(err, "failed to select racks").Err()
}
defer rows.Close()
for rows.Next() {
rack := &RackKVM{}
if err := rows.Scan(&rack.Id, &rack.Name, &rack.KVMId); err != nil {
return errors.Annotate(err, "failed to scan racks").Err()
}
t.current = append(t.current, rack)
}
return nil
} | [
"func",
"(",
"t",
"*",
"RackKVMsTable",
")",
"fetch",
"(",
"c",
"context",
".",
"Context",
")",
"error",
"{",
"db",
":=",
"database",
".",
"Get",
"(",
"c",
")",
"\n",
"rows",
",",
"err",
":=",
"db",
".",
"QueryContext",
"(",
"c",
",",
"`\n\t\tSELEC... | // fetch fetches the rack kvm_ids from the database. | [
"fetch",
"fetches",
"the",
"rack",
"kvm_ids",
"from",
"the",
"database",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/rack_kvms.go#L47-L65 |
7,884 | luci/luci-go | machine-db/appengine/model/rack_kvms.go | computeChanges | func (t *RackKVMsTable) computeChanges(c context.Context, datacenters []*config.Datacenter) error {
cfgs := make(map[string]*RackKVM, len(datacenters))
for _, dc := range datacenters {
for _, cfg := range dc.Rack {
cfgs[cfg.Name] = &RackKVM{
Rack: config.Rack{
Name: cfg.Name,
},
}
if cfg.Kvm != "" {
id, ok := t.kvms[cfg.Kvm]
if !ok {
return errors.Reason("failed to determine KVM ID for rack %q: KVM %q does not exist", cfg.Name, cfg.Kvm).Err()
}
cfgs[cfg.Name].KVMId.Int64 = id
cfgs[cfg.Name].KVMId.Valid = true
}
}
}
for _, rack := range t.current {
if cfg, ok := cfgs[rack.Name]; ok {
// Rack found in the config.
if t.needsUpdate(rack, cfg) {
// Rack doesn't match the config.
cfg.Id = rack.Id
t.updates = append(t.updates, cfg)
}
// Record that the rack config has been seen.
delete(cfgs, cfg.Name)
}
}
return nil
} | go | func (t *RackKVMsTable) computeChanges(c context.Context, datacenters []*config.Datacenter) error {
cfgs := make(map[string]*RackKVM, len(datacenters))
for _, dc := range datacenters {
for _, cfg := range dc.Rack {
cfgs[cfg.Name] = &RackKVM{
Rack: config.Rack{
Name: cfg.Name,
},
}
if cfg.Kvm != "" {
id, ok := t.kvms[cfg.Kvm]
if !ok {
return errors.Reason("failed to determine KVM ID for rack %q: KVM %q does not exist", cfg.Name, cfg.Kvm).Err()
}
cfgs[cfg.Name].KVMId.Int64 = id
cfgs[cfg.Name].KVMId.Valid = true
}
}
}
for _, rack := range t.current {
if cfg, ok := cfgs[rack.Name]; ok {
// Rack found in the config.
if t.needsUpdate(rack, cfg) {
// Rack doesn't match the config.
cfg.Id = rack.Id
t.updates = append(t.updates, cfg)
}
// Record that the rack config has been seen.
delete(cfgs, cfg.Name)
}
}
return nil
} | [
"func",
"(",
"t",
"*",
"RackKVMsTable",
")",
"computeChanges",
"(",
"c",
"context",
".",
"Context",
",",
"datacenters",
"[",
"]",
"*",
"config",
".",
"Datacenter",
")",
"error",
"{",
"cfgs",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"RackKVM",... | // computeChanges computes the changes that need to be made to the rack kvm_ids in the database. | [
"computeChanges",
"computes",
"the",
"changes",
"that",
"need",
"to",
"be",
"made",
"to",
"the",
"rack",
"kvm_ids",
"in",
"the",
"database",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/rack_kvms.go#L73-L106 |
7,885 | luci/luci-go | machine-db/appengine/model/rack_kvms.go | update | func (t *RackKVMsTable) update(c context.Context) error {
// Avoid using the database connection to prepare unnecessary statements.
if len(t.updates) == 0 {
return nil
}
db := database.Get(c)
stmt, err := db.PrepareContext(c, `
UPDATE racks
SET kvm_id = ?
WHERE id = ?
`)
if err != nil {
return errors.Annotate(err, "failed to prepare statement").Err()
}
defer stmt.Close()
// Update each rack in the table. It's more efficient to update the slice of
// racks once at the end rather than for each update, so use a defer.
updated := make(map[int64]*RackKVM, len(t.updates))
defer func() {
for _, rack := range t.current {
if u, ok := updated[rack.Id]; ok {
rack.KVMId = u.KVMId
}
}
}()
for len(t.updates) > 0 {
rack := t.updates[0]
if _, err := stmt.ExecContext(c, rack.KVMId, rack.Id); err != nil {
return errors.Annotate(err, "failed to update rack %q", rack.Name).Err()
}
updated[rack.Id] = rack
t.updates = t.updates[1:]
logging.Infof(c, "Updated KVM for rack %q", rack.Name)
}
return nil
} | go | func (t *RackKVMsTable) update(c context.Context) error {
// Avoid using the database connection to prepare unnecessary statements.
if len(t.updates) == 0 {
return nil
}
db := database.Get(c)
stmt, err := db.PrepareContext(c, `
UPDATE racks
SET kvm_id = ?
WHERE id = ?
`)
if err != nil {
return errors.Annotate(err, "failed to prepare statement").Err()
}
defer stmt.Close()
// Update each rack in the table. It's more efficient to update the slice of
// racks once at the end rather than for each update, so use a defer.
updated := make(map[int64]*RackKVM, len(t.updates))
defer func() {
for _, rack := range t.current {
if u, ok := updated[rack.Id]; ok {
rack.KVMId = u.KVMId
}
}
}()
for len(t.updates) > 0 {
rack := t.updates[0]
if _, err := stmt.ExecContext(c, rack.KVMId, rack.Id); err != nil {
return errors.Annotate(err, "failed to update rack %q", rack.Name).Err()
}
updated[rack.Id] = rack
t.updates = t.updates[1:]
logging.Infof(c, "Updated KVM for rack %q", rack.Name)
}
return nil
} | [
"func",
"(",
"t",
"*",
"RackKVMsTable",
")",
"update",
"(",
"c",
"context",
".",
"Context",
")",
"error",
"{",
"// Avoid using the database connection to prepare unnecessary statements.",
"if",
"len",
"(",
"t",
".",
"updates",
")",
"==",
"0",
"{",
"return",
"nil... | // update updates all rack kvm_ids pending update in the database, clearing pending updates.
// No-op unless computeChanges was called first. Idempotent until computeChanges is called again. | [
"update",
"updates",
"all",
"rack",
"kvm_ids",
"pending",
"update",
"in",
"the",
"database",
"clearing",
"pending",
"updates",
".",
"No",
"-",
"op",
"unless",
"computeChanges",
"was",
"called",
"first",
".",
"Idempotent",
"until",
"computeChanges",
"is",
"called... | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/rack_kvms.go#L110-L147 |
7,886 | luci/luci-go | machine-db/appengine/model/rack_kvms.go | EnsureRackKVMs | func EnsureRackKVMs(c context.Context, cfgs []*config.Datacenter, kvmIds map[string]int64) error {
t := &RackKVMsTable{}
t.kvms = kvmIds
if err := t.fetch(c); err != nil {
return errors.Annotate(err, "failed to fetch racks").Err()
}
if err := t.computeChanges(c, cfgs); err != nil {
return errors.Annotate(err, "failed to compute changes").Err()
}
if err := t.update(c); err != nil {
return errors.Annotate(err, "failed to update racks").Err()
}
return nil
} | go | func EnsureRackKVMs(c context.Context, cfgs []*config.Datacenter, kvmIds map[string]int64) error {
t := &RackKVMsTable{}
t.kvms = kvmIds
if err := t.fetch(c); err != nil {
return errors.Annotate(err, "failed to fetch racks").Err()
}
if err := t.computeChanges(c, cfgs); err != nil {
return errors.Annotate(err, "failed to compute changes").Err()
}
if err := t.update(c); err != nil {
return errors.Annotate(err, "failed to update racks").Err()
}
return nil
} | [
"func",
"EnsureRackKVMs",
"(",
"c",
"context",
".",
"Context",
",",
"cfgs",
"[",
"]",
"*",
"config",
".",
"Datacenter",
",",
"kvmIds",
"map",
"[",
"string",
"]",
"int64",
")",
"error",
"{",
"t",
":=",
"&",
"RackKVMsTable",
"{",
"}",
"\n",
"t",
".",
... | // EnsureRackKVMs ensures the database contains exactly the given rack kvm_ids. | [
"EnsureRackKVMs",
"ensures",
"the",
"database",
"contains",
"exactly",
"the",
"given",
"rack",
"kvm_ids",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/model/rack_kvms.go#L150-L163 |
7,887 | luci/luci-go | scheduler/appengine/engine/invquery.go | start | func (it *invDatastoreIter) start(c context.Context, query *datastore.Query) {
it.results = make(chan *Invocation)
it.done = make(chan struct{})
go func() {
defer close(it.results)
err := datastore.Run(c, query, func(obj *Invocation, cb datastore.CursorCB) error {
select {
case it.results <- obj:
return nil
case <-it.done:
return datastore.Stop
}
})
// Let 'next' and 'stop' know about the error. They look here if they
// receive 'nil' from the results channel (which happens if it is closed).
it.err = err
}()
} | go | func (it *invDatastoreIter) start(c context.Context, query *datastore.Query) {
it.results = make(chan *Invocation)
it.done = make(chan struct{})
go func() {
defer close(it.results)
err := datastore.Run(c, query, func(obj *Invocation, cb datastore.CursorCB) error {
select {
case it.results <- obj:
return nil
case <-it.done:
return datastore.Stop
}
})
// Let 'next' and 'stop' know about the error. They look here if they
// receive 'nil' from the results channel (which happens if it is closed).
it.err = err
}()
} | [
"func",
"(",
"it",
"*",
"invDatastoreIter",
")",
"start",
"(",
"c",
"context",
".",
"Context",
",",
"query",
"*",
"datastore",
".",
"Query",
")",
"{",
"it",
".",
"results",
"=",
"make",
"(",
"chan",
"*",
"Invocation",
")",
"\n",
"it",
".",
"done",
... | // start initiates the query.
//
// The iterator is initially positioned before the first item, so that a call
// to 'next' will return the first item. | [
"start",
"initiates",
"the",
"query",
".",
"The",
"iterator",
"is",
"initially",
"positioned",
"before",
"the",
"first",
"item",
"so",
"that",
"a",
"call",
"to",
"next",
"will",
"return",
"the",
"first",
"item",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/invquery.go#L211-L228 |
7,888 | luci/luci-go | scheduler/appengine/engine/invquery.go | encodeInvCursor | func encodeInvCursor(cur *internal.InvocationsCursor) (string, error) {
if cur.LastScanned == 0 {
return "", nil
}
blob, err := proto.Marshal(cur)
if err != nil {
return "", err // must never actually happen
}
return base64.RawURLEncoding.EncodeToString(blob), nil
} | go | func encodeInvCursor(cur *internal.InvocationsCursor) (string, error) {
if cur.LastScanned == 0 {
return "", nil
}
blob, err := proto.Marshal(cur)
if err != nil {
return "", err // must never actually happen
}
return base64.RawURLEncoding.EncodeToString(blob), nil
} | [
"func",
"encodeInvCursor",
"(",
"cur",
"*",
"internal",
".",
"InvocationsCursor",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"cur",
".",
"LastScanned",
"==",
"0",
"{",
"return",
"\"",
"\"",
",",
"nil",
"\n",
"}",
"\n\n",
"blob",
",",
"err",
":... | // encodeInvCursor serializes the cursor to base64-encoded string. | [
"encodeInvCursor",
"serializes",
"the",
"cursor",
"to",
"base64",
"-",
"encoded",
"string",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/invquery.go#L336-L347 |
7,889 | luci/luci-go | scheduler/appengine/engine/utils.go | debugLog | func debugLog(c context.Context, str *string, format string, args ...interface{}) {
prefix := clock.Now(c).UTC().Format("[15:04:05.000] ")
*str += prefix + fmt.Sprintf(format+"\n", args...)
} | go | func debugLog(c context.Context, str *string, format string, args ...interface{}) {
prefix := clock.Now(c).UTC().Format("[15:04:05.000] ")
*str += prefix + fmt.Sprintf(format+"\n", args...)
} | [
"func",
"debugLog",
"(",
"c",
"context",
".",
"Context",
",",
"str",
"*",
"string",
",",
"format",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"prefix",
":=",
"clock",
".",
"Now",
"(",
"c",
")",
".",
"UTC",
"(",
")",
".",
"Form... | // debugLog mutates a string by appending a line to it. | [
"debugLog",
"mutates",
"a",
"string",
"by",
"appending",
"a",
"line",
"to",
"it",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/utils.go#L54-L57 |
7,890 | luci/luci-go | scheduler/appengine/engine/utils.go | equalSortedLists | func equalSortedLists(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i, s := range a {
if s != b[i] {
return false
}
}
return true
} | go | func equalSortedLists(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i, s := range a {
if s != b[i] {
return false
}
}
return true
} | [
"func",
"equalSortedLists",
"(",
"a",
",",
"b",
"[",
"]",
"string",
")",
"bool",
"{",
"if",
"len",
"(",
"a",
")",
"!=",
"len",
"(",
"b",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"for",
"i",
",",
"s",
":=",
"range",
"a",
"{",
"if",
"s",
... | // equalSortedLists returns true if lists contain the same sequence of strings. | [
"equalSortedLists",
"returns",
"true",
"if",
"lists",
"contain",
"the",
"same",
"sequence",
"of",
"strings",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/utils.go#L121-L131 |
7,891 | luci/luci-go | scheduler/appengine/engine/utils.go | equalInt64Lists | func equalInt64Lists(a, b []int64) bool {
if len(a) != len(b) {
return false
}
for i, s := range a {
if s != b[i] {
return false
}
}
return true
} | go | func equalInt64Lists(a, b []int64) bool {
if len(a) != len(b) {
return false
}
for i, s := range a {
if s != b[i] {
return false
}
}
return true
} | [
"func",
"equalInt64Lists",
"(",
"a",
",",
"b",
"[",
"]",
"int64",
")",
"bool",
"{",
"if",
"len",
"(",
"a",
")",
"!=",
"len",
"(",
"b",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"for",
"i",
",",
"s",
":=",
"range",
"a",
"{",
"if",
"s",
"... | // equalInt64Lists returns true if two lists of int64 are equal.
//
// Order is important. | [
"equalInt64Lists",
"returns",
"true",
"if",
"two",
"lists",
"of",
"int64",
"are",
"equal",
".",
"Order",
"is",
"important",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/utils.go#L136-L146 |
7,892 | luci/luci-go | scheduler/appengine/engine/utils.go | marshalTriggersList | func marshalTriggersList(t []*internal.Trigger) []byte {
if len(t) == 0 {
return nil
}
blob, err := proto.Marshal(&internal.TriggerList{Triggers: t})
if err != nil {
panic(err)
}
return blob
} | go | func marshalTriggersList(t []*internal.Trigger) []byte {
if len(t) == 0 {
return nil
}
blob, err := proto.Marshal(&internal.TriggerList{Triggers: t})
if err != nil {
panic(err)
}
return blob
} | [
"func",
"marshalTriggersList",
"(",
"t",
"[",
"]",
"*",
"internal",
".",
"Trigger",
")",
"[",
"]",
"byte",
"{",
"if",
"len",
"(",
"t",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"blob",
",",
"err",
":=",
"proto",
".",
"Marshal",
"(",
... | // marshalTriggersList serializes list of triggers.
//
// Panics on errors. | [
"marshalTriggersList",
"serializes",
"list",
"of",
"triggers",
".",
"Panics",
"on",
"errors",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/utils.go#L151-L160 |
7,893 | luci/luci-go | scheduler/appengine/engine/utils.go | unmarshalTriggersList | func unmarshalTriggersList(blob []byte) ([]*internal.Trigger, error) {
if len(blob) == 0 {
return nil, nil
}
list := internal.TriggerList{}
if err := proto.Unmarshal(blob, &list); err != nil {
return nil, err
}
return list.Triggers, nil
} | go | func unmarshalTriggersList(blob []byte) ([]*internal.Trigger, error) {
if len(blob) == 0 {
return nil, nil
}
list := internal.TriggerList{}
if err := proto.Unmarshal(blob, &list); err != nil {
return nil, err
}
return list.Triggers, nil
} | [
"func",
"unmarshalTriggersList",
"(",
"blob",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"*",
"internal",
".",
"Trigger",
",",
"error",
")",
"{",
"if",
"len",
"(",
"blob",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"list",
":="... | // unmarshalTriggersList deserializes list of triggers. | [
"unmarshalTriggersList",
"deserializes",
"list",
"of",
"triggers",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/utils.go#L163-L172 |
7,894 | luci/luci-go | scheduler/appengine/engine/utils.go | mutateTriggersList | func mutateTriggersList(blob *[]byte, cb func(*[]*internal.Trigger)) error {
list, err := unmarshalTriggersList(*blob)
if err != nil {
return err
}
cb(&list)
*blob = marshalTriggersList(list)
return nil
} | go | func mutateTriggersList(blob *[]byte, cb func(*[]*internal.Trigger)) error {
list, err := unmarshalTriggersList(*blob)
if err != nil {
return err
}
cb(&list)
*blob = marshalTriggersList(list)
return nil
} | [
"func",
"mutateTriggersList",
"(",
"blob",
"*",
"[",
"]",
"byte",
",",
"cb",
"func",
"(",
"*",
"[",
"]",
"*",
"internal",
".",
"Trigger",
")",
")",
"error",
"{",
"list",
",",
"err",
":=",
"unmarshalTriggersList",
"(",
"*",
"blob",
")",
"\n",
"if",
... | // mutateTriggersList deserializes the list, calls a callback, which modifies
// the list and serializes it back. | [
"mutateTriggersList",
"deserializes",
"the",
"list",
"calls",
"a",
"callback",
"which",
"modifies",
"the",
"list",
"and",
"serializes",
"it",
"back",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/utils.go#L176-L184 |
7,895 | luci/luci-go | scheduler/appengine/engine/utils.go | sortTriggers | func sortTriggers(t []*internal.Trigger) {
sort.Slice(t, func(i, j int) bool { return isTriggerOlder(t[i], t[j]) })
} | go | func sortTriggers(t []*internal.Trigger) {
sort.Slice(t, func(i, j int) bool { return isTriggerOlder(t[i], t[j]) })
} | [
"func",
"sortTriggers",
"(",
"t",
"[",
"]",
"*",
"internal",
".",
"Trigger",
")",
"{",
"sort",
".",
"Slice",
"(",
"t",
",",
"func",
"(",
"i",
",",
"j",
"int",
")",
"bool",
"{",
"return",
"isTriggerOlder",
"(",
"t",
"[",
"i",
"]",
",",
"t",
"[",... | // sortTriggers sorts the triggers by time, most recent last. | [
"sortTriggers",
"sorts",
"the",
"triggers",
"by",
"time",
"most",
"recent",
"last",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/utils.go#L187-L189 |
7,896 | luci/luci-go | scheduler/appengine/engine/utils.go | isTriggerOlder | func isTriggerOlder(t1, t2 *internal.Trigger) bool {
ts1 := google.TimeFromProto(t1.Created)
ts2 := google.TimeFromProto(t2.Created)
switch {
case ts1.After(ts2):
return false
case ts2.After(ts1):
return true
default: // equal timestamps
if t1.OrderInBatch != t2.OrderInBatch {
return t1.OrderInBatch < t2.OrderInBatch
}
return t1.Id < t2.Id
}
} | go | func isTriggerOlder(t1, t2 *internal.Trigger) bool {
ts1 := google.TimeFromProto(t1.Created)
ts2 := google.TimeFromProto(t2.Created)
switch {
case ts1.After(ts2):
return false
case ts2.After(ts1):
return true
default: // equal timestamps
if t1.OrderInBatch != t2.OrderInBatch {
return t1.OrderInBatch < t2.OrderInBatch
}
return t1.Id < t2.Id
}
} | [
"func",
"isTriggerOlder",
"(",
"t1",
",",
"t2",
"*",
"internal",
".",
"Trigger",
")",
"bool",
"{",
"ts1",
":=",
"google",
".",
"TimeFromProto",
"(",
"t1",
".",
"Created",
")",
"\n",
"ts2",
":=",
"google",
".",
"TimeFromProto",
"(",
"t2",
".",
"Created"... | // isTriggerOlder returns true if t1 is older than t2.
//
// Compares IDs in case of a tie. | [
"isTriggerOlder",
"returns",
"true",
"if",
"t1",
"is",
"older",
"than",
"t2",
".",
"Compares",
"IDs",
"in",
"case",
"of",
"a",
"tie",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/utils.go#L194-L208 |
7,897 | luci/luci-go | scheduler/appengine/engine/utils.go | marshalTimersList | func marshalTimersList(t []*internal.Timer) []byte {
if len(t) == 0 {
return nil
}
blob, err := proto.Marshal(&internal.TimerList{Timers: t})
if err != nil {
panic(err)
}
return blob
} | go | func marshalTimersList(t []*internal.Timer) []byte {
if len(t) == 0 {
return nil
}
blob, err := proto.Marshal(&internal.TimerList{Timers: t})
if err != nil {
panic(err)
}
return blob
} | [
"func",
"marshalTimersList",
"(",
"t",
"[",
"]",
"*",
"internal",
".",
"Timer",
")",
"[",
"]",
"byte",
"{",
"if",
"len",
"(",
"t",
")",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"blob",
",",
"err",
":=",
"proto",
".",
"Marshal",
"(",
"&... | // marshalTimersList serializes list of timers.
//
// Panics on errors. | [
"marshalTimersList",
"serializes",
"list",
"of",
"timers",
".",
"Panics",
"on",
"errors",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/utils.go#L213-L222 |
7,898 | luci/luci-go | scheduler/appengine/engine/utils.go | unmarshalTimersList | func unmarshalTimersList(blob []byte) ([]*internal.Timer, error) {
if len(blob) == 0 {
return nil, nil
}
list := internal.TimerList{}
if err := proto.Unmarshal(blob, &list); err != nil {
return nil, err
}
return list.Timers, nil
} | go | func unmarshalTimersList(blob []byte) ([]*internal.Timer, error) {
if len(blob) == 0 {
return nil, nil
}
list := internal.TimerList{}
if err := proto.Unmarshal(blob, &list); err != nil {
return nil, err
}
return list.Timers, nil
} | [
"func",
"unmarshalTimersList",
"(",
"blob",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"*",
"internal",
".",
"Timer",
",",
"error",
")",
"{",
"if",
"len",
"(",
"blob",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"list",
":=",
... | // unmarshalTimersList deserializes list of timers. | [
"unmarshalTimersList",
"deserializes",
"list",
"of",
"timers",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/utils.go#L225-L234 |
7,899 | luci/luci-go | scheduler/appengine/engine/utils.go | mutateTimersList | func mutateTimersList(blob *[]byte, cb func(*[]*internal.Timer)) error {
list, err := unmarshalTimersList(*blob)
if err != nil {
return err
}
cb(&list)
*blob = marshalTimersList(list)
return nil
} | go | func mutateTimersList(blob *[]byte, cb func(*[]*internal.Timer)) error {
list, err := unmarshalTimersList(*blob)
if err != nil {
return err
}
cb(&list)
*blob = marshalTimersList(list)
return nil
} | [
"func",
"mutateTimersList",
"(",
"blob",
"*",
"[",
"]",
"byte",
",",
"cb",
"func",
"(",
"*",
"[",
"]",
"*",
"internal",
".",
"Timer",
")",
")",
"error",
"{",
"list",
",",
"err",
":=",
"unmarshalTimersList",
"(",
"*",
"blob",
")",
"\n",
"if",
"err",... | // mutateTimersList deserializes the list, calls a callback, which modifies
// the list and serializes it back. | [
"mutateTimersList",
"deserializes",
"the",
"list",
"calls",
"a",
"callback",
"which",
"modifies",
"the",
"list",
"and",
"serializes",
"it",
"back",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/utils.go#L238-L246 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.