id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
9,400
luci/luci-go
luci_notify/notify/pubsub.go
extractBuild
func extractBuild(c context.Context, r *http.Request) (*Build, error) { // sent by pubsub. // This struct is just convenient for unwrapping the json message var msg struct { Message struct { Data []byte } Attributes map[string]interface{} } if err := json.NewDecoder(r.Body).Decode(&msg); err != nil { return nil, errors.Annotate(err, "could not decode message").Err() } if v, ok := msg.Attributes["version"].(string); ok && v != "v1" { // Ignore v2 pubsub messages. TODO(nodir): use v2. return nil, nil } var message struct { Build bbv1.ApiCommonBuildMessage Hostname string } switch err := json.Unmarshal(msg.Message.Data, &message); { case err != nil: return nil, errors.Annotate(err, "could not parse pubsub message data").Err() case !strings.HasPrefix(message.Build.Bucket, "luci."): logging.Infof(c, "Received build that isn't part of LUCI, ignoring...") return nil, nil case message.Build.Status != bbv1.StatusCompleted: logging.Infof(c, "Received build that hasn't completed yet, ignoring...") return nil, nil } buildsClient, err := newBuildsClient(c, message.Hostname, message.Build.Project) if err != nil { return nil, err } logging.Infof(c, "fetching build %d", message.Build.Id) res, err := buildsClient.GetBuild(c, &buildbucketpb.GetBuildRequest{ Id: message.Build.Id, Fields: buildFieldMask, }) switch { case status.Code(err) == codes.NotFound: logging.Warningf(c, "no access to build %d", message.Build.Id) return nil, nil case err != nil: err = grpcutil.WrapIfTransient(err) err = errors.Annotate(err, "could not fetch buildbucket build %d", message.Build.Id).Err() return nil, err } emails, err := extractEmailNotifyValues(res, message.Build.ParametersJson) if err != nil { return nil, errors.Annotate(err, "could not decode email_notify").Err() } return &Build{ Build: *res, EmailNotify: emails, }, nil }
go
func extractBuild(c context.Context, r *http.Request) (*Build, error) { // sent by pubsub. // This struct is just convenient for unwrapping the json message var msg struct { Message struct { Data []byte } Attributes map[string]interface{} } if err := json.NewDecoder(r.Body).Decode(&msg); err != nil { return nil, errors.Annotate(err, "could not decode message").Err() } if v, ok := msg.Attributes["version"].(string); ok && v != "v1" { // Ignore v2 pubsub messages. TODO(nodir): use v2. return nil, nil } var message struct { Build bbv1.ApiCommonBuildMessage Hostname string } switch err := json.Unmarshal(msg.Message.Data, &message); { case err != nil: return nil, errors.Annotate(err, "could not parse pubsub message data").Err() case !strings.HasPrefix(message.Build.Bucket, "luci."): logging.Infof(c, "Received build that isn't part of LUCI, ignoring...") return nil, nil case message.Build.Status != bbv1.StatusCompleted: logging.Infof(c, "Received build that hasn't completed yet, ignoring...") return nil, nil } buildsClient, err := newBuildsClient(c, message.Hostname, message.Build.Project) if err != nil { return nil, err } logging.Infof(c, "fetching build %d", message.Build.Id) res, err := buildsClient.GetBuild(c, &buildbucketpb.GetBuildRequest{ Id: message.Build.Id, Fields: buildFieldMask, }) switch { case status.Code(err) == codes.NotFound: logging.Warningf(c, "no access to build %d", message.Build.Id) return nil, nil case err != nil: err = grpcutil.WrapIfTransient(err) err = errors.Annotate(err, "could not fetch buildbucket build %d", message.Build.Id).Err() return nil, err } emails, err := extractEmailNotifyValues(res, message.Build.ParametersJson) if err != nil { return nil, errors.Annotate(err, "could not decode email_notify").Err() } return &Build{ Build: *res, EmailNotify: emails, }, nil }
[ "func", "extractBuild", "(", "c", "context", ".", "Context", ",", "r", "*", "http", ".", "Request", ")", "(", "*", "Build", ",", "error", ")", "{", "// sent by pubsub.", "// This struct is just convenient for unwrapping the json message", "var", "msg", "struct", "{", "Message", "struct", "{", "Data", "[", "]", "byte", "\n", "}", "\n", "Attributes", "map", "[", "string", "]", "interface", "{", "}", "\n", "}", "\n", "if", "err", ":=", "json", ".", "NewDecoder", "(", "r", ".", "Body", ")", ".", "Decode", "(", "&", "msg", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "if", "v", ",", "ok", ":=", "msg", ".", "Attributes", "[", "\"", "\"", "]", ".", "(", "string", ")", ";", "ok", "&&", "v", "!=", "\"", "\"", "{", "// Ignore v2 pubsub messages. TODO(nodir): use v2.", "return", "nil", ",", "nil", "\n", "}", "\n", "var", "message", "struct", "{", "Build", "bbv1", ".", "ApiCommonBuildMessage", "\n", "Hostname", "string", "\n", "}", "\n", "switch", "err", ":=", "json", ".", "Unmarshal", "(", "msg", ".", "Message", ".", "Data", ",", "&", "message", ")", ";", "{", "case", "err", "!=", "nil", ":", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "case", "!", "strings", ".", "HasPrefix", "(", "message", ".", "Build", ".", "Bucket", ",", "\"", "\"", ")", ":", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ")", "\n", "return", "nil", ",", "nil", "\n", "case", "message", ".", "Build", ".", "Status", "!=", "bbv1", ".", "StatusCompleted", ":", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ")", "\n", "return", "nil", ",", "nil", "\n", "}", "\n\n", "buildsClient", ",", "err", ":=", "newBuildsClient", "(", "c", ",", "message", ".", "Hostname", ",", "message", ".", "Build", ".", "Project", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "message", ".", "Build", ".", "Id", ")", "\n", "res", ",", "err", ":=", "buildsClient", ".", "GetBuild", "(", "c", ",", "&", "buildbucketpb", ".", "GetBuildRequest", "{", "Id", ":", "message", ".", "Build", ".", "Id", ",", "Fields", ":", "buildFieldMask", ",", "}", ")", "\n", "switch", "{", "case", "status", ".", "Code", "(", "err", ")", "==", "codes", ".", "NotFound", ":", "logging", ".", "Warningf", "(", "c", ",", "\"", "\"", ",", "message", ".", "Build", ".", "Id", ")", "\n", "return", "nil", ",", "nil", "\n", "case", "err", "!=", "nil", ":", "err", "=", "grpcutil", ".", "WrapIfTransient", "(", "err", ")", "\n", "err", "=", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "message", ".", "Build", ".", "Id", ")", ".", "Err", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "emails", ",", "err", ":=", "extractEmailNotifyValues", "(", "res", ",", "message", ".", "Build", ".", "ParametersJson", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "return", "&", "Build", "{", "Build", ":", "*", "res", ",", "EmailNotify", ":", "emails", ",", "}", ",", "nil", "\n", "}" ]
// extractBuild constructs a Build from the PubSub HTTP request.
[ "extractBuild", "constructs", "a", "Build", "from", "the", "PubSub", "HTTP", "request", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/notify/pubsub.go#L367-L428
9,401
luci/luci-go
cipd/appengine/impl/repo/acl.go
rolesInPrefix
func rolesInPrefix(c context.Context, metas []*api.PrefixMetadata) ([]api.Role, error) { roles := roleSet() for _, meta := range metas { for _, acl := range meta.Acls { if _, ok := roles[acl.Role]; ok { continue // seen this role already } switch yes, err := isInACL(c, acl); { case err != nil: return nil, err case yes: // Add acl.Role and all roles implied by it to 'roles' set. for _, r := range impliedRoles[acl.Role] { roles[r] = struct{}{} } } } } // Arrange the result in the order of Role enum definition. out := make([]api.Role, 0, len(roles)) for r := api.Role_READER; r <= api.Role_OWNER; r++ { if _, ok := roles[r]; ok { out = append(out, r) } } return out, nil }
go
func rolesInPrefix(c context.Context, metas []*api.PrefixMetadata) ([]api.Role, error) { roles := roleSet() for _, meta := range metas { for _, acl := range meta.Acls { if _, ok := roles[acl.Role]; ok { continue // seen this role already } switch yes, err := isInACL(c, acl); { case err != nil: return nil, err case yes: // Add acl.Role and all roles implied by it to 'roles' set. for _, r := range impliedRoles[acl.Role] { roles[r] = struct{}{} } } } } // Arrange the result in the order of Role enum definition. out := make([]api.Role, 0, len(roles)) for r := api.Role_READER; r <= api.Role_OWNER; r++ { if _, ok := roles[r]; ok { out = append(out, r) } } return out, nil }
[ "func", "rolesInPrefix", "(", "c", "context", ".", "Context", ",", "metas", "[", "]", "*", "api", ".", "PrefixMetadata", ")", "(", "[", "]", "api", ".", "Role", ",", "error", ")", "{", "roles", ":=", "roleSet", "(", ")", "\n", "for", "_", ",", "meta", ":=", "range", "metas", "{", "for", "_", ",", "acl", ":=", "range", "meta", ".", "Acls", "{", "if", "_", ",", "ok", ":=", "roles", "[", "acl", ".", "Role", "]", ";", "ok", "{", "continue", "// seen this role already", "\n", "}", "\n", "switch", "yes", ",", "err", ":=", "isInACL", "(", "c", ",", "acl", ")", ";", "{", "case", "err", "!=", "nil", ":", "return", "nil", ",", "err", "\n", "case", "yes", ":", "// Add acl.Role and all roles implied by it to 'roles' set.", "for", "_", ",", "r", ":=", "range", "impliedRoles", "[", "acl", ".", "Role", "]", "{", "roles", "[", "r", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// Arrange the result in the order of Role enum definition.", "out", ":=", "make", "(", "[", "]", "api", ".", "Role", ",", "0", ",", "len", "(", "roles", ")", ")", "\n", "for", "r", ":=", "api", ".", "Role_READER", ";", "r", "<=", "api", ".", "Role_OWNER", ";", "r", "++", "{", "if", "_", ",", "ok", ":=", "roles", "[", "r", "]", ";", "ok", "{", "out", "=", "append", "(", "out", ",", "r", ")", "\n", "}", "\n", "}", "\n", "return", "out", ",", "nil", "\n", "}" ]
// rolesInPrefix returns a union of roles the caller has in given supplied // PrefixMetadata objects. // // It understands the role inheritance defined by impliedRoles map. // // Returns only transient errors.
[ "rolesInPrefix", "returns", "a", "union", "of", "roles", "the", "caller", "has", "in", "given", "supplied", "PrefixMetadata", "objects", ".", "It", "understands", "the", "role", "inheritance", "defined", "by", "impliedRoles", "map", ".", "Returns", "only", "transient", "errors", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/acl.go#L121-L148
9,402
luci/luci-go
cipd/appengine/impl/repo/acl.go
isInACL
func isInACL(c context.Context, acl *api.PrefixMetadata_ACL) (bool, error) { caller := string(auth.CurrentIdentity(c)) // e.g. "user:[email protected]" var groups []string for _, p := range acl.Principals { if p == caller { return true, nil // the caller was specified in ACLs explicitly } if s := strings.SplitN(p, ":", 2); len(s) == 2 && s[0] == "group" { groups = append(groups, s[1]) } } yes, err := auth.IsMember(c, groups...) if err != nil { return false, errors.Annotate(err, "failed to check group memberships when checking ACLs").Err() } return yes, nil }
go
func isInACL(c context.Context, acl *api.PrefixMetadata_ACL) (bool, error) { caller := string(auth.CurrentIdentity(c)) // e.g. "user:[email protected]" var groups []string for _, p := range acl.Principals { if p == caller { return true, nil // the caller was specified in ACLs explicitly } if s := strings.SplitN(p, ":", 2); len(s) == 2 && s[0] == "group" { groups = append(groups, s[1]) } } yes, err := auth.IsMember(c, groups...) if err != nil { return false, errors.Annotate(err, "failed to check group memberships when checking ACLs").Err() } return yes, nil }
[ "func", "isInACL", "(", "c", "context", ".", "Context", ",", "acl", "*", "api", ".", "PrefixMetadata_ACL", ")", "(", "bool", ",", "error", ")", "{", "caller", ":=", "string", "(", "auth", ".", "CurrentIdentity", "(", "c", ")", ")", "// e.g. \"user:[email protected]\"", "\n\n", "var", "groups", "[", "]", "string", "\n", "for", "_", ",", "p", ":=", "range", "acl", ".", "Principals", "{", "if", "p", "==", "caller", "{", "return", "true", ",", "nil", "// the caller was specified in ACLs explicitly", "\n", "}", "\n", "if", "s", ":=", "strings", ".", "SplitN", "(", "p", ",", "\"", "\"", ",", "2", ")", ";", "len", "(", "s", ")", "==", "2", "&&", "s", "[", "0", "]", "==", "\"", "\"", "{", "groups", "=", "append", "(", "groups", ",", "s", "[", "1", "]", ")", "\n", "}", "\n", "}", "\n\n", "yes", ",", "err", ":=", "auth", ".", "IsMember", "(", "c", ",", "groups", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "yes", ",", "nil", "\n", "}" ]
// isInACL is true if the caller is in the given access control list.
[ "isInACL", "is", "true", "if", "the", "caller", "is", "in", "the", "given", "access", "control", "list", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/acl.go#L151-L169
9,403
luci/luci-go
logdog/common/viewer/url.go
GetURL
func GetURL(host string, project types.ProjectName, paths ...types.StreamPath) string { values := make([]string, len(paths)) for i, p := range paths { values[i] = fmt.Sprintf("%s/%s", project, p) } u := url.URL{ Scheme: "https", Host: host, } if len(values) == 1 { u.Path = "logs/" + values[0] } else { u.Path = "v/" u.RawQuery = url.Values{ "s": values, }.Encode() } return u.String() }
go
func GetURL(host string, project types.ProjectName, paths ...types.StreamPath) string { values := make([]string, len(paths)) for i, p := range paths { values[i] = fmt.Sprintf("%s/%s", project, p) } u := url.URL{ Scheme: "https", Host: host, } if len(values) == 1 { u.Path = "logs/" + values[0] } else { u.Path = "v/" u.RawQuery = url.Values{ "s": values, }.Encode() } return u.String() }
[ "func", "GetURL", "(", "host", "string", ",", "project", "types", ".", "ProjectName", ",", "paths", "...", "types", ".", "StreamPath", ")", "string", "{", "values", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "paths", ")", ")", "\n", "for", "i", ",", "p", ":=", "range", "paths", "{", "values", "[", "i", "]", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "project", ",", "p", ")", "\n", "}", "\n", "u", ":=", "url", ".", "URL", "{", "Scheme", ":", "\"", "\"", ",", "Host", ":", "host", ",", "}", "\n", "if", "len", "(", "values", ")", "==", "1", "{", "u", ".", "Path", "=", "\"", "\"", "+", "values", "[", "0", "]", "\n", "}", "else", "{", "u", ".", "Path", "=", "\"", "\"", "\n", "u", ".", "RawQuery", "=", "url", ".", "Values", "{", "\"", "\"", ":", "values", ",", "}", ".", "Encode", "(", ")", "\n", "}", "\n", "return", "u", ".", "String", "(", ")", "\n", "}" ]
// GetURL generates a LogDog app viewer URL for the specified streams. // Uses the plain-text endpoint for single stream paths, and the client-side endpoint for multi-stream paths.
[ "GetURL", "generates", "a", "LogDog", "app", "viewer", "URL", "for", "the", "specified", "streams", ".", "Uses", "the", "plain", "-", "text", "endpoint", "for", "single", "stream", "paths", "and", "the", "client", "-", "side", "endpoint", "for", "multi", "-", "stream", "paths", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/viewer/url.go#L28-L46
9,404
luci/luci-go
gce/cmd/agent/assets.gen.go
GetAssetSHA256
func GetAssetSHA256(name string) []byte { data := fileSha256s[name] if data == nil { return nil } return append([]byte(nil), data...) }
go
func GetAssetSHA256(name string) []byte { data := fileSha256s[name] if data == nil { return nil } return append([]byte(nil), data...) }
[ "func", "GetAssetSHA256", "(", "name", "string", ")", "[", "]", "byte", "{", "data", ":=", "fileSha256s", "[", "name", "]", "\n", "if", "data", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "append", "(", "[", "]", "byte", "(", "nil", ")", ",", "data", "...", ")", "\n", "}" ]
// GetAssetSHA256 returns the asset checksum. Returns nil if no such asset // exists.
[ "GetAssetSHA256", "returns", "the", "asset", "checksum", ".", "Returns", "nil", "if", "no", "such", "asset", "exists", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/cmd/agent/assets.gen.go#L35-L41
9,405
luci/luci-go
gce/cmd/agent/assets.gen.go
Assets
func Assets() map[string]string { cpy := make(map[string]string, len(files)) for k, v := range files { cpy[k] = v } return cpy }
go
func Assets() map[string]string { cpy := make(map[string]string, len(files)) for k, v := range files { cpy[k] = v } return cpy }
[ "func", "Assets", "(", ")", "map", "[", "string", "]", "string", "{", "cpy", ":=", "make", "(", "map", "[", "string", "]", "string", ",", "len", "(", "files", ")", ")", "\n", "for", "k", ",", "v", ":=", "range", "files", "{", "cpy", "[", "k", "]", "=", "v", "\n", "}", "\n", "return", "cpy", "\n", "}" ]
// Assets returns a map of all assets.
[ "Assets", "returns", "a", "map", "of", "all", "assets", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/cmd/agent/assets.gen.go#L44-L50
9,406
luci/luci-go
machine-db/appengine/rpc/vlans.go
ListVLANs
func (*Service) ListVLANs(c context.Context, req *crimson.ListVLANsRequest) (*crimson.ListVLANsResponse, error) { ids := make(map[int64]struct{}, len(req.Ids)) for _, id := range req.Ids { ids[id] = struct{}{} } vlans, err := listVLANs(c, ids, stringset.NewFromSlice(req.Aliases...)) if err != nil { return nil, err } return &crimson.ListVLANsResponse{ Vlans: vlans, }, nil }
go
func (*Service) ListVLANs(c context.Context, req *crimson.ListVLANsRequest) (*crimson.ListVLANsResponse, error) { ids := make(map[int64]struct{}, len(req.Ids)) for _, id := range req.Ids { ids[id] = struct{}{} } vlans, err := listVLANs(c, ids, stringset.NewFromSlice(req.Aliases...)) if err != nil { return nil, err } return &crimson.ListVLANsResponse{ Vlans: vlans, }, nil }
[ "func", "(", "*", "Service", ")", "ListVLANs", "(", "c", "context", ".", "Context", ",", "req", "*", "crimson", ".", "ListVLANsRequest", ")", "(", "*", "crimson", ".", "ListVLANsResponse", ",", "error", ")", "{", "ids", ":=", "make", "(", "map", "[", "int64", "]", "struct", "{", "}", ",", "len", "(", "req", ".", "Ids", ")", ")", "\n", "for", "_", ",", "id", ":=", "range", "req", ".", "Ids", "{", "ids", "[", "id", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "vlans", ",", "err", ":=", "listVLANs", "(", "c", ",", "ids", ",", "stringset", ".", "NewFromSlice", "(", "req", ".", "Aliases", "...", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "crimson", ".", "ListVLANsResponse", "{", "Vlans", ":", "vlans", ",", "}", ",", "nil", "\n", "}" ]
// ListVLANs handles a request to retrieve VLANs.
[ "ListVLANs", "handles", "a", "request", "to", "retrieve", "VLANs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/vlans.go#L28-L40
9,407
luci/luci-go
machine-db/appengine/rpc/vlans.go
listVLANs
func listVLANs(c context.Context, ids map[int64]struct{}, aliases stringset.Set) ([]*crimson.VLAN, error) { db := database.Get(c) rows, err := db.QueryContext(c, ` SELECT id, alias, state, cidr_block FROM vlans `) if err != nil { return nil, errors.Annotate(err, "failed to fetch VLANs").Err() } defer rows.Close() var vlans []*crimson.VLAN for rows.Next() { vlan := &crimson.VLAN{} if err = rows.Scan(&vlan.Id, &vlan.Alias, &vlan.State, &vlan.CidrBlock); err != nil { return nil, errors.Annotate(err, "failed to fetch VLAN").Err() } // VLAN may match either the given IDs or aliases. // If both IDs and aliases are empty, consider all VLANs to match. if _, ok := ids[vlan.Id]; ok || aliases.Has(vlan.Alias) || (len(ids) == 0 && aliases.Len() == 0) { vlans = append(vlans, vlan) } } return vlans, nil }
go
func listVLANs(c context.Context, ids map[int64]struct{}, aliases stringset.Set) ([]*crimson.VLAN, error) { db := database.Get(c) rows, err := db.QueryContext(c, ` SELECT id, alias, state, cidr_block FROM vlans `) if err != nil { return nil, errors.Annotate(err, "failed to fetch VLANs").Err() } defer rows.Close() var vlans []*crimson.VLAN for rows.Next() { vlan := &crimson.VLAN{} if err = rows.Scan(&vlan.Id, &vlan.Alias, &vlan.State, &vlan.CidrBlock); err != nil { return nil, errors.Annotate(err, "failed to fetch VLAN").Err() } // VLAN may match either the given IDs or aliases. // If both IDs and aliases are empty, consider all VLANs to match. if _, ok := ids[vlan.Id]; ok || aliases.Has(vlan.Alias) || (len(ids) == 0 && aliases.Len() == 0) { vlans = append(vlans, vlan) } } return vlans, nil }
[ "func", "listVLANs", "(", "c", "context", ".", "Context", ",", "ids", "map", "[", "int64", "]", "struct", "{", "}", ",", "aliases", "stringset", ".", "Set", ")", "(", "[", "]", "*", "crimson", ".", "VLAN", ",", "error", ")", "{", "db", ":=", "database", ".", "Get", "(", "c", ")", "\n", "rows", ",", "err", ":=", "db", ".", "QueryContext", "(", "c", ",", "`\n\t\tSELECT id, alias, state, cidr_block\n\t\tFROM vlans\n\t`", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "defer", "rows", ".", "Close", "(", ")", "\n\n", "var", "vlans", "[", "]", "*", "crimson", ".", "VLAN", "\n", "for", "rows", ".", "Next", "(", ")", "{", "vlan", ":=", "&", "crimson", ".", "VLAN", "{", "}", "\n", "if", "err", "=", "rows", ".", "Scan", "(", "&", "vlan", ".", "Id", ",", "&", "vlan", ".", "Alias", ",", "&", "vlan", ".", "State", ",", "&", "vlan", ".", "CidrBlock", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "// VLAN may match either the given IDs or aliases.", "// If both IDs and aliases are empty, consider all VLANs to match.", "if", "_", ",", "ok", ":=", "ids", "[", "vlan", ".", "Id", "]", ";", "ok", "||", "aliases", ".", "Has", "(", "vlan", ".", "Alias", ")", "||", "(", "len", "(", "ids", ")", "==", "0", "&&", "aliases", ".", "Len", "(", ")", "==", "0", ")", "{", "vlans", "=", "append", "(", "vlans", ",", "vlan", ")", "\n", "}", "\n", "}", "\n", "return", "vlans", ",", "nil", "\n", "}" ]
// listVLANs returns a slice of VLANs in the database. // VLANs matching either a given ID or a given alias are returned. Specify no IDs or aliases to return all VLANs.
[ "listVLANs", "returns", "a", "slice", "of", "VLANs", "in", "the", "database", ".", "VLANs", "matching", "either", "a", "given", "ID", "or", "a", "given", "alias", "are", "returned", ".", "Specify", "no", "IDs", "or", "aliases", "to", "return", "all", "VLANs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/vlans.go#L44-L68
9,408
luci/luci-go
milo/frontend/view_build.go
handleLUCIBuild
func handleLUCIBuild(c *router.Context) error { bucket := c.Params.ByName("bucket") buildername := c.Params.ByName("builder") numberOrId := c.Params.ByName("numberOrId") forceBlamelist := c.Request.FormValue("blamelist") != "" if _, v2Bucket := deprecated.BucketNameToV2(bucket); v2Bucket != "" { // Params bucket is a v1 bucket, so call the legacy endpoint. return handleLUCIBuildLegacy(c, bucket, buildername, numberOrId) } // TODO(hinoka): Once v2 is default, redirect v1 bucketnames to v2 bucketname URLs. br := buildbucketpb.GetBuildRequest{} if strings.HasPrefix(numberOrId, "b") { id, err := strconv.ParseInt(numberOrId[1:], 10, 64) if err != nil { return errors.Annotate(err, "bad build id").Tag(grpcutil.InvalidArgumentTag).Err() } br.Id = int64(id) } else { number, err := strconv.Atoi(numberOrId) if err != nil { return errors.Annotate(err, "bad build number").Tag(grpcutil.InvalidArgumentTag).Err() } br.BuildNumber = int32(number) br.Builder = &buildbucketpb.BuilderID{ Project: c.Params.ByName("project"), Bucket: bucket, Builder: buildername, } } bp, err := buildbucket.GetBuildPage(c, br, forceBlamelist) return renderBuild(c, bp, err) }
go
func handleLUCIBuild(c *router.Context) error { bucket := c.Params.ByName("bucket") buildername := c.Params.ByName("builder") numberOrId := c.Params.ByName("numberOrId") forceBlamelist := c.Request.FormValue("blamelist") != "" if _, v2Bucket := deprecated.BucketNameToV2(bucket); v2Bucket != "" { // Params bucket is a v1 bucket, so call the legacy endpoint. return handleLUCIBuildLegacy(c, bucket, buildername, numberOrId) } // TODO(hinoka): Once v2 is default, redirect v1 bucketnames to v2 bucketname URLs. br := buildbucketpb.GetBuildRequest{} if strings.HasPrefix(numberOrId, "b") { id, err := strconv.ParseInt(numberOrId[1:], 10, 64) if err != nil { return errors.Annotate(err, "bad build id").Tag(grpcutil.InvalidArgumentTag).Err() } br.Id = int64(id) } else { number, err := strconv.Atoi(numberOrId) if err != nil { return errors.Annotate(err, "bad build number").Tag(grpcutil.InvalidArgumentTag).Err() } br.BuildNumber = int32(number) br.Builder = &buildbucketpb.BuilderID{ Project: c.Params.ByName("project"), Bucket: bucket, Builder: buildername, } } bp, err := buildbucket.GetBuildPage(c, br, forceBlamelist) return renderBuild(c, bp, err) }
[ "func", "handleLUCIBuild", "(", "c", "*", "router", ".", "Context", ")", "error", "{", "bucket", ":=", "c", ".", "Params", ".", "ByName", "(", "\"", "\"", ")", "\n", "buildername", ":=", "c", ".", "Params", ".", "ByName", "(", "\"", "\"", ")", "\n", "numberOrId", ":=", "c", ".", "Params", ".", "ByName", "(", "\"", "\"", ")", "\n", "forceBlamelist", ":=", "c", ".", "Request", ".", "FormValue", "(", "\"", "\"", ")", "!=", "\"", "\"", "\n\n", "if", "_", ",", "v2Bucket", ":=", "deprecated", ".", "BucketNameToV2", "(", "bucket", ")", ";", "v2Bucket", "!=", "\"", "\"", "{", "// Params bucket is a v1 bucket, so call the legacy endpoint.", "return", "handleLUCIBuildLegacy", "(", "c", ",", "bucket", ",", "buildername", ",", "numberOrId", ")", "\n", "}", "\n\n", "// TODO(hinoka): Once v2 is default, redirect v1 bucketnames to v2 bucketname URLs.", "br", ":=", "buildbucketpb", ".", "GetBuildRequest", "{", "}", "\n", "if", "strings", ".", "HasPrefix", "(", "numberOrId", ",", "\"", "\"", ")", "{", "id", ",", "err", ":=", "strconv", ".", "ParseInt", "(", "numberOrId", "[", "1", ":", "]", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Tag", "(", "grpcutil", ".", "InvalidArgumentTag", ")", ".", "Err", "(", ")", "\n", "}", "\n", "br", ".", "Id", "=", "int64", "(", "id", ")", "\n", "}", "else", "{", "number", ",", "err", ":=", "strconv", ".", "Atoi", "(", "numberOrId", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Tag", "(", "grpcutil", ".", "InvalidArgumentTag", ")", ".", "Err", "(", ")", "\n", "}", "\n", "br", ".", "BuildNumber", "=", "int32", "(", "number", ")", "\n", "br", ".", "Builder", "=", "&", "buildbucketpb", ".", "BuilderID", "{", "Project", ":", "c", ".", "Params", ".", "ByName", "(", "\"", "\"", ")", ",", "Bucket", ":", "bucket", ",", "Builder", ":", "buildername", ",", "}", "\n", "}", "\n\n", "bp", ",", "err", ":=", "buildbucket", ".", "GetBuildPage", "(", "c", ",", "br", ",", "forceBlamelist", ")", "\n", "return", "renderBuild", "(", "c", ",", "bp", ",", "err", ")", "\n", "}" ]
// handleLUCIBuild renders a LUCI build.
[ "handleLUCIBuild", "renders", "a", "LUCI", "build", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/view_build.go#L48-L82
9,409
luci/luci-go
milo/frontend/view_build.go
renderBuild
func renderBuild(c *router.Context, bp *ui.BuildPage, err error) error { if err != nil { return err } bp.StepDisplayPref = getStepDisplayPrefCookie(c) templates.MustRender(c.Context, c.Writer, "pages/build.html", templates.Args{ "BuildPage": bp, }) return nil }
go
func renderBuild(c *router.Context, bp *ui.BuildPage, err error) error { if err != nil { return err } bp.StepDisplayPref = getStepDisplayPrefCookie(c) templates.MustRender(c.Context, c.Writer, "pages/build.html", templates.Args{ "BuildPage": bp, }) return nil }
[ "func", "renderBuild", "(", "c", "*", "router", ".", "Context", ",", "bp", "*", "ui", ".", "BuildPage", ",", "err", "error", ")", "error", "{", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "bp", ".", "StepDisplayPref", "=", "getStepDisplayPrefCookie", "(", "c", ")", "\n\n", "templates", ".", "MustRender", "(", "c", ".", "Context", ",", "c", ".", "Writer", ",", "\"", "\"", ",", "templates", ".", "Args", "{", "\"", "\"", ":", "bp", ",", "}", ")", "\n", "return", "nil", "\n", "}" ]
// renderBuild is a shortcut for rendering build or returning err if it is not nil.
[ "renderBuild", "is", "a", "shortcut", "for", "rendering", "build", "or", "returning", "err", "if", "it", "is", "not", "nil", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/view_build.go#L85-L96
9,410
luci/luci-go
server/auth/openid/json_web_keys.go
NewJSONWebKeySet
func NewJSONWebKeySet(parsed *JSONWebKeySetStruct) (*JSONWebKeySet, error) { // Pick keys used to verify RS256 signatures. keys := make(map[string]rsa.PublicKey, len(parsed.Keys)) for _, k := range parsed.Keys { if k.Kty != "RSA" || k.Alg != "RS256" || k.Use != "sig" { continue // not an RSA public key } if k.Kid == "" { // Per spec 'kid' field is optional, but providers we support return them, // so make them required to keep the code simpler. return nil, fmt.Errorf("bad JSON web key - missing 'kid' field") } pub, err := decodeRSAPublicKey(k.N, k.E) if err != nil { return nil, fmt.Errorf("failed to parse RSA public key in JSON web key - %s", err) } keys[k.Kid] = pub } if len(keys) == 0 { return nil, fmt.Errorf("the JSON web key doc didn't have any signing keys") } return &JSONWebKeySet{keys: keys}, nil }
go
func NewJSONWebKeySet(parsed *JSONWebKeySetStruct) (*JSONWebKeySet, error) { // Pick keys used to verify RS256 signatures. keys := make(map[string]rsa.PublicKey, len(parsed.Keys)) for _, k := range parsed.Keys { if k.Kty != "RSA" || k.Alg != "RS256" || k.Use != "sig" { continue // not an RSA public key } if k.Kid == "" { // Per spec 'kid' field is optional, but providers we support return them, // so make them required to keep the code simpler. return nil, fmt.Errorf("bad JSON web key - missing 'kid' field") } pub, err := decodeRSAPublicKey(k.N, k.E) if err != nil { return nil, fmt.Errorf("failed to parse RSA public key in JSON web key - %s", err) } keys[k.Kid] = pub } if len(keys) == 0 { return nil, fmt.Errorf("the JSON web key doc didn't have any signing keys") } return &JSONWebKeySet{keys: keys}, nil }
[ "func", "NewJSONWebKeySet", "(", "parsed", "*", "JSONWebKeySetStruct", ")", "(", "*", "JSONWebKeySet", ",", "error", ")", "{", "// Pick keys used to verify RS256 signatures.", "keys", ":=", "make", "(", "map", "[", "string", "]", "rsa", ".", "PublicKey", ",", "len", "(", "parsed", ".", "Keys", ")", ")", "\n", "for", "_", ",", "k", ":=", "range", "parsed", ".", "Keys", "{", "if", "k", ".", "Kty", "!=", "\"", "\"", "||", "k", ".", "Alg", "!=", "\"", "\"", "||", "k", ".", "Use", "!=", "\"", "\"", "{", "continue", "// not an RSA public key", "\n", "}", "\n", "if", "k", ".", "Kid", "==", "\"", "\"", "{", "// Per spec 'kid' field is optional, but providers we support return them,", "// so make them required to keep the code simpler.", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "pub", ",", "err", ":=", "decodeRSAPublicKey", "(", "k", ".", "N", ",", "k", ".", "E", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "keys", "[", "k", ".", "Kid", "]", "=", "pub", "\n", "}", "\n\n", "if", "len", "(", "keys", ")", "==", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "&", "JSONWebKeySet", "{", "keys", ":", "keys", "}", ",", "nil", "\n", "}" ]
// NewJSONWebKeySet makes the keyset from raw JSON Web Key set struct.
[ "NewJSONWebKeySet", "makes", "the", "keyset", "from", "raw", "JSON", "Web", "Key", "set", "struct", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/openid/json_web_keys.go#L60-L84
9,411
luci/luci-go
server/auth/openid/json_web_keys.go
VerifyJWT
func (k *JSONWebKeySet) VerifyJWT(jwt string) (body []byte, err error) { chunks := strings.Split(jwt, ".") if len(chunks) != 3 { return nil, fmt.Errorf("bad JWT - expected 3 components separated by '.'") } // Check the header, grab the corresponding public key. var hdr struct { Alg string `json:"alg"` Kid string `json:"kid"` } if err := unmarshalB64JSON(chunks[0], &hdr); err != nil { return nil, fmt.Errorf("bad JWT header - %s", err) } if hdr.Alg != "RS256" { return nil, fmt.Errorf("bad JWT - only RS256 alg is supported, not %q", hdr.Alg) } if hdr.Kid == "" { return nil, fmt.Errorf("bad JWT - missing the signing key ID in the header") } pub, ok := k.keys[hdr.Kid] if !ok { return nil, fmt.Errorf("can't verify JWT - unknown signing key %q", hdr.Kid) } // Decode the signature. sig, err := base64.RawURLEncoding.DecodeString(chunks[2]) if err != nil { return nil, fmt.Errorf("bad JWT - can't base64 decode the signature - %s", err) } // Check the signature. The signed string is "b64(header).b64(body)". hasher := sha256.New() hasher.Write([]byte(chunks[0])) hasher.Write([]byte{'.'}) hasher.Write([]byte(chunks[1])) if err := rsa.VerifyPKCS1v15(&pub, crypto.SHA256, hasher.Sum(nil), sig); err != nil { return nil, fmt.Errorf("bad JWT - bad signature") } // Decode the body. There should be no errors here generally, the encoded body // is signed and the signature was already verified. body, err = base64.RawURLEncoding.DecodeString(chunks[1]) if err != nil { return nil, fmt.Errorf("bad JWT - can't base64 decode the body - %s", err) } return body, nil }
go
func (k *JSONWebKeySet) VerifyJWT(jwt string) (body []byte, err error) { chunks := strings.Split(jwt, ".") if len(chunks) != 3 { return nil, fmt.Errorf("bad JWT - expected 3 components separated by '.'") } // Check the header, grab the corresponding public key. var hdr struct { Alg string `json:"alg"` Kid string `json:"kid"` } if err := unmarshalB64JSON(chunks[0], &hdr); err != nil { return nil, fmt.Errorf("bad JWT header - %s", err) } if hdr.Alg != "RS256" { return nil, fmt.Errorf("bad JWT - only RS256 alg is supported, not %q", hdr.Alg) } if hdr.Kid == "" { return nil, fmt.Errorf("bad JWT - missing the signing key ID in the header") } pub, ok := k.keys[hdr.Kid] if !ok { return nil, fmt.Errorf("can't verify JWT - unknown signing key %q", hdr.Kid) } // Decode the signature. sig, err := base64.RawURLEncoding.DecodeString(chunks[2]) if err != nil { return nil, fmt.Errorf("bad JWT - can't base64 decode the signature - %s", err) } // Check the signature. The signed string is "b64(header).b64(body)". hasher := sha256.New() hasher.Write([]byte(chunks[0])) hasher.Write([]byte{'.'}) hasher.Write([]byte(chunks[1])) if err := rsa.VerifyPKCS1v15(&pub, crypto.SHA256, hasher.Sum(nil), sig); err != nil { return nil, fmt.Errorf("bad JWT - bad signature") } // Decode the body. There should be no errors here generally, the encoded body // is signed and the signature was already verified. body, err = base64.RawURLEncoding.DecodeString(chunks[1]) if err != nil { return nil, fmt.Errorf("bad JWT - can't base64 decode the body - %s", err) } return body, nil }
[ "func", "(", "k", "*", "JSONWebKeySet", ")", "VerifyJWT", "(", "jwt", "string", ")", "(", "body", "[", "]", "byte", ",", "err", "error", ")", "{", "chunks", ":=", "strings", ".", "Split", "(", "jwt", ",", "\"", "\"", ")", "\n", "if", "len", "(", "chunks", ")", "!=", "3", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Check the header, grab the corresponding public key.", "var", "hdr", "struct", "{", "Alg", "string", "`json:\"alg\"`", "\n", "Kid", "string", "`json:\"kid\"`", "\n", "}", "\n", "if", "err", ":=", "unmarshalB64JSON", "(", "chunks", "[", "0", "]", ",", "&", "hdr", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "hdr", ".", "Alg", "!=", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hdr", ".", "Alg", ")", "\n", "}", "\n", "if", "hdr", ".", "Kid", "==", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "pub", ",", "ok", ":=", "k", ".", "keys", "[", "hdr", ".", "Kid", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hdr", ".", "Kid", ")", "\n", "}", "\n\n", "// Decode the signature.", "sig", ",", "err", ":=", "base64", ".", "RawURLEncoding", ".", "DecodeString", "(", "chunks", "[", "2", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Check the signature. The signed string is \"b64(header).b64(body)\".", "hasher", ":=", "sha256", ".", "New", "(", ")", "\n", "hasher", ".", "Write", "(", "[", "]", "byte", "(", "chunks", "[", "0", "]", ")", ")", "\n", "hasher", ".", "Write", "(", "[", "]", "byte", "{", "'.'", "}", ")", "\n", "hasher", ".", "Write", "(", "[", "]", "byte", "(", "chunks", "[", "1", "]", ")", ")", "\n", "if", "err", ":=", "rsa", ".", "VerifyPKCS1v15", "(", "&", "pub", ",", "crypto", ".", "SHA256", ",", "hasher", ".", "Sum", "(", "nil", ")", ",", "sig", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Decode the body. There should be no errors here generally, the encoded body", "// is signed and the signature was already verified.", "body", ",", "err", "=", "base64", ".", "RawURLEncoding", ".", "DecodeString", "(", "chunks", "[", "1", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "body", ",", "nil", "\n", "}" ]
// VerifyJWT checks JWT signature and returns the token body. // // Supports only non-encrypted RS256-signed JWTs. See RFC7519.
[ "VerifyJWT", "checks", "JWT", "signature", "and", "returns", "the", "token", "body", ".", "Supports", "only", "non", "-", "encrypted", "RS256", "-", "signed", "JWTs", ".", "See", "RFC7519", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/openid/json_web_keys.go#L89-L136
9,412
luci/luci-go
common/logging/gkelogger/logger.go
GetFactory
func GetFactory(out io.Writer) func(context.Context) logging.Logger { lock := sync.Mutex{} return func(c context.Context) logging.Logger { return &jsonLogger{ ctx: c, lock: &lock, out: out, } } }
go
func GetFactory(out io.Writer) func(context.Context) logging.Logger { lock := sync.Mutex{} return func(c context.Context) logging.Logger { return &jsonLogger{ ctx: c, lock: &lock, out: out, } } }
[ "func", "GetFactory", "(", "out", "io", ".", "Writer", ")", "func", "(", "context", ".", "Context", ")", "logging", ".", "Logger", "{", "lock", ":=", "sync", ".", "Mutex", "{", "}", "\n", "return", "func", "(", "c", "context", ".", "Context", ")", "logging", ".", "Logger", "{", "return", "&", "jsonLogger", "{", "ctx", ":", "c", ",", "lock", ":", "&", "lock", ",", "out", ":", "out", ",", "}", "\n", "}", "\n", "}" ]
// GetFactory creates a goroutine safe gkelogger that writes into out.
[ "GetFactory", "creates", "a", "goroutine", "safe", "gkelogger", "that", "writes", "into", "out", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/gkelogger/logger.go#L30-L39
9,413
luci/luci-go
common/iotools/chainreader.go
Remaining
func (cr ChainReader) Remaining() int64 { result, err := cr.RemainingErr() if err != nil { panic(err) } return result }
go
func (cr ChainReader) Remaining() int64 { result, err := cr.RemainingErr() if err != nil { panic(err) } return result }
[ "func", "(", "cr", "ChainReader", ")", "Remaining", "(", ")", "int64", "{", "result", ",", "err", ":=", "cr", ".", "RemainingErr", "(", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "result", "\n", "}" ]
// Remaining calculates the amount of data left in the ChainReader. It will // panic if an error condition in RemainingErr is encountered.
[ "Remaining", "calculates", "the", "amount", "of", "data", "left", "in", "the", "ChainReader", ".", "It", "will", "panic", "if", "an", "error", "condition", "in", "RemainingErr", "is", "encountered", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/iotools/chainreader.go#L77-L83
9,414
luci/luci-go
common/iotools/chainreader.go
RemainingErr
func (cr ChainReader) RemainingErr() (int64, error) { result := int64(0) for _, source := range cr { if source == nil { continue } r, ok := source.(interface { Len() int }) if !ok { return 0, errors.New("chainreader: can only calculate Remaining for instances implementing Len()") } result += int64(r.Len()) } return result, nil }
go
func (cr ChainReader) RemainingErr() (int64, error) { result := int64(0) for _, source := range cr { if source == nil { continue } r, ok := source.(interface { Len() int }) if !ok { return 0, errors.New("chainreader: can only calculate Remaining for instances implementing Len()") } result += int64(r.Len()) } return result, nil }
[ "func", "(", "cr", "ChainReader", ")", "RemainingErr", "(", ")", "(", "int64", ",", "error", ")", "{", "result", ":=", "int64", "(", "0", ")", "\n", "for", "_", ",", "source", ":=", "range", "cr", "{", "if", "source", "==", "nil", "{", "continue", "\n", "}", "\n", "r", ",", "ok", ":=", "source", ".", "(", "interface", "{", "Len", "(", ")", "int", "\n", "}", ")", "\n", "if", "!", "ok", "{", "return", "0", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "result", "+=", "int64", "(", "r", ".", "Len", "(", ")", ")", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// RemainingErr returns the amount of data left in the ChainReader. An error is // returned if any reader in the chain is not either nil or a bytes.Reader. // // Note that this method iterates over all readers in the chain each time that // it's called.
[ "RemainingErr", "returns", "the", "amount", "of", "data", "left", "in", "the", "ChainReader", ".", "An", "error", "is", "returned", "if", "any", "reader", "in", "the", "chain", "is", "not", "either", "nil", "or", "a", "bytes", ".", "Reader", ".", "Note", "that", "this", "method", "iterates", "over", "all", "readers", "in", "the", "chain", "each", "time", "that", "it", "s", "called", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/iotools/chainreader.go#L90-L105
9,415
luci/luci-go
logdog/client/butler/streamserver/namedPipe_posix.go
NewUNIXDomainSocketServer
func NewUNIXDomainSocketServer(ctx context.Context, path string) (StreamServer, error) { switch l := len(path); { case l == 0: return nil, errors.New("cannot have empty path") case l > maxPOSIXNamedSocketLength: return nil, errors.Reason("path exceeds maximum length %d", maxPOSIXNamedSocketLength). InternalReason("path(%s)", path).Err() } abs, err := filepath.Abs(path) if err != nil { return nil, errors.Annotate(err, "could not get absolute path of [%s]", path).Err() } path = abs ctx = log.SetField(ctx, "namedPipePath", path) return &listenerStreamServer{ Context: ctx, gen: func() (net.Listener, string, error) { log.Infof(ctx, "Creating POSIX server socket Listener.") // Cleanup any previous named pipe. We don't bother checking for the file // first since the remove is atomic. We also ignore any error here, since // it's probably related to the file not being found. // // If there was an actual error removing the file, we'll catch it shortly // when we try to create it. os.Remove(path) // Create a UNIX listener l, err := net.Listen("unix", path) if err != nil { return nil, "", err } addr := "unix:" + path ul := selfCleaningUNIXListener{ Context: ctx, Listener: l, path: path, } return &ul, addr, nil }, }, nil }
go
func NewUNIXDomainSocketServer(ctx context.Context, path string) (StreamServer, error) { switch l := len(path); { case l == 0: return nil, errors.New("cannot have empty path") case l > maxPOSIXNamedSocketLength: return nil, errors.Reason("path exceeds maximum length %d", maxPOSIXNamedSocketLength). InternalReason("path(%s)", path).Err() } abs, err := filepath.Abs(path) if err != nil { return nil, errors.Annotate(err, "could not get absolute path of [%s]", path).Err() } path = abs ctx = log.SetField(ctx, "namedPipePath", path) return &listenerStreamServer{ Context: ctx, gen: func() (net.Listener, string, error) { log.Infof(ctx, "Creating POSIX server socket Listener.") // Cleanup any previous named pipe. We don't bother checking for the file // first since the remove is atomic. We also ignore any error here, since // it's probably related to the file not being found. // // If there was an actual error removing the file, we'll catch it shortly // when we try to create it. os.Remove(path) // Create a UNIX listener l, err := net.Listen("unix", path) if err != nil { return nil, "", err } addr := "unix:" + path ul := selfCleaningUNIXListener{ Context: ctx, Listener: l, path: path, } return &ul, addr, nil }, }, nil }
[ "func", "NewUNIXDomainSocketServer", "(", "ctx", "context", ".", "Context", ",", "path", "string", ")", "(", "StreamServer", ",", "error", ")", "{", "switch", "l", ":=", "len", "(", "path", ")", ";", "{", "case", "l", "==", "0", ":", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "case", "l", ">", "maxPOSIXNamedSocketLength", ":", "return", "nil", ",", "errors", ".", "Reason", "(", "\"", "\"", ",", "maxPOSIXNamedSocketLength", ")", ".", "InternalReason", "(", "\"", "\"", ",", "path", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "abs", ",", "err", ":=", "filepath", ".", "Abs", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "path", ")", ".", "Err", "(", ")", "\n", "}", "\n", "path", "=", "abs", "\n\n", "ctx", "=", "log", ".", "SetField", "(", "ctx", ",", "\"", "\"", ",", "path", ")", "\n", "return", "&", "listenerStreamServer", "{", "Context", ":", "ctx", ",", "gen", ":", "func", "(", ")", "(", "net", ".", "Listener", ",", "string", ",", "error", ")", "{", "log", ".", "Infof", "(", "ctx", ",", "\"", "\"", ")", "\n\n", "// Cleanup any previous named pipe. We don't bother checking for the file", "// first since the remove is atomic. We also ignore any error here, since", "// it's probably related to the file not being found.", "//", "// If there was an actual error removing the file, we'll catch it shortly", "// when we try to create it.", "os", ".", "Remove", "(", "path", ")", "\n\n", "// Create a UNIX listener", "l", ",", "err", ":=", "net", ".", "Listen", "(", "\"", "\"", ",", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"", "\"", ",", "err", "\n", "}", "\n\n", "addr", ":=", "\"", "\"", "+", "path", "\n", "ul", ":=", "selfCleaningUNIXListener", "{", "Context", ":", "ctx", ",", "Listener", ":", "l", ",", "path", ":", "path", ",", "}", "\n", "return", "&", "ul", ",", "addr", ",", "nil", "\n", "}", ",", "}", ",", "nil", "\n", "}" ]
// NewUNIXDomainSocketServer instantiates a new POSIX domain soecket server // instance. // // No resources are actually created until methods are called on the returned // server.
[ "NewUNIXDomainSocketServer", "instantiates", "a", "new", "POSIX", "domain", "soecket", "server", "instance", ".", "No", "resources", "are", "actually", "created", "until", "methods", "are", "called", "on", "the", "returned", "server", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/streamserver/namedPipe_posix.go#L39-L83
9,416
luci/luci-go
grpc/internal/svctool/tool.go
ParseArgs
func (t *Tool) ParseArgs(args []string) { args = t.parseFlags(args) switch len(args) { case 0: args = []string{"."} fallthrough case 1: info, err := os.Stat(args[0]) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(2) } if info.IsDir() { t.Dir = args[0] t.FileNames, err = goFilesIn(args[0]) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(2) } break } fallthrough default: t.Dir = filepath.Dir(args[0]) t.FileNames = args } }
go
func (t *Tool) ParseArgs(args []string) { args = t.parseFlags(args) switch len(args) { case 0: args = []string{"."} fallthrough case 1: info, err := os.Stat(args[0]) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(2) } if info.IsDir() { t.Dir = args[0] t.FileNames, err = goFilesIn(args[0]) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(2) } break } fallthrough default: t.Dir = filepath.Dir(args[0]) t.FileNames = args } }
[ "func", "(", "t", "*", "Tool", ")", "ParseArgs", "(", "args", "[", "]", "string", ")", "{", "args", "=", "t", ".", "parseFlags", "(", "args", ")", "\n\n", "switch", "len", "(", "args", ")", "{", "case", "0", ":", "args", "=", "[", "]", "string", "{", "\"", "\"", "}", "\n", "fallthrough", "\n\n", "case", "1", ":", "info", ",", "err", ":=", "os", ".", "Stat", "(", "args", "[", "0", "]", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Fprintln", "(", "os", ".", "Stderr", ",", "err", ")", "\n", "os", ".", "Exit", "(", "2", ")", "\n", "}", "\n", "if", "info", ".", "IsDir", "(", ")", "{", "t", ".", "Dir", "=", "args", "[", "0", "]", "\n", "t", ".", "FileNames", ",", "err", "=", "goFilesIn", "(", "args", "[", "0", "]", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Fprintln", "(", "os", ".", "Stderr", ",", "err", ")", "\n", "os", ".", "Exit", "(", "2", ")", "\n", "}", "\n", "break", "\n", "}", "\n", "fallthrough", "\n\n", "default", ":", "t", ".", "Dir", "=", "filepath", ".", "Dir", "(", "args", "[", "0", "]", ")", "\n", "t", ".", "FileNames", "=", "args", "\n", "}", "\n", "}" ]
// ParseArgs parses command arguments. Exits if they are invalid.
[ "ParseArgs", "parses", "command", "arguments", ".", "Exits", "if", "they", "are", "invalid", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/internal/svctool/tool.go#L107-L136
9,417
luci/luci-go
grpc/internal/svctool/tool.go
Run
func (t *Tool) Run(c context.Context, f Generator) error { // Validate arguments. if len(t.FileNames) == 0 { return fmt.Errorf("files not specified") } if len(t.Types) == 0 { return fmt.Errorf("types not specified") } // Determine output file name. outputName := t.Output if outputName == "" { if t.Dir == "" { return fmt.Errorf("neither output not dir are specified") } baseName := fmt.Sprintf("%s_%s.go", t.Types[0], t.OutputFilenameSuffix) outputName = filepath.Join(t.Dir, strings.ToLower(baseName)) } // Parse Go files and resolve specified types. p := &parser{ fileSet: token.NewFileSet(), types: t.Types, } if err := p.parsePackage(t.FileNames); err != nil { return fmt.Errorf("could not parse .go files: %s", err) } if err := p.resolveServices(c); err != nil { return err } // Run the generator. var buf bytes.Buffer genArgs := &GeneratorArgs{ PackageName: p.files[0].Name.Name, Services: p.services, ExtraImports: importSorted(p.extraImports), Out: &buf, } if err := f(c, genArgs); err != nil { return err } // Format the output. src, err := format.Source(buf.Bytes()) if err != nil { println(buf.String()) return fmt.Errorf("gofmt: %s", err) } // Write to file. return ioutil.WriteFile(outputName, src, 0644) }
go
func (t *Tool) Run(c context.Context, f Generator) error { // Validate arguments. if len(t.FileNames) == 0 { return fmt.Errorf("files not specified") } if len(t.Types) == 0 { return fmt.Errorf("types not specified") } // Determine output file name. outputName := t.Output if outputName == "" { if t.Dir == "" { return fmt.Errorf("neither output not dir are specified") } baseName := fmt.Sprintf("%s_%s.go", t.Types[0], t.OutputFilenameSuffix) outputName = filepath.Join(t.Dir, strings.ToLower(baseName)) } // Parse Go files and resolve specified types. p := &parser{ fileSet: token.NewFileSet(), types: t.Types, } if err := p.parsePackage(t.FileNames); err != nil { return fmt.Errorf("could not parse .go files: %s", err) } if err := p.resolveServices(c); err != nil { return err } // Run the generator. var buf bytes.Buffer genArgs := &GeneratorArgs{ PackageName: p.files[0].Name.Name, Services: p.services, ExtraImports: importSorted(p.extraImports), Out: &buf, } if err := f(c, genArgs); err != nil { return err } // Format the output. src, err := format.Source(buf.Bytes()) if err != nil { println(buf.String()) return fmt.Errorf("gofmt: %s", err) } // Write to file. return ioutil.WriteFile(outputName, src, 0644) }
[ "func", "(", "t", "*", "Tool", ")", "Run", "(", "c", "context", ".", "Context", ",", "f", "Generator", ")", "error", "{", "// Validate arguments.", "if", "len", "(", "t", ".", "FileNames", ")", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "t", ".", "Types", ")", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// Determine output file name.", "outputName", ":=", "t", ".", "Output", "\n", "if", "outputName", "==", "\"", "\"", "{", "if", "t", ".", "Dir", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "baseName", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "t", ".", "Types", "[", "0", "]", ",", "t", ".", "OutputFilenameSuffix", ")", "\n", "outputName", "=", "filepath", ".", "Join", "(", "t", ".", "Dir", ",", "strings", ".", "ToLower", "(", "baseName", ")", ")", "\n", "}", "\n\n", "// Parse Go files and resolve specified types.", "p", ":=", "&", "parser", "{", "fileSet", ":", "token", ".", "NewFileSet", "(", ")", ",", "types", ":", "t", ".", "Types", ",", "}", "\n", "if", "err", ":=", "p", ".", "parsePackage", "(", "t", ".", "FileNames", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "p", ".", "resolveServices", "(", "c", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Run the generator.", "var", "buf", "bytes", ".", "Buffer", "\n", "genArgs", ":=", "&", "GeneratorArgs", "{", "PackageName", ":", "p", ".", "files", "[", "0", "]", ".", "Name", ".", "Name", ",", "Services", ":", "p", ".", "services", ",", "ExtraImports", ":", "importSorted", "(", "p", ".", "extraImports", ")", ",", "Out", ":", "&", "buf", ",", "}", "\n", "if", "err", ":=", "f", "(", "c", ",", "genArgs", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Format the output.", "src", ",", "err", ":=", "format", ".", "Source", "(", "buf", ".", "Bytes", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "println", "(", "buf", ".", "String", "(", ")", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Write to file.", "return", "ioutil", ".", "WriteFile", "(", "outputName", ",", "src", ",", "0644", ")", "\n", "}" ]
// Run parses Go files and generates a new file using f.
[ "Run", "parses", "Go", "files", "and", "generates", "a", "new", "file", "using", "f", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/internal/svctool/tool.go#L162-L214
9,418
luci/luci-go
grpc/internal/svctool/tool.go
goFilesIn
func goFilesIn(dir string) ([]string, error) { pkg, err := build.ImportDir(dir, 0) if err != nil { return nil, fmt.Errorf("cannot process directory %s: %s", dir, err) } var names []string names = append(names, pkg.GoFiles...) names = append(names, pkg.CgoFiles...) names = prefixDirectory(dir, names) return names, nil }
go
func goFilesIn(dir string) ([]string, error) { pkg, err := build.ImportDir(dir, 0) if err != nil { return nil, fmt.Errorf("cannot process directory %s: %s", dir, err) } var names []string names = append(names, pkg.GoFiles...) names = append(names, pkg.CgoFiles...) names = prefixDirectory(dir, names) return names, nil }
[ "func", "goFilesIn", "(", "dir", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "pkg", ",", "err", ":=", "build", ".", "ImportDir", "(", "dir", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "dir", ",", "err", ")", "\n", "}", "\n", "var", "names", "[", "]", "string", "\n", "names", "=", "append", "(", "names", ",", "pkg", ".", "GoFiles", "...", ")", "\n", "names", "=", "append", "(", "names", ",", "pkg", ".", "CgoFiles", "...", ")", "\n", "names", "=", "prefixDirectory", "(", "dir", ",", "names", ")", "\n", "return", "names", ",", "nil", "\n", "}" ]
// goFilesIn lists .go files in dir.
[ "goFilesIn", "lists", ".", "go", "files", "in", "dir", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/internal/svctool/tool.go#L230-L240
9,419
luci/luci-go
appengine/gaemiddleware/settings.go
reportDSCacheDisabled
func reportDSCacheDisabled(c context.Context) { dsCacheDisabled.Set(c, bool(fetchCachedSettings(c).DisableDSCache)) }
go
func reportDSCacheDisabled(c context.Context) { dsCacheDisabled.Set(c, bool(fetchCachedSettings(c).DisableDSCache)) }
[ "func", "reportDSCacheDisabled", "(", "c", "context", ".", "Context", ")", "{", "dsCacheDisabled", ".", "Set", "(", "c", ",", "bool", "(", "fetchCachedSettings", "(", "c", ")", ".", "DisableDSCache", ")", ")", "\n", "}" ]
// reportDSCacheDisabled reports the value of DSCacheDisabled in settings to // tsmon.
[ "reportDSCacheDisabled", "reports", "the", "value", "of", "DSCacheDisabled", "in", "settings", "to", "tsmon", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaemiddleware/settings.go#L87-L89
9,420
luci/luci-go
logdog/server/archivist/archivist.go
ArchiveTask
func (a *Archivist) ArchiveTask(c context.Context, task *logdog.ArchiveTask) error { c = log.SetFields(c, log.Fields{ "project": task.Project, "id": task.Id, }) log.Debugf(c, "Received archival task.") err := a.archiveTaskImpl(c, task) failure := isFailure(err) log.Fields{ log.ErrorKey: err, "failure": failure, }.Infof(c, "Finished archive task.") // Add a result metric. tsCount.Add(c, 1, !failure) return err }
go
func (a *Archivist) ArchiveTask(c context.Context, task *logdog.ArchiveTask) error { c = log.SetFields(c, log.Fields{ "project": task.Project, "id": task.Id, }) log.Debugf(c, "Received archival task.") err := a.archiveTaskImpl(c, task) failure := isFailure(err) log.Fields{ log.ErrorKey: err, "failure": failure, }.Infof(c, "Finished archive task.") // Add a result metric. tsCount.Add(c, 1, !failure) return err }
[ "func", "(", "a", "*", "Archivist", ")", "ArchiveTask", "(", "c", "context", ".", "Context", ",", "task", "*", "logdog", ".", "ArchiveTask", ")", "error", "{", "c", "=", "log", ".", "SetFields", "(", "c", ",", "log", ".", "Fields", "{", "\"", "\"", ":", "task", ".", "Project", ",", "\"", "\"", ":", "task", ".", "Id", ",", "}", ")", "\n", "log", ".", "Debugf", "(", "c", ",", "\"", "\"", ")", "\n\n", "err", ":=", "a", ".", "archiveTaskImpl", "(", "c", ",", "task", ")", "\n\n", "failure", ":=", "isFailure", "(", "err", ")", "\n", "log", ".", "Fields", "{", "log", ".", "ErrorKey", ":", "err", ",", "\"", "\"", ":", "failure", ",", "}", ".", "Infof", "(", "c", ",", "\"", "\"", ")", "\n\n", "// Add a result metric.", "tsCount", ".", "Add", "(", "c", ",", "1", ",", "!", "failure", ")", "\n\n", "return", "err", "\n", "}" ]
// ArchiveTask processes and executes a single log stream archive task. // // If the supplied Context is Done, operation may terminate before completion, // returning the Context's error.
[ "ArchiveTask", "processes", "and", "executes", "a", "single", "log", "stream", "archive", "task", ".", "If", "the", "supplied", "Context", "is", "Done", "operation", "may", "terminate", "before", "completion", "returning", "the", "Context", "s", "error", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/server/archivist/archivist.go#L163-L182
9,421
luci/luci-go
logdog/server/archivist/archivist.go
loadSettings
func (a *Archivist) loadSettings(c context.Context, project types.ProjectName) (*Settings, error) { if a.SettingsLoader == nil { panic("no settings loader configured") } st, err := a.SettingsLoader(c, project) switch { case err != nil: return nil, err case st.GSBase.Bucket() == "": log.Fields{ log.ErrorKey: err, "gsBase": st.GSBase, }.Errorf(c, "Invalid storage base.") return nil, errors.New("invalid storage base") case st.GSStagingBase.Bucket() == "": log.Fields{ log.ErrorKey: err, "gsStagingBase": st.GSStagingBase, }.Errorf(c, "Invalid storage staging base.") return nil, errors.New("invalid storage staging base") default: return st, nil } }
go
func (a *Archivist) loadSettings(c context.Context, project types.ProjectName) (*Settings, error) { if a.SettingsLoader == nil { panic("no settings loader configured") } st, err := a.SettingsLoader(c, project) switch { case err != nil: return nil, err case st.GSBase.Bucket() == "": log.Fields{ log.ErrorKey: err, "gsBase": st.GSBase, }.Errorf(c, "Invalid storage base.") return nil, errors.New("invalid storage base") case st.GSStagingBase.Bucket() == "": log.Fields{ log.ErrorKey: err, "gsStagingBase": st.GSStagingBase, }.Errorf(c, "Invalid storage staging base.") return nil, errors.New("invalid storage staging base") default: return st, nil } }
[ "func", "(", "a", "*", "Archivist", ")", "loadSettings", "(", "c", "context", ".", "Context", ",", "project", "types", ".", "ProjectName", ")", "(", "*", "Settings", ",", "error", ")", "{", "if", "a", ".", "SettingsLoader", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "st", ",", "err", ":=", "a", ".", "SettingsLoader", "(", "c", ",", "project", ")", "\n", "switch", "{", "case", "err", "!=", "nil", ":", "return", "nil", ",", "err", "\n\n", "case", "st", ".", "GSBase", ".", "Bucket", "(", ")", "==", "\"", "\"", ":", "log", ".", "Fields", "{", "log", ".", "ErrorKey", ":", "err", ",", "\"", "\"", ":", "st", ".", "GSBase", ",", "}", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n\n", "case", "st", ".", "GSStagingBase", ".", "Bucket", "(", ")", "==", "\"", "\"", ":", "log", ".", "Fields", "{", "log", ".", "ErrorKey", ":", "err", ",", "\"", "\"", ":", "st", ".", "GSStagingBase", ",", "}", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n\n", "default", ":", "return", "st", ",", "nil", "\n", "}", "\n", "}" ]
// loadSettings loads and validates archival settings.
[ "loadSettings", "loads", "and", "validates", "archival", "settings", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/server/archivist/archivist.go#L323-L350
9,422
luci/luci-go
logdog/server/archivist/archivist.go
checkComplete
func (sa *stagedArchival) checkComplete(c context.Context) error { if sa.terminalIndex < 0 { log.Warningf(c, "Cannot archive complete stream with no terminal index.") return statusErr(errors.New("completeness required, but stream has no terminal index")) } sreq := storage.GetRequest{ Project: sa.project, Path: sa.path, KeysOnly: true, } nextIndex := types.MessageIndex(0) var ierr error err := sa.Storage.Get(c, sreq, func(e *storage.Entry) bool { idx, err := e.GetStreamIndex() if err != nil { ierr = errors.Annotate(err, "could not get stream index").Err() return false } switch { case idx != nextIndex: ierr = fmt.Errorf("missing log entry index %d (next %d)", nextIndex, idx) return false case idx == sa.terminalIndex: // We have hit our terminal index, so all of the log data is here! return false default: nextIndex++ return true } }) if ierr != nil { return ierr } if err != nil { return err } return nil }
go
func (sa *stagedArchival) checkComplete(c context.Context) error { if sa.terminalIndex < 0 { log.Warningf(c, "Cannot archive complete stream with no terminal index.") return statusErr(errors.New("completeness required, but stream has no terminal index")) } sreq := storage.GetRequest{ Project: sa.project, Path: sa.path, KeysOnly: true, } nextIndex := types.MessageIndex(0) var ierr error err := sa.Storage.Get(c, sreq, func(e *storage.Entry) bool { idx, err := e.GetStreamIndex() if err != nil { ierr = errors.Annotate(err, "could not get stream index").Err() return false } switch { case idx != nextIndex: ierr = fmt.Errorf("missing log entry index %d (next %d)", nextIndex, idx) return false case idx == sa.terminalIndex: // We have hit our terminal index, so all of the log data is here! return false default: nextIndex++ return true } }) if ierr != nil { return ierr } if err != nil { return err } return nil }
[ "func", "(", "sa", "*", "stagedArchival", ")", "checkComplete", "(", "c", "context", ".", "Context", ")", "error", "{", "if", "sa", ".", "terminalIndex", "<", "0", "{", "log", ".", "Warningf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "statusErr", "(", "errors", ".", "New", "(", "\"", "\"", ")", ")", "\n", "}", "\n\n", "sreq", ":=", "storage", ".", "GetRequest", "{", "Project", ":", "sa", ".", "project", ",", "Path", ":", "sa", ".", "path", ",", "KeysOnly", ":", "true", ",", "}", "\n\n", "nextIndex", ":=", "types", ".", "MessageIndex", "(", "0", ")", "\n", "var", "ierr", "error", "\n", "err", ":=", "sa", ".", "Storage", ".", "Get", "(", "c", ",", "sreq", ",", "func", "(", "e", "*", "storage", ".", "Entry", ")", "bool", "{", "idx", ",", "err", ":=", "e", ".", "GetStreamIndex", "(", ")", "\n", "if", "err", "!=", "nil", "{", "ierr", "=", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "return", "false", "\n", "}", "\n\n", "switch", "{", "case", "idx", "!=", "nextIndex", ":", "ierr", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "nextIndex", ",", "idx", ")", "\n", "return", "false", "\n\n", "case", "idx", "==", "sa", ".", "terminalIndex", ":", "// We have hit our terminal index, so all of the log data is here!", "return", "false", "\n\n", "default", ":", "nextIndex", "++", "\n", "return", "true", "\n", "}", "\n", "}", ")", "\n", "if", "ierr", "!=", "nil", "{", "return", "ierr", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// checkComplete performs a quick scan of intermediate storage to ensure that // all of the log stream's records are available.
[ "checkComplete", "performs", "a", "quick", "scan", "of", "intermediate", "storage", "to", "ensure", "that", "all", "of", "the", "log", "stream", "s", "records", "are", "available", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/server/archivist/archivist.go#L437-L479
9,423
luci/luci-go
common/tsmon/target/target.go
NewFromFlags
func NewFromFlags(fl *Flags) (types.Target, error) { if fl.TargetType == "task" { if fl.TaskServiceName == "" { return nil, errors.New( "--ts-mon-task-service-name must be provided when using --ts-mon-target-type=task") } if fl.TaskJobName == "" { return nil, errors.New( "--ts-mon-task-job-name must be provided when using --ts-mon-target-type=task") } return &Task{ ServiceName: fl.TaskServiceName, JobName: fl.TaskJobName, DataCenter: fl.TaskRegion, HostName: fl.TaskHostname, TaskNum: int32(fl.TaskNumber), }, nil } else if fl.TargetType == "device" { return &NetworkDevice{ Metro: fl.DeviceRegion, Role: fl.DeviceRole, Hostname: fl.DeviceHostname, Hostgroup: fl.DeviceNetwork, }, nil } else { return nil, fmt.Errorf("unknown --ts-mon-target-type '%s'", fl.TargetType) } }
go
func NewFromFlags(fl *Flags) (types.Target, error) { if fl.TargetType == "task" { if fl.TaskServiceName == "" { return nil, errors.New( "--ts-mon-task-service-name must be provided when using --ts-mon-target-type=task") } if fl.TaskJobName == "" { return nil, errors.New( "--ts-mon-task-job-name must be provided when using --ts-mon-target-type=task") } return &Task{ ServiceName: fl.TaskServiceName, JobName: fl.TaskJobName, DataCenter: fl.TaskRegion, HostName: fl.TaskHostname, TaskNum: int32(fl.TaskNumber), }, nil } else if fl.TargetType == "device" { return &NetworkDevice{ Metro: fl.DeviceRegion, Role: fl.DeviceRole, Hostname: fl.DeviceHostname, Hostgroup: fl.DeviceNetwork, }, nil } else { return nil, fmt.Errorf("unknown --ts-mon-target-type '%s'", fl.TargetType) } }
[ "func", "NewFromFlags", "(", "fl", "*", "Flags", ")", "(", "types", ".", "Target", ",", "error", ")", "{", "if", "fl", ".", "TargetType", "==", "\"", "\"", "{", "if", "fl", ".", "TaskServiceName", "==", "\"", "\"", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "fl", ".", "TaskJobName", "==", "\"", "\"", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "&", "Task", "{", "ServiceName", ":", "fl", ".", "TaskServiceName", ",", "JobName", ":", "fl", ".", "TaskJobName", ",", "DataCenter", ":", "fl", ".", "TaskRegion", ",", "HostName", ":", "fl", ".", "TaskHostname", ",", "TaskNum", ":", "int32", "(", "fl", ".", "TaskNumber", ")", ",", "}", ",", "nil", "\n", "}", "else", "if", "fl", ".", "TargetType", "==", "\"", "\"", "{", "return", "&", "NetworkDevice", "{", "Metro", ":", "fl", ".", "DeviceRegion", ",", "Role", ":", "fl", ".", "DeviceRole", ",", "Hostname", ":", "fl", ".", "DeviceHostname", ",", "Hostgroup", ":", "fl", ".", "DeviceNetwork", ",", "}", ",", "nil", "\n", "}", "else", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "fl", ".", "TargetType", ")", "\n", "}", "\n", "}" ]
// NewFromFlags returns a Target configured from commandline flags.
[ "NewFromFlags", "returns", "a", "Target", "configured", "from", "commandline", "flags", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/target/target.go#L83-L111
9,424
luci/luci-go
common/data/stringset/stringset.go
NewFromSlice
func NewFromSlice(vals ...string) Set { ret := make(Set, len(vals)) for _, k := range vals { ret[k] = struct{}{} } return ret }
go
func NewFromSlice(vals ...string) Set { ret := make(Set, len(vals)) for _, k := range vals { ret[k] = struct{}{} } return ret }
[ "func", "NewFromSlice", "(", "vals", "...", "string", ")", "Set", "{", "ret", ":=", "make", "(", "Set", ",", "len", "(", "vals", ")", ")", "\n", "for", "_", ",", "k", ":=", "range", "vals", "{", "ret", "[", "k", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// NewFromSlice returns a new string Set implementation, // initialized with the values in the provided slice.
[ "NewFromSlice", "returns", "a", "new", "string", "Set", "implementation", "initialized", "with", "the", "values", "in", "the", "provided", "slice", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/stringset/stringset.go#L27-L33
9,425
luci/luci-go
common/data/stringset/stringset.go
Has
func (s Set) Has(value string) bool { _, ret := s[value] return ret }
go
func (s Set) Has(value string) bool { _, ret := s[value] return ret }
[ "func", "(", "s", "Set", ")", "Has", "(", "value", "string", ")", "bool", "{", "_", ",", "ret", ":=", "s", "[", "value", "]", "\n", "return", "ret", "\n", "}" ]
// Has returns true iff the Set contains value.
[ "Has", "returns", "true", "iff", "the", "Set", "contains", "value", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/stringset/stringset.go#L36-L39
9,426
luci/luci-go
common/data/stringset/stringset.go
HasAll
func (s Set) HasAll(values ...string) bool { for _, v := range values { if !s.Has(v) { return false } } return true }
go
func (s Set) HasAll(values ...string) bool { for _, v := range values { if !s.Has(v) { return false } } return true }
[ "func", "(", "s", "Set", ")", "HasAll", "(", "values", "...", "string", ")", "bool", "{", "for", "_", ",", "v", ":=", "range", "values", "{", "if", "!", "s", ".", "Has", "(", "v", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// HasAll returns true iff the Set contains all the given values.
[ "HasAll", "returns", "true", "iff", "the", "Set", "contains", "all", "the", "given", "values", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/stringset/stringset.go#L42-L49
9,427
luci/luci-go
common/data/stringset/stringset.go
Iter
func (s Set) Iter(cb func(string) bool) { for k := range s { if !cb(k) { break } } }
go
func (s Set) Iter(cb func(string) bool) { for k := range s { if !cb(k) { break } } }
[ "func", "(", "s", "Set", ")", "Iter", "(", "cb", "func", "(", "string", ")", "bool", ")", "{", "for", "k", ":=", "range", "s", "{", "if", "!", "cb", "(", "k", ")", "{", "break", "\n", "}", "\n", "}", "\n", "}" ]
// Iter calls `cb` for each item in the set. If `cb` returns false, the // iteration stops.
[ "Iter", "calls", "cb", "for", "each", "item", "in", "the", "set", ".", "If", "cb", "returns", "false", "the", "iteration", "stops", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/stringset/stringset.go#L92-L98
9,428
luci/luci-go
common/data/stringset/stringset.go
Dup
func (s Set) Dup() Set { ret := make(Set, len(s)) for k := range s { ret[k] = struct{}{} } return ret }
go
func (s Set) Dup() Set { ret := make(Set, len(s)) for k := range s { ret[k] = struct{}{} } return ret }
[ "func", "(", "s", "Set", ")", "Dup", "(", ")", "Set", "{", "ret", ":=", "make", "(", "Set", ",", "len", "(", "s", ")", ")", "\n", "for", "k", ":=", "range", "s", "{", "ret", "[", "k", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// Dup returns a duplicate set.
[ "Dup", "returns", "a", "duplicate", "set", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/stringset/stringset.go#L106-L112
9,429
luci/luci-go
common/data/stringset/stringset.go
ToSlice
func (s Set) ToSlice() []string { ret := make([]string, 0, len(s)) for k := range s { ret = append(ret, k) } return ret }
go
func (s Set) ToSlice() []string { ret := make([]string, 0, len(s)) for k := range s { ret = append(ret, k) } return ret }
[ "func", "(", "s", "Set", ")", "ToSlice", "(", ")", "[", "]", "string", "{", "ret", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "s", ")", ")", "\n", "for", "k", ":=", "range", "s", "{", "ret", "=", "append", "(", "ret", ",", "k", ")", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// ToSlice renders this set to a slice of all values.
[ "ToSlice", "renders", "this", "set", "to", "a", "slice", "of", "all", "values", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/stringset/stringset.go#L115-L121
9,430
luci/luci-go
common/data/stringset/stringset.go
Intersect
func (s Set) Intersect(other Set) Set { smallLen := len(s) if lo := len(other); lo < smallLen { smallLen = lo } ret := make(Set, smallLen) for k := range s { if _, ok := other[k]; ok { ret[k] = struct{}{} } } return ret }
go
func (s Set) Intersect(other Set) Set { smallLen := len(s) if lo := len(other); lo < smallLen { smallLen = lo } ret := make(Set, smallLen) for k := range s { if _, ok := other[k]; ok { ret[k] = struct{}{} } } return ret }
[ "func", "(", "s", "Set", ")", "Intersect", "(", "other", "Set", ")", "Set", "{", "smallLen", ":=", "len", "(", "s", ")", "\n", "if", "lo", ":=", "len", "(", "other", ")", ";", "lo", "<", "smallLen", "{", "smallLen", "=", "lo", "\n", "}", "\n", "ret", ":=", "make", "(", "Set", ",", "smallLen", ")", "\n", "for", "k", ":=", "range", "s", "{", "if", "_", ",", "ok", ":=", "other", "[", "k", "]", ";", "ok", "{", "ret", "[", "k", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// Intersect returns a new Set which is the intersection of this set with the // other set. // // `other` must have the same underlying type as the current set, or this will // panic.
[ "Intersect", "returns", "a", "new", "Set", "which", "is", "the", "intersection", "of", "this", "set", "with", "the", "other", "set", ".", "other", "must", "have", "the", "same", "underlying", "type", "as", "the", "current", "set", "or", "this", "will", "panic", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/stringset/stringset.go#L128-L140
9,431
luci/luci-go
common/data/stringset/stringset.go
Union
func (s Set) Union(other Set) Set { ret := make(Set, len(s)) for k := range s { ret[k] = struct{}{} } for k := range other { ret[k] = struct{}{} } return ret }
go
func (s Set) Union(other Set) Set { ret := make(Set, len(s)) for k := range s { ret[k] = struct{}{} } for k := range other { ret[k] = struct{}{} } return ret }
[ "func", "(", "s", "Set", ")", "Union", "(", "other", "Set", ")", "Set", "{", "ret", ":=", "make", "(", "Set", ",", "len", "(", "s", ")", ")", "\n", "for", "k", ":=", "range", "s", "{", "ret", "[", "k", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "for", "k", ":=", "range", "other", "{", "ret", "[", "k", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// Union returns a new Set which contains all element from this set, as well // as all elements from the other set. // // `other` must have the same underlying type as the current set, or this will // panic.
[ "Union", "returns", "a", "new", "Set", "which", "contains", "all", "element", "from", "this", "set", "as", "well", "as", "all", "elements", "from", "the", "other", "set", ".", "other", "must", "have", "the", "same", "underlying", "type", "as", "the", "current", "set", "or", "this", "will", "panic", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/stringset/stringset.go#L162-L171
9,432
luci/luci-go
common/data/stringset/stringset.go
Contains
func (s Set) Contains(other Set) bool { for k := range other { if !s.Has(k) { return false } } return true }
go
func (s Set) Contains(other Set) bool { for k := range other { if !s.Has(k) { return false } } return true }
[ "func", "(", "s", "Set", ")", "Contains", "(", "other", "Set", ")", "bool", "{", "for", "k", ":=", "range", "other", "{", "if", "!", "s", ".", "Has", "(", "k", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Contains returns true iff the given set contains all elements from the other set.
[ "Contains", "returns", "true", "iff", "the", "given", "set", "contains", "all", "elements", "from", "the", "other", "set", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/stringset/stringset.go#L174-L181
9,433
luci/luci-go
cipd/appengine/impl/repo/processing/client_extractor.go
GetClientPackage
func GetClientPackage(platform string) (string, error) { pkg := clientPkgPrefix + platform if err := common.ValidatePackageName(pkg); err != nil { return "", err } return pkg, nil }
go
func GetClientPackage(platform string) (string, error) { pkg := clientPkgPrefix + platform if err := common.ValidatePackageName(pkg); err != nil { return "", err } return pkg, nil }
[ "func", "GetClientPackage", "(", "platform", "string", ")", "(", "string", ",", "error", ")", "{", "pkg", ":=", "clientPkgPrefix", "+", "platform", "\n", "if", "err", ":=", "common", ".", "ValidatePackageName", "(", "pkg", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "pkg", ",", "nil", "\n", "}" ]
// GetClientPackage returns the name of the client package for CIPD client for // the given platform. // // Returns an error if the platform name is invalid.
[ "GetClientPackage", "returns", "the", "name", "of", "the", "client", "package", "for", "CIPD", "client", "for", "the", "given", "platform", ".", "Returns", "an", "error", "if", "the", "platform", "name", "is", "invalid", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/processing/client_extractor.go#L47-L53
9,434
luci/luci-go
cipd/appengine/impl/repo/processing/client_extractor.go
ToObjectRef
func (r *ClientExtractorResult) ToObjectRef() (*api.ObjectRef, error) { algo := api.HashAlgo_value[r.ClientBinary.HashAlgo] if algo == 0 { // Note: this means OLD version of the server may not be able to serve // NEW ClientExtractorResult entries due to unknown hash algo. Many other // things will also break in this situation. If this is really happening, // all new entries can be manually removed from the datastore, to stop // confusing the old server version. return nil, fmt.Errorf("unrecognized hash algo %q", r.ClientBinary.HashAlgo) } ref := &api.ObjectRef{ HashAlgo: api.HashAlgo(algo), HexDigest: r.ClientBinary.HashDigest, } if err := common.ValidateObjectRef(ref, common.KnownHash); err != nil { return nil, err } return ref, nil }
go
func (r *ClientExtractorResult) ToObjectRef() (*api.ObjectRef, error) { algo := api.HashAlgo_value[r.ClientBinary.HashAlgo] if algo == 0 { // Note: this means OLD version of the server may not be able to serve // NEW ClientExtractorResult entries due to unknown hash algo. Many other // things will also break in this situation. If this is really happening, // all new entries can be manually removed from the datastore, to stop // confusing the old server version. return nil, fmt.Errorf("unrecognized hash algo %q", r.ClientBinary.HashAlgo) } ref := &api.ObjectRef{ HashAlgo: api.HashAlgo(algo), HexDigest: r.ClientBinary.HashDigest, } if err := common.ValidateObjectRef(ref, common.KnownHash); err != nil { return nil, err } return ref, nil }
[ "func", "(", "r", "*", "ClientExtractorResult", ")", "ToObjectRef", "(", ")", "(", "*", "api", ".", "ObjectRef", ",", "error", ")", "{", "algo", ":=", "api", ".", "HashAlgo_value", "[", "r", ".", "ClientBinary", ".", "HashAlgo", "]", "\n", "if", "algo", "==", "0", "{", "// Note: this means OLD version of the server may not be able to serve", "// NEW ClientExtractorResult entries due to unknown hash algo. Many other", "// things will also break in this situation. If this is really happening,", "// all new entries can be manually removed from the datastore, to stop", "// confusing the old server version.", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "r", ".", "ClientBinary", ".", "HashAlgo", ")", "\n", "}", "\n", "ref", ":=", "&", "api", ".", "ObjectRef", "{", "HashAlgo", ":", "api", ".", "HashAlgo", "(", "algo", ")", ",", "HexDigest", ":", "r", ".", "ClientBinary", ".", "HashDigest", ",", "}", "\n", "if", "err", ":=", "common", ".", "ValidateObjectRef", "(", "ref", ",", "common", ".", "KnownHash", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "ref", ",", "nil", "\n", "}" ]
// ToObjectRef returns a reference to the extracted client binary in CAS. // // The returned ObjectRef is validated to be syntactically correct already.
[ "ToObjectRef", "returns", "a", "reference", "to", "the", "extracted", "client", "binary", "in", "CAS", ".", "The", "returned", "ObjectRef", "is", "validated", "to", "be", "syntactically", "correct", "already", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/processing/client_extractor.go#L99-L117
9,435
luci/luci-go
cipd/appengine/impl/repo/processing/client_extractor.go
ObjectRefAliases
func (r *ClientExtractorResult) ObjectRefAliases() []*api.ObjectRef { all := r.ClientBinary.AllHashDigests // Older entries do not have AllHashDigests field at all. if len(all) == 0 { ref := &api.ObjectRef{ HashAlgo: api.HashAlgo(api.HashAlgo_value[r.ClientBinary.HashAlgo]), HexDigest: r.ClientBinary.HashDigest, } if common.ValidateObjectRef(ref, common.KnownHash) == nil { return []*api.ObjectRef{ref} } return nil // welp, have 0 supported algos, should not really happen } // Order the result by HashAlgo enum values. This loop also naturally skips // algos not understood by the current version of the server, since they are // not in HashAlgo_name map. refs := make([]*api.ObjectRef, 0, len(all)) for algo := int32(1); api.HashAlgo_name[algo] != ""; algo++ { // skip UNSPECIFIED if digest := all[api.HashAlgo_name[algo]]; digest != "" { ref := &api.ObjectRef{HashAlgo: api.HashAlgo(algo), HexDigest: digest} if common.ValidateObjectRef(ref, common.KnownHash) == nil { refs = append(refs, ref) } } } return refs }
go
func (r *ClientExtractorResult) ObjectRefAliases() []*api.ObjectRef { all := r.ClientBinary.AllHashDigests // Older entries do not have AllHashDigests field at all. if len(all) == 0 { ref := &api.ObjectRef{ HashAlgo: api.HashAlgo(api.HashAlgo_value[r.ClientBinary.HashAlgo]), HexDigest: r.ClientBinary.HashDigest, } if common.ValidateObjectRef(ref, common.KnownHash) == nil { return []*api.ObjectRef{ref} } return nil // welp, have 0 supported algos, should not really happen } // Order the result by HashAlgo enum values. This loop also naturally skips // algos not understood by the current version of the server, since they are // not in HashAlgo_name map. refs := make([]*api.ObjectRef, 0, len(all)) for algo := int32(1); api.HashAlgo_name[algo] != ""; algo++ { // skip UNSPECIFIED if digest := all[api.HashAlgo_name[algo]]; digest != "" { ref := &api.ObjectRef{HashAlgo: api.HashAlgo(algo), HexDigest: digest} if common.ValidateObjectRef(ref, common.KnownHash) == nil { refs = append(refs, ref) } } } return refs }
[ "func", "(", "r", "*", "ClientExtractorResult", ")", "ObjectRefAliases", "(", ")", "[", "]", "*", "api", ".", "ObjectRef", "{", "all", ":=", "r", ".", "ClientBinary", ".", "AllHashDigests", "\n\n", "// Older entries do not have AllHashDigests field at all.", "if", "len", "(", "all", ")", "==", "0", "{", "ref", ":=", "&", "api", ".", "ObjectRef", "{", "HashAlgo", ":", "api", ".", "HashAlgo", "(", "api", ".", "HashAlgo_value", "[", "r", ".", "ClientBinary", ".", "HashAlgo", "]", ")", ",", "HexDigest", ":", "r", ".", "ClientBinary", ".", "HashDigest", ",", "}", "\n", "if", "common", ".", "ValidateObjectRef", "(", "ref", ",", "common", ".", "KnownHash", ")", "==", "nil", "{", "return", "[", "]", "*", "api", ".", "ObjectRef", "{", "ref", "}", "\n", "}", "\n", "return", "nil", "// welp, have 0 supported algos, should not really happen", "\n", "}", "\n\n", "// Order the result by HashAlgo enum values. This loop also naturally skips", "// algos not understood by the current version of the server, since they are", "// not in HashAlgo_name map.", "refs", ":=", "make", "(", "[", "]", "*", "api", ".", "ObjectRef", ",", "0", ",", "len", "(", "all", ")", ")", "\n", "for", "algo", ":=", "int32", "(", "1", ")", ";", "api", ".", "HashAlgo_name", "[", "algo", "]", "!=", "\"", "\"", ";", "algo", "++", "{", "// skip UNSPECIFIED", "if", "digest", ":=", "all", "[", "api", ".", "HashAlgo_name", "[", "algo", "]", "]", ";", "digest", "!=", "\"", "\"", "{", "ref", ":=", "&", "api", ".", "ObjectRef", "{", "HashAlgo", ":", "api", ".", "HashAlgo", "(", "algo", ")", ",", "HexDigest", ":", "digest", "}", "\n", "if", "common", ".", "ValidateObjectRef", "(", "ref", ",", "common", ".", "KnownHash", ")", "==", "nil", "{", "refs", "=", "append", "(", "refs", ",", "ref", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "refs", "\n", "}" ]
// ObjectRefAliases is list of ObjectRefs calculated using all hash algos known // to the server when the client binary was extracted. // // Additionally all algos not understood by the server right NOW are skipped // too. This may arise if the server was rolled back, but some files have // already been uploaded with a newer algo.
[ "ObjectRefAliases", "is", "list", "of", "ObjectRefs", "calculated", "using", "all", "hash", "algos", "known", "to", "the", "server", "when", "the", "client", "binary", "was", "extracted", ".", "Additionally", "all", "algos", "not", "understood", "by", "the", "server", "right", "NOW", "are", "skipped", "too", ".", "This", "may", "arise", "if", "the", "server", "was", "rolled", "back", "but", "some", "files", "have", "already", "been", "uploaded", "with", "a", "newer", "algo", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/processing/client_extractor.go#L125-L153
9,436
luci/luci-go
cipd/appengine/impl/repo/processing/client_extractor.go
Applicable
func (e *ClientExtractor) Applicable(inst *model.Instance) bool { return IsClientPackage(inst.Package.StringID()) }
go
func (e *ClientExtractor) Applicable(inst *model.Instance) bool { return IsClientPackage(inst.Package.StringID()) }
[ "func", "(", "e", "*", "ClientExtractor", ")", "Applicable", "(", "inst", "*", "model", ".", "Instance", ")", "bool", "{", "return", "IsClientPackage", "(", "inst", ".", "Package", ".", "StringID", "(", ")", ")", "\n", "}" ]
// Applicable is part of Processor interface.
[ "Applicable", "is", "part", "of", "Processor", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/processing/client_extractor.go#L178-L180
9,437
luci/luci-go
cipd/appengine/impl/cas/cas.go
Internal
func Internal(d *tq.Dispatcher) StorageServer { impl := &storageImpl{ tq: d, getGS: gs.Get, settings: settings.Get, getSignedURL: getSignedURL, } impl.registerTasks() return impl }
go
func Internal(d *tq.Dispatcher) StorageServer { impl := &storageImpl{ tq: d, getGS: gs.Get, settings: settings.Get, getSignedURL: getSignedURL, } impl.registerTasks() return impl }
[ "func", "Internal", "(", "d", "*", "tq", ".", "Dispatcher", ")", "StorageServer", "{", "impl", ":=", "&", "storageImpl", "{", "tq", ":", "d", ",", "getGS", ":", "gs", ".", "Get", ",", "settings", ":", "settings", ".", "Get", ",", "getSignedURL", ":", "getSignedURL", ",", "}", "\n", "impl", ".", "registerTasks", "(", ")", "\n", "return", "impl", "\n", "}" ]
// Internal returns non-ACLed implementation of StorageService. // // It can be used internally by the backend. Assumes ACL checks are already // done. // // Registers some task queue tasks in the given dispatcher.
[ "Internal", "returns", "non", "-", "ACLed", "implementation", "of", "StorageService", ".", "It", "can", "be", "used", "internally", "by", "the", "backend", ".", "Assumes", "ACL", "checks", "are", "already", "done", ".", "Registers", "some", "task", "queue", "tasks", "in", "the", "given", "dispatcher", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/cas/cas.go#L71-L80
9,438
luci/luci-go
cipd/appengine/impl/cas/cas.go
GetReader
func (s *storageImpl) GetReader(c context.Context, ref *api.ObjectRef) (r gs.Reader, err error) { defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }() if err = common.ValidateObjectRef(ref, common.KnownHash); err != nil { return nil, errors.Annotate(err, "bad ref").Err() } cfg, err := s.settings(c) if err != nil { return nil, err } r, err = s.getGS(c).Reader(c, cfg.ObjectPath(ref), 0) if err != nil { ann := errors.Annotate(err, "can't read the object") if gs.StatusCode(err) == http.StatusNotFound { ann.Tag(grpcutil.NotFoundTag) } return nil, ann.Err() } return r, nil }
go
func (s *storageImpl) GetReader(c context.Context, ref *api.ObjectRef) (r gs.Reader, err error) { defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }() if err = common.ValidateObjectRef(ref, common.KnownHash); err != nil { return nil, errors.Annotate(err, "bad ref").Err() } cfg, err := s.settings(c) if err != nil { return nil, err } r, err = s.getGS(c).Reader(c, cfg.ObjectPath(ref), 0) if err != nil { ann := errors.Annotate(err, "can't read the object") if gs.StatusCode(err) == http.StatusNotFound { ann.Tag(grpcutil.NotFoundTag) } return nil, ann.Err() } return r, nil }
[ "func", "(", "s", "*", "storageImpl", ")", "GetReader", "(", "c", "context", ".", "Context", ",", "ref", "*", "api", ".", "ObjectRef", ")", "(", "r", "gs", ".", "Reader", ",", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "err", "=", "grpcutil", ".", "GRPCifyAndLogErr", "(", "c", ",", "err", ")", "}", "(", ")", "\n\n", "if", "err", "=", "common", ".", "ValidateObjectRef", "(", "ref", ",", "common", ".", "KnownHash", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "cfg", ",", "err", ":=", "s", ".", "settings", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "r", ",", "err", "=", "s", ".", "getGS", "(", "c", ")", ".", "Reader", "(", "c", ",", "cfg", ".", "ObjectPath", "(", "ref", ")", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "ann", ":=", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", "\n", "if", "gs", ".", "StatusCode", "(", "err", ")", "==", "http", ".", "StatusNotFound", "{", "ann", ".", "Tag", "(", "grpcutil", ".", "NotFoundTag", ")", "\n", "}", "\n", "return", "nil", ",", "ann", ".", "Err", "(", ")", "\n", "}", "\n", "return", "r", ",", "nil", "\n", "}" ]
// GetReader is part of StorageServer interface.
[ "GetReader", "is", "part", "of", "StorageServer", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/cas/cas.go#L106-L127
9,439
luci/luci-go
cipd/appengine/impl/cas/cas.go
GetObjectURL
func (s *storageImpl) GetObjectURL(c context.Context, r *api.GetObjectURLRequest) (resp *api.ObjectURL, err error) { defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }() if err := common.ValidateObjectRef(r.Object, common.KnownHash); err != nil { return nil, errors.Annotate(err, "bad 'object' field").Err() } // Lite validation for Content-Disposition header. As long as the filename // doesn't have '"' or '\n', we are constructing a valid header. Let the // browser do the rest of the validation however it likes. if strings.ContainsAny(r.DownloadFilename, "\"\r\n") { return nil, status.Errorf(codes.InvalidArgument, "bad 'download_filename' field, contains one of %q", "\"\r\n") } cfg, err := s.settings(c) if err != nil { return nil, err } sigFactory := defaultSigner if cfg.SignAs != "" { sigFactory = func(c context.Context) (*signer, error) { return iamSigner(c, cfg.SignAs) } } url, err := s.getSignedURL(c, cfg.ObjectPath(r.Object), r.DownloadFilename, sigFactory, s.getGS(c)) if err != nil { return nil, errors.Annotate(err, "failed to get signed URL").Err() } return &api.ObjectURL{SignedUrl: url}, nil }
go
func (s *storageImpl) GetObjectURL(c context.Context, r *api.GetObjectURLRequest) (resp *api.ObjectURL, err error) { defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }() if err := common.ValidateObjectRef(r.Object, common.KnownHash); err != nil { return nil, errors.Annotate(err, "bad 'object' field").Err() } // Lite validation for Content-Disposition header. As long as the filename // doesn't have '"' or '\n', we are constructing a valid header. Let the // browser do the rest of the validation however it likes. if strings.ContainsAny(r.DownloadFilename, "\"\r\n") { return nil, status.Errorf(codes.InvalidArgument, "bad 'download_filename' field, contains one of %q", "\"\r\n") } cfg, err := s.settings(c) if err != nil { return nil, err } sigFactory := defaultSigner if cfg.SignAs != "" { sigFactory = func(c context.Context) (*signer, error) { return iamSigner(c, cfg.SignAs) } } url, err := s.getSignedURL(c, cfg.ObjectPath(r.Object), r.DownloadFilename, sigFactory, s.getGS(c)) if err != nil { return nil, errors.Annotate(err, "failed to get signed URL").Err() } return &api.ObjectURL{SignedUrl: url}, nil }
[ "func", "(", "s", "*", "storageImpl", ")", "GetObjectURL", "(", "c", "context", ".", "Context", ",", "r", "*", "api", ".", "GetObjectURLRequest", ")", "(", "resp", "*", "api", ".", "ObjectURL", ",", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "err", "=", "grpcutil", ".", "GRPCifyAndLogErr", "(", "c", ",", "err", ")", "}", "(", ")", "\n\n", "if", "err", ":=", "common", ".", "ValidateObjectRef", "(", "r", ".", "Object", ",", "common", ".", "KnownHash", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "// Lite validation for Content-Disposition header. As long as the filename", "// doesn't have '\"' or '\\n', we are constructing a valid header. Let the", "// browser do the rest of the validation however it likes.", "if", "strings", ".", "ContainsAny", "(", "r", ".", "DownloadFilename", ",", "\"", "\\\"", "\\r", "\\n", "\"", ")", "{", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ",", "\"", "\\\"", "\\r", "\\n", "\"", ")", "\n", "}", "\n\n", "cfg", ",", "err", ":=", "s", ".", "settings", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "sigFactory", ":=", "defaultSigner", "\n", "if", "cfg", ".", "SignAs", "!=", "\"", "\"", "{", "sigFactory", "=", "func", "(", "c", "context", ".", "Context", ")", "(", "*", "signer", ",", "error", ")", "{", "return", "iamSigner", "(", "c", ",", "cfg", ".", "SignAs", ")", "\n", "}", "\n", "}", "\n\n", "url", ",", "err", ":=", "s", ".", "getSignedURL", "(", "c", ",", "cfg", ".", "ObjectPath", "(", "r", ".", "Object", ")", ",", "r", ".", "DownloadFilename", ",", "sigFactory", ",", "s", ".", "getGS", "(", "c", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "&", "api", ".", "ObjectURL", "{", "SignedUrl", ":", "url", "}", ",", "nil", "\n", "}" ]
// GetObjectURL implements the corresponding RPC method, see the proto doc.
[ "GetObjectURL", "implements", "the", "corresponding", "RPC", "method", "see", "the", "proto", "doc", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/cas/cas.go#L130-L161
9,440
luci/luci-go
cipd/appengine/impl/cas/cas.go
FinishUpload
func (s *storageImpl) FinishUpload(c context.Context, r *api.FinishUploadRequest) (resp *api.UploadOperation, err error) { defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }() if r.ForceHash != nil { if err := common.ValidateObjectRef(r.ForceHash, common.KnownHash); err != nil { return nil, errors.Annotate(err, "bad 'force_hash' field").Err() } } // Grab the corresponding operation and inspect its status. op, err := fetchOp(c, r.UploadOperationId) switch { case err != nil: return nil, err case op.Status != api.UploadStatus_UPLOADING: // Nothing to do if the operation is already closed or being verified. return op.ToProto(r.UploadOperationId), nil } // If the forced hash is provided by the (trusted) caller, we are almost done. // Just need to move the temp file to its final location based on this hash // and close the operation. if r.ForceHash != nil { mutated, err := s.finishAndForcedHash(c, op, r.ForceHash) if err != nil { return nil, err } return mutated.ToProto(r.UploadOperationId), nil } // Otherwise start the hash verification task, see verifyUploadTask below. mutated, err := op.Advance(c, func(c context.Context, op *upload.Operation) error { op.Status = api.UploadStatus_VERIFYING return s.tq.AddTask(c, &tq.Task{ Payload: &tasks.VerifyUpload{UploadOperationId: op.ID}, Title: fmt.Sprintf("%d", op.ID), }) }) if err != nil { return nil, errors.Annotate(err, "failed to start the verification task"). Tag(grpcutil.InternalTag).Err() } return mutated.ToProto(r.UploadOperationId), nil }
go
func (s *storageImpl) FinishUpload(c context.Context, r *api.FinishUploadRequest) (resp *api.UploadOperation, err error) { defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }() if r.ForceHash != nil { if err := common.ValidateObjectRef(r.ForceHash, common.KnownHash); err != nil { return nil, errors.Annotate(err, "bad 'force_hash' field").Err() } } // Grab the corresponding operation and inspect its status. op, err := fetchOp(c, r.UploadOperationId) switch { case err != nil: return nil, err case op.Status != api.UploadStatus_UPLOADING: // Nothing to do if the operation is already closed or being verified. return op.ToProto(r.UploadOperationId), nil } // If the forced hash is provided by the (trusted) caller, we are almost done. // Just need to move the temp file to its final location based on this hash // and close the operation. if r.ForceHash != nil { mutated, err := s.finishAndForcedHash(c, op, r.ForceHash) if err != nil { return nil, err } return mutated.ToProto(r.UploadOperationId), nil } // Otherwise start the hash verification task, see verifyUploadTask below. mutated, err := op.Advance(c, func(c context.Context, op *upload.Operation) error { op.Status = api.UploadStatus_VERIFYING return s.tq.AddTask(c, &tq.Task{ Payload: &tasks.VerifyUpload{UploadOperationId: op.ID}, Title: fmt.Sprintf("%d", op.ID), }) }) if err != nil { return nil, errors.Annotate(err, "failed to start the verification task"). Tag(grpcutil.InternalTag).Err() } return mutated.ToProto(r.UploadOperationId), nil }
[ "func", "(", "s", "*", "storageImpl", ")", "FinishUpload", "(", "c", "context", ".", "Context", ",", "r", "*", "api", ".", "FinishUploadRequest", ")", "(", "resp", "*", "api", ".", "UploadOperation", ",", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "err", "=", "grpcutil", ".", "GRPCifyAndLogErr", "(", "c", ",", "err", ")", "}", "(", ")", "\n\n", "if", "r", ".", "ForceHash", "!=", "nil", "{", "if", "err", ":=", "common", ".", "ValidateObjectRef", "(", "r", ".", "ForceHash", ",", "common", ".", "KnownHash", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "}", "\n\n", "// Grab the corresponding operation and inspect its status.", "op", ",", "err", ":=", "fetchOp", "(", "c", ",", "r", ".", "UploadOperationId", ")", "\n", "switch", "{", "case", "err", "!=", "nil", ":", "return", "nil", ",", "err", "\n", "case", "op", ".", "Status", "!=", "api", ".", "UploadStatus_UPLOADING", ":", "// Nothing to do if the operation is already closed or being verified.", "return", "op", ".", "ToProto", "(", "r", ".", "UploadOperationId", ")", ",", "nil", "\n", "}", "\n\n", "// If the forced hash is provided by the (trusted) caller, we are almost done.", "// Just need to move the temp file to its final location based on this hash", "// and close the operation.", "if", "r", ".", "ForceHash", "!=", "nil", "{", "mutated", ",", "err", ":=", "s", ".", "finishAndForcedHash", "(", "c", ",", "op", ",", "r", ".", "ForceHash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "mutated", ".", "ToProto", "(", "r", ".", "UploadOperationId", ")", ",", "nil", "\n", "}", "\n\n", "// Otherwise start the hash verification task, see verifyUploadTask below.", "mutated", ",", "err", ":=", "op", ".", "Advance", "(", "c", ",", "func", "(", "c", "context", ".", "Context", ",", "op", "*", "upload", ".", "Operation", ")", "error", "{", "op", ".", "Status", "=", "api", ".", "UploadStatus_VERIFYING", "\n", "return", "s", ".", "tq", ".", "AddTask", "(", "c", ",", "&", "tq", ".", "Task", "{", "Payload", ":", "&", "tasks", ".", "VerifyUpload", "{", "UploadOperationId", ":", "op", ".", "ID", "}", ",", "Title", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "op", ".", "ID", ")", ",", "}", ")", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Tag", "(", "grpcutil", ".", "InternalTag", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "mutated", ".", "ToProto", "(", "r", ".", "UploadOperationId", ")", ",", "nil", "\n", "}" ]
// FinishUpload implements the corresponding RPC method, see the proto doc.
[ "FinishUpload", "implements", "the", "corresponding", "RPC", "method", "see", "the", "proto", "doc", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/cas/cas.go#L260-L303
9,441
luci/luci-go
cipd/appengine/impl/cas/cas.go
CancelUpload
func (s *storageImpl) CancelUpload(c context.Context, r *api.CancelUploadRequest) (resp *api.UploadOperation, err error) { defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }() handleOpStatus := func(op *upload.Operation) (*api.UploadOperation, error) { if op.Status == api.UploadStatus_ERRORED || op.Status == api.UploadStatus_CANCELED { return op.ToProto(r.UploadOperationId), nil } return nil, errors.Reason("the operation is in state %s and can't be canceled", op.Status).Tag(grpcutil.FailedPreconditionTag).Err() } // Grab the corresponding operation and inspect its status. op, err := fetchOp(c, r.UploadOperationId) switch { case err != nil: return nil, err case op.Status != api.UploadStatus_UPLOADING: return handleOpStatus(op) } // Move the operation to canceled state and launch the TQ task to cleanup. mutated, err := op.Advance(c, func(c context.Context, op *upload.Operation) error { op.Status = api.UploadStatus_CANCELED return s.tq.AddTask(c, &tq.Task{ Payload: &tasks.CleanupUpload{ UploadOperationId: op.ID, UploadUrl: op.UploadURL, PathToCleanup: op.TempGSPath, }, Title: fmt.Sprintf("%d", op.ID), }) }) if err != nil { return nil, errors.Annotate(err, "failed to start the cleanup task"). Tag(grpcutil.InternalTag).Err() } return handleOpStatus(mutated) }
go
func (s *storageImpl) CancelUpload(c context.Context, r *api.CancelUploadRequest) (resp *api.UploadOperation, err error) { defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }() handleOpStatus := func(op *upload.Operation) (*api.UploadOperation, error) { if op.Status == api.UploadStatus_ERRORED || op.Status == api.UploadStatus_CANCELED { return op.ToProto(r.UploadOperationId), nil } return nil, errors.Reason("the operation is in state %s and can't be canceled", op.Status).Tag(grpcutil.FailedPreconditionTag).Err() } // Grab the corresponding operation and inspect its status. op, err := fetchOp(c, r.UploadOperationId) switch { case err != nil: return nil, err case op.Status != api.UploadStatus_UPLOADING: return handleOpStatus(op) } // Move the operation to canceled state and launch the TQ task to cleanup. mutated, err := op.Advance(c, func(c context.Context, op *upload.Operation) error { op.Status = api.UploadStatus_CANCELED return s.tq.AddTask(c, &tq.Task{ Payload: &tasks.CleanupUpload{ UploadOperationId: op.ID, UploadUrl: op.UploadURL, PathToCleanup: op.TempGSPath, }, Title: fmt.Sprintf("%d", op.ID), }) }) if err != nil { return nil, errors.Annotate(err, "failed to start the cleanup task"). Tag(grpcutil.InternalTag).Err() } return handleOpStatus(mutated) }
[ "func", "(", "s", "*", "storageImpl", ")", "CancelUpload", "(", "c", "context", ".", "Context", ",", "r", "*", "api", ".", "CancelUploadRequest", ")", "(", "resp", "*", "api", ".", "UploadOperation", ",", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "err", "=", "grpcutil", ".", "GRPCifyAndLogErr", "(", "c", ",", "err", ")", "}", "(", ")", "\n\n", "handleOpStatus", ":=", "func", "(", "op", "*", "upload", ".", "Operation", ")", "(", "*", "api", ".", "UploadOperation", ",", "error", ")", "{", "if", "op", ".", "Status", "==", "api", ".", "UploadStatus_ERRORED", "||", "op", ".", "Status", "==", "api", ".", "UploadStatus_CANCELED", "{", "return", "op", ".", "ToProto", "(", "r", ".", "UploadOperationId", ")", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "errors", ".", "Reason", "(", "\"", "\"", ",", "op", ".", "Status", ")", ".", "Tag", "(", "grpcutil", ".", "FailedPreconditionTag", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "// Grab the corresponding operation and inspect its status.", "op", ",", "err", ":=", "fetchOp", "(", "c", ",", "r", ".", "UploadOperationId", ")", "\n", "switch", "{", "case", "err", "!=", "nil", ":", "return", "nil", ",", "err", "\n", "case", "op", ".", "Status", "!=", "api", ".", "UploadStatus_UPLOADING", ":", "return", "handleOpStatus", "(", "op", ")", "\n", "}", "\n\n", "// Move the operation to canceled state and launch the TQ task to cleanup.", "mutated", ",", "err", ":=", "op", ".", "Advance", "(", "c", ",", "func", "(", "c", "context", ".", "Context", ",", "op", "*", "upload", ".", "Operation", ")", "error", "{", "op", ".", "Status", "=", "api", ".", "UploadStatus_CANCELED", "\n", "return", "s", ".", "tq", ".", "AddTask", "(", "c", ",", "&", "tq", ".", "Task", "{", "Payload", ":", "&", "tasks", ".", "CleanupUpload", "{", "UploadOperationId", ":", "op", ".", "ID", ",", "UploadUrl", ":", "op", ".", "UploadURL", ",", "PathToCleanup", ":", "op", ".", "TempGSPath", ",", "}", ",", "Title", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "op", ".", "ID", ")", ",", "}", ")", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Tag", "(", "grpcutil", ".", "InternalTag", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "handleOpStatus", "(", "mutated", ")", "\n", "}" ]
// CancelUpload implements the corresponding RPC method, see the proto doc.
[ "CancelUpload", "implements", "the", "corresponding", "RPC", "method", "see", "the", "proto", "doc", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/cas/cas.go#L306-L342
9,442
luci/luci-go
cipd/appengine/impl/cas/cas.go
fetchOp
func fetchOp(c context.Context, wrappedOpID string) (*upload.Operation, error) { opID, err := upload.UnwrapOpID(c, wrappedOpID, auth.CurrentIdentity(c)) if err != nil { if transient.Tag.In(err) { return nil, errors.Annotate(err, "failed to check HMAC on upload_operation_id").Err() } return nil, errors.Reason("no such upload operation"). InternalReason("HMAC check failed - %s", err). Tag(grpcutil.NotFoundTag).Err() } op := &upload.Operation{ID: opID} switch err := datastore.Get(c, op); { case err == datastore.ErrNoSuchEntity: return nil, errors.Reason("no such upload operation"). Tag(grpcutil.NotFoundTag).Err() case err != nil: return nil, errors.Annotate(err, "failed to fetch the upload operation"). Tag(grpcutil.InternalTag).Err() } return op, nil }
go
func fetchOp(c context.Context, wrappedOpID string) (*upload.Operation, error) { opID, err := upload.UnwrapOpID(c, wrappedOpID, auth.CurrentIdentity(c)) if err != nil { if transient.Tag.In(err) { return nil, errors.Annotate(err, "failed to check HMAC on upload_operation_id").Err() } return nil, errors.Reason("no such upload operation"). InternalReason("HMAC check failed - %s", err). Tag(grpcutil.NotFoundTag).Err() } op := &upload.Operation{ID: opID} switch err := datastore.Get(c, op); { case err == datastore.ErrNoSuchEntity: return nil, errors.Reason("no such upload operation"). Tag(grpcutil.NotFoundTag).Err() case err != nil: return nil, errors.Annotate(err, "failed to fetch the upload operation"). Tag(grpcutil.InternalTag).Err() } return op, nil }
[ "func", "fetchOp", "(", "c", "context", ".", "Context", ",", "wrappedOpID", "string", ")", "(", "*", "upload", ".", "Operation", ",", "error", ")", "{", "opID", ",", "err", ":=", "upload", ".", "UnwrapOpID", "(", "c", ",", "wrappedOpID", ",", "auth", ".", "CurrentIdentity", "(", "c", ")", ")", "\n", "if", "err", "!=", "nil", "{", "if", "transient", ".", "Tag", ".", "In", "(", "err", ")", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "nil", ",", "errors", ".", "Reason", "(", "\"", "\"", ")", ".", "InternalReason", "(", "\"", "\"", ",", "err", ")", ".", "Tag", "(", "grpcutil", ".", "NotFoundTag", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "op", ":=", "&", "upload", ".", "Operation", "{", "ID", ":", "opID", "}", "\n", "switch", "err", ":=", "datastore", ".", "Get", "(", "c", ",", "op", ")", ";", "{", "case", "err", "==", "datastore", ".", "ErrNoSuchEntity", ":", "return", "nil", ",", "errors", ".", "Reason", "(", "\"", "\"", ")", ".", "Tag", "(", "grpcutil", ".", "NotFoundTag", ")", ".", "Err", "(", ")", "\n", "case", "err", "!=", "nil", ":", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Tag", "(", "grpcutil", ".", "InternalTag", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "return", "op", ",", "nil", "\n", "}" ]
// fethcOp unwraps upload operation ID and fetches upload.Operation entity. // // Returns an grpc-tagged error on failure that can be returned to the RPC // caller right away.
[ "fethcOp", "unwraps", "upload", "operation", "ID", "and", "fetches", "upload", ".", "Operation", "entity", ".", "Returns", "an", "grpc", "-", "tagged", "error", "on", "failure", "that", "can", "be", "returned", "to", "the", "RPC", "caller", "right", "away", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/cas/cas.go#L348-L370
9,443
luci/luci-go
cipd/appengine/impl/cas/cas.go
finishAndForcedHash
func (s *storageImpl) finishAndForcedHash(c context.Context, op *upload.Operation, hash *api.ObjectRef) (*upload.Operation, error) { gs := s.getGS(c) cfg, err := s.settings(c) if err != nil { return nil, err } // Try to move the object into the final location. This may fail // transiently, in which case we ask the client to retry, or fatally, in // which case we close the upload operation with an error. pubErr := gs.Publish(c, cfg.ObjectPath(hash), op.TempGSPath, -1) if transient.Tag.In(pubErr) { return nil, errors.Annotate(pubErr, "failed to publish the object"). Tag(grpcutil.InternalTag).Err() } // Try to remove the leftover garbage. See maybeDelete doc for possible // caveats. if err := s.maybeDelete(c, gs, op.TempGSPath); err != nil { return nil, err } // Set the status of the operation based on whether we published the file // or not. return op.Advance(c, func(_ context.Context, op *upload.Operation) error { if pubErr != nil { op.Status = api.UploadStatus_ERRORED op.Error = fmt.Sprintf("Failed to publish the object - %s", pubErr) } else { op.Status = api.UploadStatus_PUBLISHED op.HashAlgo = hash.HashAlgo op.HexDigest = hash.HexDigest } return nil }) }
go
func (s *storageImpl) finishAndForcedHash(c context.Context, op *upload.Operation, hash *api.ObjectRef) (*upload.Operation, error) { gs := s.getGS(c) cfg, err := s.settings(c) if err != nil { return nil, err } // Try to move the object into the final location. This may fail // transiently, in which case we ask the client to retry, or fatally, in // which case we close the upload operation with an error. pubErr := gs.Publish(c, cfg.ObjectPath(hash), op.TempGSPath, -1) if transient.Tag.In(pubErr) { return nil, errors.Annotate(pubErr, "failed to publish the object"). Tag(grpcutil.InternalTag).Err() } // Try to remove the leftover garbage. See maybeDelete doc for possible // caveats. if err := s.maybeDelete(c, gs, op.TempGSPath); err != nil { return nil, err } // Set the status of the operation based on whether we published the file // or not. return op.Advance(c, func(_ context.Context, op *upload.Operation) error { if pubErr != nil { op.Status = api.UploadStatus_ERRORED op.Error = fmt.Sprintf("Failed to publish the object - %s", pubErr) } else { op.Status = api.UploadStatus_PUBLISHED op.HashAlgo = hash.HashAlgo op.HexDigest = hash.HexDigest } return nil }) }
[ "func", "(", "s", "*", "storageImpl", ")", "finishAndForcedHash", "(", "c", "context", ".", "Context", ",", "op", "*", "upload", ".", "Operation", ",", "hash", "*", "api", ".", "ObjectRef", ")", "(", "*", "upload", ".", "Operation", ",", "error", ")", "{", "gs", ":=", "s", ".", "getGS", "(", "c", ")", "\n", "cfg", ",", "err", ":=", "s", ".", "settings", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Try to move the object into the final location. This may fail", "// transiently, in which case we ask the client to retry, or fatally, in", "// which case we close the upload operation with an error.", "pubErr", ":=", "gs", ".", "Publish", "(", "c", ",", "cfg", ".", "ObjectPath", "(", "hash", ")", ",", "op", ".", "TempGSPath", ",", "-", "1", ")", "\n", "if", "transient", ".", "Tag", ".", "In", "(", "pubErr", ")", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "pubErr", ",", "\"", "\"", ")", ".", "Tag", "(", "grpcutil", ".", "InternalTag", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "// Try to remove the leftover garbage. See maybeDelete doc for possible", "// caveats.", "if", "err", ":=", "s", ".", "maybeDelete", "(", "c", ",", "gs", ",", "op", ".", "TempGSPath", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Set the status of the operation based on whether we published the file", "// or not.", "return", "op", ".", "Advance", "(", "c", ",", "func", "(", "_", "context", ".", "Context", ",", "op", "*", "upload", ".", "Operation", ")", "error", "{", "if", "pubErr", "!=", "nil", "{", "op", ".", "Status", "=", "api", ".", "UploadStatus_ERRORED", "\n", "op", ".", "Error", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "pubErr", ")", "\n", "}", "else", "{", "op", ".", "Status", "=", "api", ".", "UploadStatus_PUBLISHED", "\n", "op", ".", "HashAlgo", "=", "hash", ".", "HashAlgo", "\n", "op", ".", "HexDigest", "=", "hash", ".", "HexDigest", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "}" ]
// finishAndForcedHash finalizes uploads that use ForceHash field. // // It publishes the object immediately, skipping the verification.
[ "finishAndForcedHash", "finalizes", "uploads", "that", "use", "ForceHash", "field", ".", "It", "publishes", "the", "object", "immediately", "skipping", "the", "verification", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/cas/cas.go#L375-L410
9,444
luci/luci-go
cipd/appengine/impl/cas/cas.go
cleanupUploadTask
func (s *storageImpl) cleanupUploadTask(c context.Context, task *tasks.CleanupUpload) (err error) { gs := s.getGS(c) if err := gs.CancelUpload(c, task.UploadUrl); err != nil { if transient.Tag.In(err) { return errors.Annotate(err, "transient error when canceling the resumable upload").Err() } logging.WithError(err).Errorf(c, "Failed to cancel resumable upload") } if err := gs.Delete(c, task.PathToCleanup); err != nil { if transient.Tag.In(err) { return errors.Annotate(err, "transient error when deleting the temp file").Err() } logging.WithError(err).Errorf(c, "Failed to delete the temp file") } return nil }
go
func (s *storageImpl) cleanupUploadTask(c context.Context, task *tasks.CleanupUpload) (err error) { gs := s.getGS(c) if err := gs.CancelUpload(c, task.UploadUrl); err != nil { if transient.Tag.In(err) { return errors.Annotate(err, "transient error when canceling the resumable upload").Err() } logging.WithError(err).Errorf(c, "Failed to cancel resumable upload") } if err := gs.Delete(c, task.PathToCleanup); err != nil { if transient.Tag.In(err) { return errors.Annotate(err, "transient error when deleting the temp file").Err() } logging.WithError(err).Errorf(c, "Failed to delete the temp file") } return nil }
[ "func", "(", "s", "*", "storageImpl", ")", "cleanupUploadTask", "(", "c", "context", ".", "Context", ",", "task", "*", "tasks", ".", "CleanupUpload", ")", "(", "err", "error", ")", "{", "gs", ":=", "s", ".", "getGS", "(", "c", ")", "\n\n", "if", "err", ":=", "gs", ".", "CancelUpload", "(", "c", ",", "task", ".", "UploadUrl", ")", ";", "err", "!=", "nil", "{", "if", "transient", ".", "Tag", ".", "In", "(", "err", ")", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "err", ":=", "gs", ".", "Delete", "(", "c", ",", "task", ".", "PathToCleanup", ")", ";", "err", "!=", "nil", "{", "if", "transient", ".", "Tag", ".", "In", "(", "err", ")", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// cleanupUploadTask is called to clean up after a canceled upload. // // Best effort. If the temporary file can't be deleted from GS due to some // non-transient error, logs the error and ignores it, since retrying won't // help.
[ "cleanupUploadTask", "is", "called", "to", "clean", "up", "after", "a", "canceled", "upload", ".", "Best", "effort", ".", "If", "the", "temporary", "file", "can", "t", "be", "deleted", "from", "GS", "due", "to", "some", "non", "-", "transient", "error", "logs", "the", "error", "and", "ignores", "it", "since", "retrying", "won", "t", "help", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/cas/cas.go#L555-L573
9,445
luci/luci-go
milo/common/config.go
ProjectID
func (c *Console) ProjectID() string { if c.Parent == nil { return "" } return c.Parent.StringID() }
go
func (c *Console) ProjectID() string { if c.Parent == nil { return "" } return c.Parent.StringID() }
[ "func", "(", "c", "*", "Console", ")", "ProjectID", "(", ")", "string", "{", "if", "c", ".", "Parent", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "c", ".", "Parent", ".", "StringID", "(", ")", "\n", "}" ]
// ProjectID retrieves the project ID string of the console out of the Console's // parent key.
[ "ProjectID", "retrieves", "the", "project", "ID", "string", "of", "the", "console", "out", "of", "the", "Console", "s", "parent", "key", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/config.go#L93-L98
9,446
luci/luci-go
milo/common/config.go
FilterBuilders
func (c *Console) FilterBuilders(perms access.Permissions) { okBuilderIDs := make([]string, 0, len(c.Builders)) for _, id := range c.Builders { if bucket := extractBucket(id); bucket != "" && !perms.Can(bucket, access.AccessBucket) { continue } okBuilderIDs = append(okBuilderIDs, id) } c.Builders = okBuilderIDs okBuilders := make([]*config.Builder, 0, len(c.Def.Builders)) // A single builder entry could have multiple builder names. for _, b := range c.Def.Builders { okNames := make([]string, 0, len(b.Name)) for _, name := range b.Name { if bucket := extractBucket(name); bucket != "" && !perms.Can(bucket, access.AccessBucket) { continue } okNames = append(okNames, name) } b.Name = okNames if len(b.Name) > 0 { okBuilders = append(okBuilders, b) } } c.Def.Builders = okBuilders }
go
func (c *Console) FilterBuilders(perms access.Permissions) { okBuilderIDs := make([]string, 0, len(c.Builders)) for _, id := range c.Builders { if bucket := extractBucket(id); bucket != "" && !perms.Can(bucket, access.AccessBucket) { continue } okBuilderIDs = append(okBuilderIDs, id) } c.Builders = okBuilderIDs okBuilders := make([]*config.Builder, 0, len(c.Def.Builders)) // A single builder entry could have multiple builder names. for _, b := range c.Def.Builders { okNames := make([]string, 0, len(b.Name)) for _, name := range b.Name { if bucket := extractBucket(name); bucket != "" && !perms.Can(bucket, access.AccessBucket) { continue } okNames = append(okNames, name) } b.Name = okNames if len(b.Name) > 0 { okBuilders = append(okBuilders, b) } } c.Def.Builders = okBuilders }
[ "func", "(", "c", "*", "Console", ")", "FilterBuilders", "(", "perms", "access", ".", "Permissions", ")", "{", "okBuilderIDs", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "c", ".", "Builders", ")", ")", "\n", "for", "_", ",", "id", ":=", "range", "c", ".", "Builders", "{", "if", "bucket", ":=", "extractBucket", "(", "id", ")", ";", "bucket", "!=", "\"", "\"", "&&", "!", "perms", ".", "Can", "(", "bucket", ",", "access", ".", "AccessBucket", ")", "{", "continue", "\n", "}", "\n", "okBuilderIDs", "=", "append", "(", "okBuilderIDs", ",", "id", ")", "\n", "}", "\n", "c", ".", "Builders", "=", "okBuilderIDs", "\n", "okBuilders", ":=", "make", "(", "[", "]", "*", "config", ".", "Builder", ",", "0", ",", "len", "(", "c", ".", "Def", ".", "Builders", ")", ")", "\n", "// A single builder entry could have multiple builder names.", "for", "_", ",", "b", ":=", "range", "c", ".", "Def", ".", "Builders", "{", "okNames", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "b", ".", "Name", ")", ")", "\n", "for", "_", ",", "name", ":=", "range", "b", ".", "Name", "{", "if", "bucket", ":=", "extractBucket", "(", "name", ")", ";", "bucket", "!=", "\"", "\"", "&&", "!", "perms", ".", "Can", "(", "bucket", ",", "access", ".", "AccessBucket", ")", "{", "continue", "\n", "}", "\n", "okNames", "=", "append", "(", "okNames", ",", "name", ")", "\n", "}", "\n", "b", ".", "Name", "=", "okNames", "\n", "if", "len", "(", "b", ".", "Name", ")", ">", "0", "{", "okBuilders", "=", "append", "(", "okBuilders", ",", "b", ")", "\n", "}", "\n", "}", "\n", "c", ".", "Def", ".", "Builders", "=", "okBuilders", "\n", "}" ]
// FilterBuilders uses an access.Permissions to filter out builder IDs and builders // from the definition, and builders in the definition's header, which are not // allowed by the permissions.
[ "FilterBuilders", "uses", "an", "access", ".", "Permissions", "to", "filter", "out", "builder", "IDs", "and", "builders", "from", "the", "definition", "and", "builders", "in", "the", "definition", "s", "header", "which", "are", "not", "allowed", "by", "the", "permissions", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/config.go#L103-L128
9,447
luci/luci-go
milo/common/config.go
Buckets
func (c *Console) Buckets() stringset.Set { buckets := stringset.New(1) for _, id := range c.Builders { if bucket := extractBucket(id); bucket != "" { buckets.Add(bucket) } } return buckets }
go
func (c *Console) Buckets() stringset.Set { buckets := stringset.New(1) for _, id := range c.Builders { if bucket := extractBucket(id); bucket != "" { buckets.Add(bucket) } } return buckets }
[ "func", "(", "c", "*", "Console", ")", "Buckets", "(", ")", "stringset", ".", "Set", "{", "buckets", ":=", "stringset", ".", "New", "(", "1", ")", "\n", "for", "_", ",", "id", ":=", "range", "c", ".", "Builders", "{", "if", "bucket", ":=", "extractBucket", "(", "id", ")", ";", "bucket", "!=", "\"", "\"", "{", "buckets", ".", "Add", "(", "bucket", ")", "\n", "}", "\n", "}", "\n", "return", "buckets", "\n", "}" ]
// Buckets returns all buckets referenced by this Console's Builders.
[ "Buckets", "returns", "all", "buckets", "referenced", "by", "this", "Console", "s", "Builders", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/config.go#L131-L139
9,448
luci/luci-go
milo/common/config.go
SetID
func (id *ConsoleID) SetID(c context.Context, console *Console) *Console { if console == nil { console = &Console{} } console.Parent = datastore.MakeKey(c, "Project", id.Project) console.ID = id.ID return console }
go
func (id *ConsoleID) SetID(c context.Context, console *Console) *Console { if console == nil { console = &Console{} } console.Parent = datastore.MakeKey(c, "Project", id.Project) console.ID = id.ID return console }
[ "func", "(", "id", "*", "ConsoleID", ")", "SetID", "(", "c", "context", ".", "Context", ",", "console", "*", "Console", ")", "*", "Console", "{", "if", "console", "==", "nil", "{", "console", "=", "&", "Console", "{", "}", "\n", "}", "\n", "console", ".", "Parent", "=", "datastore", ".", "MakeKey", "(", "c", ",", "\"", "\"", ",", "id", ".", "Project", ")", "\n", "console", ".", "ID", "=", "id", ".", "ID", "\n", "return", "console", "\n", "}" ]
// NewEntity returns an empty Console datastore entity keyed with itself.
[ "NewEntity", "returns", "an", "empty", "Console", "datastore", "entity", "keyed", "with", "itself", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/config.go#L180-L187
9,449
luci/luci-go
milo/common/config.go
LuciConfigURL
func LuciConfigURL(c context.Context, configSet, path, revision string) string { // TODO(hinoka): This shouldn't be hardcoded, instead we should get the // luci-config instance from the context. But we only use this instance at // the moment so it is okay for now. // TODO(hinoka): The UI doesn't allow specifying paths and revision yet. Add // that in when it is supported. return fmt.Sprintf("https://luci-config.appspot.com/newui#/%s", configSet) }
go
func LuciConfigURL(c context.Context, configSet, path, revision string) string { // TODO(hinoka): This shouldn't be hardcoded, instead we should get the // luci-config instance from the context. But we only use this instance at // the moment so it is okay for now. // TODO(hinoka): The UI doesn't allow specifying paths and revision yet. Add // that in when it is supported. return fmt.Sprintf("https://luci-config.appspot.com/newui#/%s", configSet) }
[ "func", "LuciConfigURL", "(", "c", "context", ".", "Context", ",", "configSet", ",", "path", ",", "revision", "string", ")", "string", "{", "// TODO(hinoka): This shouldn't be hardcoded, instead we should get the", "// luci-config instance from the context. But we only use this instance at", "// the moment so it is okay for now.", "// TODO(hinoka): The UI doesn't allow specifying paths and revision yet. Add", "// that in when it is supported.", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "configSet", ")", "\n", "}" ]
// LuciConfigURL returns a user friendly URL that specifies where to view // this console definition.
[ "LuciConfigURL", "returns", "a", "user", "friendly", "URL", "that", "specifies", "where", "to", "view", "this", "console", "definition", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/config.go#L200-L207
9,450
luci/luci-go
milo/common/config.go
GetCurrentServiceConfig
func GetCurrentServiceConfig(c context.Context) (*ServiceConfig, error) { // This maker function is used to do the actual fetch of the ServiceConfig // from datastore. It is called if the ServiceConfig is not in proc cache. item, err := serviceCfgCache.Fetch(c, func(interface{}) (interface{}, time.Duration, error) { msg := ServiceConfig{ID: ServiceConfigID} err := datastore.Get(c, &msg) if err != nil { return nil, time.Minute, err } logging.Infof(c, "loaded service config from datastore") return msg, time.Minute, nil }) if err != nil { return nil, fmt.Errorf("failed to get service config: %s", err.Error()) } if msg, ok := item.(ServiceConfig); ok { logging.Infof(c, "loaded config entry from %s", msg.LastUpdated.Format(time.RFC3339)) return &msg, nil } return nil, fmt.Errorf("could not load service config %#v", item) }
go
func GetCurrentServiceConfig(c context.Context) (*ServiceConfig, error) { // This maker function is used to do the actual fetch of the ServiceConfig // from datastore. It is called if the ServiceConfig is not in proc cache. item, err := serviceCfgCache.Fetch(c, func(interface{}) (interface{}, time.Duration, error) { msg := ServiceConfig{ID: ServiceConfigID} err := datastore.Get(c, &msg) if err != nil { return nil, time.Minute, err } logging.Infof(c, "loaded service config from datastore") return msg, time.Minute, nil }) if err != nil { return nil, fmt.Errorf("failed to get service config: %s", err.Error()) } if msg, ok := item.(ServiceConfig); ok { logging.Infof(c, "loaded config entry from %s", msg.LastUpdated.Format(time.RFC3339)) return &msg, nil } return nil, fmt.Errorf("could not load service config %#v", item) }
[ "func", "GetCurrentServiceConfig", "(", "c", "context", ".", "Context", ")", "(", "*", "ServiceConfig", ",", "error", ")", "{", "// This maker function is used to do the actual fetch of the ServiceConfig", "// from datastore. It is called if the ServiceConfig is not in proc cache.", "item", ",", "err", ":=", "serviceCfgCache", ".", "Fetch", "(", "c", ",", "func", "(", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "time", ".", "Duration", ",", "error", ")", "{", "msg", ":=", "ServiceConfig", "{", "ID", ":", "ServiceConfigID", "}", "\n", "err", ":=", "datastore", ".", "Get", "(", "c", ",", "&", "msg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "time", ".", "Minute", ",", "err", "\n", "}", "\n", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ")", "\n", "return", "msg", ",", "time", ".", "Minute", ",", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "}", "\n", "if", "msg", ",", "ok", ":=", "item", ".", "(", "ServiceConfig", ")", ";", "ok", "{", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "msg", ".", "LastUpdated", ".", "Format", "(", "time", ".", "RFC3339", ")", ")", "\n", "return", "&", "msg", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "item", ")", "\n", "}" ]
// GetCurrentServiceConfig gets the service config for the instance from either // process cache or datastore cache.
[ "GetCurrentServiceConfig", "gets", "the", "service", "config", "for", "the", "instance", "from", "either", "process", "cache", "or", "datastore", "cache", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/config.go#L278-L298
9,451
luci/luci-go
milo/common/config.go
UpdateServiceConfig
func UpdateServiceConfig(c context.Context) (*config.Settings, error) { // Load the settings from luci-config. cs := cfgclient.CurrentServiceConfigSet(c) // Acquire the raw config client. lucicfg := backend.Get(c).GetConfigInterface(c, backend.AsService) cfg, err := lucicfg.GetConfig(c, cs, globalConfigFilename, false) if err != nil { return nil, fmt.Errorf("could not load %s from luci-config: %s", globalConfigFilename, err) } settings := &config.Settings{} err = protoutil.UnmarshalTextML(cfg.Content, settings) if err != nil { return nil, fmt.Errorf( "could not unmarshal proto from luci-config:\n%s", cfg.Content) } newConfig := ServiceConfig{ ID: ServiceConfigID, Text: cfg.Content, Revision: cfg.Revision, LastUpdated: time.Now().UTC(), } newConfig.Data, err = proto.Marshal(settings) if err != nil { return nil, fmt.Errorf("could not marshal proto into binary\n%s", newConfig.Text) } // Do the revision check & swap in a datastore transaction. err = datastore.RunInTransaction(c, func(c context.Context) error { oldConfig := ServiceConfig{ID: ServiceConfigID} err := datastore.Get(c, &oldConfig) switch err { case datastore.ErrNoSuchEntity: // Might be the first time this has run. logging.WithError(err).Warningf(c, "No existing service config.") case nil: // Continue default: return fmt.Errorf("could not load existing config: %s", err) } // Check to see if we need to update if oldConfig.Revision == newConfig.Revision { logging.Infof(c, "revisions matched (%s), no need to update", oldConfig.Revision) return nil } logging.Infof(c, "revisions differ (old %s, new %s), updating", oldConfig.Revision, newConfig.Revision) return datastore.Put(c, &newConfig) }, nil) if err != nil { return nil, errors.Annotate(err, "failed to update config entry in transaction").Err() } logging.Infof(c, "successfully updated to new config") return settings, nil }
go
func UpdateServiceConfig(c context.Context) (*config.Settings, error) { // Load the settings from luci-config. cs := cfgclient.CurrentServiceConfigSet(c) // Acquire the raw config client. lucicfg := backend.Get(c).GetConfigInterface(c, backend.AsService) cfg, err := lucicfg.GetConfig(c, cs, globalConfigFilename, false) if err != nil { return nil, fmt.Errorf("could not load %s from luci-config: %s", globalConfigFilename, err) } settings := &config.Settings{} err = protoutil.UnmarshalTextML(cfg.Content, settings) if err != nil { return nil, fmt.Errorf( "could not unmarshal proto from luci-config:\n%s", cfg.Content) } newConfig := ServiceConfig{ ID: ServiceConfigID, Text: cfg.Content, Revision: cfg.Revision, LastUpdated: time.Now().UTC(), } newConfig.Data, err = proto.Marshal(settings) if err != nil { return nil, fmt.Errorf("could not marshal proto into binary\n%s", newConfig.Text) } // Do the revision check & swap in a datastore transaction. err = datastore.RunInTransaction(c, func(c context.Context) error { oldConfig := ServiceConfig{ID: ServiceConfigID} err := datastore.Get(c, &oldConfig) switch err { case datastore.ErrNoSuchEntity: // Might be the first time this has run. logging.WithError(err).Warningf(c, "No existing service config.") case nil: // Continue default: return fmt.Errorf("could not load existing config: %s", err) } // Check to see if we need to update if oldConfig.Revision == newConfig.Revision { logging.Infof(c, "revisions matched (%s), no need to update", oldConfig.Revision) return nil } logging.Infof(c, "revisions differ (old %s, new %s), updating", oldConfig.Revision, newConfig.Revision) return datastore.Put(c, &newConfig) }, nil) if err != nil { return nil, errors.Annotate(err, "failed to update config entry in transaction").Err() } logging.Infof(c, "successfully updated to new config") return settings, nil }
[ "func", "UpdateServiceConfig", "(", "c", "context", ".", "Context", ")", "(", "*", "config", ".", "Settings", ",", "error", ")", "{", "// Load the settings from luci-config.", "cs", ":=", "cfgclient", ".", "CurrentServiceConfigSet", "(", "c", ")", "\n", "// Acquire the raw config client.", "lucicfg", ":=", "backend", ".", "Get", "(", "c", ")", ".", "GetConfigInterface", "(", "c", ",", "backend", ".", "AsService", ")", "\n", "cfg", ",", "err", ":=", "lucicfg", ".", "GetConfig", "(", "c", ",", "cs", ",", "globalConfigFilename", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "globalConfigFilename", ",", "err", ")", "\n", "}", "\n", "settings", ":=", "&", "config", ".", "Settings", "{", "}", "\n", "err", "=", "protoutil", ".", "UnmarshalTextML", "(", "cfg", ".", "Content", ",", "settings", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "cfg", ".", "Content", ")", "\n", "}", "\n", "newConfig", ":=", "ServiceConfig", "{", "ID", ":", "ServiceConfigID", ",", "Text", ":", "cfg", ".", "Content", ",", "Revision", ":", "cfg", ".", "Revision", ",", "LastUpdated", ":", "time", ".", "Now", "(", ")", ".", "UTC", "(", ")", ",", "}", "\n", "newConfig", ".", "Data", ",", "err", "=", "proto", ".", "Marshal", "(", "settings", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "newConfig", ".", "Text", ")", "\n", "}", "\n\n", "// Do the revision check & swap in a datastore transaction.", "err", "=", "datastore", ".", "RunInTransaction", "(", "c", ",", "func", "(", "c", "context", ".", "Context", ")", "error", "{", "oldConfig", ":=", "ServiceConfig", "{", "ID", ":", "ServiceConfigID", "}", "\n", "err", ":=", "datastore", ".", "Get", "(", "c", ",", "&", "oldConfig", ")", "\n", "switch", "err", "{", "case", "datastore", ".", "ErrNoSuchEntity", ":", "// Might be the first time this has run.", "logging", ".", "WithError", "(", "err", ")", ".", "Warningf", "(", "c", ",", "\"", "\"", ")", "\n", "case", "nil", ":", "// Continue", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "// Check to see if we need to update", "if", "oldConfig", ".", "Revision", "==", "newConfig", ".", "Revision", "{", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "oldConfig", ".", "Revision", ")", "\n", "return", "nil", "\n", "}", "\n", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "oldConfig", ".", "Revision", ",", "newConfig", ".", "Revision", ")", "\n", "return", "datastore", ".", "Put", "(", "c", ",", "&", "newConfig", ")", "\n", "}", ",", "nil", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ")", "\n\n", "return", "settings", ",", "nil", "\n", "}" ]
// UpdateServiceConfig fetches the service config from luci-config // and then stores a snapshot of the configuration in datastore.
[ "UpdateServiceConfig", "fetches", "the", "service", "config", "from", "luci", "-", "config", "and", "then", "stores", "a", "snapshot", "of", "the", "configuration", "in", "datastore", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/config.go#L304-L359
9,452
luci/luci-go
milo/common/config.go
updateProjectConsoles
func updateProjectConsoles(c context.Context, projectID string, cfg *configInterface.Config) (stringset.Set, error) { proj := config.Project{} if err := protoutil.UnmarshalTextML(cfg.Content, &proj); err != nil { return nil, errors.Annotate(err, "unmarshalling proto").Err() } // Extract the headers into a map for convenience. headers := make(map[string]*config.Header, len(proj.Headers)) for _, header := range proj.Headers { headers[header.Id] = header } // Keep a list of known consoles so we can prune deleted ones later. knownConsoles := stringset.New(len(proj.Consoles)) // Save the project into the datastore. project := Project{ID: projectID, LogoURL: proj.LogoUrl} if proj.BuildBugTemplate != nil { project.BuildBugTemplate = *proj.BuildBugTemplate } if err := datastore.Put(c, &project); err != nil { return nil, err } parentKey := datastore.KeyForObj(c, &project) // Iterate through all the proto consoles, adding and replacing the // known ones if needed. err := datastore.RunInTransaction(c, func(c context.Context) error { toPut := make([]*Console, 0, len(proj.Consoles)) for i, pc := range proj.Consoles { if header, ok := headers[pc.HeaderId]; pc.Header == nil && ok { // Inject a header if HeaderId is specified, and it doesn't already have one. pc.Header = header } knownConsoles.Add(pc.Id) con, err := GetConsole(c, projectID, pc.Id) switch { case err == ErrConsoleNotFound: // continue case err != nil: return errors.Annotate(err, "checking %s", pc.Id).Err() case con.ConfigRevision == cfg.Revision && con.Ordinal == i: // Check if revisions match; if so just skip it. // TODO(jchinlee): remove Ordinal check when Version field is added to Console. continue } toPut = append(toPut, &Console{ Parent: parentKey, ID: pc.Id, Ordinal: i, ConfigURL: LuciConfigURL(c, string(cfg.ConfigSet), cfg.Path, cfg.Revision), ConfigRevision: cfg.Revision, Builders: pc.AllBuilderIDs(), Def: *pc, }) } return datastore.Put(c, toPut) }, nil) if err != nil { logging.WithError(err).Errorf(c, "failed to save consoles of project %q at revision %q", projectID, cfg.Revision) return nil, err } logging.Infof(c, "saved consoles of project %q at revision %q", projectID, cfg.Revision) return knownConsoles, nil }
go
func updateProjectConsoles(c context.Context, projectID string, cfg *configInterface.Config) (stringset.Set, error) { proj := config.Project{} if err := protoutil.UnmarshalTextML(cfg.Content, &proj); err != nil { return nil, errors.Annotate(err, "unmarshalling proto").Err() } // Extract the headers into a map for convenience. headers := make(map[string]*config.Header, len(proj.Headers)) for _, header := range proj.Headers { headers[header.Id] = header } // Keep a list of known consoles so we can prune deleted ones later. knownConsoles := stringset.New(len(proj.Consoles)) // Save the project into the datastore. project := Project{ID: projectID, LogoURL: proj.LogoUrl} if proj.BuildBugTemplate != nil { project.BuildBugTemplate = *proj.BuildBugTemplate } if err := datastore.Put(c, &project); err != nil { return nil, err } parentKey := datastore.KeyForObj(c, &project) // Iterate through all the proto consoles, adding and replacing the // known ones if needed. err := datastore.RunInTransaction(c, func(c context.Context) error { toPut := make([]*Console, 0, len(proj.Consoles)) for i, pc := range proj.Consoles { if header, ok := headers[pc.HeaderId]; pc.Header == nil && ok { // Inject a header if HeaderId is specified, and it doesn't already have one. pc.Header = header } knownConsoles.Add(pc.Id) con, err := GetConsole(c, projectID, pc.Id) switch { case err == ErrConsoleNotFound: // continue case err != nil: return errors.Annotate(err, "checking %s", pc.Id).Err() case con.ConfigRevision == cfg.Revision && con.Ordinal == i: // Check if revisions match; if so just skip it. // TODO(jchinlee): remove Ordinal check when Version field is added to Console. continue } toPut = append(toPut, &Console{ Parent: parentKey, ID: pc.Id, Ordinal: i, ConfigURL: LuciConfigURL(c, string(cfg.ConfigSet), cfg.Path, cfg.Revision), ConfigRevision: cfg.Revision, Builders: pc.AllBuilderIDs(), Def: *pc, }) } return datastore.Put(c, toPut) }, nil) if err != nil { logging.WithError(err).Errorf(c, "failed to save consoles of project %q at revision %q", projectID, cfg.Revision) return nil, err } logging.Infof(c, "saved consoles of project %q at revision %q", projectID, cfg.Revision) return knownConsoles, nil }
[ "func", "updateProjectConsoles", "(", "c", "context", ".", "Context", ",", "projectID", "string", ",", "cfg", "*", "configInterface", ".", "Config", ")", "(", "stringset", ".", "Set", ",", "error", ")", "{", "proj", ":=", "config", ".", "Project", "{", "}", "\n", "if", "err", ":=", "protoutil", ".", "UnmarshalTextML", "(", "cfg", ".", "Content", ",", "&", "proj", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "// Extract the headers into a map for convenience.", "headers", ":=", "make", "(", "map", "[", "string", "]", "*", "config", ".", "Header", ",", "len", "(", "proj", ".", "Headers", ")", ")", "\n", "for", "_", ",", "header", ":=", "range", "proj", ".", "Headers", "{", "headers", "[", "header", ".", "Id", "]", "=", "header", "\n", "}", "\n", "// Keep a list of known consoles so we can prune deleted ones later.", "knownConsoles", ":=", "stringset", ".", "New", "(", "len", "(", "proj", ".", "Consoles", ")", ")", "\n", "// Save the project into the datastore.", "project", ":=", "Project", "{", "ID", ":", "projectID", ",", "LogoURL", ":", "proj", ".", "LogoUrl", "}", "\n", "if", "proj", ".", "BuildBugTemplate", "!=", "nil", "{", "project", ".", "BuildBugTemplate", "=", "*", "proj", ".", "BuildBugTemplate", "\n", "}", "\n", "if", "err", ":=", "datastore", ".", "Put", "(", "c", ",", "&", "project", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "parentKey", ":=", "datastore", ".", "KeyForObj", "(", "c", ",", "&", "project", ")", "\n", "// Iterate through all the proto consoles, adding and replacing the", "// known ones if needed.", "err", ":=", "datastore", ".", "RunInTransaction", "(", "c", ",", "func", "(", "c", "context", ".", "Context", ")", "error", "{", "toPut", ":=", "make", "(", "[", "]", "*", "Console", ",", "0", ",", "len", "(", "proj", ".", "Consoles", ")", ")", "\n", "for", "i", ",", "pc", ":=", "range", "proj", ".", "Consoles", "{", "if", "header", ",", "ok", ":=", "headers", "[", "pc", ".", "HeaderId", "]", ";", "pc", ".", "Header", "==", "nil", "&&", "ok", "{", "// Inject a header if HeaderId is specified, and it doesn't already have one.", "pc", ".", "Header", "=", "header", "\n", "}", "\n", "knownConsoles", ".", "Add", "(", "pc", ".", "Id", ")", "\n", "con", ",", "err", ":=", "GetConsole", "(", "c", ",", "projectID", ",", "pc", ".", "Id", ")", "\n", "switch", "{", "case", "err", "==", "ErrConsoleNotFound", ":", "// continue", "case", "err", "!=", "nil", ":", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "pc", ".", "Id", ")", ".", "Err", "(", ")", "\n", "case", "con", ".", "ConfigRevision", "==", "cfg", ".", "Revision", "&&", "con", ".", "Ordinal", "==", "i", ":", "// Check if revisions match; if so just skip it.", "// TODO(jchinlee): remove Ordinal check when Version field is added to Console.", "continue", "\n", "}", "\n", "toPut", "=", "append", "(", "toPut", ",", "&", "Console", "{", "Parent", ":", "parentKey", ",", "ID", ":", "pc", ".", "Id", ",", "Ordinal", ":", "i", ",", "ConfigURL", ":", "LuciConfigURL", "(", "c", ",", "string", "(", "cfg", ".", "ConfigSet", ")", ",", "cfg", ".", "Path", ",", "cfg", ".", "Revision", ")", ",", "ConfigRevision", ":", "cfg", ".", "Revision", ",", "Builders", ":", "pc", ".", "AllBuilderIDs", "(", ")", ",", "Def", ":", "*", "pc", ",", "}", ")", "\n", "}", "\n", "return", "datastore", ".", "Put", "(", "c", ",", "toPut", ")", "\n", "}", ",", "nil", ")", "\n\n", "if", "err", "!=", "nil", "{", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ",", "projectID", ",", "cfg", ".", "Revision", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "projectID", ",", "cfg", ".", "Revision", ")", "\n\n", "return", "knownConsoles", ",", "nil", "\n", "}" ]
// updateProjectConsoles updates all of the consoles for a given project, // and then returns a set of known console names.
[ "updateProjectConsoles", "updates", "all", "of", "the", "consoles", "for", "a", "given", "project", "and", "then", "returns", "a", "set", "of", "known", "console", "names", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/config.go#L363-L427
9,453
luci/luci-go
milo/common/config.go
UpdateConsoles
func UpdateConsoles(c context.Context) error { cfgName := info.AppID(c) + ".cfg" logging.Debugf(c, "fetching configs for %s", cfgName) // Acquire the raw config client. lucicfg := backend.Get(c).GetConfigInterface(c, backend.AsService) // Project configs for Milo contains console definitions. configs, err := lucicfg.GetProjectConfigs(c, cfgName, false) if err != nil { return errors.Annotate(err, "while fetching project configs").Err() } logging.Infof(c, "got %d project configs", len(configs)) merr := errors.MultiError{} knownProjects := map[string]stringset.Set{} // Iterate through each project config, extracting the console definition. for _, cfg := range configs { projectName := cfg.ConfigSet.Project() if projectName == "" { return fmt.Errorf("Invalid config set path %s", cfg.ConfigSet) } knownProjects[projectName] = nil if kp, err := updateProjectConsoles(c, projectName, &cfg); err != nil { err = errors.Annotate(err, "processing project %s", projectName).Err() merr = append(merr, err) } else { knownProjects[projectName] = kp } } // Delete all the consoles that no longer exists or are part of deleted projects. toDelete := []*datastore.Key{} err = datastore.Run(c, datastore.NewQuery("Console"), func(key *datastore.Key) error { proj := key.Parent().StringID() id := key.StringID() // If this console is either: // 1. In a project that no longer exists, or // 2. Not in the project, then delete it. knownConsoles, ok := knownProjects[proj] if !ok { logging.Infof( c, "deleting %s/%s because the project no longer exists", proj, id) toDelete = append(toDelete, key) return nil } if knownConsoles == nil { // The project exists but we couldn't check it this time. Skip it and // try again the next cron cycle. return nil } if !knownConsoles.Has(id) { logging.Infof( c, "deleting %s/%s because the console no longer exists", proj, id) toDelete = append(toDelete, key) } return nil }) if err != nil { merr = append(merr, err) } else if err := datastore.Delete(c, toDelete); err != nil { merr = append(merr, err) } // Print some stats. processedConsoles := 0 for _, cons := range knownProjects { if cons != nil { processedConsoles += cons.Len() } } logging.Infof( c, "processed %d consoles over %d projects", processedConsoles, len(knownProjects)) if len(merr) == 0 { return nil } return merr }
go
func UpdateConsoles(c context.Context) error { cfgName := info.AppID(c) + ".cfg" logging.Debugf(c, "fetching configs for %s", cfgName) // Acquire the raw config client. lucicfg := backend.Get(c).GetConfigInterface(c, backend.AsService) // Project configs for Milo contains console definitions. configs, err := lucicfg.GetProjectConfigs(c, cfgName, false) if err != nil { return errors.Annotate(err, "while fetching project configs").Err() } logging.Infof(c, "got %d project configs", len(configs)) merr := errors.MultiError{} knownProjects := map[string]stringset.Set{} // Iterate through each project config, extracting the console definition. for _, cfg := range configs { projectName := cfg.ConfigSet.Project() if projectName == "" { return fmt.Errorf("Invalid config set path %s", cfg.ConfigSet) } knownProjects[projectName] = nil if kp, err := updateProjectConsoles(c, projectName, &cfg); err != nil { err = errors.Annotate(err, "processing project %s", projectName).Err() merr = append(merr, err) } else { knownProjects[projectName] = kp } } // Delete all the consoles that no longer exists or are part of deleted projects. toDelete := []*datastore.Key{} err = datastore.Run(c, datastore.NewQuery("Console"), func(key *datastore.Key) error { proj := key.Parent().StringID() id := key.StringID() // If this console is either: // 1. In a project that no longer exists, or // 2. Not in the project, then delete it. knownConsoles, ok := knownProjects[proj] if !ok { logging.Infof( c, "deleting %s/%s because the project no longer exists", proj, id) toDelete = append(toDelete, key) return nil } if knownConsoles == nil { // The project exists but we couldn't check it this time. Skip it and // try again the next cron cycle. return nil } if !knownConsoles.Has(id) { logging.Infof( c, "deleting %s/%s because the console no longer exists", proj, id) toDelete = append(toDelete, key) } return nil }) if err != nil { merr = append(merr, err) } else if err := datastore.Delete(c, toDelete); err != nil { merr = append(merr, err) } // Print some stats. processedConsoles := 0 for _, cons := range knownProjects { if cons != nil { processedConsoles += cons.Len() } } logging.Infof( c, "processed %d consoles over %d projects", processedConsoles, len(knownProjects)) if len(merr) == 0 { return nil } return merr }
[ "func", "UpdateConsoles", "(", "c", "context", ".", "Context", ")", "error", "{", "cfgName", ":=", "info", ".", "AppID", "(", "c", ")", "+", "\"", "\"", "\n\n", "logging", ".", "Debugf", "(", "c", ",", "\"", "\"", ",", "cfgName", ")", "\n", "// Acquire the raw config client.", "lucicfg", ":=", "backend", ".", "Get", "(", "c", ")", ".", "GetConfigInterface", "(", "c", ",", "backend", ".", "AsService", ")", "\n", "// Project configs for Milo contains console definitions.", "configs", ",", "err", ":=", "lucicfg", ".", "GetProjectConfigs", "(", "c", ",", "cfgName", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "len", "(", "configs", ")", ")", "\n\n", "merr", ":=", "errors", ".", "MultiError", "{", "}", "\n", "knownProjects", ":=", "map", "[", "string", "]", "stringset", ".", "Set", "{", "}", "\n", "// Iterate through each project config, extracting the console definition.", "for", "_", ",", "cfg", ":=", "range", "configs", "{", "projectName", ":=", "cfg", ".", "ConfigSet", ".", "Project", "(", ")", "\n", "if", "projectName", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "cfg", ".", "ConfigSet", ")", "\n", "}", "\n", "knownProjects", "[", "projectName", "]", "=", "nil", "\n", "if", "kp", ",", "err", ":=", "updateProjectConsoles", "(", "c", ",", "projectName", ",", "&", "cfg", ")", ";", "err", "!=", "nil", "{", "err", "=", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "projectName", ")", ".", "Err", "(", ")", "\n", "merr", "=", "append", "(", "merr", ",", "err", ")", "\n", "}", "else", "{", "knownProjects", "[", "projectName", "]", "=", "kp", "\n", "}", "\n", "}", "\n\n", "// Delete all the consoles that no longer exists or are part of deleted projects.", "toDelete", ":=", "[", "]", "*", "datastore", ".", "Key", "{", "}", "\n", "err", "=", "datastore", ".", "Run", "(", "c", ",", "datastore", ".", "NewQuery", "(", "\"", "\"", ")", ",", "func", "(", "key", "*", "datastore", ".", "Key", ")", "error", "{", "proj", ":=", "key", ".", "Parent", "(", ")", ".", "StringID", "(", ")", "\n", "id", ":=", "key", ".", "StringID", "(", ")", "\n", "// If this console is either:", "// 1. In a project that no longer exists, or", "// 2. Not in the project, then delete it.", "knownConsoles", ",", "ok", ":=", "knownProjects", "[", "proj", "]", "\n", "if", "!", "ok", "{", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "proj", ",", "id", ")", "\n", "toDelete", "=", "append", "(", "toDelete", ",", "key", ")", "\n", "return", "nil", "\n", "}", "\n", "if", "knownConsoles", "==", "nil", "{", "// The project exists but we couldn't check it this time. Skip it and", "// try again the next cron cycle.", "return", "nil", "\n", "}", "\n", "if", "!", "knownConsoles", ".", "Has", "(", "id", ")", "{", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "proj", ",", "id", ")", "\n", "toDelete", "=", "append", "(", "toDelete", ",", "key", ")", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "merr", "=", "append", "(", "merr", ",", "err", ")", "\n", "}", "else", "if", "err", ":=", "datastore", ".", "Delete", "(", "c", ",", "toDelete", ")", ";", "err", "!=", "nil", "{", "merr", "=", "append", "(", "merr", ",", "err", ")", "\n", "}", "\n\n", "// Print some stats.", "processedConsoles", ":=", "0", "\n", "for", "_", ",", "cons", ":=", "range", "knownProjects", "{", "if", "cons", "!=", "nil", "{", "processedConsoles", "+=", "cons", ".", "Len", "(", ")", "\n", "}", "\n", "}", "\n", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "processedConsoles", ",", "len", "(", "knownProjects", ")", ")", "\n\n", "if", "len", "(", "merr", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "return", "merr", "\n", "}" ]
// UpdateConsoles updates internal console definitions entities based off luci-config.
[ "UpdateConsoles", "updates", "internal", "console", "definitions", "entities", "based", "off", "luci", "-", "config", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/config.go#L430-L507
9,454
luci/luci-go
milo/common/config.go
GetAllProjects
func GetAllProjects(c context.Context) ([]Project, error) { q := datastore.NewQuery("Project") projs := []Project{} if err := datastore.GetAll(c, q, &projs); err != nil { return nil, errors.Annotate(err, "getting projects").Err() } result := []Project{} for _, proj := range projs { switch allowed, err := IsAllowed(c, proj.ID); { case err != nil: return nil, err case allowed: result = append(result, proj) } } return result, nil }
go
func GetAllProjects(c context.Context) ([]Project, error) { q := datastore.NewQuery("Project") projs := []Project{} if err := datastore.GetAll(c, q, &projs); err != nil { return nil, errors.Annotate(err, "getting projects").Err() } result := []Project{} for _, proj := range projs { switch allowed, err := IsAllowed(c, proj.ID); { case err != nil: return nil, err case allowed: result = append(result, proj) } } return result, nil }
[ "func", "GetAllProjects", "(", "c", "context", ".", "Context", ")", "(", "[", "]", "Project", ",", "error", ")", "{", "q", ":=", "datastore", ".", "NewQuery", "(", "\"", "\"", ")", "\n", "projs", ":=", "[", "]", "Project", "{", "}", "\n\n", "if", "err", ":=", "datastore", ".", "GetAll", "(", "c", ",", "q", ",", "&", "projs", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "result", ":=", "[", "]", "Project", "{", "}", "\n", "for", "_", ",", "proj", ":=", "range", "projs", "{", "switch", "allowed", ",", "err", ":=", "IsAllowed", "(", "c", ",", "proj", ".", "ID", ")", ";", "{", "case", "err", "!=", "nil", ":", "return", "nil", ",", "err", "\n", "case", "allowed", ":", "result", "=", "append", "(", "result", ",", "proj", ")", "\n", "}", "\n", "}", "\n", "return", "result", ",", "nil", "\n", "}" ]
// GetAllProjects returns all projects the current user has access to.
[ "GetAllProjects", "returns", "all", "projects", "the", "current", "user", "has", "access", "to", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/config.go#L551-L568
9,455
luci/luci-go
milo/common/config.go
GetProjectConsoles
func GetProjectConsoles(c context.Context, projectID string) ([]*Console, error) { // Query datastore for consoles related to the project. q := datastore.NewQuery("Console") parentKey := datastore.MakeKey(c, "Project", projectID) q = q.Ancestor(parentKey) con := []*Console{} err := datastore.GetAll(c, q, &con) sort.Slice(con, func(i, j int) bool { return con[i].Ordinal < con[j].Ordinal }) return con, errors.Annotate(err, "getting project %q consoles", projectID).Err() }
go
func GetProjectConsoles(c context.Context, projectID string) ([]*Console, error) { // Query datastore for consoles related to the project. q := datastore.NewQuery("Console") parentKey := datastore.MakeKey(c, "Project", projectID) q = q.Ancestor(parentKey) con := []*Console{} err := datastore.GetAll(c, q, &con) sort.Slice(con, func(i, j int) bool { return con[i].Ordinal < con[j].Ordinal }) return con, errors.Annotate(err, "getting project %q consoles", projectID).Err() }
[ "func", "GetProjectConsoles", "(", "c", "context", ".", "Context", ",", "projectID", "string", ")", "(", "[", "]", "*", "Console", ",", "error", ")", "{", "// Query datastore for consoles related to the project.", "q", ":=", "datastore", ".", "NewQuery", "(", "\"", "\"", ")", "\n", "parentKey", ":=", "datastore", ".", "MakeKey", "(", "c", ",", "\"", "\"", ",", "projectID", ")", "\n", "q", "=", "q", ".", "Ancestor", "(", "parentKey", ")", "\n", "con", ":=", "[", "]", "*", "Console", "{", "}", "\n", "err", ":=", "datastore", ".", "GetAll", "(", "c", ",", "q", ",", "&", "con", ")", "\n", "sort", ".", "Slice", "(", "con", ",", "func", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "con", "[", "i", "]", ".", "Ordinal", "<", "con", "[", "j", "]", ".", "Ordinal", "}", ")", "\n", "return", "con", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "projectID", ")", ".", "Err", "(", ")", "\n", "}" ]
// GetProjectConsoles returns all consoles for the given project ordered as in config.
[ "GetProjectConsoles", "returns", "all", "consoles", "for", "the", "given", "project", "ordered", "as", "in", "config", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/config.go#L571-L580
9,456
luci/luci-go
milo/common/config.go
init
func init() { // Milo is only responsible for validating the config matching the instance's // appID in a project config. validation.Rules.Add("regex:projects/.*", "${appid}.cfg", validateProjectCfg) validation.Rules.Add("services/${appid}", globalConfigFilename, validateServiceCfg) }
go
func init() { // Milo is only responsible for validating the config matching the instance's // appID in a project config. validation.Rules.Add("regex:projects/.*", "${appid}.cfg", validateProjectCfg) validation.Rules.Add("services/${appid}", globalConfigFilename, validateServiceCfg) }
[ "func", "init", "(", ")", "{", "// Milo is only responsible for validating the config matching the instance's", "// appID in a project config.", "validation", ".", "Rules", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ",", "validateProjectCfg", ")", "\n", "validation", ".", "Rules", ".", "Add", "(", "\"", "\"", ",", "globalConfigFilename", ",", "validateServiceCfg", ")", "\n", "}" ]
// Config validation rules go here.
[ "Config", "validation", "rules", "go", "here", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/config.go#L617-L622
9,457
luci/luci-go
lucictx/local_auth.go
GetLocalAuth
func GetLocalAuth(ctx context.Context) *LocalAuth { ret := LocalAuth{} ok, err := Lookup(ctx, "local_auth", &ret) if err != nil { panic(err) } if !ok { return nil } return &ret }
go
func GetLocalAuth(ctx context.Context) *LocalAuth { ret := LocalAuth{} ok, err := Lookup(ctx, "local_auth", &ret) if err != nil { panic(err) } if !ok { return nil } return &ret }
[ "func", "GetLocalAuth", "(", "ctx", "context", ".", "Context", ")", "*", "LocalAuth", "{", "ret", ":=", "LocalAuth", "{", "}", "\n", "ok", ",", "err", ":=", "Lookup", "(", "ctx", ",", "\"", "\"", ",", "&", "ret", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "if", "!", "ok", "{", "return", "nil", "\n", "}", "\n", "return", "&", "ret", "\n", "}" ]
// GetLocalAuth calls Lookup and returns a copy of the current LocalAuth from // LUCI_CONTEXT if it was present. If no LocalAuth is in the context, this // returns nil.
[ "GetLocalAuth", "calls", "Lookup", "and", "returns", "a", "copy", "of", "the", "current", "LocalAuth", "from", "LUCI_CONTEXT", "if", "it", "was", "present", ".", "If", "no", "LocalAuth", "is", "in", "the", "context", "this", "returns", "nil", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucictx/local_auth.go#L52-L62
9,458
luci/luci-go
lucictx/local_auth.go
SetLocalAuth
func SetLocalAuth(ctx context.Context, la *LocalAuth) context.Context { var raw interface{} if la != nil { raw = la } ctx, err := Set(ctx, "local_auth", raw) if err != nil { panic(fmt.Errorf("impossible: %s", err)) } return ctx }
go
func SetLocalAuth(ctx context.Context, la *LocalAuth) context.Context { var raw interface{} if la != nil { raw = la } ctx, err := Set(ctx, "local_auth", raw) if err != nil { panic(fmt.Errorf("impossible: %s", err)) } return ctx }
[ "func", "SetLocalAuth", "(", "ctx", "context", ".", "Context", ",", "la", "*", "LocalAuth", ")", "context", ".", "Context", "{", "var", "raw", "interface", "{", "}", "\n", "if", "la", "!=", "nil", "{", "raw", "=", "la", "\n", "}", "\n", "ctx", ",", "err", ":=", "Set", "(", "ctx", ",", "\"", "\"", ",", "raw", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n", "return", "ctx", "\n", "}" ]
// SetLocalAuth sets the LocalAuth in the LUCI_CONTEXT.
[ "SetLocalAuth", "sets", "the", "LocalAuth", "in", "the", "LUCI_CONTEXT", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucictx/local_auth.go#L65-L75
9,459
luci/luci-go
logdog/client/bootstrapResult/result.go
WriteJSON
func (r *Result) WriteJSON(path string) error { fd, err := os.Create(path) if err != nil { return err } defer fd.Close() return json.NewEncoder(fd).Encode(r) }
go
func (r *Result) WriteJSON(path string) error { fd, err := os.Create(path) if err != nil { return err } defer fd.Close() return json.NewEncoder(fd).Encode(r) }
[ "func", "(", "r", "*", "Result", ")", "WriteJSON", "(", "path", "string", ")", "error", "{", "fd", ",", "err", ":=", "os", ".", "Create", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "fd", ".", "Close", "(", ")", "\n", "return", "json", ".", "NewEncoder", "(", "fd", ")", ".", "Encode", "(", "r", ")", "\n", "}" ]
// WriteJSON writes Result as a JSON document to the specified path.
[ "WriteJSON", "writes", "Result", "as", "a", "JSON", "document", "to", "the", "specified", "path", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/bootstrapResult/result.go#L33-L40
9,460
luci/luci-go
tokenserver/appengine/impl/utils/policy/entities.go
updateImportedPolicy
func updateImportedPolicy(c context.Context, name, rev, sha256 string, serialized []byte) error { header := &importedPolicyHeader{ Name: name, Revision: rev, SHA256: sha256, } body := &importedPolicyBody{ Parent: datastore.KeyForObj(c, header), Revision: rev, SHA256: sha256, Data: serialized, } return transient.Tag.Apply(datastore.RunInTransaction(c, func(c context.Context) error { return datastore.Put(c, header, body) }, nil)) }
go
func updateImportedPolicy(c context.Context, name, rev, sha256 string, serialized []byte) error { header := &importedPolicyHeader{ Name: name, Revision: rev, SHA256: sha256, } body := &importedPolicyBody{ Parent: datastore.KeyForObj(c, header), Revision: rev, SHA256: sha256, Data: serialized, } return transient.Tag.Apply(datastore.RunInTransaction(c, func(c context.Context) error { return datastore.Put(c, header, body) }, nil)) }
[ "func", "updateImportedPolicy", "(", "c", "context", ".", "Context", ",", "name", ",", "rev", ",", "sha256", "string", ",", "serialized", "[", "]", "byte", ")", "error", "{", "header", ":=", "&", "importedPolicyHeader", "{", "Name", ":", "name", ",", "Revision", ":", "rev", ",", "SHA256", ":", "sha256", ",", "}", "\n", "body", ":=", "&", "importedPolicyBody", "{", "Parent", ":", "datastore", ".", "KeyForObj", "(", "c", ",", "header", ")", ",", "Revision", ":", "rev", ",", "SHA256", ":", "sha256", ",", "Data", ":", "serialized", ",", "}", "\n", "return", "transient", ".", "Tag", ".", "Apply", "(", "datastore", ".", "RunInTransaction", "(", "c", ",", "func", "(", "c", "context", ".", "Context", ")", "error", "{", "return", "datastore", ".", "Put", "(", "c", ",", "header", ",", "body", ")", "\n", "}", ",", "nil", ")", ")", "\n", "}" ]
// updateImportedPolicy replaces the currently stored policy. // // It transactionally updates both importedPolicyHeader and importedPolicyBody.
[ "updateImportedPolicy", "replaces", "the", "currently", "stored", "policy", ".", "It", "transactionally", "updates", "both", "importedPolicyHeader", "and", "importedPolicyBody", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/policy/entities.go#L56-L71
9,461
luci/luci-go
common/flag/multiflag/multiflag.go
GetOutput
func (mf *MultiFlag) GetOutput() io.Writer { if w := mf.Output; w != nil { return w } return os.Stderr }
go
func (mf *MultiFlag) GetOutput() io.Writer { if w := mf.Output; w != nil { return w } return os.Stderr }
[ "func", "(", "mf", "*", "MultiFlag", ")", "GetOutput", "(", ")", "io", ".", "Writer", "{", "if", "w", ":=", "mf", ".", "Output", ";", "w", "!=", "nil", "{", "return", "w", "\n", "}", "\n", "return", "os", ".", "Stderr", "\n", "}" ]
// GetOutput returns the output Writer used for help output.
[ "GetOutput", "returns", "the", "output", "Writer", "used", "for", "help", "output", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/flag/multiflag/multiflag.go#L92-L97
9,462
luci/luci-go
common/flag/multiflag/multiflag.go
GetOptionFor
func (mf *MultiFlag) GetOptionFor(name string) Option { for _, option := range mf.Options { if option.Descriptor().Name == name { return option } } return nil }
go
func (mf *MultiFlag) GetOptionFor(name string) Option { for _, option := range mf.Options { if option.Descriptor().Name == name { return option } } return nil }
[ "func", "(", "mf", "*", "MultiFlag", ")", "GetOptionFor", "(", "name", "string", ")", "Option", "{", "for", "_", ",", "option", ":=", "range", "mf", ".", "Options", "{", "if", "option", ".", "Descriptor", "(", ")", ".", "Name", "==", "name", "{", "return", "option", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetOptionFor returns the Option associated with the specified name, or nil // if one isn't defined.
[ "GetOptionFor", "returns", "the", "Option", "associated", "with", "the", "specified", "name", "or", "nil", "if", "one", "isn", "t", "defined", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/flag/multiflag/multiflag.go#L131-L138
9,463
luci/luci-go
common/flag/multiflag/multiflag.go
OptionNames
func (mf MultiFlag) OptionNames() []string { optionNames := make([]string, 0, len(mf.Options)) for _, opt := range mf.Options { optionNames = append(optionNames, opt.Descriptor().Name) } return optionNames }
go
func (mf MultiFlag) OptionNames() []string { optionNames := make([]string, 0, len(mf.Options)) for _, opt := range mf.Options { optionNames = append(optionNames, opt.Descriptor().Name) } return optionNames }
[ "func", "(", "mf", "MultiFlag", ")", "OptionNames", "(", ")", "[", "]", "string", "{", "optionNames", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "mf", ".", "Options", ")", ")", "\n", "for", "_", ",", "opt", ":=", "range", "mf", ".", "Options", "{", "optionNames", "=", "append", "(", "optionNames", ",", "opt", ".", "Descriptor", "(", ")", ".", "Name", ")", "\n", "}", "\n", "return", "optionNames", "\n", "}" ]
// OptionNames returns a list of the option names registered with a MultiFlag.
[ "OptionNames", "returns", "a", "list", "of", "the", "option", "names", "registered", "with", "a", "MultiFlag", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/flag/multiflag/multiflag.go#L141-L147
9,464
luci/luci-go
common/flag/multiflag/multiflag.go
PrintHelp
func (mf *MultiFlag) PrintHelp() error { descriptors := make(optionDescriptorSlice, len(mf.Options)) for idx, opt := range mf.Options { descriptors[idx] = opt.Descriptor() } sort.Sort(descriptors) fmt.Fprintln(mf.Output, mf.Description) return writeAlignedOptionDescriptors(mf.Output, []*OptionDescriptor(descriptors)) }
go
func (mf *MultiFlag) PrintHelp() error { descriptors := make(optionDescriptorSlice, len(mf.Options)) for idx, opt := range mf.Options { descriptors[idx] = opt.Descriptor() } sort.Sort(descriptors) fmt.Fprintln(mf.Output, mf.Description) return writeAlignedOptionDescriptors(mf.Output, []*OptionDescriptor(descriptors)) }
[ "func", "(", "mf", "*", "MultiFlag", ")", "PrintHelp", "(", ")", "error", "{", "descriptors", ":=", "make", "(", "optionDescriptorSlice", ",", "len", "(", "mf", ".", "Options", ")", ")", "\n", "for", "idx", ",", "opt", ":=", "range", "mf", ".", "Options", "{", "descriptors", "[", "idx", "]", "=", "opt", ".", "Descriptor", "(", ")", "\n", "}", "\n", "sort", ".", "Sort", "(", "descriptors", ")", "\n\n", "fmt", ".", "Fprintln", "(", "mf", ".", "Output", ",", "mf", ".", "Description", ")", "\n", "return", "writeAlignedOptionDescriptors", "(", "mf", ".", "Output", ",", "[", "]", "*", "OptionDescriptor", "(", "descriptors", ")", ")", "\n", "}" ]
// PrintHelp prints a formatted help string for a MultiFlag. This help string // details the Options registered with the MultiFlag.
[ "PrintHelp", "prints", "a", "formatted", "help", "string", "for", "a", "MultiFlag", ".", "This", "help", "string", "details", "the", "Options", "registered", "with", "the", "MultiFlag", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/flag/multiflag/multiflag.go#L151-L160
9,465
luci/luci-go
common/flag/multiflag/multiflag.go
Descriptor
func (o *FlagOption) Descriptor() *OptionDescriptor { return &OptionDescriptor{ Name: o.Name, Description: o.Description, Pinned: o.Pinned, } }
go
func (o *FlagOption) Descriptor() *OptionDescriptor { return &OptionDescriptor{ Name: o.Name, Description: o.Description, Pinned: o.Pinned, } }
[ "func", "(", "o", "*", "FlagOption", ")", "Descriptor", "(", ")", "*", "OptionDescriptor", "{", "return", "&", "OptionDescriptor", "{", "Name", ":", "o", ".", "Name", ",", "Description", ":", "o", ".", "Description", ",", "Pinned", ":", "o", ".", "Pinned", ",", "}", "\n", "}" ]
// Descriptor implements Option.
[ "Descriptor", "implements", "Option", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/flag/multiflag/multiflag.go#L180-L186
9,466
luci/luci-go
common/flag/multiflag/multiflag.go
PrintHelp
func (o *FlagOption) PrintHelp(output io.Writer) { flags := o.Flags() flags.SetOutput(output) flags.PrintDefaults() }
go
func (o *FlagOption) PrintHelp(output io.Writer) { flags := o.Flags() flags.SetOutput(output) flags.PrintDefaults() }
[ "func", "(", "o", "*", "FlagOption", ")", "PrintHelp", "(", "output", "io", ".", "Writer", ")", "{", "flags", ":=", "o", ".", "Flags", "(", ")", "\n", "flags", ".", "SetOutput", "(", "output", ")", "\n", "flags", ".", "PrintDefaults", "(", ")", "\n", "}" ]
// PrintHelp implements Option.
[ "PrintHelp", "implements", "Option", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/flag/multiflag/multiflag.go#L189-L193
9,467
luci/luci-go
common/flag/multiflag/multiflag.go
Run
func (o *FlagOption) Run(value string) error { if err := o.flags.Parse(value); err != nil { return err } return nil }
go
func (o *FlagOption) Run(value string) error { if err := o.flags.Parse(value); err != nil { return err } return nil }
[ "func", "(", "o", "*", "FlagOption", ")", "Run", "(", "value", "string", ")", "error", "{", "if", "err", ":=", "o", ".", "flags", ".", "Parse", "(", "value", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Run implements Option.
[ "Run", "implements", "Option", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/flag/multiflag/multiflag.go#L201-L206
9,468
luci/luci-go
common/flag/multiflag/multiflag.go
writeAlignedOptionDescriptors
func writeAlignedOptionDescriptors(w io.Writer, descriptors []*OptionDescriptor) error { tw := tabwriter.NewWriter(w, 0, 4, 2, ' ', 0) for _, desc := range descriptors { fmt.Fprintf(tw, "%s\t%s\n", desc.Name, desc.Description) } if err := tw.Flush(); err != nil { return err } return nil }
go
func writeAlignedOptionDescriptors(w io.Writer, descriptors []*OptionDescriptor) error { tw := tabwriter.NewWriter(w, 0, 4, 2, ' ', 0) for _, desc := range descriptors { fmt.Fprintf(tw, "%s\t%s\n", desc.Name, desc.Description) } if err := tw.Flush(); err != nil { return err } return nil }
[ "func", "writeAlignedOptionDescriptors", "(", "w", "io", ".", "Writer", ",", "descriptors", "[", "]", "*", "OptionDescriptor", ")", "error", "{", "tw", ":=", "tabwriter", ".", "NewWriter", "(", "w", ",", "0", ",", "4", ",", "2", ",", "' '", ",", "0", ")", "\n\n", "for", "_", ",", "desc", ":=", "range", "descriptors", "{", "fmt", ".", "Fprintf", "(", "tw", ",", "\"", "\\t", "\\n", "\"", ",", "desc", ".", "Name", ",", "desc", ".", "Description", ")", "\n", "}", "\n\n", "if", "err", ":=", "tw", ".", "Flush", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// writeAlignedOptionDescriptors writes help entries for a series of Options.
[ "writeAlignedOptionDescriptors", "writes", "help", "entries", "for", "a", "series", "of", "Options", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/flag/multiflag/multiflag.go#L297-L308
9,469
luci/luci-go
milo/buildsource/buildbot/grpc.go
GetBuildbotBuildJSON
func (s *Service) GetBuildbotBuildJSON(c context.Context, req *milo.BuildbotBuildRequest) ( *milo.BuildbotBuildJSON, error) { apiUsage.Add(c, 1, "GetBuildbotBuildJSON", req.Master, req.Builder, req.ExcludeDeprecated, false) if req.Master == "" { return nil, status.Errorf(codes.InvalidArgument, "No master specified") } if req.Builder == "" { return nil, status.Errorf(codes.InvalidArgument, "No builder specified") } cu := auth.CurrentUser(c) logging.Debugf(c, "%s is requesting %s/%s/%d", cu.Identity, req.Master, req.Builder, req.BuildNum) if err := buildstore.CanAccessMaster(c, req.Master); err != nil { return nil, err } b, err := buildstore.GetBuild(c, buildbot.BuildID{ Master: req.Master, Builder: req.Builder, Number: int(req.BuildNum), }) switch code := grpcutil.Code(err); { case code == codes.PermissionDenied, code == codes.NotFound: return nil, errNotFoundGRPC case err != nil: return nil, err case b == nil: return nil, errNotFoundGRPC } if req.ExcludeDeprecated { excludeDeprecatedFromBuild(b) } bs, err := json.Marshal(b) if err != nil { return nil, err } // Marshal the build back into JSON format. return &milo.BuildbotBuildJSON{Data: bs}, nil }
go
func (s *Service) GetBuildbotBuildJSON(c context.Context, req *milo.BuildbotBuildRequest) ( *milo.BuildbotBuildJSON, error) { apiUsage.Add(c, 1, "GetBuildbotBuildJSON", req.Master, req.Builder, req.ExcludeDeprecated, false) if req.Master == "" { return nil, status.Errorf(codes.InvalidArgument, "No master specified") } if req.Builder == "" { return nil, status.Errorf(codes.InvalidArgument, "No builder specified") } cu := auth.CurrentUser(c) logging.Debugf(c, "%s is requesting %s/%s/%d", cu.Identity, req.Master, req.Builder, req.BuildNum) if err := buildstore.CanAccessMaster(c, req.Master); err != nil { return nil, err } b, err := buildstore.GetBuild(c, buildbot.BuildID{ Master: req.Master, Builder: req.Builder, Number: int(req.BuildNum), }) switch code := grpcutil.Code(err); { case code == codes.PermissionDenied, code == codes.NotFound: return nil, errNotFoundGRPC case err != nil: return nil, err case b == nil: return nil, errNotFoundGRPC } if req.ExcludeDeprecated { excludeDeprecatedFromBuild(b) } bs, err := json.Marshal(b) if err != nil { return nil, err } // Marshal the build back into JSON format. return &milo.BuildbotBuildJSON{Data: bs}, nil }
[ "func", "(", "s", "*", "Service", ")", "GetBuildbotBuildJSON", "(", "c", "context", ".", "Context", ",", "req", "*", "milo", ".", "BuildbotBuildRequest", ")", "(", "*", "milo", ".", "BuildbotBuildJSON", ",", "error", ")", "{", "apiUsage", ".", "Add", "(", "c", ",", "1", ",", "\"", "\"", ",", "req", ".", "Master", ",", "req", ".", "Builder", ",", "req", ".", "ExcludeDeprecated", ",", "false", ")", "\n\n", "if", "req", ".", "Master", "==", "\"", "\"", "{", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "req", ".", "Builder", "==", "\"", "\"", "{", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n", "cu", ":=", "auth", ".", "CurrentUser", "(", "c", ")", "\n", "logging", ".", "Debugf", "(", "c", ",", "\"", "\"", ",", "cu", ".", "Identity", ",", "req", ".", "Master", ",", "req", ".", "Builder", ",", "req", ".", "BuildNum", ")", "\n\n", "if", "err", ":=", "buildstore", ".", "CanAccessMaster", "(", "c", ",", "req", ".", "Master", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "b", ",", "err", ":=", "buildstore", ".", "GetBuild", "(", "c", ",", "buildbot", ".", "BuildID", "{", "Master", ":", "req", ".", "Master", ",", "Builder", ":", "req", ".", "Builder", ",", "Number", ":", "int", "(", "req", ".", "BuildNum", ")", ",", "}", ")", "\n", "switch", "code", ":=", "grpcutil", ".", "Code", "(", "err", ")", ";", "{", "case", "code", "==", "codes", ".", "PermissionDenied", ",", "code", "==", "codes", ".", "NotFound", ":", "return", "nil", ",", "errNotFoundGRPC", "\n", "case", "err", "!=", "nil", ":", "return", "nil", ",", "err", "\n", "case", "b", "==", "nil", ":", "return", "nil", ",", "errNotFoundGRPC", "\n", "}", "\n\n", "if", "req", ".", "ExcludeDeprecated", "{", "excludeDeprecatedFromBuild", "(", "b", ")", "\n", "}", "\n\n", "bs", ",", "err", ":=", "json", ".", "Marshal", "(", "b", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Marshal the build back into JSON format.", "return", "&", "milo", ".", "BuildbotBuildJSON", "{", "Data", ":", "bs", "}", ",", "nil", "\n", "}" ]
// GetBuildbotBuildJSON implements milo.BuildbotServer.
[ "GetBuildbotBuildJSON", "implements", "milo", ".", "BuildbotServer", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/grpc.go#L55-L99
9,470
luci/luci-go
milo/buildsource/buildbot/grpc.go
GetBuildbotBuildsJSON
func (s *Service) GetBuildbotBuildsJSON(c context.Context, req *milo.BuildbotBuildsRequest) ( *milo.BuildbotBuildsJSON, error) { apiUsage.Add(c, 1, "GetBuildbotBuildsJSON", req.Master, req.Builder, req.ExcludeDeprecated, req.NoEmulation) if req.Master == "" { return nil, status.Errorf(codes.InvalidArgument, "No master specified") } if req.Builder == "" { return nil, status.Errorf(codes.InvalidArgument, "No builder specified") } limit := int(req.Limit) if limit == 0 { limit = 20 } cu := auth.CurrentUser(c) logging.Debugf(c, "%s is requesting %s/%s (limit %d)", cu.Identity, req.Master, req.Builder, limit) if err := buildstore.CanAccessMaster(c, req.Master); err != nil { return nil, err } q := buildstore.Query{ Master: req.Master, Builder: req.Builder, Limit: limit, } if !req.IncludeCurrent { q.Finished = buildstore.Yes } res, err := buildstore.GetBuilds(c, q) switch code := grpcutil.Code(err); { case code == codes.NotFound, code == codes.PermissionDenied: return nil, errNotFoundGRPC case err != nil: return nil, err } buildsJSON := &milo.BuildbotBuildsJSON{ Builds: make([]*milo.BuildbotBuildJSON, len(res.Builds)), } for i, b := range res.Builds { if req.ExcludeDeprecated { excludeDeprecatedFromBuild(b) } bs, err := json.Marshal(b) if err != nil { return nil, err } buildsJSON.Builds[i] = &milo.BuildbotBuildJSON{Data: bs} } return buildsJSON, nil }
go
func (s *Service) GetBuildbotBuildsJSON(c context.Context, req *milo.BuildbotBuildsRequest) ( *milo.BuildbotBuildsJSON, error) { apiUsage.Add(c, 1, "GetBuildbotBuildsJSON", req.Master, req.Builder, req.ExcludeDeprecated, req.NoEmulation) if req.Master == "" { return nil, status.Errorf(codes.InvalidArgument, "No master specified") } if req.Builder == "" { return nil, status.Errorf(codes.InvalidArgument, "No builder specified") } limit := int(req.Limit) if limit == 0 { limit = 20 } cu := auth.CurrentUser(c) logging.Debugf(c, "%s is requesting %s/%s (limit %d)", cu.Identity, req.Master, req.Builder, limit) if err := buildstore.CanAccessMaster(c, req.Master); err != nil { return nil, err } q := buildstore.Query{ Master: req.Master, Builder: req.Builder, Limit: limit, } if !req.IncludeCurrent { q.Finished = buildstore.Yes } res, err := buildstore.GetBuilds(c, q) switch code := grpcutil.Code(err); { case code == codes.NotFound, code == codes.PermissionDenied: return nil, errNotFoundGRPC case err != nil: return nil, err } buildsJSON := &milo.BuildbotBuildsJSON{ Builds: make([]*milo.BuildbotBuildJSON, len(res.Builds)), } for i, b := range res.Builds { if req.ExcludeDeprecated { excludeDeprecatedFromBuild(b) } bs, err := json.Marshal(b) if err != nil { return nil, err } buildsJSON.Builds[i] = &milo.BuildbotBuildJSON{Data: bs} } return buildsJSON, nil }
[ "func", "(", "s", "*", "Service", ")", "GetBuildbotBuildsJSON", "(", "c", "context", ".", "Context", ",", "req", "*", "milo", ".", "BuildbotBuildsRequest", ")", "(", "*", "milo", ".", "BuildbotBuildsJSON", ",", "error", ")", "{", "apiUsage", ".", "Add", "(", "c", ",", "1", ",", "\"", "\"", ",", "req", ".", "Master", ",", "req", ".", "Builder", ",", "req", ".", "ExcludeDeprecated", ",", "req", ".", "NoEmulation", ")", "\n\n", "if", "req", ".", "Master", "==", "\"", "\"", "{", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "req", ".", "Builder", "==", "\"", "\"", "{", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n\n", "limit", ":=", "int", "(", "req", ".", "Limit", ")", "\n", "if", "limit", "==", "0", "{", "limit", "=", "20", "\n", "}", "\n\n", "cu", ":=", "auth", ".", "CurrentUser", "(", "c", ")", "\n", "logging", ".", "Debugf", "(", "c", ",", "\"", "\"", ",", "cu", ".", "Identity", ",", "req", ".", "Master", ",", "req", ".", "Builder", ",", "limit", ")", "\n\n", "if", "err", ":=", "buildstore", ".", "CanAccessMaster", "(", "c", ",", "req", ".", "Master", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "q", ":=", "buildstore", ".", "Query", "{", "Master", ":", "req", ".", "Master", ",", "Builder", ":", "req", ".", "Builder", ",", "Limit", ":", "limit", ",", "}", "\n", "if", "!", "req", ".", "IncludeCurrent", "{", "q", ".", "Finished", "=", "buildstore", ".", "Yes", "\n", "}", "\n", "res", ",", "err", ":=", "buildstore", ".", "GetBuilds", "(", "c", ",", "q", ")", "\n", "switch", "code", ":=", "grpcutil", ".", "Code", "(", "err", ")", ";", "{", "case", "code", "==", "codes", ".", "NotFound", ",", "code", "==", "codes", ".", "PermissionDenied", ":", "return", "nil", ",", "errNotFoundGRPC", "\n", "case", "err", "!=", "nil", ":", "return", "nil", ",", "err", "\n", "}", "\n\n", "buildsJSON", ":=", "&", "milo", ".", "BuildbotBuildsJSON", "{", "Builds", ":", "make", "(", "[", "]", "*", "milo", ".", "BuildbotBuildJSON", ",", "len", "(", "res", ".", "Builds", ")", ")", ",", "}", "\n", "for", "i", ",", "b", ":=", "range", "res", ".", "Builds", "{", "if", "req", ".", "ExcludeDeprecated", "{", "excludeDeprecatedFromBuild", "(", "b", ")", "\n", "}", "\n", "bs", ",", "err", ":=", "json", ".", "Marshal", "(", "b", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "buildsJSON", ".", "Builds", "[", "i", "]", "=", "&", "milo", ".", "BuildbotBuildJSON", "{", "Data", ":", "bs", "}", "\n", "}", "\n", "return", "buildsJSON", ",", "nil", "\n", "}" ]
// GetBuildbotBuildsJSON implements milo.BuildbotServer.
[ "GetBuildbotBuildsJSON", "implements", "milo", ".", "BuildbotServer", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/grpc.go#L102-L157
9,471
luci/luci-go
milo/buildsource/buildbot/grpc.go
GetCompressedMasterJSON
func (s *Service) GetCompressedMasterJSON(c context.Context, req *milo.MasterRequest) ( *milo.CompressedMasterJSON, error) { if req.Name == "" { return nil, status.Errorf(codes.InvalidArgument, "No master specified") } apiUsage.Add(c, 1, "GetCompressedMasterJSON", req.Name, "", req.ExcludeDeprecated, req.NoEmulation) cu := auth.CurrentUser(c) logging.Debugf(c, "%s is making a master request for %s", cu.Identity, req.Name) if err := buildstore.CanAccessMaster(c, req.Name); err != nil { return nil, err } master, err := buildstore.GetMaster(c, req.Name, true) switch code := grpcutil.Code(err); { case code == codes.NotFound, code == codes.PermissionDenied: return nil, errNotFoundGRPC case err != nil: return nil, err } for _, builder := range master.Builders { // Nobody uses PendingBuildStates. // Exclude them from the response // because they are hard to emulate. builder.PendingBuildStates = nil } if req.ExcludeDeprecated { excludeDeprecatedFromMaster(&master.Master) } // Compress it. gzbs := bytes.Buffer{} gsw := gzip.NewWriter(&gzbs) cw := iotools.CountingWriter{Writer: gsw} e := json.NewEncoder(&cw) if err := e.Encode(master); err != nil { gsw.Close() return nil, err } gsw.Close() logging.Infof(c, "Returning %d bytes", cw.Count) return &milo.CompressedMasterJSON{ Internal: master.Internal, Modified: google.NewTimestamp(master.Modified), Data: gzbs.Bytes(), }, nil }
go
func (s *Service) GetCompressedMasterJSON(c context.Context, req *milo.MasterRequest) ( *milo.CompressedMasterJSON, error) { if req.Name == "" { return nil, status.Errorf(codes.InvalidArgument, "No master specified") } apiUsage.Add(c, 1, "GetCompressedMasterJSON", req.Name, "", req.ExcludeDeprecated, req.NoEmulation) cu := auth.CurrentUser(c) logging.Debugf(c, "%s is making a master request for %s", cu.Identity, req.Name) if err := buildstore.CanAccessMaster(c, req.Name); err != nil { return nil, err } master, err := buildstore.GetMaster(c, req.Name, true) switch code := grpcutil.Code(err); { case code == codes.NotFound, code == codes.PermissionDenied: return nil, errNotFoundGRPC case err != nil: return nil, err } for _, builder := range master.Builders { // Nobody uses PendingBuildStates. // Exclude them from the response // because they are hard to emulate. builder.PendingBuildStates = nil } if req.ExcludeDeprecated { excludeDeprecatedFromMaster(&master.Master) } // Compress it. gzbs := bytes.Buffer{} gsw := gzip.NewWriter(&gzbs) cw := iotools.CountingWriter{Writer: gsw} e := json.NewEncoder(&cw) if err := e.Encode(master); err != nil { gsw.Close() return nil, err } gsw.Close() logging.Infof(c, "Returning %d bytes", cw.Count) return &milo.CompressedMasterJSON{ Internal: master.Internal, Modified: google.NewTimestamp(master.Modified), Data: gzbs.Bytes(), }, nil }
[ "func", "(", "s", "*", "Service", ")", "GetCompressedMasterJSON", "(", "c", "context", ".", "Context", ",", "req", "*", "milo", ".", "MasterRequest", ")", "(", "*", "milo", ".", "CompressedMasterJSON", ",", "error", ")", "{", "if", "req", ".", "Name", "==", "\"", "\"", "{", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n\n", "apiUsage", ".", "Add", "(", "c", ",", "1", ",", "\"", "\"", ",", "req", ".", "Name", ",", "\"", "\"", ",", "req", ".", "ExcludeDeprecated", ",", "req", ".", "NoEmulation", ")", "\n\n", "cu", ":=", "auth", ".", "CurrentUser", "(", "c", ")", "\n", "logging", ".", "Debugf", "(", "c", ",", "\"", "\"", ",", "cu", ".", "Identity", ",", "req", ".", "Name", ")", "\n\n", "if", "err", ":=", "buildstore", ".", "CanAccessMaster", "(", "c", ",", "req", ".", "Name", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "master", ",", "err", ":=", "buildstore", ".", "GetMaster", "(", "c", ",", "req", ".", "Name", ",", "true", ")", "\n\n", "switch", "code", ":=", "grpcutil", ".", "Code", "(", "err", ")", ";", "{", "case", "code", "==", "codes", ".", "NotFound", ",", "code", "==", "codes", ".", "PermissionDenied", ":", "return", "nil", ",", "errNotFoundGRPC", "\n", "case", "err", "!=", "nil", ":", "return", "nil", ",", "err", "\n", "}", "\n\n", "for", "_", ",", "builder", ":=", "range", "master", ".", "Builders", "{", "// Nobody uses PendingBuildStates.", "// Exclude them from the response", "// because they are hard to emulate.", "builder", ".", "PendingBuildStates", "=", "nil", "\n", "}", "\n\n", "if", "req", ".", "ExcludeDeprecated", "{", "excludeDeprecatedFromMaster", "(", "&", "master", ".", "Master", ")", "\n", "}", "\n\n", "// Compress it.", "gzbs", ":=", "bytes", ".", "Buffer", "{", "}", "\n", "gsw", ":=", "gzip", ".", "NewWriter", "(", "&", "gzbs", ")", "\n", "cw", ":=", "iotools", ".", "CountingWriter", "{", "Writer", ":", "gsw", "}", "\n", "e", ":=", "json", ".", "NewEncoder", "(", "&", "cw", ")", "\n", "if", "err", ":=", "e", ".", "Encode", "(", "master", ")", ";", "err", "!=", "nil", "{", "gsw", ".", "Close", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "gsw", ".", "Close", "(", ")", "\n\n", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "cw", ".", "Count", ")", "\n\n", "return", "&", "milo", ".", "CompressedMasterJSON", "{", "Internal", ":", "master", ".", "Internal", ",", "Modified", ":", "google", ".", "NewTimestamp", "(", "master", ".", "Modified", ")", ",", "Data", ":", "gzbs", ".", "Bytes", "(", ")", ",", "}", ",", "nil", "\n", "}" ]
// GetCompressedMasterJSON assembles a CompressedMasterJSON object from the // provided MasterRequest.
[ "GetCompressedMasterJSON", "assembles", "a", "CompressedMasterJSON", "object", "from", "the", "provided", "MasterRequest", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/grpc.go#L161-L215
9,472
luci/luci-go
buildbucket/cli/collect.go
dedupInt64s
func dedupInt64s(nums []int64) []int64 { seen := make(map[int64]struct{}, len(nums)) res := make([]int64, 0, len(nums)) for _, x := range nums { if _, ok := seen[x]; !ok { seen[x] = struct{}{} res = append(res, x) } } return res }
go
func dedupInt64s(nums []int64) []int64 { seen := make(map[int64]struct{}, len(nums)) res := make([]int64, 0, len(nums)) for _, x := range nums { if _, ok := seen[x]; !ok { seen[x] = struct{}{} res = append(res, x) } } return res }
[ "func", "dedupInt64s", "(", "nums", "[", "]", "int64", ")", "[", "]", "int64", "{", "seen", ":=", "make", "(", "map", "[", "int64", "]", "struct", "{", "}", ",", "len", "(", "nums", ")", ")", "\n", "res", ":=", "make", "(", "[", "]", "int64", ",", "0", ",", "len", "(", "nums", ")", ")", "\n", "for", "_", ",", "x", ":=", "range", "nums", "{", "if", "_", ",", "ok", ":=", "seen", "[", "x", "]", ";", "!", "ok", "{", "seen", "[", "x", "]", "=", "struct", "{", "}", "{", "}", "\n", "res", "=", "append", "(", "res", ",", "x", ")", "\n", "}", "\n", "}", "\n", "return", "res", "\n", "}" ]
// dedupInt64s dedups int64s.
[ "dedupInt64s", "dedups", "int64s", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/cli/collect.go#L94-L104
9,473
luci/luci-go
buildbucket/access/acl.go
Can
func (p Permissions) Can(bucket string, action Action) bool { return (p[bucket] & action) == action }
go
func (p Permissions) Can(bucket string, action Action) bool { return (p[bucket] & action) == action }
[ "func", "(", "p", "Permissions", ")", "Can", "(", "bucket", "string", ",", "action", "Action", ")", "bool", "{", "return", "(", "p", "[", "bucket", "]", "&", "action", ")", "==", "action", "\n", "}" ]
// Can checks whether an Action is allowed for a given bucket.
[ "Can", "checks", "whether", "an", "Action", "is", "allowed", "for", "a", "given", "bucket", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/access/acl.go#L36-L38
9,474
luci/luci-go
buildbucket/access/acl.go
FromProto
func (p Permissions) FromProto(resp *access.PermittedActionsResponse) error { // Clean up p before we populate it. for bucket := range p { delete(p, bucket) } for bucket, actions := range resp.Permitted { newActions := Action(0) for _, action := range actions.Actions { newAction, err := ParseAction(action) if err != nil { return err } newActions |= newAction } p[bucket] = newActions } return nil }
go
func (p Permissions) FromProto(resp *access.PermittedActionsResponse) error { // Clean up p before we populate it. for bucket := range p { delete(p, bucket) } for bucket, actions := range resp.Permitted { newActions := Action(0) for _, action := range actions.Actions { newAction, err := ParseAction(action) if err != nil { return err } newActions |= newAction } p[bucket] = newActions } return nil }
[ "func", "(", "p", "Permissions", ")", "FromProto", "(", "resp", "*", "access", ".", "PermittedActionsResponse", ")", "error", "{", "// Clean up p before we populate it.", "for", "bucket", ":=", "range", "p", "{", "delete", "(", "p", ",", "bucket", ")", "\n", "}", "\n", "for", "bucket", ",", "actions", ":=", "range", "resp", ".", "Permitted", "{", "newActions", ":=", "Action", "(", "0", ")", "\n", "for", "_", ",", "action", ":=", "range", "actions", ".", "Actions", "{", "newAction", ",", "err", ":=", "ParseAction", "(", "action", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "newActions", "|=", "newAction", "\n", "}", "\n", "p", "[", "bucket", "]", "=", "newActions", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// FromProto populates a Permissions from an access.PermittedActionsResponse.
[ "FromProto", "populates", "a", "Permissions", "from", "an", "access", ".", "PermittedActionsResponse", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/access/acl.go#L41-L58
9,475
luci/luci-go
buildbucket/access/acl.go
ToProto
func (p Permissions) ToProto(validTime time.Duration) *access.PermittedActionsResponse { perms := make(map[string]*access.PermittedActionsResponse_ResourcePermissions, len(p)) for bucket, action := range p { var actions []string for a, name := range actionToName { if action&a == a { actions = append(actions, name) } } sort.Strings(actions) perms[bucket] = &access.PermittedActionsResponse_ResourcePermissions{Actions: actions} } return &access.PermittedActionsResponse{ Permitted: perms, ValidityDuration: ptypes.DurationProto(validTime), } }
go
func (p Permissions) ToProto(validTime time.Duration) *access.PermittedActionsResponse { perms := make(map[string]*access.PermittedActionsResponse_ResourcePermissions, len(p)) for bucket, action := range p { var actions []string for a, name := range actionToName { if action&a == a { actions = append(actions, name) } } sort.Strings(actions) perms[bucket] = &access.PermittedActionsResponse_ResourcePermissions{Actions: actions} } return &access.PermittedActionsResponse{ Permitted: perms, ValidityDuration: ptypes.DurationProto(validTime), } }
[ "func", "(", "p", "Permissions", ")", "ToProto", "(", "validTime", "time", ".", "Duration", ")", "*", "access", ".", "PermittedActionsResponse", "{", "perms", ":=", "make", "(", "map", "[", "string", "]", "*", "access", ".", "PermittedActionsResponse_ResourcePermissions", ",", "len", "(", "p", ")", ")", "\n", "for", "bucket", ",", "action", ":=", "range", "p", "{", "var", "actions", "[", "]", "string", "\n", "for", "a", ",", "name", ":=", "range", "actionToName", "{", "if", "action", "&", "a", "==", "a", "{", "actions", "=", "append", "(", "actions", ",", "name", ")", "\n", "}", "\n", "}", "\n", "sort", ".", "Strings", "(", "actions", ")", "\n", "perms", "[", "bucket", "]", "=", "&", "access", ".", "PermittedActionsResponse_ResourcePermissions", "{", "Actions", ":", "actions", "}", "\n", "}", "\n", "return", "&", "access", ".", "PermittedActionsResponse", "{", "Permitted", ":", "perms", ",", "ValidityDuration", ":", "ptypes", ".", "DurationProto", "(", "validTime", ")", ",", "}", "\n", "}" ]
// ToProto converts a Permissions into a PermittedActionsResponse.
[ "ToProto", "converts", "a", "Permissions", "into", "a", "PermittedActionsResponse", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/access/acl.go#L61-L77
9,476
luci/luci-go
buildbucket/access/acl.go
NewClient
func NewClient(host string, client *http.Client) access.AccessClient { return access.NewAccessPRPCClient(&prpc.Client{ Host: host, C: client, }) }
go
func NewClient(host string, client *http.Client) access.AccessClient { return access.NewAccessPRPCClient(&prpc.Client{ Host: host, C: client, }) }
[ "func", "NewClient", "(", "host", "string", ",", "client", "*", "http", ".", "Client", ")", "access", ".", "AccessClient", "{", "return", "access", ".", "NewAccessPRPCClient", "(", "&", "prpc", ".", "Client", "{", "Host", ":", "host", ",", "C", ":", "client", ",", "}", ")", "\n", "}" ]
// NewClient returns a new AccessClient which can be used to talk to // buildbucket's access API.
[ "NewClient", "returns", "a", "new", "AccessClient", "which", "can", "be", "used", "to", "talk", "to", "buildbucket", "s", "access", "API", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/access/acl.go#L81-L86
9,477
luci/luci-go
buildbucket/access/acl.go
BucketPermissions
func BucketPermissions(c context.Context, client access.AccessClient, buckets []string) (Permissions, time.Duration, error) { // Make permitted actions call. req := access.PermittedActionsRequest{ ResourceKind: "bucket", ResourceIds: buckets, } resp, err := client.PermittedActions(c, &req) if err != nil { return nil, 0, err } // Parse proto into a convenient format. perms := make(Permissions, len(resp.Permitted)) if err := perms.FromProto(resp); err != nil { return nil, 0, err } dur, err := ptypes.Duration(resp.ValidityDuration) if err != nil { return nil, 0, err } return perms, dur, nil }
go
func BucketPermissions(c context.Context, client access.AccessClient, buckets []string) (Permissions, time.Duration, error) { // Make permitted actions call. req := access.PermittedActionsRequest{ ResourceKind: "bucket", ResourceIds: buckets, } resp, err := client.PermittedActions(c, &req) if err != nil { return nil, 0, err } // Parse proto into a convenient format. perms := make(Permissions, len(resp.Permitted)) if err := perms.FromProto(resp); err != nil { return nil, 0, err } dur, err := ptypes.Duration(resp.ValidityDuration) if err != nil { return nil, 0, err } return perms, dur, nil }
[ "func", "BucketPermissions", "(", "c", "context", ".", "Context", ",", "client", "access", ".", "AccessClient", ",", "buckets", "[", "]", "string", ")", "(", "Permissions", ",", "time", ".", "Duration", ",", "error", ")", "{", "// Make permitted actions call.", "req", ":=", "access", ".", "PermittedActionsRequest", "{", "ResourceKind", ":", "\"", "\"", ",", "ResourceIds", ":", "buckets", ",", "}", "\n", "resp", ",", "err", ":=", "client", ".", "PermittedActions", "(", "c", ",", "&", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "err", "\n", "}", "\n\n", "// Parse proto into a convenient format.", "perms", ":=", "make", "(", "Permissions", ",", "len", "(", "resp", ".", "Permitted", ")", ")", "\n", "if", "err", ":=", "perms", ".", "FromProto", "(", "resp", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "err", "\n", "}", "\n", "dur", ",", "err", ":=", "ptypes", ".", "Duration", "(", "resp", ".", "ValidityDuration", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "err", "\n", "}", "\n", "return", "perms", ",", "dur", ",", "nil", "\n", "}" ]
// BucketPermissions retrieves permitted actions for a set of buckets, for the // identity specified in the client. It also returns the duration for which the // client is allowed to cache the permissions.
[ "BucketPermissions", "retrieves", "permitted", "actions", "for", "a", "set", "of", "buckets", "for", "the", "identity", "specified", "in", "the", "client", ".", "It", "also", "returns", "the", "duration", "for", "which", "the", "client", "is", "allowed", "to", "cache", "the", "permissions", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/access/acl.go#L91-L112
9,478
luci/luci-go
logdog/client/butlerlib/streamproto/tee.go
Writer
func (t TeeType) Writer() io.Writer { switch t { case TeeNone: return nil case TeeStdout: return os.Stdout case TeeStderr: return os.Stderr default: panic(fmt.Errorf("streamproto: unknown tee type [%v]", t)) } }
go
func (t TeeType) Writer() io.Writer { switch t { case TeeNone: return nil case TeeStdout: return os.Stdout case TeeStderr: return os.Stderr default: panic(fmt.Errorf("streamproto: unknown tee type [%v]", t)) } }
[ "func", "(", "t", "TeeType", ")", "Writer", "(", ")", "io", ".", "Writer", "{", "switch", "t", "{", "case", "TeeNone", ":", "return", "nil", "\n\n", "case", "TeeStdout", ":", "return", "os", ".", "Stdout", "\n\n", "case", "TeeStderr", ":", "return", "os", ".", "Stderr", "\n\n", "default", ":", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "t", ")", ")", "\n", "}", "\n", "}" ]
// Writer returns the io.Writer object
[ "Writer", "returns", "the", "io", ".", "Writer", "object" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butlerlib/streamproto/tee.go#L46-L60
9,479
luci/luci-go
vpython/options.go
ResolveSpec
func (o *Options) ResolveSpec(c context.Context) error { if o.CommandLine == nil { panic("a CommandLine must be specified") } // If a spec is explicitly provided, we're done. if o.EnvConfig.Spec != nil { return nil } o.EnvConfig.Spec = &o.DefaultSpec // If we're running a Python script, assert that the target script exists. // Additionally, track whether it's a file or a module (directory). target := o.CommandLine.Target script, isScriptTarget := target.(python.ScriptTarget) if isScriptTarget && script.Path == "-" { logging.Infof(c, "Skipping specification probing for script via stdin.") return nil } isModule := false if isScriptTarget { logging.Debugf(c, "Resolved Python target script: %s", target) // Resolve to absolute script path. if err := filesystem.AbsPath(&script.Path); err != nil { return errors.Annotate(err, "failed to get absolute path of: %s", target).Err() } // Confirm that the script path actually exists. st, err := os.Stat(script.Path) if err != nil { return IsUserError.Apply(err) } // If the script is a directory, then we assume that we're doing a module // invocation (__main__.py). isModule = st.IsDir() } // If it's a script, try resolving from filesystem first. if isScriptTarget { spec, err := o.SpecLoader.LoadForScript(c, script.Path, isModule) if err != nil { return errors.Annotate(err, "failed to load spec for script: %s", target). InternalReason("isModule(%v)", isModule).Err() } if spec != nil { o.EnvConfig.Spec = spec return nil } } // If standard resolution doesn't yield a spec, fall back on our default spec. logging.Infof(c, "Unable to resolve specification path. Using default specification.") return nil }
go
func (o *Options) ResolveSpec(c context.Context) error { if o.CommandLine == nil { panic("a CommandLine must be specified") } // If a spec is explicitly provided, we're done. if o.EnvConfig.Spec != nil { return nil } o.EnvConfig.Spec = &o.DefaultSpec // If we're running a Python script, assert that the target script exists. // Additionally, track whether it's a file or a module (directory). target := o.CommandLine.Target script, isScriptTarget := target.(python.ScriptTarget) if isScriptTarget && script.Path == "-" { logging.Infof(c, "Skipping specification probing for script via stdin.") return nil } isModule := false if isScriptTarget { logging.Debugf(c, "Resolved Python target script: %s", target) // Resolve to absolute script path. if err := filesystem.AbsPath(&script.Path); err != nil { return errors.Annotate(err, "failed to get absolute path of: %s", target).Err() } // Confirm that the script path actually exists. st, err := os.Stat(script.Path) if err != nil { return IsUserError.Apply(err) } // If the script is a directory, then we assume that we're doing a module // invocation (__main__.py). isModule = st.IsDir() } // If it's a script, try resolving from filesystem first. if isScriptTarget { spec, err := o.SpecLoader.LoadForScript(c, script.Path, isModule) if err != nil { return errors.Annotate(err, "failed to load spec for script: %s", target). InternalReason("isModule(%v)", isModule).Err() } if spec != nil { o.EnvConfig.Spec = spec return nil } } // If standard resolution doesn't yield a spec, fall back on our default spec. logging.Infof(c, "Unable to resolve specification path. Using default specification.") return nil }
[ "func", "(", "o", "*", "Options", ")", "ResolveSpec", "(", "c", "context", ".", "Context", ")", "error", "{", "if", "o", ".", "CommandLine", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// If a spec is explicitly provided, we're done.", "if", "o", ".", "EnvConfig", ".", "Spec", "!=", "nil", "{", "return", "nil", "\n", "}", "\n\n", "o", ".", "EnvConfig", ".", "Spec", "=", "&", "o", ".", "DefaultSpec", "\n\n", "// If we're running a Python script, assert that the target script exists.", "// Additionally, track whether it's a file or a module (directory).", "target", ":=", "o", ".", "CommandLine", ".", "Target", "\n", "script", ",", "isScriptTarget", ":=", "target", ".", "(", "python", ".", "ScriptTarget", ")", "\n", "if", "isScriptTarget", "&&", "script", ".", "Path", "==", "\"", "\"", "{", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n\n", "isModule", ":=", "false", "\n", "if", "isScriptTarget", "{", "logging", ".", "Debugf", "(", "c", ",", "\"", "\"", ",", "target", ")", "\n\n", "// Resolve to absolute script path.", "if", "err", ":=", "filesystem", ".", "AbsPath", "(", "&", "script", ".", "Path", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "target", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "// Confirm that the script path actually exists.", "st", ",", "err", ":=", "os", ".", "Stat", "(", "script", ".", "Path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "IsUserError", ".", "Apply", "(", "err", ")", "\n", "}", "\n\n", "// If the script is a directory, then we assume that we're doing a module", "// invocation (__main__.py).", "isModule", "=", "st", ".", "IsDir", "(", ")", "\n", "}", "\n\n", "// If it's a script, try resolving from filesystem first.", "if", "isScriptTarget", "{", "spec", ",", "err", ":=", "o", ".", "SpecLoader", ".", "LoadForScript", "(", "c", ",", "script", ".", "Path", ",", "isModule", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "target", ")", ".", "InternalReason", "(", "\"", "\"", ",", "isModule", ")", ".", "Err", "(", ")", "\n", "}", "\n", "if", "spec", "!=", "nil", "{", "o", ".", "EnvConfig", ".", "Spec", "=", "spec", "\n", "return", "nil", "\n", "}", "\n", "}", "\n\n", "// If standard resolution doesn't yield a spec, fall back on our default spec.", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ")", "\n", "return", "nil", "\n", "}" ]
// ResolveSpec resolves the configured environment specification. The resulting // spec is installed into o's EnvConfig.Spec field.
[ "ResolveSpec", "resolves", "the", "configured", "environment", "specification", ".", "The", "resulting", "spec", "is", "installed", "into", "o", "s", "EnvConfig", ".", "Spec", "field", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/options.go#L111-L168
9,480
luci/luci-go
milo/frontend/view_logs.go
HandleSwarmingLog
func HandleSwarmingLog(c *router.Context) error { log, closed, err := swarming.GetLog( c.Context, c.Request.FormValue("server"), c.Params.ByName("id"), c.Params.ByName("logname")) if err != nil { return err } templates.MustRender(c.Context, c.Writer, "pages/log.html", templates.Args{ "Log": log, "Closed": closed, }) return nil }
go
func HandleSwarmingLog(c *router.Context) error { log, closed, err := swarming.GetLog( c.Context, c.Request.FormValue("server"), c.Params.ByName("id"), c.Params.ByName("logname")) if err != nil { return err } templates.MustRender(c.Context, c.Writer, "pages/log.html", templates.Args{ "Log": log, "Closed": closed, }) return nil }
[ "func", "HandleSwarmingLog", "(", "c", "*", "router", ".", "Context", ")", "error", "{", "log", ",", "closed", ",", "err", ":=", "swarming", ".", "GetLog", "(", "c", ".", "Context", ",", "c", ".", "Request", ".", "FormValue", "(", "\"", "\"", ")", ",", "c", ".", "Params", ".", "ByName", "(", "\"", "\"", ")", ",", "c", ".", "Params", ".", "ByName", "(", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "templates", ".", "MustRender", "(", "c", ".", "Context", ",", "c", ".", "Writer", ",", "\"", "\"", ",", "templates", ".", "Args", "{", "\"", "\"", ":", "log", ",", "\"", "\"", ":", "closed", ",", "}", ")", "\n", "return", "nil", "\n", "}" ]
// HandleSwarmingLog renders a step log from a swarming build.
[ "HandleSwarmingLog", "renders", "a", "step", "log", "from", "a", "swarming", "build", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/view_logs.go#L15-L30
9,481
luci/luci-go
lucicfg/normalize/buildbucket.go
Buildbucket
func Buildbucket(c context.Context, cfg *pb.BuildbucketCfg) error { // Install or update 'flatten_buildbucket_cfg' tool. bin, err := installFlattenBuildbucketCfg(c) if err != nil { return fmt.Errorf("failed to install buildbucket config flattener: %s", err) } // 'flatten_buildbucket_cfg' wants a real file as input. f, err := ioutil.TempFile("", "lucicfg") if err != nil { return err } defer func() { f.Close() os.Remove(f.Name()) }() if err := proto.MarshalText(f, cfg); err != nil { return err } if err := f.Close(); err != nil { return err } buf := bytes.Buffer{} cmd := exec.Command(bin, f.Name()) cmd.Stderr = os.Stderr cmd.Stdin = os.Stdin cmd.Stdout = &buf if err := cmd.Run(); err != nil { return fmt.Errorf("failed to flatten the config - %s", err) } *cfg = pb.BuildbucketCfg{} if err := proto.UnmarshalText(buf.String(), cfg); err != nil { return err } return nil }
go
func Buildbucket(c context.Context, cfg *pb.BuildbucketCfg) error { // Install or update 'flatten_buildbucket_cfg' tool. bin, err := installFlattenBuildbucketCfg(c) if err != nil { return fmt.Errorf("failed to install buildbucket config flattener: %s", err) } // 'flatten_buildbucket_cfg' wants a real file as input. f, err := ioutil.TempFile("", "lucicfg") if err != nil { return err } defer func() { f.Close() os.Remove(f.Name()) }() if err := proto.MarshalText(f, cfg); err != nil { return err } if err := f.Close(); err != nil { return err } buf := bytes.Buffer{} cmd := exec.Command(bin, f.Name()) cmd.Stderr = os.Stderr cmd.Stdin = os.Stdin cmd.Stdout = &buf if err := cmd.Run(); err != nil { return fmt.Errorf("failed to flatten the config - %s", err) } *cfg = pb.BuildbucketCfg{} if err := proto.UnmarshalText(buf.String(), cfg); err != nil { return err } return nil }
[ "func", "Buildbucket", "(", "c", "context", ".", "Context", ",", "cfg", "*", "pb", ".", "BuildbucketCfg", ")", "error", "{", "// Install or update 'flatten_buildbucket_cfg' tool.", "bin", ",", "err", ":=", "installFlattenBuildbucketCfg", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// 'flatten_buildbucket_cfg' wants a real file as input.", "f", ",", "err", ":=", "ioutil", ".", "TempFile", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "func", "(", ")", "{", "f", ".", "Close", "(", ")", "\n", "os", ".", "Remove", "(", "f", ".", "Name", "(", ")", ")", "\n", "}", "(", ")", "\n", "if", "err", ":=", "proto", ".", "MarshalText", "(", "f", ",", "cfg", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "f", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "buf", ":=", "bytes", ".", "Buffer", "{", "}", "\n\n", "cmd", ":=", "exec", ".", "Command", "(", "bin", ",", "f", ".", "Name", "(", ")", ")", "\n", "cmd", ".", "Stderr", "=", "os", ".", "Stderr", "\n", "cmd", ".", "Stdin", "=", "os", ".", "Stdin", "\n", "cmd", ".", "Stdout", "=", "&", "buf", "\n", "if", "err", ":=", "cmd", ".", "Run", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "*", "cfg", "=", "pb", ".", "BuildbucketCfg", "{", "}", "\n", "if", "err", ":=", "proto", ".", "UnmarshalText", "(", "buf", ".", "String", "(", ")", ",", "cfg", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Buildbucket normalizes cr-buildbucket.cfg config.
[ "Buildbucket", "normalizes", "cr", "-", "buildbucket", ".", "cfg", "config", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/normalize/buildbucket.go#L38-L76
9,482
luci/luci-go
common/data/chunkstream/buffer.go
Append
func (b *Buffer) Append(c ...Chunk) { for _, chunk := range c { b.appendChunk(chunk) } }
go
func (b *Buffer) Append(c ...Chunk) { for _, chunk := range c { b.appendChunk(chunk) } }
[ "func", "(", "b", "*", "Buffer", ")", "Append", "(", "c", "...", "Chunk", ")", "{", "for", "_", ",", "chunk", ":=", "range", "c", "{", "b", ".", "appendChunk", "(", "chunk", ")", "\n", "}", "\n", "}" ]
// Append adds additional Chunks to the buffer. // // After completion, the Chunk is now owned by the Buffer and should not be used // anymore externally.
[ "Append", "adds", "additional", "Chunks", "to", "the", "buffer", ".", "After", "completion", "the", "Chunk", "is", "now", "owned", "by", "the", "Buffer", "and", "should", "not", "be", "used", "anymore", "externally", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/chunkstream/buffer.go#L46-L50
9,483
luci/luci-go
common/data/chunkstream/buffer.go
Bytes
func (b *Buffer) Bytes() []byte { if b.Len() == 0 { return nil } m := make([]byte, 0, b.Len()) idx := b.fidx for cur := b.first; cur != nil; cur = cur.next { m = append(m, cur.Bytes()[idx:]...) idx = 0 } return m }
go
func (b *Buffer) Bytes() []byte { if b.Len() == 0 { return nil } m := make([]byte, 0, b.Len()) idx := b.fidx for cur := b.first; cur != nil; cur = cur.next { m = append(m, cur.Bytes()[idx:]...) idx = 0 } return m }
[ "func", "(", "b", "*", "Buffer", ")", "Bytes", "(", ")", "[", "]", "byte", "{", "if", "b", ".", "Len", "(", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "m", ":=", "make", "(", "[", "]", "byte", ",", "0", ",", "b", ".", "Len", "(", ")", ")", "\n", "idx", ":=", "b", ".", "fidx", "\n", "for", "cur", ":=", "b", ".", "first", ";", "cur", "!=", "nil", ";", "cur", "=", "cur", ".", "next", "{", "m", "=", "append", "(", "m", ",", "cur", ".", "Bytes", "(", ")", "[", "idx", ":", "]", "...", ")", "\n", "idx", "=", "0", "\n", "}", "\n", "return", "m", "\n", "}" ]
// Bytes constructs a byte slice containing the contents of the Buffer. // // This is a potentially expensive operation, and should generally be used only // for debugging and tests, as it defeats most of the purpose of this package.
[ "Bytes", "constructs", "a", "byte", "slice", "containing", "the", "contents", "of", "the", "Buffer", ".", "This", "is", "a", "potentially", "expensive", "operation", "and", "should", "generally", "be", "used", "only", "for", "debugging", "and", "tests", "as", "it", "defeats", "most", "of", "the", "purpose", "of", "this", "package", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/chunkstream/buffer.go#L75-L87
9,484
luci/luci-go
common/data/chunkstream/buffer.go
FirstChunk
func (b *Buffer) FirstChunk() Chunk { if b.first == nil { return nil } return b.first.Chunk }
go
func (b *Buffer) FirstChunk() Chunk { if b.first == nil { return nil } return b.first.Chunk }
[ "func", "(", "b", "*", "Buffer", ")", "FirstChunk", "(", ")", "Chunk", "{", "if", "b", ".", "first", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "b", ".", "first", ".", "Chunk", "\n", "}" ]
// FirstChunk returns the first Chunk in the Buffer, or nil if the Buffer has // no Chunks.
[ "FirstChunk", "returns", "the", "first", "Chunk", "in", "the", "Buffer", "or", "nil", "if", "the", "Buffer", "has", "no", "Chunks", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/chunkstream/buffer.go#L96-L101
9,485
luci/luci-go
common/data/chunkstream/buffer.go
ViewLimit
func (b *Buffer) ViewLimit(limit int64) *View { if limit > b.size { limit = b.size } return &View{ cur: b.first, cidx: b.fidx, size: limit, b: b, } }
go
func (b *Buffer) ViewLimit(limit int64) *View { if limit > b.size { limit = b.size } return &View{ cur: b.first, cidx: b.fidx, size: limit, b: b, } }
[ "func", "(", "b", "*", "Buffer", ")", "ViewLimit", "(", "limit", "int64", ")", "*", "View", "{", "if", "limit", ">", "b", ".", "size", "{", "limit", "=", "b", ".", "size", "\n", "}", "\n\n", "return", "&", "View", "{", "cur", ":", "b", ".", "first", ",", "cidx", ":", "b", ".", "fidx", ",", "size", ":", "limit", ",", "b", ":", "b", ",", "}", "\n", "}" ]
// ViewLimit constructs a View instance, but artificially constrains it to // read at most the specified number of bytes. // // This is useful when reading a subset of the data into a Buffer, as ReadFrom // does not allow a size to be specified.
[ "ViewLimit", "constructs", "a", "View", "instance", "but", "artificially", "constrains", "it", "to", "read", "at", "most", "the", "specified", "number", "of", "bytes", ".", "This", "is", "useful", "when", "reading", "a", "subset", "of", "the", "data", "into", "a", "Buffer", "as", "ReadFrom", "does", "not", "allow", "a", "size", "to", "be", "specified", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/chunkstream/buffer.go#L116-L128
9,486
luci/luci-go
common/gcloud/pubsub/topic.go
SplitErr
func (t Topic) SplitErr() (p, n string, err error) { p, n, err = resourceProjectName(string(t)) return }
go
func (t Topic) SplitErr() (p, n string, err error) { p, n, err = resourceProjectName(string(t)) return }
[ "func", "(", "t", "Topic", ")", "SplitErr", "(", ")", "(", "p", ",", "n", "string", ",", "err", "error", ")", "{", "p", ",", "n", ",", "err", "=", "resourceProjectName", "(", "string", "(", "t", ")", ")", "\n", "return", "\n", "}" ]
// SplitErr returns the Topic's project and name components.
[ "SplitErr", "returns", "the", "Topic", "s", "project", "and", "name", "components", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/gcloud/pubsub/topic.go#L58-L61
9,487
luci/luci-go
tools/internal/apigen/filesystem.go
getPackagePath
func getPackagePath(p string) (string, error) { pkg := strings.Split(p, "/") for i := len(pkg) - 1; i > 0; i-- { p, err := build.Import(strings.Join(pkg[:i], "/"), "", build.FindOnly) if err != nil { continue } return augPath(p.Dir, pkg[i:]...), nil } return "", errors.New("could not find package path") }
go
func getPackagePath(p string) (string, error) { pkg := strings.Split(p, "/") for i := len(pkg) - 1; i > 0; i-- { p, err := build.Import(strings.Join(pkg[:i], "/"), "", build.FindOnly) if err != nil { continue } return augPath(p.Dir, pkg[i:]...), nil } return "", errors.New("could not find package path") }
[ "func", "getPackagePath", "(", "p", "string", ")", "(", "string", ",", "error", ")", "{", "pkg", ":=", "strings", ".", "Split", "(", "p", ",", "\"", "\"", ")", "\n\n", "for", "i", ":=", "len", "(", "pkg", ")", "-", "1", ";", "i", ">", "0", ";", "i", "--", "{", "p", ",", "err", ":=", "build", ".", "Import", "(", "strings", ".", "Join", "(", "pkg", "[", ":", "i", "]", ",", "\"", "\"", ")", ",", "\"", "\"", ",", "build", ".", "FindOnly", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n", "return", "augPath", "(", "p", ".", "Dir", ",", "pkg", "[", "i", ":", "]", "...", ")", ",", "nil", "\n", "}", "\n", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// getPackagePath searches through GOPATH to find the filesystem path of the // named package. // // This is complicated by the fact that the named package might not exist. In // this case, the package's path will be traversed until one of its parent's // paths is found.
[ "getPackagePath", "searches", "through", "GOPATH", "to", "find", "the", "filesystem", "path", "of", "the", "named", "package", ".", "This", "is", "complicated", "by", "the", "fact", "that", "the", "named", "package", "might", "not", "exist", ".", "In", "this", "case", "the", "package", "s", "path", "will", "be", "traversed", "until", "one", "of", "its", "parent", "s", "paths", "is", "found", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tools/internal/apigen/filesystem.go#L40-L51
9,488
luci/luci-go
tools/internal/apigen/filesystem.go
augPath
func augPath(base string, parts ...string) string { cpath := make([]string, 0, len(parts)+1) cpath = append(cpath, base) cpath = append(cpath, parts...) return filepath.Join(cpath...) }
go
func augPath(base string, parts ...string) string { cpath := make([]string, 0, len(parts)+1) cpath = append(cpath, base) cpath = append(cpath, parts...) return filepath.Join(cpath...) }
[ "func", "augPath", "(", "base", "string", ",", "parts", "...", "string", ")", "string", "{", "cpath", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "parts", ")", "+", "1", ")", "\n", "cpath", "=", "append", "(", "cpath", ",", "base", ")", "\n", "cpath", "=", "append", "(", "cpath", ",", "parts", "...", ")", "\n", "return", "filepath", ".", "Join", "(", "cpath", "...", ")", "\n", "}" ]
// augPath joins a series of path elements to a base path.
[ "augPath", "joins", "a", "series", "of", "path", "elements", "to", "a", "base", "path", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tools/internal/apigen/filesystem.go#L54-L59
9,489
luci/luci-go
tools/internal/apigen/filesystem.go
installSource
func installSource(src, dst string, edit editFunc) error { return filepath.Walk(src, func(path string, info os.FileInfo, err error) error { if err != nil { return err } relpath, err := filepath.Rel(src, path) if err != nil { return fmt.Errorf("failed to get relative path [%s]: %s", path, err) } dstpath := filepath.Join(dst, relpath) switch { case info.IsDir(): // Make sure the directory exists in the target filesystem. if err := ensureDirectory(dstpath); err != nil { return fmt.Errorf("failed to ensure directory [%s]: %s", dstpath, err) } case !info.Mode().IsRegular(): // Skip non-regular files. break default: // Copy the file from source to destination. if err := copyFile(path, dstpath, relpath, edit); err != nil { return fmt.Errorf("failed to copy file ([%s] => [%s]): %s", path, dstpath, err) } } return nil }) }
go
func installSource(src, dst string, edit editFunc) error { return filepath.Walk(src, func(path string, info os.FileInfo, err error) error { if err != nil { return err } relpath, err := filepath.Rel(src, path) if err != nil { return fmt.Errorf("failed to get relative path [%s]: %s", path, err) } dstpath := filepath.Join(dst, relpath) switch { case info.IsDir(): // Make sure the directory exists in the target filesystem. if err := ensureDirectory(dstpath); err != nil { return fmt.Errorf("failed to ensure directory [%s]: %s", dstpath, err) } case !info.Mode().IsRegular(): // Skip non-regular files. break default: // Copy the file from source to destination. if err := copyFile(path, dstpath, relpath, edit); err != nil { return fmt.Errorf("failed to copy file ([%s] => [%s]): %s", path, dstpath, err) } } return nil }) }
[ "func", "installSource", "(", "src", ",", "dst", "string", ",", "edit", "editFunc", ")", "error", "{", "return", "filepath", ".", "Walk", "(", "src", ",", "func", "(", "path", "string", ",", "info", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "relpath", ",", "err", ":=", "filepath", ".", "Rel", "(", "src", ",", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "path", ",", "err", ")", "\n", "}", "\n\n", "dstpath", ":=", "filepath", ".", "Join", "(", "dst", ",", "relpath", ")", "\n", "switch", "{", "case", "info", ".", "IsDir", "(", ")", ":", "// Make sure the directory exists in the target filesystem.", "if", "err", ":=", "ensureDirectory", "(", "dstpath", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "dstpath", ",", "err", ")", "\n", "}", "\n\n", "case", "!", "info", ".", "Mode", "(", ")", ".", "IsRegular", "(", ")", ":", "// Skip non-regular files.", "break", "\n\n", "default", ":", "// Copy the file from source to destination.", "if", "err", ":=", "copyFile", "(", "path", ",", "dstpath", ",", "relpath", ",", "edit", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "path", ",", "dstpath", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}", ")", "\n", "}" ]
// installSource recursively copies an API generator output directory to a // package location.
[ "installSource", "recursively", "copies", "an", "API", "generator", "output", "directory", "to", "a", "package", "location", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tools/internal/apigen/filesystem.go#L63-L95
9,490
luci/luci-go
tools/internal/apigen/filesystem.go
copyFile
func copyFile(src, dst string, relPath string, edit editFunc) error { data, err := ioutil.ReadFile(src) if err != nil { return fmt.Errorf("failed to read source: %s", err) } if edit != nil { data, err = edit(relPath, data) if err != nil { return fmt.Errorf("edit error: %s", err) } } if data == nil { return nil } return ioutil.WriteFile(dst, data, 0644) }
go
func copyFile(src, dst string, relPath string, edit editFunc) error { data, err := ioutil.ReadFile(src) if err != nil { return fmt.Errorf("failed to read source: %s", err) } if edit != nil { data, err = edit(relPath, data) if err != nil { return fmt.Errorf("edit error: %s", err) } } if data == nil { return nil } return ioutil.WriteFile(dst, data, 0644) }
[ "func", "copyFile", "(", "src", ",", "dst", "string", ",", "relPath", "string", ",", "edit", "editFunc", ")", "error", "{", "data", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "src", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "edit", "!=", "nil", "{", "data", ",", "err", "=", "edit", "(", "relPath", ",", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "}", "\n", "if", "data", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "ioutil", ".", "WriteFile", "(", "dst", ",", "data", ",", "0644", ")", "\n", "}" ]
// copyFile copies the contents of a single file to a destination.
[ "copyFile", "copies", "the", "contents", "of", "a", "single", "file", "to", "a", "destination", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tools/internal/apigen/filesystem.go#L104-L121
9,491
luci/luci-go
tokenserver/appengine/impl/utils/pem.go
ParsePEM
func ParsePEM(data, header string) ([]byte, error) { block, rest := pem.Decode([]byte(data)) if len(rest) != 0 || block == nil { return nil, fmt.Errorf("not a valid %q PEM", header) } if block.Type != header { return nil, fmt.Errorf("expecting %q, got %q", header, block.Type) } return block.Bytes, nil }
go
func ParsePEM(data, header string) ([]byte, error) { block, rest := pem.Decode([]byte(data)) if len(rest) != 0 || block == nil { return nil, fmt.Errorf("not a valid %q PEM", header) } if block.Type != header { return nil, fmt.Errorf("expecting %q, got %q", header, block.Type) } return block.Bytes, nil }
[ "func", "ParsePEM", "(", "data", ",", "header", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "block", ",", "rest", ":=", "pem", ".", "Decode", "(", "[", "]", "byte", "(", "data", ")", ")", "\n", "if", "len", "(", "rest", ")", "!=", "0", "||", "block", "==", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "header", ")", "\n", "}", "\n", "if", "block", ".", "Type", "!=", "header", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "header", ",", "block", ".", "Type", ")", "\n", "}", "\n", "return", "block", ".", "Bytes", ",", "nil", "\n", "}" ]
// ParsePEM takes pem-encoded block and decodes it, checking the header.
[ "ParsePEM", "takes", "pem", "-", "encoded", "block", "and", "decodes", "it", "checking", "the", "header", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/pem.go#L23-L32
9,492
luci/luci-go
tokenserver/appengine/impl/utils/pem.go
DumpPEM
func DumpPEM(data []byte, header string) string { return string(pem.EncodeToMemory(&pem.Block{ Type: header, Bytes: data, })) }
go
func DumpPEM(data []byte, header string) string { return string(pem.EncodeToMemory(&pem.Block{ Type: header, Bytes: data, })) }
[ "func", "DumpPEM", "(", "data", "[", "]", "byte", ",", "header", "string", ")", "string", "{", "return", "string", "(", "pem", ".", "EncodeToMemory", "(", "&", "pem", ".", "Block", "{", "Type", ":", "header", ",", "Bytes", ":", "data", ",", "}", ")", ")", "\n", "}" ]
// DumpPEM transforms block to pem-encoding. // // Reverse of ParsePEM.
[ "DumpPEM", "transforms", "block", "to", "pem", "-", "encoding", ".", "Reverse", "of", "ParsePEM", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/pem.go#L37-L42
9,493
luci/luci-go
dm/api/distributor/jobsim/iterate.go
ToSlice
func (s *SparseRange) ToSlice() (ret []uint32) { for _, itm := range s.Items { switch x := itm.RangeItem.(type) { case *RangeItem_Single: ret = append(ret, x.Single) case *RangeItem_Range: for i := x.Range.Low; i <= x.Range.High; i++ { ret = append(ret, i) } } } return }
go
func (s *SparseRange) ToSlice() (ret []uint32) { for _, itm := range s.Items { switch x := itm.RangeItem.(type) { case *RangeItem_Single: ret = append(ret, x.Single) case *RangeItem_Range: for i := x.Range.Low; i <= x.Range.High; i++ { ret = append(ret, i) } } } return }
[ "func", "(", "s", "*", "SparseRange", ")", "ToSlice", "(", ")", "(", "ret", "[", "]", "uint32", ")", "{", "for", "_", ",", "itm", ":=", "range", "s", ".", "Items", "{", "switch", "x", ":=", "itm", ".", "RangeItem", ".", "(", "type", ")", "{", "case", "*", "RangeItem_Single", ":", "ret", "=", "append", "(", "ret", ",", "x", ".", "Single", ")", "\n", "case", "*", "RangeItem_Range", ":", "for", "i", ":=", "x", ".", "Range", ".", "Low", ";", "i", "<=", "x", ".", "Range", ".", "High", ";", "i", "++", "{", "ret", "=", "append", "(", "ret", ",", "i", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// ToSlice returns this SparseRange as an expanded slice of uint32s.
[ "ToSlice", "returns", "this", "SparseRange", "as", "an", "expanded", "slice", "of", "uint32s", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/distributor/jobsim/iterate.go#L26-L38
9,494
luci/luci-go
dm/api/distributor/jobsim/iterate.go
ExpandShards
func (s *DepsStage) ExpandShards() { newSlice := make([]*Dependency, 0, len(s.Deps)) for _, dep := range s.Deps { if dep.Shards != 0 { for i := uint64(0); i < dep.Shards; i++ { depCopy := *dep depCopy.Shards = 0 phraseCopy := *depCopy.Phrase phraseCopy.Name = fmt.Sprintf("%s_%d", phraseCopy.Name, i) depCopy.Phrase = &phraseCopy newSlice = append(newSlice, &depCopy) } } else { newSlice = append(newSlice, dep) } } s.Deps = newSlice }
go
func (s *DepsStage) ExpandShards() { newSlice := make([]*Dependency, 0, len(s.Deps)) for _, dep := range s.Deps { if dep.Shards != 0 { for i := uint64(0); i < dep.Shards; i++ { depCopy := *dep depCopy.Shards = 0 phraseCopy := *depCopy.Phrase phraseCopy.Name = fmt.Sprintf("%s_%d", phraseCopy.Name, i) depCopy.Phrase = &phraseCopy newSlice = append(newSlice, &depCopy) } } else { newSlice = append(newSlice, dep) } } s.Deps = newSlice }
[ "func", "(", "s", "*", "DepsStage", ")", "ExpandShards", "(", ")", "{", "newSlice", ":=", "make", "(", "[", "]", "*", "Dependency", ",", "0", ",", "len", "(", "s", ".", "Deps", ")", ")", "\n", "for", "_", ",", "dep", ":=", "range", "s", ".", "Deps", "{", "if", "dep", ".", "Shards", "!=", "0", "{", "for", "i", ":=", "uint64", "(", "0", ")", ";", "i", "<", "dep", ".", "Shards", ";", "i", "++", "{", "depCopy", ":=", "*", "dep", "\n", "depCopy", ".", "Shards", "=", "0", "\n", "phraseCopy", ":=", "*", "depCopy", ".", "Phrase", "\n", "phraseCopy", ".", "Name", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "phraseCopy", ".", "Name", ",", "i", ")", "\n", "depCopy", ".", "Phrase", "=", "&", "phraseCopy", "\n", "newSlice", "=", "append", "(", "newSlice", ",", "&", "depCopy", ")", "\n", "}", "\n", "}", "else", "{", "newSlice", "=", "append", "(", "newSlice", ",", "dep", ")", "\n", "}", "\n", "}", "\n", "s", ".", "Deps", "=", "newSlice", "\n", "}" ]
// ExpandShards expands any dependencies that have non-zero Shards values.
[ "ExpandShards", "expands", "any", "dependencies", "that", "have", "non", "-", "zero", "Shards", "values", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/distributor/jobsim/iterate.go#L41-L58
9,495
luci/luci-go
dm/api/distributor/jobsim/iterate.go
fastHash
func fastHash(a int64, bs ...int64) int64 { buf := make([]byte, 8) hasher := fnv.New64a() w := func(v int64) { binary.LittleEndian.PutUint64(buf, uint64(v)) if _, err := hasher.Write(buf); err != nil { panic(err) } } w(a) for _, b := range bs { w(b) } return int64(hasher.Sum64()) }
go
func fastHash(a int64, bs ...int64) int64 { buf := make([]byte, 8) hasher := fnv.New64a() w := func(v int64) { binary.LittleEndian.PutUint64(buf, uint64(v)) if _, err := hasher.Write(buf); err != nil { panic(err) } } w(a) for _, b := range bs { w(b) } return int64(hasher.Sum64()) }
[ "func", "fastHash", "(", "a", "int64", ",", "bs", "...", "int64", ")", "int64", "{", "buf", ":=", "make", "(", "[", "]", "byte", ",", "8", ")", "\n", "hasher", ":=", "fnv", ".", "New64a", "(", ")", "\n", "w", ":=", "func", "(", "v", "int64", ")", "{", "binary", ".", "LittleEndian", ".", "PutUint64", "(", "buf", ",", "uint64", "(", "v", ")", ")", "\n", "if", "_", ",", "err", ":=", "hasher", ".", "Write", "(", "buf", ")", ";", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "}", "\n", "w", "(", "a", ")", "\n", "for", "_", ",", "b", ":=", "range", "bs", "{", "w", "(", "b", ")", "\n", "}", "\n", "return", "int64", "(", "hasher", ".", "Sum64", "(", ")", ")", "\n", "}" ]
// fastHash is a non-cryptographic NxN -> N hash function. It's used to // deterministically blend seeds for subjobs.
[ "fastHash", "is", "a", "non", "-", "cryptographic", "NxN", "-", ">", "N", "hash", "function", ".", "It", "s", "used", "to", "deterministically", "blend", "seeds", "for", "subjobs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/distributor/jobsim/iterate.go#L62-L76
9,496
luci/luci-go
dm/api/distributor/jobsim/iterate.go
Seed
func (d *Dependency) Seed(rnd *rand.Rand, seed, round int64) { if d.MixSeed { if d.Phrase.Seed == 0 { d.Phrase.Seed = rnd.Int63() } else { d.Phrase.Seed = fastHash(seed*(math.MaxInt32), d.Phrase.Seed, round) } } else if d.Phrase.Seed == 0 { d.Phrase.Seed = seed } }
go
func (d *Dependency) Seed(rnd *rand.Rand, seed, round int64) { if d.MixSeed { if d.Phrase.Seed == 0 { d.Phrase.Seed = rnd.Int63() } else { d.Phrase.Seed = fastHash(seed*(math.MaxInt32), d.Phrase.Seed, round) } } else if d.Phrase.Seed == 0 { d.Phrase.Seed = seed } }
[ "func", "(", "d", "*", "Dependency", ")", "Seed", "(", "rnd", "*", "rand", ".", "Rand", ",", "seed", ",", "round", "int64", ")", "{", "if", "d", ".", "MixSeed", "{", "if", "d", ".", "Phrase", ".", "Seed", "==", "0", "{", "d", ".", "Phrase", ".", "Seed", "=", "rnd", ".", "Int63", "(", ")", "\n", "}", "else", "{", "d", ".", "Phrase", ".", "Seed", "=", "fastHash", "(", "seed", "*", "(", "math", ".", "MaxInt32", ")", ",", "d", ".", "Phrase", ".", "Seed", ",", "round", ")", "\n", "}", "\n", "}", "else", "if", "d", ".", "Phrase", ".", "Seed", "==", "0", "{", "d", ".", "Phrase", ".", "Seed", "=", "seed", "\n", "}", "\n", "}" ]
// Seed rewrites this dependency's Seed value
[ "Seed", "rewrites", "this", "dependency", "s", "Seed", "value" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/distributor/jobsim/iterate.go#L79-L89
9,497
luci/luci-go
common/logging/config.go
AddFlagsPrefix
func (c *Config) AddFlagsPrefix(fs *flag.FlagSet, prefix string) { fs.Var(&c.Level, prefix+"log-level", "The logging level. Valid options are: debug, info, warning, error.") }
go
func (c *Config) AddFlagsPrefix(fs *flag.FlagSet, prefix string) { fs.Var(&c.Level, prefix+"log-level", "The logging level. Valid options are: debug, info, warning, error.") }
[ "func", "(", "c", "*", "Config", ")", "AddFlagsPrefix", "(", "fs", "*", "flag", ".", "FlagSet", ",", "prefix", "string", ")", "{", "fs", ".", "Var", "(", "&", "c", ".", "Level", ",", "prefix", "+", "\"", "\"", ",", "\"", "\"", ")", "\n", "}" ]
// AddFlagsPrefix adds common flags to a supplied FlagSet with a prefix. // // A string prefix must be supplied which will be prepended to // each added flag verbatim.
[ "AddFlagsPrefix", "adds", "common", "flags", "to", "a", "supplied", "FlagSet", "with", "a", "prefix", ".", "A", "string", "prefix", "must", "be", "supplied", "which", "will", "be", "prepended", "to", "each", "added", "flag", "verbatim", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/config.go#L36-L39
9,498
luci/luci-go
common/logging/config.go
Set
func (c *Config) Set(ctx context.Context) context.Context { return SetLevel(ctx, c.Level) }
go
func (c *Config) Set(ctx context.Context) context.Context { return SetLevel(ctx, c.Level) }
[ "func", "(", "c", "*", "Config", ")", "Set", "(", "ctx", "context", ".", "Context", ")", "context", ".", "Context", "{", "return", "SetLevel", "(", "ctx", ",", "c", ".", "Level", ")", "\n", "}" ]
// Set returns a new context configured to use logging level passed via the // command-line level flag.
[ "Set", "returns", "a", "new", "context", "configured", "to", "use", "logging", "level", "passed", "via", "the", "command", "-", "line", "level", "flag", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/logging/config.go#L43-L45
9,499
luci/luci-go
machine-db/api/crimson/v1/pb.discovery.go
FileDescriptorSet
func FileDescriptorSet() *descriptor.FileDescriptorSet { // We just need ONE of the service names to look up the FileDescriptorSet. ret, err := discovery.GetDescriptorSet("crimson.Crimson") if err != nil { panic(err) } return ret }
go
func FileDescriptorSet() *descriptor.FileDescriptorSet { // We just need ONE of the service names to look up the FileDescriptorSet. ret, err := discovery.GetDescriptorSet("crimson.Crimson") if err != nil { panic(err) } return ret }
[ "func", "FileDescriptorSet", "(", ")", "*", "descriptor", ".", "FileDescriptorSet", "{", "// We just need ONE of the service names to look up the FileDescriptorSet.", "ret", ",", "err", ":=", "discovery", ".", "GetDescriptorSet", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// FileDescriptorSet returns a descriptor set for this proto package, which // includes all defined services, and all transitive dependencies. // // Will not return nil. // // Do NOT modify the returned descriptor.
[ "FileDescriptorSet", "returns", "a", "descriptor", "set", "for", "this", "proto", "package", "which", "includes", "all", "defined", "services", "and", "all", "transitive", "dependencies", ".", "Will", "not", "return", "nil", ".", "Do", "NOT", "modify", "the", "returned", "descriptor", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/api/crimson/v1/pb.discovery.go#L1119-L1126