id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
8,900
luci/luci-go
lucicfg/normalize/cq.go
CQ
func CQ(c context.Context, cfg *pb.Config) error { // Normalize each ConfigGroup individually first. for _, cg := range cfg.ConfigGroups { for _, g := range cg.Gerrit { normalizeGerrit(g) } sort.Slice(cg.Gerrit, func(i, j int) bool { return cg.Gerrit[i].Url < cg.Gerrit[j].Url }) if cg.Verifiers != nil { normalizeGerritCqAbility(cg.Verifiers.GerritCqAbility) normalizeTryjobs(cg.Verifiers.Tryjob) } } // Sort by some synthetic key. It doesn't really matter what it is exactly as // long as the final ordering is "stable" across multiple invocations. Note // that we rely here on sorting of Gerrit/Project/Refs done above. sortKeys := make(map[*pb.ConfigGroup]string, len(cfg.ConfigGroups)) for _, cg := range cfg.ConfigGroups { sortKeys[cg] = cgSortKey(cg) } sort.Slice(cfg.ConfigGroups, func(i, j int) bool { return sortKeys[cfg.ConfigGroups[i]] < sortKeys[cfg.ConfigGroups[j]] }) return nil }
go
func CQ(c context.Context, cfg *pb.Config) error { // Normalize each ConfigGroup individually first. for _, cg := range cfg.ConfigGroups { for _, g := range cg.Gerrit { normalizeGerrit(g) } sort.Slice(cg.Gerrit, func(i, j int) bool { return cg.Gerrit[i].Url < cg.Gerrit[j].Url }) if cg.Verifiers != nil { normalizeGerritCqAbility(cg.Verifiers.GerritCqAbility) normalizeTryjobs(cg.Verifiers.Tryjob) } } // Sort by some synthetic key. It doesn't really matter what it is exactly as // long as the final ordering is "stable" across multiple invocations. Note // that we rely here on sorting of Gerrit/Project/Refs done above. sortKeys := make(map[*pb.ConfigGroup]string, len(cfg.ConfigGroups)) for _, cg := range cfg.ConfigGroups { sortKeys[cg] = cgSortKey(cg) } sort.Slice(cfg.ConfigGroups, func(i, j int) bool { return sortKeys[cfg.ConfigGroups[i]] < sortKeys[cfg.ConfigGroups[j]] }) return nil }
[ "func", "CQ", "(", "c", "context", ".", "Context", ",", "cfg", "*", "pb", ".", "Config", ")", "error", "{", "// Normalize each ConfigGroup individually first.", "for", "_", ",", "cg", ":=", "range", "cfg", ".", "ConfigGroups", "{", "for", "_", ",", "g", ":=", "range", "cg", ".", "Gerrit", "{", "normalizeGerrit", "(", "g", ")", "\n", "}", "\n", "sort", ".", "Slice", "(", "cg", ".", "Gerrit", ",", "func", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "cg", ".", "Gerrit", "[", "i", "]", ".", "Url", "<", "cg", ".", "Gerrit", "[", "j", "]", ".", "Url", "\n", "}", ")", "\n", "if", "cg", ".", "Verifiers", "!=", "nil", "{", "normalizeGerritCqAbility", "(", "cg", ".", "Verifiers", ".", "GerritCqAbility", ")", "\n", "normalizeTryjobs", "(", "cg", ".", "Verifiers", ".", "Tryjob", ")", "\n", "}", "\n", "}", "\n\n", "// Sort by some synthetic key. It doesn't really matter what it is exactly as", "// long as the final ordering is \"stable\" across multiple invocations. Note", "// that we rely here on sorting of Gerrit/Project/Refs done above.", "sortKeys", ":=", "make", "(", "map", "[", "*", "pb", ".", "ConfigGroup", "]", "string", ",", "len", "(", "cfg", ".", "ConfigGroups", ")", ")", "\n", "for", "_", ",", "cg", ":=", "range", "cfg", ".", "ConfigGroups", "{", "sortKeys", "[", "cg", "]", "=", "cgSortKey", "(", "cg", ")", "\n", "}", "\n", "sort", ".", "Slice", "(", "cfg", ".", "ConfigGroups", ",", "func", "(", "i", ",", "j", "int", ")", "bool", "{", "return", "sortKeys", "[", "cfg", ".", "ConfigGroups", "[", "i", "]", "]", "<", "sortKeys", "[", "cfg", ".", "ConfigGroups", "[", "j", "]", "]", "\n", "}", ")", "\n\n", "return", "nil", "\n", "}" ]
// CQ normalizes cq.cfg config.
[ "CQ", "normalizes", "cq", ".", "cfg", "config", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/normalize/cq.go#L26-L53
8,901
luci/luci-go
logdog/common/types/streamname.go
Construct
func Construct(parts ...string) string { pidx := 0 for _, v := range parts { if v == "" { continue } parts[pidx] = strings.Trim(v, StreamNameSepStr) pidx++ } return strings.Join(parts[:pidx], StreamNameSepStr) }
go
func Construct(parts ...string) string { pidx := 0 for _, v := range parts { if v == "" { continue } parts[pidx] = strings.Trim(v, StreamNameSepStr) pidx++ } return strings.Join(parts[:pidx], StreamNameSepStr) }
[ "func", "Construct", "(", "parts", "...", "string", ")", "string", "{", "pidx", ":=", "0", "\n", "for", "_", ",", "v", ":=", "range", "parts", "{", "if", "v", "==", "\"", "\"", "{", "continue", "\n", "}", "\n", "parts", "[", "pidx", "]", "=", "strings", ".", "Trim", "(", "v", ",", "StreamNameSepStr", ")", "\n", "pidx", "++", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "parts", "[", ":", "pidx", "]", ",", "StreamNameSepStr", ")", "\n", "}" ]
// Construct builds a path string from a series of individual path components. // Any leading and trailing separators will be stripped from the components. // // The result value will be a valid StreamName if all of the parts are // valid StreamName strings. Likewise, it may be a valid StreamPath if // StreamPathSep is one of the parts.
[ "Construct", "builds", "a", "path", "string", "from", "a", "series", "of", "individual", "path", "components", ".", "Any", "leading", "and", "trailing", "separators", "will", "be", "stripped", "from", "the", "components", ".", "The", "result", "value", "will", "be", "a", "valid", "StreamName", "if", "all", "of", "the", "parts", "are", "valid", "StreamName", "strings", ".", "Likewise", "it", "may", "be", "a", "valid", "StreamPath", "if", "StreamPathSep", "is", "one", "of", "the", "parts", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/types/streamname.go#L68-L78
8,902
luci/luci-go
logdog/common/types/streamname.go
Join
func (s StreamName) Join(o StreamName) StreamPath { return StreamPath(fmt.Sprintf("%s%c%c%c%s", s.Trim(), StreamNameSep, StreamPathSep, StreamNameSep, o.Trim())) }
go
func (s StreamName) Join(o StreamName) StreamPath { return StreamPath(fmt.Sprintf("%s%c%c%c%s", s.Trim(), StreamNameSep, StreamPathSep, StreamNameSep, o.Trim())) }
[ "func", "(", "s", "StreamName", ")", "Join", "(", "o", "StreamName", ")", "StreamPath", "{", "return", "StreamPath", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "s", ".", "Trim", "(", ")", ",", "StreamNameSep", ",", "StreamPathSep", ",", "StreamNameSep", ",", "o", ".", "Trim", "(", ")", ")", ")", "\n", "}" ]
// Join concatenates a stream name onto the end of the current name, separating // it with a separator character.
[ "Join", "concatenates", "a", "stream", "name", "onto", "the", "end", "of", "the", "current", "name", "separating", "it", "with", "a", "separator", "character", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/types/streamname.go#L166-L169
8,903
luci/luci-go
logdog/common/types/streamname.go
Concat
func (s StreamName) Concat(o ...StreamName) StreamName { parts := make([]string, len(o)+1) parts[0] = string(s) for i, c := range o { parts[i+1] = string(c) } return StreamName(Construct(parts...)) }
go
func (s StreamName) Concat(o ...StreamName) StreamName { parts := make([]string, len(o)+1) parts[0] = string(s) for i, c := range o { parts[i+1] = string(c) } return StreamName(Construct(parts...)) }
[ "func", "(", "s", "StreamName", ")", "Concat", "(", "o", "...", "StreamName", ")", "StreamName", "{", "parts", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "o", ")", "+", "1", ")", "\n", "parts", "[", "0", "]", "=", "string", "(", "s", ")", "\n", "for", "i", ",", "c", ":=", "range", "o", "{", "parts", "[", "i", "+", "1", "]", "=", "string", "(", "c", ")", "\n", "}", "\n", "return", "StreamName", "(", "Construct", "(", "parts", "...", ")", ")", "\n", "}" ]
// Concat constructs a StreamName by concatenating several StreamName components // together.
[ "Concat", "constructs", "a", "StreamName", "by", "concatenating", "several", "StreamName", "components", "together", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/types/streamname.go#L173-L180
8,904
luci/luci-go
logdog/common/types/streamname.go
Validate
func (s StreamName) Validate() error { if len(s) == 0 { return errors.New("must contain at least one character") } if len(s) > MaxStreamNameLength { return fmt.Errorf("stream name is too long (%d > %d)", len(s), MaxStreamNameLength) } var lastRune rune var segmentIdx int for idx, r := range s { // Alphanumeric. if !isAlnum(r) { // The stream name must begin with an alphanumeric character. if idx == segmentIdx { return fmt.Errorf("Segment (at %d) must begin with alphanumeric character.", segmentIdx) } // Test forward slash, and ensure no adjacent forward slashes. if r == StreamNameSep { segmentIdx = idx + utf8.RuneLen(r) } else if !(r == '.' || r == '_' || r == '-' || r == ':') { // Test remaining allowed characters. return fmt.Errorf("Illegal charater (%c) at index %d.", r, idx) } } lastRune = r } // The last rune may not be a separator. if lastRune == StreamNameSep { return errors.New("Name may not end with a separator.") } return nil }
go
func (s StreamName) Validate() error { if len(s) == 0 { return errors.New("must contain at least one character") } if len(s) > MaxStreamNameLength { return fmt.Errorf("stream name is too long (%d > %d)", len(s), MaxStreamNameLength) } var lastRune rune var segmentIdx int for idx, r := range s { // Alphanumeric. if !isAlnum(r) { // The stream name must begin with an alphanumeric character. if idx == segmentIdx { return fmt.Errorf("Segment (at %d) must begin with alphanumeric character.", segmentIdx) } // Test forward slash, and ensure no adjacent forward slashes. if r == StreamNameSep { segmentIdx = idx + utf8.RuneLen(r) } else if !(r == '.' || r == '_' || r == '-' || r == ':') { // Test remaining allowed characters. return fmt.Errorf("Illegal charater (%c) at index %d.", r, idx) } } lastRune = r } // The last rune may not be a separator. if lastRune == StreamNameSep { return errors.New("Name may not end with a separator.") } return nil }
[ "func", "(", "s", "StreamName", ")", "Validate", "(", ")", "error", "{", "if", "len", "(", "s", ")", "==", "0", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "s", ")", ">", "MaxStreamNameLength", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "s", ")", ",", "MaxStreamNameLength", ")", "\n", "}", "\n\n", "var", "lastRune", "rune", "\n", "var", "segmentIdx", "int", "\n", "for", "idx", ",", "r", ":=", "range", "s", "{", "// Alphanumeric.", "if", "!", "isAlnum", "(", "r", ")", "{", "// The stream name must begin with an alphanumeric character.", "if", "idx", "==", "segmentIdx", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "segmentIdx", ")", "\n", "}", "\n\n", "// Test forward slash, and ensure no adjacent forward slashes.", "if", "r", "==", "StreamNameSep", "{", "segmentIdx", "=", "idx", "+", "utf8", ".", "RuneLen", "(", "r", ")", "\n", "}", "else", "if", "!", "(", "r", "==", "'.'", "||", "r", "==", "'_'", "||", "r", "==", "'-'", "||", "r", "==", "':'", ")", "{", "// Test remaining allowed characters.", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "r", ",", "idx", ")", "\n", "}", "\n", "}", "\n", "lastRune", "=", "r", "\n", "}", "\n\n", "// The last rune may not be a separator.", "if", "lastRune", "==", "StreamNameSep", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate tests whether the stream name is valid.
[ "Validate", "tests", "whether", "the", "stream", "name", "is", "valid", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/types/streamname.go#L196-L230
8,905
luci/luci-go
logdog/common/types/streamname.go
Segments
func (s StreamName) Segments() []string { if len(s) == 0 { return nil } return strings.Split(string(s), string(StreamNameSep)) }
go
func (s StreamName) Segments() []string { if len(s) == 0 { return nil } return strings.Split(string(s), string(StreamNameSep)) }
[ "func", "(", "s", "StreamName", ")", "Segments", "(", ")", "[", "]", "string", "{", "if", "len", "(", "s", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "return", "strings", ".", "Split", "(", "string", "(", "s", ")", ",", "string", "(", "StreamNameSep", ")", ")", "\n", "}" ]
// Segments returns the individual StreamName segments by splitting splitting // the StreamName with StreamNameSep.
[ "Segments", "returns", "the", "individual", "StreamName", "segments", "by", "splitting", "splitting", "the", "StreamName", "with", "StreamNameSep", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/types/streamname.go#L234-L239
8,906
luci/luci-go
logdog/common/types/streamname.go
Append
func (p StreamPath) Append(n string) StreamPath { return StreamPath(Construct(string(p), n)) }
go
func (p StreamPath) Append(n string) StreamPath { return StreamPath(Construct(string(p), n)) }
[ "func", "(", "p", "StreamPath", ")", "Append", "(", "n", "string", ")", "StreamPath", "{", "return", "StreamPath", "(", "Construct", "(", "string", "(", "p", ")", ",", "n", ")", ")", "\n", "}" ]
// Append returns a StreamPath consisting of the current StreamPath with the // supplied StreamName appended to the end. // // Append will return a valid StreamPath if p and n are both valid.
[ "Append", "returns", "a", "StreamPath", "consisting", "of", "the", "current", "StreamPath", "with", "the", "supplied", "StreamName", "appended", "to", "the", "end", ".", "Append", "will", "return", "a", "valid", "StreamPath", "if", "p", "and", "n", "are", "both", "valid", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/types/streamname.go#L401-L403
8,907
luci/luci-go
dm/api/service/v1/quest_desc_normalize.go
IsEmpty
func (q *Quest_Desc_Meta_Retry) IsEmpty() bool { return q.Crashed == 0 && q.Expired == 0 && q.Failed == 0 && q.TimedOut == 0 }
go
func (q *Quest_Desc_Meta_Retry) IsEmpty() bool { return q.Crashed == 0 && q.Expired == 0 && q.Failed == 0 && q.TimedOut == 0 }
[ "func", "(", "q", "*", "Quest_Desc_Meta_Retry", ")", "IsEmpty", "(", ")", "bool", "{", "return", "q", ".", "Crashed", "==", "0", "&&", "q", ".", "Expired", "==", "0", "&&", "q", ".", "Failed", "==", "0", "&&", "q", ".", "TimedOut", "==", "0", "\n", "}" ]
// IsEmpty returns true if this metadata retry message only contains // zero-values.
[ "IsEmpty", "returns", "true", "if", "this", "metadata", "retry", "message", "only", "contains", "zero", "-", "values", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/quest_desc_normalize.go#L29-L31
8,908
luci/luci-go
dm/api/service/v1/quest_desc_normalize.go
Normalize
func (t *Quest_Desc_Meta_Timeouts) Normalize() error { if d := google.DurationFromProto(t.Start); d < 0 { return fmt.Errorf("desc.meta.timeouts.start < 0: %s", d) } if d := google.DurationFromProto(t.Run); d < 0 { return fmt.Errorf("desc.meta.timeouts.run < 0: %s", d) } if d := google.DurationFromProto(t.Stop); d < 0 { return fmt.Errorf("desc.meta.timeouts.stop < 0: %s", d) } return nil }
go
func (t *Quest_Desc_Meta_Timeouts) Normalize() error { if d := google.DurationFromProto(t.Start); d < 0 { return fmt.Errorf("desc.meta.timeouts.start < 0: %s", d) } if d := google.DurationFromProto(t.Run); d < 0 { return fmt.Errorf("desc.meta.timeouts.run < 0: %s", d) } if d := google.DurationFromProto(t.Stop); d < 0 { return fmt.Errorf("desc.meta.timeouts.stop < 0: %s", d) } return nil }
[ "func", "(", "t", "*", "Quest_Desc_Meta_Timeouts", ")", "Normalize", "(", ")", "error", "{", "if", "d", ":=", "google", ".", "DurationFromProto", "(", "t", ".", "Start", ")", ";", "d", "<", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "d", ")", "\n", "}", "\n", "if", "d", ":=", "google", ".", "DurationFromProto", "(", "t", ".", "Run", ")", ";", "d", "<", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "d", ")", "\n", "}", "\n", "if", "d", ":=", "google", ".", "DurationFromProto", "(", "t", ".", "Stop", ")", ";", "d", "<", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "d", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Normalize ensures that all timeouts are >= 0
[ "Normalize", "ensures", "that", "all", "timeouts", "are", ">", "=", "0" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/quest_desc_normalize.go#L34-L45
8,909
luci/luci-go
dm/api/service/v1/quest_desc_normalize.go
Normalize
func (q *Quest_Desc) Normalize() error { if q.Meta == nil { q.Meta = &Quest_Desc_Meta{ Retry: &Quest_Desc_Meta_Retry{}, Timeouts: &Quest_Desc_Meta_Timeouts{}, } } else { if q.Meta.Retry == nil { q.Meta.Retry = &Quest_Desc_Meta_Retry{} } if q.Meta.Timeouts == nil { q.Meta.Timeouts = &Quest_Desc_Meta_Timeouts{} } } if err := q.Meta.Timeouts.Normalize(); err != nil { return err } length := len(q.Parameters) + len(q.DistributorParameters) if length > QuestDescPayloadMaxLength { return fmt.Errorf("quest payload is too large: %d > %d", length, QuestDescPayloadMaxLength) } normed, err := templateproto.NormalizeJSON(q.Parameters, true) if err != nil { return fmt.Errorf("failed to normalize parameters: %s", err) } q.Parameters = normed normed, err = templateproto.NormalizeJSON(q.DistributorParameters, true) if err != nil { return fmt.Errorf("failed to normalize distributor parameters: %s", err) } q.DistributorParameters = normed return nil }
go
func (q *Quest_Desc) Normalize() error { if q.Meta == nil { q.Meta = &Quest_Desc_Meta{ Retry: &Quest_Desc_Meta_Retry{}, Timeouts: &Quest_Desc_Meta_Timeouts{}, } } else { if q.Meta.Retry == nil { q.Meta.Retry = &Quest_Desc_Meta_Retry{} } if q.Meta.Timeouts == nil { q.Meta.Timeouts = &Quest_Desc_Meta_Timeouts{} } } if err := q.Meta.Timeouts.Normalize(); err != nil { return err } length := len(q.Parameters) + len(q.DistributorParameters) if length > QuestDescPayloadMaxLength { return fmt.Errorf("quest payload is too large: %d > %d", length, QuestDescPayloadMaxLength) } normed, err := templateproto.NormalizeJSON(q.Parameters, true) if err != nil { return fmt.Errorf("failed to normalize parameters: %s", err) } q.Parameters = normed normed, err = templateproto.NormalizeJSON(q.DistributorParameters, true) if err != nil { return fmt.Errorf("failed to normalize distributor parameters: %s", err) } q.DistributorParameters = normed return nil }
[ "func", "(", "q", "*", "Quest_Desc", ")", "Normalize", "(", ")", "error", "{", "if", "q", ".", "Meta", "==", "nil", "{", "q", ".", "Meta", "=", "&", "Quest_Desc_Meta", "{", "Retry", ":", "&", "Quest_Desc_Meta_Retry", "{", "}", ",", "Timeouts", ":", "&", "Quest_Desc_Meta_Timeouts", "{", "}", ",", "}", "\n", "}", "else", "{", "if", "q", ".", "Meta", ".", "Retry", "==", "nil", "{", "q", ".", "Meta", ".", "Retry", "=", "&", "Quest_Desc_Meta_Retry", "{", "}", "\n", "}", "\n", "if", "q", ".", "Meta", ".", "Timeouts", "==", "nil", "{", "q", ".", "Meta", ".", "Timeouts", "=", "&", "Quest_Desc_Meta_Timeouts", "{", "}", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "q", ".", "Meta", ".", "Timeouts", ".", "Normalize", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "length", ":=", "len", "(", "q", ".", "Parameters", ")", "+", "len", "(", "q", ".", "DistributorParameters", ")", "\n", "if", "length", ">", "QuestDescPayloadMaxLength", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "length", ",", "QuestDescPayloadMaxLength", ")", "\n", "}", "\n", "normed", ",", "err", ":=", "templateproto", ".", "NormalizeJSON", "(", "q", ".", "Parameters", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "q", ".", "Parameters", "=", "normed", "\n\n", "normed", ",", "err", "=", "templateproto", ".", "NormalizeJSON", "(", "q", ".", "DistributorParameters", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "q", ".", "DistributorParameters", "=", "normed", "\n", "return", "nil", "\n", "}" ]
// Normalize returns an error iff the Quest_Desc is invalid.
[ "Normalize", "returns", "an", "error", "iff", "the", "Quest_Desc", "is", "invalid", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/quest_desc_normalize.go#L63-L98
8,910
luci/luci-go
common/gcloud/iam/client.go
GetIAMPolicy
func (cl *Client) GetIAMPolicy(c context.Context, resource string) (*Policy, error) { response := &Policy{} if err := cl.iamAPIRequest(c, resource, "getIamPolicy", nil, response); err != nil { return nil, err } return response, nil }
go
func (cl *Client) GetIAMPolicy(c context.Context, resource string) (*Policy, error) { response := &Policy{} if err := cl.iamAPIRequest(c, resource, "getIamPolicy", nil, response); err != nil { return nil, err } return response, nil }
[ "func", "(", "cl", "*", "Client", ")", "GetIAMPolicy", "(", "c", "context", ".", "Context", ",", "resource", "string", ")", "(", "*", "Policy", ",", "error", ")", "{", "response", ":=", "&", "Policy", "{", "}", "\n", "if", "err", ":=", "cl", ".", "iamAPIRequest", "(", "c", ",", "resource", ",", "\"", "\"", ",", "nil", ",", "response", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "response", ",", "nil", "\n", "}" ]
// GetIAMPolicy fetches an IAM policy of a resource. // // On non-success HTTP status codes returns googleapi.Error.
[ "GetIAMPolicy", "fetches", "an", "IAM", "policy", "of", "a", "resource", ".", "On", "non", "-", "success", "HTTP", "status", "codes", "returns", "googleapi", ".", "Error", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/gcloud/iam/client.go#L145-L151
8,911
luci/luci-go
common/gcloud/iam/client.go
iamAPIRequest
func (cl *Client) iamAPIRequest(c context.Context, resource, action string, body, resp interface{}) error { if cl.BasePath != "" { // We are in "testing" base, err := url.Parse(cl.BasePath) if err != nil { return err } return cl.genericAPIRequest(c, base, resource, action, body, resp) } return cl.genericAPIRequest(c, DefaultIamBaseURL, resource, action, body, resp) }
go
func (cl *Client) iamAPIRequest(c context.Context, resource, action string, body, resp interface{}) error { if cl.BasePath != "" { // We are in "testing" base, err := url.Parse(cl.BasePath) if err != nil { return err } return cl.genericAPIRequest(c, base, resource, action, body, resp) } return cl.genericAPIRequest(c, DefaultIamBaseURL, resource, action, body, resp) }
[ "func", "(", "cl", "*", "Client", ")", "iamAPIRequest", "(", "c", "context", ".", "Context", ",", "resource", ",", "action", "string", ",", "body", ",", "resp", "interface", "{", "}", ")", "error", "{", "if", "cl", ".", "BasePath", "!=", "\"", "\"", "{", "// We are in \"testing\"", "base", ",", "err", ":=", "url", ".", "Parse", "(", "cl", ".", "BasePath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "cl", ".", "genericAPIRequest", "(", "c", ",", "base", ",", "resource", ",", "action", ",", "body", ",", "resp", ")", "\n", "}", "\n", "return", "cl", ".", "genericAPIRequest", "(", "c", ",", "DefaultIamBaseURL", ",", "resource", ",", "action", ",", "body", ",", "resp", ")", "\n", "}" ]
// iamAPIRequest performs HTTP POST to the core IAM API endpoint.
[ "iamAPIRequest", "performs", "HTTP", "POST", "to", "the", "core", "IAM", "API", "endpoint", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/gcloud/iam/client.go#L237-L247
8,912
luci/luci-go
common/gcloud/iam/client.go
genericAPIRequest
func (cl *Client) genericAPIRequest(c context.Context, base *url.URL, resource, action string, body, resp interface{}) error { query, err := url.Parse(fmt.Sprintf("v1/%s:%s?alt=json", resource, action)) if err != nil { return err } endpoint := base.ResolveReference(query) // Serialize the body. var reader io.Reader if body != nil { blob, err := json.Marshal(body) if err != nil { return err } reader = bytes.NewReader(blob) } // Issue the request req, err := http.NewRequest("POST", endpoint.String(), reader) if err != nil { return err } if reader != nil { req.Header.Set("Content-Type", "application/json") } // Send and handle errors. This is roughly how google-api-go-client calls // methods. CheckResponse returns *googleapi.Error. logging.Debugf(c, "POST %s", endpoint) res, err := ctxhttp.Do(c, cl.Client, req) if err != nil { return err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { logging.WithError(err).Errorf(c, "POST %s failed", endpoint) return err } return json.NewDecoder(res.Body).Decode(resp) }
go
func (cl *Client) genericAPIRequest(c context.Context, base *url.URL, resource, action string, body, resp interface{}) error { query, err := url.Parse(fmt.Sprintf("v1/%s:%s?alt=json", resource, action)) if err != nil { return err } endpoint := base.ResolveReference(query) // Serialize the body. var reader io.Reader if body != nil { blob, err := json.Marshal(body) if err != nil { return err } reader = bytes.NewReader(blob) } // Issue the request req, err := http.NewRequest("POST", endpoint.String(), reader) if err != nil { return err } if reader != nil { req.Header.Set("Content-Type", "application/json") } // Send and handle errors. This is roughly how google-api-go-client calls // methods. CheckResponse returns *googleapi.Error. logging.Debugf(c, "POST %s", endpoint) res, err := ctxhttp.Do(c, cl.Client, req) if err != nil { return err } defer googleapi.CloseBody(res) if err := googleapi.CheckResponse(res); err != nil { logging.WithError(err).Errorf(c, "POST %s failed", endpoint) return err } return json.NewDecoder(res.Body).Decode(resp) }
[ "func", "(", "cl", "*", "Client", ")", "genericAPIRequest", "(", "c", "context", ".", "Context", ",", "base", "*", "url", ".", "URL", ",", "resource", ",", "action", "string", ",", "body", ",", "resp", "interface", "{", "}", ")", "error", "{", "query", ",", "err", ":=", "url", ".", "Parse", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "resource", ",", "action", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "endpoint", ":=", "base", ".", "ResolveReference", "(", "query", ")", "\n\n", "// Serialize the body.", "var", "reader", "io", ".", "Reader", "\n", "if", "body", "!=", "nil", "{", "blob", ",", "err", ":=", "json", ".", "Marshal", "(", "body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "reader", "=", "bytes", ".", "NewReader", "(", "blob", ")", "\n", "}", "\n\n", "// Issue the request", "req", ",", "err", ":=", "http", ".", "NewRequest", "(", "\"", "\"", ",", "endpoint", ".", "String", "(", ")", ",", "reader", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "reader", "!=", "nil", "{", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Send and handle errors. This is roughly how google-api-go-client calls", "// methods. CheckResponse returns *googleapi.Error.", "logging", ".", "Debugf", "(", "c", ",", "\"", "\"", ",", "endpoint", ")", "\n", "res", ",", "err", ":=", "ctxhttp", ".", "Do", "(", "c", ",", "cl", ".", "Client", ",", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "googleapi", ".", "CloseBody", "(", "res", ")", "\n", "if", "err", ":=", "googleapi", ".", "CheckResponse", "(", "res", ")", ";", "err", "!=", "nil", "{", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ",", "endpoint", ")", "\n", "return", "err", "\n", "}", "\n", "return", "json", ".", "NewDecoder", "(", "res", ".", "Body", ")", ".", "Decode", "(", "resp", ")", "\n", "}" ]
// genericAPIRequest performs HTTP POST to an IAM API endpoint.
[ "genericAPIRequest", "performs", "HTTP", "POST", "to", "an", "IAM", "API", "endpoint", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/gcloud/iam/client.go#L263-L302
8,913
luci/luci-go
cipd/appengine/impl/model/instance.go
Proto
func (e *Instance) Proto() *api.Instance { return &api.Instance{ Package: e.Package.StringID(), Instance: common.InstanceIDToObjectRef(e.InstanceID), RegisteredBy: e.RegisteredBy, RegisteredTs: google.NewTimestamp(e.RegisteredTs), } }
go
func (e *Instance) Proto() *api.Instance { return &api.Instance{ Package: e.Package.StringID(), Instance: common.InstanceIDToObjectRef(e.InstanceID), RegisteredBy: e.RegisteredBy, RegisteredTs: google.NewTimestamp(e.RegisteredTs), } }
[ "func", "(", "e", "*", "Instance", ")", "Proto", "(", ")", "*", "api", ".", "Instance", "{", "return", "&", "api", ".", "Instance", "{", "Package", ":", "e", ".", "Package", ".", "StringID", "(", ")", ",", "Instance", ":", "common", ".", "InstanceIDToObjectRef", "(", "e", ".", "InstanceID", ")", ",", "RegisteredBy", ":", "e", ".", "RegisteredBy", ",", "RegisteredTs", ":", "google", ".", "NewTimestamp", "(", "e", ".", "RegisteredTs", ")", ",", "}", "\n", "}" ]
// Proto returns cipd.Instance proto with information from this entity.
[ "Proto", "returns", "cipd", ".", "Instance", "proto", "with", "information", "from", "this", "entity", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/model/instance.go#L61-L68
8,914
luci/luci-go
cipd/appengine/impl/model/instance.go
FromProto
func (e *Instance) FromProto(c context.Context, p *api.Instance) *Instance { e.InstanceID = common.ObjectRefToInstanceID(p.Instance) e.Package = PackageKey(c, p.Package) return e }
go
func (e *Instance) FromProto(c context.Context, p *api.Instance) *Instance { e.InstanceID = common.ObjectRefToInstanceID(p.Instance) e.Package = PackageKey(c, p.Package) return e }
[ "func", "(", "e", "*", "Instance", ")", "FromProto", "(", "c", "context", ".", "Context", ",", "p", "*", "api", ".", "Instance", ")", "*", "Instance", "{", "e", ".", "InstanceID", "=", "common", ".", "ObjectRefToInstanceID", "(", "p", ".", "Instance", ")", "\n", "e", ".", "Package", "=", "PackageKey", "(", "c", ",", "p", ".", "Package", ")", "\n", "return", "e", "\n", "}" ]
// FromProto fills in the entity based on the proto message. // // Returns the entity itself for easier chaining. // // Doesn't touch output-only fields at all.
[ "FromProto", "fills", "in", "the", "entity", "based", "on", "the", "proto", "message", ".", "Returns", "the", "entity", "itself", "for", "easier", "chaining", ".", "Doesn", "t", "touch", "output", "-", "only", "fields", "at", "all", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/model/instance.go#L75-L79
8,915
luci/luci-go
cipd/appengine/impl/model/instance.go
CheckInstanceExists
func CheckInstanceExists(c context.Context, inst *Instance) error { switch err := datastore.Get(c, inst); { case err == datastore.ErrNoSuchEntity: // Maybe the package is missing completely? if err := CheckPackageExists(c, inst.Package.StringID()); err != nil { return err } return errors.Reason("no such instance").Tag(grpcutil.NotFoundTag).Err() case err != nil: return errors.Annotate(err, "failed to check the instance presence").Tag(transient.Tag).Err() default: return nil } }
go
func CheckInstanceExists(c context.Context, inst *Instance) error { switch err := datastore.Get(c, inst); { case err == datastore.ErrNoSuchEntity: // Maybe the package is missing completely? if err := CheckPackageExists(c, inst.Package.StringID()); err != nil { return err } return errors.Reason("no such instance").Tag(grpcutil.NotFoundTag).Err() case err != nil: return errors.Annotate(err, "failed to check the instance presence").Tag(transient.Tag).Err() default: return nil } }
[ "func", "CheckInstanceExists", "(", "c", "context", ".", "Context", ",", "inst", "*", "Instance", ")", "error", "{", "switch", "err", ":=", "datastore", ".", "Get", "(", "c", ",", "inst", ")", ";", "{", "case", "err", "==", "datastore", ".", "ErrNoSuchEntity", ":", "// Maybe the package is missing completely?", "if", "err", ":=", "CheckPackageExists", "(", "c", ",", "inst", ".", "Package", ".", "StringID", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "errors", ".", "Reason", "(", "\"", "\"", ")", ".", "Tag", "(", "grpcutil", ".", "NotFoundTag", ")", ".", "Err", "(", ")", "\n", "case", "err", "!=", "nil", ":", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Tag", "(", "transient", ".", "Tag", ")", ".", "Err", "(", ")", "\n", "default", ":", "return", "nil", "\n", "}", "\n", "}" ]
// CheckInstanceExists fetches the instance and verifies it exists. // // Can be called as part of a transaction. Updates 'inst' in place. // // Returns gRPC-tagged NotFound error if there's no such instance or package.
[ "CheckInstanceExists", "fetches", "the", "instance", "and", "verifies", "it", "exists", ".", "Can", "be", "called", "as", "part", "of", "a", "transaction", ".", "Updates", "inst", "in", "place", ".", "Returns", "gRPC", "-", "tagged", "NotFound", "error", "if", "there", "s", "no", "such", "instance", "or", "package", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/model/instance.go#L197-L210
8,916
luci/luci-go
tokenserver/cmd/luci_machine_tokend/status.go
OutcomeFromRPCError
func OutcomeFromRPCError(err error) UpdateOutcome { if err == nil { return OutcomeUpdateSuccess } if details, ok := err.(client.RPCError); ok { if details.GrpcCode != codes.OK { return UpdateOutcome(fmt.Sprintf("GRPC_ERROR_%d", details.GrpcCode)) } return UpdateOutcome(fmt.Sprintf("MINT_TOKEN_ERROR_%s", details.ErrorCode)) } return OutcomeUnknownRPCError }
go
func OutcomeFromRPCError(err error) UpdateOutcome { if err == nil { return OutcomeUpdateSuccess } if details, ok := err.(client.RPCError); ok { if details.GrpcCode != codes.OK { return UpdateOutcome(fmt.Sprintf("GRPC_ERROR_%d", details.GrpcCode)) } return UpdateOutcome(fmt.Sprintf("MINT_TOKEN_ERROR_%s", details.ErrorCode)) } return OutcomeUnknownRPCError }
[ "func", "OutcomeFromRPCError", "(", "err", "error", ")", "UpdateOutcome", "{", "if", "err", "==", "nil", "{", "return", "OutcomeUpdateSuccess", "\n", "}", "\n", "if", "details", ",", "ok", ":=", "err", ".", "(", "client", ".", "RPCError", ")", ";", "ok", "{", "if", "details", ".", "GrpcCode", "!=", "codes", ".", "OK", "{", "return", "UpdateOutcome", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "details", ".", "GrpcCode", ")", ")", "\n", "}", "\n", "return", "UpdateOutcome", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "details", ".", "ErrorCode", ")", ")", "\n", "}", "\n", "return", "OutcomeUnknownRPCError", "\n", "}" ]
// OutcomeFromRPCError transform MintToken error into an update outcome.
[ "OutcomeFromRPCError", "transform", "MintToken", "error", "into", "an", "update", "outcome", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/cmd/luci_machine_tokend/status.go#L52-L63
8,917
luci/luci-go
tokenserver/cmd/luci_machine_tokend/status.go
Report
func (s *StatusReport) Report() *Report { rep := &Report{ TokendVersion: s.Version, ServiceVersion: s.ServiceVersion, StartedTS: s.Started.Unix(), TotalDuration: s.Finished.Sub(s.Started).Nanoseconds() / 1000, RPCDuration: s.MintTokenDuration.Nanoseconds() / 1000, UpdateOutcome: string(s.UpdateOutcome), UpdateReason: string(s.UpdateReason), } if s.FailureError != nil { rep.FailureError = s.FailureError.Error() } if s.LastToken != nil { rep.TokenLastUpdateTS = s.LastToken.LastUpdate rep.TokenNextUpdateTS = s.LastToken.NextUpdate rep.TokenExpiryTS = s.LastToken.Expiry } return rep }
go
func (s *StatusReport) Report() *Report { rep := &Report{ TokendVersion: s.Version, ServiceVersion: s.ServiceVersion, StartedTS: s.Started.Unix(), TotalDuration: s.Finished.Sub(s.Started).Nanoseconds() / 1000, RPCDuration: s.MintTokenDuration.Nanoseconds() / 1000, UpdateOutcome: string(s.UpdateOutcome), UpdateReason: string(s.UpdateReason), } if s.FailureError != nil { rep.FailureError = s.FailureError.Error() } if s.LastToken != nil { rep.TokenLastUpdateTS = s.LastToken.LastUpdate rep.TokenNextUpdateTS = s.LastToken.NextUpdate rep.TokenExpiryTS = s.LastToken.Expiry } return rep }
[ "func", "(", "s", "*", "StatusReport", ")", "Report", "(", ")", "*", "Report", "{", "rep", ":=", "&", "Report", "{", "TokendVersion", ":", "s", ".", "Version", ",", "ServiceVersion", ":", "s", ".", "ServiceVersion", ",", "StartedTS", ":", "s", ".", "Started", ".", "Unix", "(", ")", ",", "TotalDuration", ":", "s", ".", "Finished", ".", "Sub", "(", "s", ".", "Started", ")", ".", "Nanoseconds", "(", ")", "/", "1000", ",", "RPCDuration", ":", "s", ".", "MintTokenDuration", ".", "Nanoseconds", "(", ")", "/", "1000", ",", "UpdateOutcome", ":", "string", "(", "s", ".", "UpdateOutcome", ")", ",", "UpdateReason", ":", "string", "(", "s", ".", "UpdateReason", ")", ",", "}", "\n", "if", "s", ".", "FailureError", "!=", "nil", "{", "rep", ".", "FailureError", "=", "s", ".", "FailureError", ".", "Error", "(", ")", "\n", "}", "\n", "if", "s", ".", "LastToken", "!=", "nil", "{", "rep", ".", "TokenLastUpdateTS", "=", "s", ".", "LastToken", ".", "LastUpdate", "\n", "rep", ".", "TokenNextUpdateTS", "=", "s", ".", "LastToken", ".", "NextUpdate", "\n", "rep", ".", "TokenExpiryTS", "=", "s", ".", "LastToken", ".", "Expiry", "\n", "}", "\n", "return", "rep", "\n", "}" ]
// Report gathers the report into single JSON-serializable struct.
[ "Report", "gathers", "the", "report", "into", "single", "JSON", "-", "serializable", "struct", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/cmd/luci_machine_tokend/status.go#L109-L128
8,918
luci/luci-go
tokenserver/cmd/luci_machine_tokend/status.go
SaveToFile
func (s *StatusReport) SaveToFile(ctx context.Context, l *memlogger.MemLogger, path string) error { report := s.Report() buf := bytes.Buffer{} l.Dump(&buf) report.LogDump = buf.String() blob, err := json.MarshalIndent(report, "", " ") if err != nil { return err } return AtomicWriteFile(ctx, path, blob, 0644) }
go
func (s *StatusReport) SaveToFile(ctx context.Context, l *memlogger.MemLogger, path string) error { report := s.Report() buf := bytes.Buffer{} l.Dump(&buf) report.LogDump = buf.String() blob, err := json.MarshalIndent(report, "", " ") if err != nil { return err } return AtomicWriteFile(ctx, path, blob, 0644) }
[ "func", "(", "s", "*", "StatusReport", ")", "SaveToFile", "(", "ctx", "context", ".", "Context", ",", "l", "*", "memlogger", ".", "MemLogger", ",", "path", "string", ")", "error", "{", "report", ":=", "s", ".", "Report", "(", ")", "\n\n", "buf", ":=", "bytes", ".", "Buffer", "{", "}", "\n", "l", ".", "Dump", "(", "&", "buf", ")", "\n", "report", ".", "LogDump", "=", "buf", ".", "String", "(", ")", "\n\n", "blob", ",", "err", ":=", "json", ".", "MarshalIndent", "(", "report", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "AtomicWriteFile", "(", "ctx", ",", "path", ",", "blob", ",", "0644", ")", "\n", "}" ]
// SaveToFile saves the status report and log to a file on disk.
[ "SaveToFile", "saves", "the", "status", "report", "and", "log", "to", "a", "file", "on", "disk", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/cmd/luci_machine_tokend/status.go#L131-L143
8,919
luci/luci-go
tokenserver/cmd/luci_machine_tokend/status.go
SendMetrics
func (s *StatusReport) SendMetrics(c context.Context) error { c, _ = context.WithTimeout(c, 10*time.Second) rep := s.Report() metricVersion.Set(c, rep.TokendVersion) if rep.ServiceVersion != "" { metricServiceVersion.Set(c, rep.ServiceVersion) } if rep.TokenExpiryTS != 0 { metricTokenExpiry.Set(c, rep.TokenExpiryTS*1000000) } if rep.TokenLastUpdateTS != 0 { metricTokenLastUpdate.Set(c, rep.TokenLastUpdateTS*1000000) } if rep.TokenNextUpdateTS != 0 { metricTokenNextUpdate.Set(c, rep.TokenNextUpdateTS*1000000) } metricUpdateOutcome.Set(c, rep.UpdateOutcome) metricUpdateReason.Set(c, rep.UpdateReason) metricTotalDuration.Set(c, rep.TotalDuration) metricRPCDuration.Set(c, rep.RPCDuration) return tsmon.Flush(c) }
go
func (s *StatusReport) SendMetrics(c context.Context) error { c, _ = context.WithTimeout(c, 10*time.Second) rep := s.Report() metricVersion.Set(c, rep.TokendVersion) if rep.ServiceVersion != "" { metricServiceVersion.Set(c, rep.ServiceVersion) } if rep.TokenExpiryTS != 0 { metricTokenExpiry.Set(c, rep.TokenExpiryTS*1000000) } if rep.TokenLastUpdateTS != 0 { metricTokenLastUpdate.Set(c, rep.TokenLastUpdateTS*1000000) } if rep.TokenNextUpdateTS != 0 { metricTokenNextUpdate.Set(c, rep.TokenNextUpdateTS*1000000) } metricUpdateOutcome.Set(c, rep.UpdateOutcome) metricUpdateReason.Set(c, rep.UpdateReason) metricTotalDuration.Set(c, rep.TotalDuration) metricRPCDuration.Set(c, rep.RPCDuration) return tsmon.Flush(c) }
[ "func", "(", "s", "*", "StatusReport", ")", "SendMetrics", "(", "c", "context", ".", "Context", ")", "error", "{", "c", ",", "_", "=", "context", ".", "WithTimeout", "(", "c", ",", "10", "*", "time", ".", "Second", ")", "\n", "rep", ":=", "s", ".", "Report", "(", ")", "\n\n", "metricVersion", ".", "Set", "(", "c", ",", "rep", ".", "TokendVersion", ")", "\n", "if", "rep", ".", "ServiceVersion", "!=", "\"", "\"", "{", "metricServiceVersion", ".", "Set", "(", "c", ",", "rep", ".", "ServiceVersion", ")", "\n", "}", "\n", "if", "rep", ".", "TokenExpiryTS", "!=", "0", "{", "metricTokenExpiry", ".", "Set", "(", "c", ",", "rep", ".", "TokenExpiryTS", "*", "1000000", ")", "\n", "}", "\n", "if", "rep", ".", "TokenLastUpdateTS", "!=", "0", "{", "metricTokenLastUpdate", ".", "Set", "(", "c", ",", "rep", ".", "TokenLastUpdateTS", "*", "1000000", ")", "\n", "}", "\n", "if", "rep", ".", "TokenNextUpdateTS", "!=", "0", "{", "metricTokenNextUpdate", ".", "Set", "(", "c", ",", "rep", ".", "TokenNextUpdateTS", "*", "1000000", ")", "\n", "}", "\n", "metricUpdateOutcome", ".", "Set", "(", "c", ",", "rep", ".", "UpdateOutcome", ")", "\n", "metricUpdateReason", ".", "Set", "(", "c", ",", "rep", ".", "UpdateReason", ")", "\n", "metricTotalDuration", ".", "Set", "(", "c", ",", "rep", ".", "TotalDuration", ")", "\n", "metricRPCDuration", ".", "Set", "(", "c", ",", "rep", ".", "RPCDuration", ")", "\n\n", "return", "tsmon", ".", "Flush", "(", "c", ")", "\n", "}" ]
// SendMetrics is called at the end of the token update process. // // It dumps all relevant metrics to tsmon.
[ "SendMetrics", "is", "called", "at", "the", "end", "of", "the", "token", "update", "process", ".", "It", "dumps", "all", "relevant", "metrics", "to", "tsmon", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/cmd/luci_machine_tokend/status.go#L211-L234
8,920
luci/luci-go
grpc/cmd/prpc/printer.go
SetFile
func (p *printer) SetFile(f *descriptor.FileDescriptorProto) error { p.file = f var err error p.sourceCodeInfo, err = descutil.IndexSourceCodeInfo(f) return err }
go
func (p *printer) SetFile(f *descriptor.FileDescriptorProto) error { p.file = f var err error p.sourceCodeInfo, err = descutil.IndexSourceCodeInfo(f) return err }
[ "func", "(", "p", "*", "printer", ")", "SetFile", "(", "f", "*", "descriptor", ".", "FileDescriptorProto", ")", "error", "{", "p", ".", "file", "=", "f", "\n", "var", "err", "error", "\n", "p", ".", "sourceCodeInfo", ",", "err", "=", "descutil", ".", "IndexSourceCodeInfo", "(", "f", ")", "\n", "return", "err", "\n", "}" ]
// SetFile specifies the file containing the descriptors being printed. // Used to relativize names and print comments.
[ "SetFile", "specifies", "the", "file", "containing", "the", "descriptors", "being", "printed", ".", "Used", "to", "relativize", "names", "and", "print", "comments", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/cmd/prpc/printer.go#L46-L51
8,921
luci/luci-go
grpc/cmd/prpc/printer.go
Printf
func (p *printer) Printf(format string, a ...interface{}) { if p.Err == nil { _, p.Err = fmt.Fprintf(&p.Out, format, a...) } }
go
func (p *printer) Printf(format string, a ...interface{}) { if p.Err == nil { _, p.Err = fmt.Fprintf(&p.Out, format, a...) } }
[ "func", "(", "p", "*", "printer", ")", "Printf", "(", "format", "string", ",", "a", "...", "interface", "{", "}", ")", "{", "if", "p", ".", "Err", "==", "nil", "{", "_", ",", "p", ".", "Err", "=", "fmt", ".", "Fprintf", "(", "&", "p", ".", "Out", ",", "format", ",", "a", "...", ")", "\n", "}", "\n", "}" ]
// Printf prints to p.Out unless there was an error.
[ "Printf", "prints", "to", "p", ".", "Out", "unless", "there", "was", "an", "error", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/cmd/prpc/printer.go#L54-L58
8,922
luci/luci-go
grpc/cmd/prpc/printer.go
MaybeLeadingComments
func (p *printer) MaybeLeadingComments(ptr interface{}) { comments := p.sourceCodeInfo[ptr].GetLeadingComments() // print comments, but insert "//" before each newline. for len(comments) > 0 { var toPrint string if lineEnd := strings.Index(comments, "\n"); lineEnd >= 0 { toPrint = comments[:lineEnd+1] // includes newline comments = comments[lineEnd+1:] } else { // actually this does not happen, because comments always end with // newline, but just in case. toPrint = comments + "\n" comments = "" } p.Printf("//%s", toPrint) } }
go
func (p *printer) MaybeLeadingComments(ptr interface{}) { comments := p.sourceCodeInfo[ptr].GetLeadingComments() // print comments, but insert "//" before each newline. for len(comments) > 0 { var toPrint string if lineEnd := strings.Index(comments, "\n"); lineEnd >= 0 { toPrint = comments[:lineEnd+1] // includes newline comments = comments[lineEnd+1:] } else { // actually this does not happen, because comments always end with // newline, but just in case. toPrint = comments + "\n" comments = "" } p.Printf("//%s", toPrint) } }
[ "func", "(", "p", "*", "printer", ")", "MaybeLeadingComments", "(", "ptr", "interface", "{", "}", ")", "{", "comments", ":=", "p", ".", "sourceCodeInfo", "[", "ptr", "]", ".", "GetLeadingComments", "(", ")", "\n", "// print comments, but insert \"//\" before each newline.", "for", "len", "(", "comments", ")", ">", "0", "{", "var", "toPrint", "string", "\n", "if", "lineEnd", ":=", "strings", ".", "Index", "(", "comments", ",", "\"", "\\n", "\"", ")", ";", "lineEnd", ">=", "0", "{", "toPrint", "=", "comments", "[", ":", "lineEnd", "+", "1", "]", "// includes newline", "\n", "comments", "=", "comments", "[", "lineEnd", "+", "1", ":", "]", "\n", "}", "else", "{", "// actually this does not happen, because comments always end with", "// newline, but just in case.", "toPrint", "=", "comments", "+", "\"", "\\n", "\"", "\n", "comments", "=", "\"", "\"", "\n", "}", "\n", "p", ".", "Printf", "(", "\"", "\"", ",", "toPrint", ")", "\n", "}", "\n", "}" ]
// MaybeLeadingComments prints leading comments of the descriptor proto // if found.
[ "MaybeLeadingComments", "prints", "leading", "comments", "of", "the", "descriptor", "proto", "if", "found", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/cmd/prpc/printer.go#L80-L96
8,923
luci/luci-go
grpc/cmd/prpc/printer.go
shorten
func (p *printer) shorten(name string) string { name = strings.TrimPrefix(name, ".") if p.file.GetPackage() != "" { name = strings.TrimPrefix(name, p.file.GetPackage()+".") } return name }
go
func (p *printer) shorten(name string) string { name = strings.TrimPrefix(name, ".") if p.file.GetPackage() != "" { name = strings.TrimPrefix(name, p.file.GetPackage()+".") } return name }
[ "func", "(", "p", "*", "printer", ")", "shorten", "(", "name", "string", ")", "string", "{", "name", "=", "strings", ".", "TrimPrefix", "(", "name", ",", "\"", "\"", ")", "\n", "if", "p", ".", "file", ".", "GetPackage", "(", ")", "!=", "\"", "\"", "{", "name", "=", "strings", ".", "TrimPrefix", "(", "name", ",", "p", ".", "file", ".", "GetPackage", "(", ")", "+", "\"", "\"", ")", "\n", "}", "\n", "return", "name", "\n", "}" ]
// shorten removes leading "." and trims package name if it matches p.file.
[ "shorten", "removes", "leading", ".", "and", "trims", "package", "name", "if", "it", "matches", "p", ".", "file", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/cmd/prpc/printer.go#L99-L105
8,924
luci/luci-go
grpc/cmd/prpc/printer.go
Service
func (p *printer) Service(service *descriptor.ServiceDescriptorProto, methodIndex int) { p.MaybeLeadingComments(service) defer p.open("service %s", service.GetName())() if methodIndex < 0 { for i := range service.Method { p.Method(service.Method[i]) } } else { p.Method(service.Method[methodIndex]) if len(service.Method) > 1 { p.Printf("// other methods were omitted.\n") } } }
go
func (p *printer) Service(service *descriptor.ServiceDescriptorProto, methodIndex int) { p.MaybeLeadingComments(service) defer p.open("service %s", service.GetName())() if methodIndex < 0 { for i := range service.Method { p.Method(service.Method[i]) } } else { p.Method(service.Method[methodIndex]) if len(service.Method) > 1 { p.Printf("// other methods were omitted.\n") } } }
[ "func", "(", "p", "*", "printer", ")", "Service", "(", "service", "*", "descriptor", ".", "ServiceDescriptorProto", ",", "methodIndex", "int", ")", "{", "p", ".", "MaybeLeadingComments", "(", "service", ")", "\n", "defer", "p", ".", "open", "(", "\"", "\"", ",", "service", ".", "GetName", "(", ")", ")", "(", ")", "\n\n", "if", "methodIndex", "<", "0", "{", "for", "i", ":=", "range", "service", ".", "Method", "{", "p", ".", "Method", "(", "service", ".", "Method", "[", "i", "]", ")", "\n", "}", "\n", "}", "else", "{", "p", ".", "Method", "(", "service", ".", "Method", "[", "methodIndex", "]", ")", "\n", "if", "len", "(", "service", ".", "Method", ")", ">", "1", "{", "p", ".", "Printf", "(", "\"", "\\n", "\"", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Service prints a service definition. // If methodIndex != -1, only one method is printed. // If serviceIndex != -1, leading comments are printed if found.
[ "Service", "prints", "a", "service", "definition", ".", "If", "methodIndex", "!", "=", "-", "1", "only", "one", "method", "is", "printed", ".", "If", "serviceIndex", "!", "=", "-", "1", "leading", "comments", "are", "printed", "if", "found", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/cmd/prpc/printer.go#L110-L124
8,925
luci/luci-go
grpc/cmd/prpc/printer.go
Method
func (p *printer) Method(method *descriptor.MethodDescriptorProto) { p.MaybeLeadingComments(method) p.Printf( "rpc %s(%s) returns (%s) {};\n", method.GetName(), p.shorten(method.GetInputType()), p.shorten(method.GetOutputType()), ) }
go
func (p *printer) Method(method *descriptor.MethodDescriptorProto) { p.MaybeLeadingComments(method) p.Printf( "rpc %s(%s) returns (%s) {};\n", method.GetName(), p.shorten(method.GetInputType()), p.shorten(method.GetOutputType()), ) }
[ "func", "(", "p", "*", "printer", ")", "Method", "(", "method", "*", "descriptor", ".", "MethodDescriptorProto", ")", "{", "p", ".", "MaybeLeadingComments", "(", "method", ")", "\n", "p", ".", "Printf", "(", "\"", "\\n", "\"", ",", "method", ".", "GetName", "(", ")", ",", "p", ".", "shorten", "(", "method", ".", "GetInputType", "(", ")", ")", ",", "p", ".", "shorten", "(", "method", ".", "GetOutputType", "(", ")", ")", ",", ")", "\n", "}" ]
// Method prints a service method definition.
[ "Method", "prints", "a", "service", "method", "definition", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/cmd/prpc/printer.go#L127-L135
8,926
luci/luci-go
grpc/cmd/prpc/printer.go
Field
func (p *printer) Field(field *descriptor.FieldDescriptorProto) { p.MaybeLeadingComments(field) if descutil.Repeated(field) { p.Printf("repeated ") } typeName := fieldTypeName[field.GetType()] if typeName == "" { typeName = p.shorten(field.GetTypeName()) } if typeName == "" { typeName = "<unsupported type>" } p.Printf("%s %s = %d;\n", typeName, field.GetName(), field.GetNumber()) }
go
func (p *printer) Field(field *descriptor.FieldDescriptorProto) { p.MaybeLeadingComments(field) if descutil.Repeated(field) { p.Printf("repeated ") } typeName := fieldTypeName[field.GetType()] if typeName == "" { typeName = p.shorten(field.GetTypeName()) } if typeName == "" { typeName = "<unsupported type>" } p.Printf("%s %s = %d;\n", typeName, field.GetName(), field.GetNumber()) }
[ "func", "(", "p", "*", "printer", ")", "Field", "(", "field", "*", "descriptor", ".", "FieldDescriptorProto", ")", "{", "p", ".", "MaybeLeadingComments", "(", "field", ")", "\n", "if", "descutil", ".", "Repeated", "(", "field", ")", "{", "p", ".", "Printf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "typeName", ":=", "fieldTypeName", "[", "field", ".", "GetType", "(", ")", "]", "\n", "if", "typeName", "==", "\"", "\"", "{", "typeName", "=", "p", ".", "shorten", "(", "field", ".", "GetTypeName", "(", ")", ")", "\n", "}", "\n", "if", "typeName", "==", "\"", "\"", "{", "typeName", "=", "\"", "\"", "\n", "}", "\n", "p", ".", "Printf", "(", "\"", "\\n", "\"", ",", "typeName", ",", "field", ".", "GetName", "(", ")", ",", "field", ".", "GetNumber", "(", ")", ")", "\n", "}" ]
// Field prints a field definition.
[ "Field", "prints", "a", "field", "definition", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/cmd/prpc/printer.go#L156-L170
8,927
luci/luci-go
grpc/cmd/prpc/printer.go
Message
func (p *printer) Message(msg *descriptor.DescriptorProto) { p.MaybeLeadingComments(msg) defer p.open("message %s", msg.GetName())() for i := range msg.GetOneofDecl() { p.OneOf(msg, i) } for i, f := range msg.Field { if f.OneofIndex == nil { p.Field(msg.Field[i]) } } }
go
func (p *printer) Message(msg *descriptor.DescriptorProto) { p.MaybeLeadingComments(msg) defer p.open("message %s", msg.GetName())() for i := range msg.GetOneofDecl() { p.OneOf(msg, i) } for i, f := range msg.Field { if f.OneofIndex == nil { p.Field(msg.Field[i]) } } }
[ "func", "(", "p", "*", "printer", ")", "Message", "(", "msg", "*", "descriptor", ".", "DescriptorProto", ")", "{", "p", ".", "MaybeLeadingComments", "(", "msg", ")", "\n", "defer", "p", ".", "open", "(", "\"", "\"", ",", "msg", ".", "GetName", "(", ")", ")", "(", ")", "\n\n", "for", "i", ":=", "range", "msg", ".", "GetOneofDecl", "(", ")", "{", "p", ".", "OneOf", "(", "msg", ",", "i", ")", "\n", "}", "\n\n", "for", "i", ",", "f", ":=", "range", "msg", ".", "Field", "{", "if", "f", ".", "OneofIndex", "==", "nil", "{", "p", ".", "Field", "(", "msg", ".", "Field", "[", "i", "]", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Message prints a message definition.
[ "Message", "prints", "a", "message", "definition", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/cmd/prpc/printer.go#L173-L186
8,928
luci/luci-go
grpc/cmd/prpc/printer.go
OneOf
func (p *printer) OneOf(msg *descriptor.DescriptorProto, oneOfIndex int) { of := msg.GetOneofDecl()[oneOfIndex] p.MaybeLeadingComments(of) defer p.open("oneof %s", of.GetName())() for i, f := range msg.Field { if f.OneofIndex != nil && int(f.GetOneofIndex()) == oneOfIndex { p.Field(msg.Field[i]) } } }
go
func (p *printer) OneOf(msg *descriptor.DescriptorProto, oneOfIndex int) { of := msg.GetOneofDecl()[oneOfIndex] p.MaybeLeadingComments(of) defer p.open("oneof %s", of.GetName())() for i, f := range msg.Field { if f.OneofIndex != nil && int(f.GetOneofIndex()) == oneOfIndex { p.Field(msg.Field[i]) } } }
[ "func", "(", "p", "*", "printer", ")", "OneOf", "(", "msg", "*", "descriptor", ".", "DescriptorProto", ",", "oneOfIndex", "int", ")", "{", "of", ":=", "msg", ".", "GetOneofDecl", "(", ")", "[", "oneOfIndex", "]", "\n", "p", ".", "MaybeLeadingComments", "(", "of", ")", "\n", "defer", "p", ".", "open", "(", "\"", "\"", ",", "of", ".", "GetName", "(", ")", ")", "(", ")", "\n\n", "for", "i", ",", "f", ":=", "range", "msg", ".", "Field", "{", "if", "f", ".", "OneofIndex", "!=", "nil", "&&", "int", "(", "f", ".", "GetOneofIndex", "(", ")", ")", "==", "oneOfIndex", "{", "p", ".", "Field", "(", "msg", ".", "Field", "[", "i", "]", ")", "\n", "}", "\n", "}", "\n", "}" ]
// OneOf prints a oneof definition.
[ "OneOf", "prints", "a", "oneof", "definition", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/cmd/prpc/printer.go#L189-L199
8,929
luci/luci-go
grpc/cmd/prpc/printer.go
Enum
func (p *printer) Enum(enum *descriptor.EnumDescriptorProto) { p.MaybeLeadingComments(enum) defer p.open("enum %s", enum.GetName())() for _, v := range enum.Value { p.EnumValue(v) } }
go
func (p *printer) Enum(enum *descriptor.EnumDescriptorProto) { p.MaybeLeadingComments(enum) defer p.open("enum %s", enum.GetName())() for _, v := range enum.Value { p.EnumValue(v) } }
[ "func", "(", "p", "*", "printer", ")", "Enum", "(", "enum", "*", "descriptor", ".", "EnumDescriptorProto", ")", "{", "p", ".", "MaybeLeadingComments", "(", "enum", ")", "\n", "defer", "p", ".", "open", "(", "\"", "\"", ",", "enum", ".", "GetName", "(", ")", ")", "(", ")", "\n\n", "for", "_", ",", "v", ":=", "range", "enum", ".", "Value", "{", "p", ".", "EnumValue", "(", "v", ")", "\n", "}", "\n", "}" ]
// Enum prints an enum definition.
[ "Enum", "prints", "an", "enum", "definition", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/cmd/prpc/printer.go#L202-L209
8,930
luci/luci-go
grpc/cmd/prpc/printer.go
EnumValue
func (p *printer) EnumValue(v *descriptor.EnumValueDescriptorProto) { p.MaybeLeadingComments(v) p.Printf("%s = %d;\n", v.GetName(), v.GetNumber()) }
go
func (p *printer) EnumValue(v *descriptor.EnumValueDescriptorProto) { p.MaybeLeadingComments(v) p.Printf("%s = %d;\n", v.GetName(), v.GetNumber()) }
[ "func", "(", "p", "*", "printer", ")", "EnumValue", "(", "v", "*", "descriptor", ".", "EnumValueDescriptorProto", ")", "{", "p", ".", "MaybeLeadingComments", "(", "v", ")", "\n", "p", ".", "Printf", "(", "\"", "\\n", "\"", ",", "v", ".", "GetName", "(", ")", ",", "v", ".", "GetNumber", "(", ")", ")", "\n", "}" ]
// EnumValue prints an enum value definition.
[ "EnumValue", "prints", "an", "enum", "value", "definition", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/cmd/prpc/printer.go#L212-L215
8,931
luci/luci-go
cipd/client/cipd/acl.go
prefixMetadataToACLs
func prefixMetadataToACLs(m *api.InheritedPrefixMetadata) (out []PackageACL) { for _, p := range m.PerPrefixMetadata { var acls []PackageACL for _, acl := range p.Acls { role := acl.Role.String() found := false for i, existing := range acls { if existing.Role == role { acls[i].Principals = append(acls[i].Principals, acl.Principals...) found = true break } } if !found { acls = append(acls, PackageACL{ PackagePath: p.Prefix, Role: role, Principals: acl.Principals, ModifiedBy: p.UpdateUser, ModifiedTs: UnixTime(google.TimeFromProto(p.UpdateTime)), }) } } out = append(out, acls...) } return }
go
func prefixMetadataToACLs(m *api.InheritedPrefixMetadata) (out []PackageACL) { for _, p := range m.PerPrefixMetadata { var acls []PackageACL for _, acl := range p.Acls { role := acl.Role.String() found := false for i, existing := range acls { if existing.Role == role { acls[i].Principals = append(acls[i].Principals, acl.Principals...) found = true break } } if !found { acls = append(acls, PackageACL{ PackagePath: p.Prefix, Role: role, Principals: acl.Principals, ModifiedBy: p.UpdateUser, ModifiedTs: UnixTime(google.TimeFromProto(p.UpdateTime)), }) } } out = append(out, acls...) } return }
[ "func", "prefixMetadataToACLs", "(", "m", "*", "api", ".", "InheritedPrefixMetadata", ")", "(", "out", "[", "]", "PackageACL", ")", "{", "for", "_", ",", "p", ":=", "range", "m", ".", "PerPrefixMetadata", "{", "var", "acls", "[", "]", "PackageACL", "\n", "for", "_", ",", "acl", ":=", "range", "p", ".", "Acls", "{", "role", ":=", "acl", ".", "Role", ".", "String", "(", ")", "\n", "found", ":=", "false", "\n", "for", "i", ",", "existing", ":=", "range", "acls", "{", "if", "existing", ".", "Role", "==", "role", "{", "acls", "[", "i", "]", ".", "Principals", "=", "append", "(", "acls", "[", "i", "]", ".", "Principals", ",", "acl", ".", "Principals", "...", ")", "\n", "found", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "!", "found", "{", "acls", "=", "append", "(", "acls", ",", "PackageACL", "{", "PackagePath", ":", "p", ".", "Prefix", ",", "Role", ":", "role", ",", "Principals", ":", "acl", ".", "Principals", ",", "ModifiedBy", ":", "p", ".", "UpdateUser", ",", "ModifiedTs", ":", "UnixTime", "(", "google", ".", "TimeFromProto", "(", "p", ".", "UpdateTime", ")", ")", ",", "}", ")", "\n", "}", "\n", "}", "\n", "out", "=", "append", "(", "out", ",", "acls", "...", ")", "\n", "}", "\n", "return", "\n", "}" ]
// prefixMetadataToACLs extracts ACLs for a prefix and all its parent prefixes // from the prefix's metadata.
[ "prefixMetadataToACLs", "extracts", "ACLs", "for", "a", "prefix", "and", "all", "its", "parent", "prefixes", "from", "the", "prefix", "s", "metadata", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/acl.go#L67-L93
8,932
luci/luci-go
common/sync/promise/promise.go
New
func New(c context.Context, gen Generator) *Promise { p := Promise{ signalC: make(chan struct{}), } // Execute our generator function in a separate goroutine. go p.runGen(c, gen) return &p }
go
func New(c context.Context, gen Generator) *Promise { p := Promise{ signalC: make(chan struct{}), } // Execute our generator function in a separate goroutine. go p.runGen(c, gen) return &p }
[ "func", "New", "(", "c", "context", ".", "Context", ",", "gen", "Generator", ")", "*", "Promise", "{", "p", ":=", "Promise", "{", "signalC", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n\n", "// Execute our generator function in a separate goroutine.", "go", "p", ".", "runGen", "(", "c", ",", "gen", ")", "\n", "return", "&", "p", "\n", "}" ]
// New instantiates a new, empty Promise instance. The Promise's value will be // the value returned by the supplied generator function. // // The generator will be invoked immediately in its own goroutine.
[ "New", "instantiates", "a", "new", "empty", "Promise", "instance", ".", "The", "Promise", "s", "value", "will", "be", "the", "value", "returned", "by", "the", "supplied", "generator", "function", ".", "The", "generator", "will", "be", "invoked", "immediately", "in", "its", "own", "goroutine", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/sync/promise/promise.go#L53-L61
8,933
luci/luci-go
common/sync/promise/promise.go
NewDeferred
func NewDeferred(gen Generator) *Promise { var startOnce sync.Once p := Promise{ signalC: make(chan struct{}), } p.onGet = func(c context.Context) { startOnce.Do(func() { p.runGen(c, gen) }) } return &p }
go
func NewDeferred(gen Generator) *Promise { var startOnce sync.Once p := Promise{ signalC: make(chan struct{}), } p.onGet = func(c context.Context) { startOnce.Do(func() { p.runGen(c, gen) }) } return &p }
[ "func", "NewDeferred", "(", "gen", "Generator", ")", "*", "Promise", "{", "var", "startOnce", "sync", ".", "Once", "\n\n", "p", ":=", "Promise", "{", "signalC", ":", "make", "(", "chan", "struct", "{", "}", ")", ",", "}", "\n", "p", ".", "onGet", "=", "func", "(", "c", "context", ".", "Context", ")", "{", "startOnce", ".", "Do", "(", "func", "(", ")", "{", "p", ".", "runGen", "(", "c", ",", "gen", ")", "}", ")", "\n", "}", "\n", "return", "&", "p", "\n", "}" ]
// NewDeferred instantiates a new, empty Promise instance. The Promise's value // will be the value returned by the supplied generator function. // // Unlike New, the generator function will not be immediately executed. Instead, // it will be run when the first call to Get is made, and will use one of the // Get callers' goroutines. // goroutine a Get caller.
[ "NewDeferred", "instantiates", "a", "new", "empty", "Promise", "instance", ".", "The", "Promise", "s", "value", "will", "be", "the", "value", "returned", "by", "the", "supplied", "generator", "function", ".", "Unlike", "New", "the", "generator", "function", "will", "not", "be", "immediately", "executed", ".", "Instead", "it", "will", "be", "run", "when", "the", "first", "call", "to", "Get", "is", "made", "and", "will", "use", "one", "of", "the", "Get", "callers", "goroutines", ".", "goroutine", "a", "Get", "caller", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/sync/promise/promise.go#L70-L80
8,934
luci/luci-go
common/sync/promise/promise.go
Get
func (p *Promise) Get(c context.Context) (interface{}, error) { // If we have an onGet function, run it (deferred case). if p.onGet != nil { p.onGet(c) } // Block until at least one of these conditions is satisfied. If both are, // "select" will choose one pseudo-randomly. select { case <-p.signalC: return p.data, p.err case <-c.Done(): // Make sure we don't actually have data. select { case <-p.signalC: return p.data, p.err default: return nil, c.Err() } } }
go
func (p *Promise) Get(c context.Context) (interface{}, error) { // If we have an onGet function, run it (deferred case). if p.onGet != nil { p.onGet(c) } // Block until at least one of these conditions is satisfied. If both are, // "select" will choose one pseudo-randomly. select { case <-p.signalC: return p.data, p.err case <-c.Done(): // Make sure we don't actually have data. select { case <-p.signalC: return p.data, p.err default: return nil, c.Err() } } }
[ "func", "(", "p", "*", "Promise", ")", "Get", "(", "c", "context", ".", "Context", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "// If we have an onGet function, run it (deferred case).", "if", "p", ".", "onGet", "!=", "nil", "{", "p", ".", "onGet", "(", "c", ")", "\n", "}", "\n\n", "// Block until at least one of these conditions is satisfied. If both are,", "// \"select\" will choose one pseudo-randomly.", "select", "{", "case", "<-", "p", ".", "signalC", ":", "return", "p", ".", "data", ",", "p", ".", "err", "\n\n", "case", "<-", "c", ".", "Done", "(", ")", ":", "// Make sure we don't actually have data.", "select", "{", "case", "<-", "p", ".", "signalC", ":", "return", "p", ".", "data", ",", "p", ".", "err", "\n\n", "default", ":", "return", "nil", ",", "c", ".", "Err", "(", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Get returns the promise's value. If the value isn't set, Get will block until // the value is available, following the Context's timeout parameters. // // If the value is available, it will be returned with its error status. If the // context times out or is cancelled, the appropriate context error will be // returned.
[ "Get", "returns", "the", "promise", "s", "value", ".", "If", "the", "value", "isn", "t", "set", "Get", "will", "block", "until", "the", "value", "is", "available", "following", "the", "Context", "s", "timeout", "parameters", ".", "If", "the", "value", "is", "available", "it", "will", "be", "returned", "with", "its", "error", "status", ".", "If", "the", "context", "times", "out", "or", "is", "cancelled", "the", "appropriate", "context", "error", "will", "be", "returned", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/sync/promise/promise.go#L93-L115
8,935
luci/luci-go
common/sync/promise/promise.go
Peek
func (p *Promise) Peek() (interface{}, error) { select { case <-p.signalC: return p.data, p.err default: return nil, ErrNoData } }
go
func (p *Promise) Peek() (interface{}, error) { select { case <-p.signalC: return p.data, p.err default: return nil, ErrNoData } }
[ "func", "(", "p", "*", "Promise", ")", "Peek", "(", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "select", "{", "case", "<-", "p", ".", "signalC", ":", "return", "p", ".", "data", ",", "p", ".", "err", "\n\n", "default", ":", "return", "nil", ",", "ErrNoData", "\n", "}", "\n", "}" ]
// Peek returns the promise's current value. If the value isn't set, Peek will // return immediately with ErrNoData.
[ "Peek", "returns", "the", "promise", "s", "current", "value", ".", "If", "the", "value", "isn", "t", "set", "Peek", "will", "return", "immediately", "with", "ErrNoData", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/sync/promise/promise.go#L119-L127
8,936
luci/luci-go
buildbucket/cli/print.go
f
func (p *printer) f(format string, args ...interface{}) { if p.Err != nil { return } if _, err := fmt.Fprintf(&p.indent, format, args...); err != nil && err != io.ErrShortWrite { p.Err = err } }
go
func (p *printer) f(format string, args ...interface{}) { if p.Err != nil { return } if _, err := fmt.Fprintf(&p.indent, format, args...); err != nil && err != io.ErrShortWrite { p.Err = err } }
[ "func", "(", "p", "*", "printer", ")", "f", "(", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "if", "p", ".", "Err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "_", ",", "err", ":=", "fmt", ".", "Fprintf", "(", "&", "p", ".", "indent", ",", "format", ",", "args", "...", ")", ";", "err", "!=", "nil", "&&", "err", "!=", "io", ".", "ErrShortWrite", "{", "p", ".", "Err", "=", "err", "\n", "}", "\n", "}" ]
// f prints a formatted message.
[ "f", "prints", "a", "formatted", "message", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/cli/print.go#L91-L98
8,937
luci/luci-go
buildbucket/cli/print.go
fw
func (p *printer) fw(minWidth int, format string, args ...interface{}) { s := fmt.Sprintf(format, args...) pad := minWidth - utf8.RuneCountInString(s) if pad < 1 { pad = 1 } p.f("%s%s", s, strings.Repeat(" ", pad)) }
go
func (p *printer) fw(minWidth int, format string, args ...interface{}) { s := fmt.Sprintf(format, args...) pad := minWidth - utf8.RuneCountInString(s) if pad < 1 { pad = 1 } p.f("%s%s", s, strings.Repeat(" ", pad)) }
[ "func", "(", "p", "*", "printer", ")", "fw", "(", "minWidth", "int", ",", "format", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "s", ":=", "fmt", ".", "Sprintf", "(", "format", ",", "args", "...", ")", "\n", "pad", ":=", "minWidth", "-", "utf8", ".", "RuneCountInString", "(", "s", ")", "\n", "if", "pad", "<", "1", "{", "pad", "=", "1", "\n", "}", "\n", "p", ".", "f", "(", "\"", "\"", ",", "s", ",", "strings", ".", "Repeat", "(", "\"", "\"", ",", "pad", ")", ")", "\n", "}" ]
// fw is like f, but appends whitespace such that the printed string takes at // least minWidth. // Appends at least one space.
[ "fw", "is", "like", "f", "but", "appends", "whitespace", "such", "that", "the", "printed", "string", "takes", "at", "least", "minWidth", ".", "Appends", "at", "least", "one", "space", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/cli/print.go#L103-L110
8,938
luci/luci-go
buildbucket/cli/print.go
JSONPB
func (p *printer) JSONPB(pb proto.Message) { m := &jsonpb.Marshaler{} buf := &bytes.Buffer{} if err := m.Marshal(buf, pb); err != nil { panic(fmt.Errorf("failed to marshal a message: %s", err)) } // Note: json.Marshal indents JSON more nicely than jsonpb.Marshaler.Indent. indented := &bytes.Buffer{} if err := json.Indent(indented, buf.Bytes(), "", " "); err != nil { panic(err) } p.f("%s\n", indented.Bytes()) }
go
func (p *printer) JSONPB(pb proto.Message) { m := &jsonpb.Marshaler{} buf := &bytes.Buffer{} if err := m.Marshal(buf, pb); err != nil { panic(fmt.Errorf("failed to marshal a message: %s", err)) } // Note: json.Marshal indents JSON more nicely than jsonpb.Marshaler.Indent. indented := &bytes.Buffer{} if err := json.Indent(indented, buf.Bytes(), "", " "); err != nil { panic(err) } p.f("%s\n", indented.Bytes()) }
[ "func", "(", "p", "*", "printer", ")", "JSONPB", "(", "pb", "proto", ".", "Message", ")", "{", "m", ":=", "&", "jsonpb", ".", "Marshaler", "{", "}", "\n", "buf", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "if", "err", ":=", "m", ".", "Marshal", "(", "buf", ",", "pb", ")", ";", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n\n", "// Note: json.Marshal indents JSON more nicely than jsonpb.Marshaler.Indent.", "indented", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "if", "err", ":=", "json", ".", "Indent", "(", "indented", ",", "buf", ".", "Bytes", "(", ")", ",", "\"", "\"", ",", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "p", ".", "f", "(", "\"", "\\n", "\"", ",", "indented", ".", "Bytes", "(", ")", ")", "\n", "}" ]
// JSONPB prints pb in JSON format, indented.
[ "JSONPB", "prints", "pb", "in", "JSON", "format", "indented", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/cli/print.go#L113-L126
8,939
luci/luci-go
buildbucket/cli/print.go
Build
func (p *printer) Build(b *pb.Build) { // Print the build URL bold, underline and a color matching the status. p.f("%s%s%shttp://ci.chromium.org/b/%d", ansiWhiteBold, ansiWhiteUnderline, ansiStatus[b.Status], b.Id) // Undo underline. p.f("%s%s%s ", ansi.Reset, ansiWhiteBold, ansiStatus[b.Status]) p.fw(10, "%s", b.Status) p.f("'%s/%s/%s", b.Builder.Project, b.Builder.Bucket, b.Builder.Builder) if b.Number != 0 { p.f("/%d", b.Number) } p.f("'%s\n", ansi.Reset) // Summary. if b.SummaryMarkdown != "" { p.attr("Summary") p.summary(b.SummaryMarkdown) } if b.Input.GetExperimental() { p.keyword("Experimental") p.f("\n") } // Timing. p.buildTime(b) p.f("\n") if b.CreatedBy != "" { p.attr("By") p.f("%s\n", b.CreatedBy) } // Commit, CLs and tags. if c := b.Input.GetGitilesCommit(); c != nil { p.attr("Commit") p.commit(c) p.f("\n") } for _, cl := range b.Input.GetGerritChanges() { p.attr("CL") p.change(cl) p.f("\n") } for _, t := range b.Tags { p.attr("Tag") p.f("%s:%s\n", t.Key, t.Value) } // Properties if props := b.Input.GetProperties(); props != nil { p.attr("Input properties") p.JSONPB(props) } if props := b.Output.GetProperties(); props != nil { p.attr("Output properties") p.JSONPB(props) } // Steps p.steps(b.Steps) }
go
func (p *printer) Build(b *pb.Build) { // Print the build URL bold, underline and a color matching the status. p.f("%s%s%shttp://ci.chromium.org/b/%d", ansiWhiteBold, ansiWhiteUnderline, ansiStatus[b.Status], b.Id) // Undo underline. p.f("%s%s%s ", ansi.Reset, ansiWhiteBold, ansiStatus[b.Status]) p.fw(10, "%s", b.Status) p.f("'%s/%s/%s", b.Builder.Project, b.Builder.Bucket, b.Builder.Builder) if b.Number != 0 { p.f("/%d", b.Number) } p.f("'%s\n", ansi.Reset) // Summary. if b.SummaryMarkdown != "" { p.attr("Summary") p.summary(b.SummaryMarkdown) } if b.Input.GetExperimental() { p.keyword("Experimental") p.f("\n") } // Timing. p.buildTime(b) p.f("\n") if b.CreatedBy != "" { p.attr("By") p.f("%s\n", b.CreatedBy) } // Commit, CLs and tags. if c := b.Input.GetGitilesCommit(); c != nil { p.attr("Commit") p.commit(c) p.f("\n") } for _, cl := range b.Input.GetGerritChanges() { p.attr("CL") p.change(cl) p.f("\n") } for _, t := range b.Tags { p.attr("Tag") p.f("%s:%s\n", t.Key, t.Value) } // Properties if props := b.Input.GetProperties(); props != nil { p.attr("Input properties") p.JSONPB(props) } if props := b.Output.GetProperties(); props != nil { p.attr("Output properties") p.JSONPB(props) } // Steps p.steps(b.Steps) }
[ "func", "(", "p", "*", "printer", ")", "Build", "(", "b", "*", "pb", ".", "Build", ")", "{", "// Print the build URL bold, underline and a color matching the status.", "p", ".", "f", "(", "\"", "\"", ",", "ansiWhiteBold", ",", "ansiWhiteUnderline", ",", "ansiStatus", "[", "b", ".", "Status", "]", ",", "b", ".", "Id", ")", "\n", "// Undo underline.", "p", ".", "f", "(", "\"", "\"", ",", "ansi", ".", "Reset", ",", "ansiWhiteBold", ",", "ansiStatus", "[", "b", ".", "Status", "]", ")", "\n", "p", ".", "fw", "(", "10", ",", "\"", "\"", ",", "b", ".", "Status", ")", "\n", "p", ".", "f", "(", "\"", "\"", ",", "b", ".", "Builder", ".", "Project", ",", "b", ".", "Builder", ".", "Bucket", ",", "b", ".", "Builder", ".", "Builder", ")", "\n", "if", "b", ".", "Number", "!=", "0", "{", "p", ".", "f", "(", "\"", "\"", ",", "b", ".", "Number", ")", "\n", "}", "\n", "p", ".", "f", "(", "\"", "\\n", "\"", ",", "ansi", ".", "Reset", ")", "\n\n", "// Summary.", "if", "b", ".", "SummaryMarkdown", "!=", "\"", "\"", "{", "p", ".", "attr", "(", "\"", "\"", ")", "\n", "p", ".", "summary", "(", "b", ".", "SummaryMarkdown", ")", "\n", "}", "\n\n", "if", "b", ".", "Input", ".", "GetExperimental", "(", ")", "{", "p", ".", "keyword", "(", "\"", "\"", ")", "\n", "p", ".", "f", "(", "\"", "\\n", "\"", ")", "\n", "}", "\n\n", "// Timing.", "p", ".", "buildTime", "(", "b", ")", "\n", "p", ".", "f", "(", "\"", "\\n", "\"", ")", "\n", "if", "b", ".", "CreatedBy", "!=", "\"", "\"", "{", "p", ".", "attr", "(", "\"", "\"", ")", "\n", "p", ".", "f", "(", "\"", "\\n", "\"", ",", "b", ".", "CreatedBy", ")", "\n", "}", "\n\n", "// Commit, CLs and tags.", "if", "c", ":=", "b", ".", "Input", ".", "GetGitilesCommit", "(", ")", ";", "c", "!=", "nil", "{", "p", ".", "attr", "(", "\"", "\"", ")", "\n", "p", ".", "commit", "(", "c", ")", "\n", "p", ".", "f", "(", "\"", "\\n", "\"", ")", "\n", "}", "\n", "for", "_", ",", "cl", ":=", "range", "b", ".", "Input", ".", "GetGerritChanges", "(", ")", "{", "p", ".", "attr", "(", "\"", "\"", ")", "\n", "p", ".", "change", "(", "cl", ")", "\n", "p", ".", "f", "(", "\"", "\\n", "\"", ")", "\n", "}", "\n", "for", "_", ",", "t", ":=", "range", "b", ".", "Tags", "{", "p", ".", "attr", "(", "\"", "\"", ")", "\n", "p", ".", "f", "(", "\"", "\\n", "\"", ",", "t", ".", "Key", ",", "t", ".", "Value", ")", "\n", "}", "\n\n", "// Properties", "if", "props", ":=", "b", ".", "Input", ".", "GetProperties", "(", ")", ";", "props", "!=", "nil", "{", "p", ".", "attr", "(", "\"", "\"", ")", "\n", "p", ".", "JSONPB", "(", "props", ")", "\n", "}", "\n\n", "if", "props", ":=", "b", ".", "Output", ".", "GetProperties", "(", ")", ";", "props", "!=", "nil", "{", "p", ".", "attr", "(", "\"", "\"", ")", "\n", "p", ".", "JSONPB", "(", "props", ")", "\n", "}", "\n\n", "// Steps", "p", ".", "steps", "(", "b", ".", "Steps", ")", "\n", "}" ]
// Build prints b.
[ "Build", "prints", "b", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/cli/print.go#L129-L189
8,940
luci/luci-go
buildbucket/cli/print.go
commit
func (p *printer) commit(c *pb.GitilesCommit) { if c.Id == "" { p.linkf("https://%s/%s/+/%s", c.Host, c.Project, c.Ref) return } switch c.Host { // This shamelessly hardcodes https://cr-rev.appspot.com/_ah/api/crrev/v1/projects response // TODO(nodir): make an RPC and cache on the file system. case "aomedia.googlesource.com", "boringssl.googlesource.com", "chromium.googlesource.com", "gerrit.googlesource.com", "webrtc.googlesource.com": p.linkf("https://crrev.com/" + c.Id) default: p.linkf("https://%s/%s/+/%s", c.Host, c.Project, c.Id) } if c.Ref != "" { p.f(" on %s", c.Ref) } }
go
func (p *printer) commit(c *pb.GitilesCommit) { if c.Id == "" { p.linkf("https://%s/%s/+/%s", c.Host, c.Project, c.Ref) return } switch c.Host { // This shamelessly hardcodes https://cr-rev.appspot.com/_ah/api/crrev/v1/projects response // TODO(nodir): make an RPC and cache on the file system. case "aomedia.googlesource.com", "boringssl.googlesource.com", "chromium.googlesource.com", "gerrit.googlesource.com", "webrtc.googlesource.com": p.linkf("https://crrev.com/" + c.Id) default: p.linkf("https://%s/%s/+/%s", c.Host, c.Project, c.Id) } if c.Ref != "" { p.f(" on %s", c.Ref) } }
[ "func", "(", "p", "*", "printer", ")", "commit", "(", "c", "*", "pb", ".", "GitilesCommit", ")", "{", "if", "c", ".", "Id", "==", "\"", "\"", "{", "p", ".", "linkf", "(", "\"", "\"", ",", "c", ".", "Host", ",", "c", ".", "Project", ",", "c", ".", "Ref", ")", "\n", "return", "\n", "}", "\n\n", "switch", "c", ".", "Host", "{", "// This shamelessly hardcodes https://cr-rev.appspot.com/_ah/api/crrev/v1/projects response", "// TODO(nodir): make an RPC and cache on the file system.", "case", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ":", "p", ".", "linkf", "(", "\"", "\"", "+", "c", ".", "Id", ")", "\n", "default", ":", "p", ".", "linkf", "(", "\"", "\"", ",", "c", ".", "Host", ",", "c", ".", "Project", ",", "c", ".", "Id", ")", "\n", "}", "\n", "if", "c", ".", "Ref", "!=", "\"", "\"", "{", "p", ".", "f", "(", "\"", "\"", ",", "c", ".", "Ref", ")", "\n", "}", "\n", "}" ]
// commit prints c.
[ "commit", "prints", "c", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/cli/print.go#L192-L214
8,941
luci/luci-go
buildbucket/cli/print.go
change
func (p *printer) change(cl *pb.GerritChange) { switch { case cl.Host == "chromium-review.googlesource.com": p.linkf("https://crrev.com/c/%d/%d", cl.Change, cl.Patchset) case cl.Host == "chrome-internal-review.googlesource.com": p.linkf("https://crrev.com/i/%d/%d", cl.Change, cl.Patchset) default: p.linkf("https://%s/c/%s/+/%d/%d", cl.Host, cl.Project, cl.Change, cl.Patchset) } }
go
func (p *printer) change(cl *pb.GerritChange) { switch { case cl.Host == "chromium-review.googlesource.com": p.linkf("https://crrev.com/c/%d/%d", cl.Change, cl.Patchset) case cl.Host == "chrome-internal-review.googlesource.com": p.linkf("https://crrev.com/i/%d/%d", cl.Change, cl.Patchset) default: p.linkf("https://%s/c/%s/+/%d/%d", cl.Host, cl.Project, cl.Change, cl.Patchset) } }
[ "func", "(", "p", "*", "printer", ")", "change", "(", "cl", "*", "pb", ".", "GerritChange", ")", "{", "switch", "{", "case", "cl", ".", "Host", "==", "\"", "\"", ":", "p", ".", "linkf", "(", "\"", "\"", ",", "cl", ".", "Change", ",", "cl", ".", "Patchset", ")", "\n", "case", "cl", ".", "Host", "==", "\"", "\"", ":", "p", ".", "linkf", "(", "\"", "\"", ",", "cl", ".", "Change", ",", "cl", ".", "Patchset", ")", "\n", "default", ":", "p", ".", "linkf", "(", "\"", "\"", ",", "cl", ".", "Host", ",", "cl", ".", "Project", ",", "cl", ".", "Change", ",", "cl", ".", "Patchset", ")", "\n", "}", "\n", "}" ]
// change prints cl.
[ "change", "prints", "cl", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/cli/print.go#L217-L226
8,942
luci/luci-go
buildbucket/cli/print.go
steps
func (p *printer) steps(steps []*pb.Step) { maxNameWidth := 0 for _, s := range steps { if w := utf8.RuneCountInString(s.Name); w > maxNameWidth { maxNameWidth = w } } for _, s := range steps { p.f("%sStep ", ansiStatus[s.Status]) p.fw(maxNameWidth+5, "%q", s.Name) p.fw(10, "%s", s.Status) // Print duration. durString := "" if start, err := ptypes.Timestamp(s.StartTime); err == nil { var stepDur time.Duration if end, err := ptypes.Timestamp(s.EndTime); err == nil { stepDur = end.Sub(start) } else { now := p.nowFn() stepDur = now.Sub(start.In(now.Location())) } durString = truncateDuration(stepDur).String() } p.fw(10, "%s", durString) // Print log names. // Do not print log URLs because they are very long and // bb has `log` subcommand. if len(s.Logs) > 0 { p.f("Logs: ") for i, l := range s.Logs { if i > 0 { p.f(", ") } p.f("%q", l.Name) } } p.f("%s\n", ansi.Reset) p.indent.Level += 2 if s.SummaryMarkdown != "" { // TODO(nodir): transform lists of links to look like logs p.summary(s.SummaryMarkdown) } p.indent.Level -= 2 } }
go
func (p *printer) steps(steps []*pb.Step) { maxNameWidth := 0 for _, s := range steps { if w := utf8.RuneCountInString(s.Name); w > maxNameWidth { maxNameWidth = w } } for _, s := range steps { p.f("%sStep ", ansiStatus[s.Status]) p.fw(maxNameWidth+5, "%q", s.Name) p.fw(10, "%s", s.Status) // Print duration. durString := "" if start, err := ptypes.Timestamp(s.StartTime); err == nil { var stepDur time.Duration if end, err := ptypes.Timestamp(s.EndTime); err == nil { stepDur = end.Sub(start) } else { now := p.nowFn() stepDur = now.Sub(start.In(now.Location())) } durString = truncateDuration(stepDur).String() } p.fw(10, "%s", durString) // Print log names. // Do not print log URLs because they are very long and // bb has `log` subcommand. if len(s.Logs) > 0 { p.f("Logs: ") for i, l := range s.Logs { if i > 0 { p.f(", ") } p.f("%q", l.Name) } } p.f("%s\n", ansi.Reset) p.indent.Level += 2 if s.SummaryMarkdown != "" { // TODO(nodir): transform lists of links to look like logs p.summary(s.SummaryMarkdown) } p.indent.Level -= 2 } }
[ "func", "(", "p", "*", "printer", ")", "steps", "(", "steps", "[", "]", "*", "pb", ".", "Step", ")", "{", "maxNameWidth", ":=", "0", "\n", "for", "_", ",", "s", ":=", "range", "steps", "{", "if", "w", ":=", "utf8", ".", "RuneCountInString", "(", "s", ".", "Name", ")", ";", "w", ">", "maxNameWidth", "{", "maxNameWidth", "=", "w", "\n", "}", "\n", "}", "\n\n", "for", "_", ",", "s", ":=", "range", "steps", "{", "p", ".", "f", "(", "\"", "\"", ",", "ansiStatus", "[", "s", ".", "Status", "]", ")", "\n", "p", ".", "fw", "(", "maxNameWidth", "+", "5", ",", "\"", "\"", ",", "s", ".", "Name", ")", "\n", "p", ".", "fw", "(", "10", ",", "\"", "\"", ",", "s", ".", "Status", ")", "\n\n", "// Print duration.", "durString", ":=", "\"", "\"", "\n", "if", "start", ",", "err", ":=", "ptypes", ".", "Timestamp", "(", "s", ".", "StartTime", ")", ";", "err", "==", "nil", "{", "var", "stepDur", "time", ".", "Duration", "\n", "if", "end", ",", "err", ":=", "ptypes", ".", "Timestamp", "(", "s", ".", "EndTime", ")", ";", "err", "==", "nil", "{", "stepDur", "=", "end", ".", "Sub", "(", "start", ")", "\n", "}", "else", "{", "now", ":=", "p", ".", "nowFn", "(", ")", "\n", "stepDur", "=", "now", ".", "Sub", "(", "start", ".", "In", "(", "now", ".", "Location", "(", ")", ")", ")", "\n", "}", "\n", "durString", "=", "truncateDuration", "(", "stepDur", ")", ".", "String", "(", ")", "\n", "}", "\n", "p", ".", "fw", "(", "10", ",", "\"", "\"", ",", "durString", ")", "\n\n", "// Print log names.", "// Do not print log URLs because they are very long and", "// bb has `log` subcommand.", "if", "len", "(", "s", ".", "Logs", ")", ">", "0", "{", "p", ".", "f", "(", "\"", "\"", ")", "\n", "for", "i", ",", "l", ":=", "range", "s", ".", "Logs", "{", "if", "i", ">", "0", "{", "p", ".", "f", "(", "\"", "\"", ")", "\n", "}", "\n", "p", ".", "f", "(", "\"", "\"", ",", "l", ".", "Name", ")", "\n", "}", "\n", "}", "\n\n", "p", ".", "f", "(", "\"", "\\n", "\"", ",", "ansi", ".", "Reset", ")", "\n\n", "p", ".", "indent", ".", "Level", "+=", "2", "\n", "if", "s", ".", "SummaryMarkdown", "!=", "\"", "\"", "{", "// TODO(nodir): transform lists of links to look like logs", "p", ".", "summary", "(", "s", ".", "SummaryMarkdown", ")", "\n", "}", "\n", "p", ".", "indent", ".", "Level", "-=", "2", "\n", "}", "\n", "}" ]
// steps print steps.
[ "steps", "print", "steps", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/cli/print.go#L229-L278
8,943
luci/luci-go
buildbucket/cli/print.go
Error
func (p *printer) Error(err error) { st, _ := status.FromError(err) p.f("%s", st.Message()) }
go
func (p *printer) Error(err error) { st, _ := status.FromError(err) p.f("%s", st.Message()) }
[ "func", "(", "p", "*", "printer", ")", "Error", "(", "err", "error", ")", "{", "st", ",", "_", ":=", "status", ".", "FromError", "(", "err", ")", "\n", "p", ".", "f", "(", "\"", "\"", ",", "st", ".", "Message", "(", ")", ")", "\n", "}" ]
// Error prints the err. If err is a gRPC error, then prints only the message // without the code.
[ "Error", "prints", "the", "err", ".", "If", "err", "is", "a", "gRPC", "error", "then", "prints", "only", "the", "message", "without", "the", "code", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/cli/print.go#L391-L394
8,944
luci/luci-go
buildbucket/cli/print.go
readTimestamp
func readTimestamp(ts *timestamp.Timestamp) time.Time { t, err := ptypes.Timestamp(ts) if err != nil { return time.Time{} } return t }
go
func readTimestamp(ts *timestamp.Timestamp) time.Time { t, err := ptypes.Timestamp(ts) if err != nil { return time.Time{} } return t }
[ "func", "readTimestamp", "(", "ts", "*", "timestamp", ".", "Timestamp", ")", "time", ".", "Time", "{", "t", ",", "err", ":=", "ptypes", ".", "Timestamp", "(", "ts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "time", ".", "Time", "{", "}", "\n", "}", "\n", "return", "t", "\n", "}" ]
// readTimestamp converts ts to time.Time. // Returns zero if ts is invalid.
[ "readTimestamp", "converts", "ts", "to", "time", ".", "Time", ".", "Returns", "zero", "if", "ts", "is", "invalid", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/cli/print.go#L398-L404
8,945
luci/luci-go
buildbucket/cli/print.go
truncateDuration
func truncateDuration(d time.Duration) time.Duration { for _, t := range durTransactions { if d > t.threshold { return d.Round(t.round) } } return d }
go
func truncateDuration(d time.Duration) time.Duration { for _, t := range durTransactions { if d > t.threshold { return d.Round(t.round) } } return d }
[ "func", "truncateDuration", "(", "d", "time", ".", "Duration", ")", "time", ".", "Duration", "{", "for", "_", ",", "t", ":=", "range", "durTransactions", "{", "if", "d", ">", "t", ".", "threshold", "{", "return", "d", ".", "Round", "(", "t", ".", "round", ")", "\n", "}", "\n", "}", "\n", "return", "d", "\n", "}" ]
// truncateDuration truncates d to make it more human-readable.
[ "truncateDuration", "truncates", "d", "to", "make", "it", "more", "human", "-", "readable", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/cli/print.go#L421-L428
8,946
luci/luci-go
machine-db/client/cli/dracs.go
printDRACs
func printDRACs(tsv bool, dracs ...*crimson.DRAC) { if len(dracs) > 0 { p := newStdoutPrinter(tsv) defer p.Flush() if !tsv { p.Row("Name", "Machine", "MAC Address", "Switch", "Port", "IP Address", "VLAN") } for _, d := range dracs { p.Row(d.Name, d.Machine, d.MacAddress, d.Switch, d.Switchport, d.Ipv4, d.Vlan) } } }
go
func printDRACs(tsv bool, dracs ...*crimson.DRAC) { if len(dracs) > 0 { p := newStdoutPrinter(tsv) defer p.Flush() if !tsv { p.Row("Name", "Machine", "MAC Address", "Switch", "Port", "IP Address", "VLAN") } for _, d := range dracs { p.Row(d.Name, d.Machine, d.MacAddress, d.Switch, d.Switchport, d.Ipv4, d.Vlan) } } }
[ "func", "printDRACs", "(", "tsv", "bool", ",", "dracs", "...", "*", "crimson", ".", "DRAC", ")", "{", "if", "len", "(", "dracs", ")", ">", "0", "{", "p", ":=", "newStdoutPrinter", "(", "tsv", ")", "\n", "defer", "p", ".", "Flush", "(", ")", "\n", "if", "!", "tsv", "{", "p", ".", "Row", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n", "for", "_", ",", "d", ":=", "range", "dracs", "{", "p", ".", "Row", "(", "d", ".", "Name", ",", "d", ".", "Machine", ",", "d", ".", "MacAddress", ",", "d", ".", "Switch", ",", "d", ".", "Switchport", ",", "d", ".", "Ipv4", ",", "d", ".", "Vlan", ")", "\n", "}", "\n", "}", "\n", "}" ]
// printDRACs prints DRAC data to stdout in tab-separated columns.
[ "printDRACs", "prints", "DRAC", "data", "to", "stdout", "in", "tab", "-", "separated", "columns", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/dracs.go#L28-L39
8,947
luci/luci-go
machine-db/client/cli/dracs.go
Run
func (c *AddDRACCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int { ctx := cli.GetContext(app, c, env) // TODO(smut): Validate required fields client-side. req := &crimson.CreateDRACRequest{ Drac: &c.drac, } client := getClient(ctx) resp, err := client.CreateDRAC(ctx, req) if err != nil { errors.Log(ctx, err) return 1 } printDRACs(c.f.tsv, resp) return 0 }
go
func (c *AddDRACCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int { ctx := cli.GetContext(app, c, env) // TODO(smut): Validate required fields client-side. req := &crimson.CreateDRACRequest{ Drac: &c.drac, } client := getClient(ctx) resp, err := client.CreateDRAC(ctx, req) if err != nil { errors.Log(ctx, err) return 1 } printDRACs(c.f.tsv, resp) return 0 }
[ "func", "(", "c", "*", "AddDRACCmd", ")", "Run", "(", "app", "subcommands", ".", "Application", ",", "args", "[", "]", "string", ",", "env", "subcommands", ".", "Env", ")", "int", "{", "ctx", ":=", "cli", ".", "GetContext", "(", "app", ",", "c", ",", "env", ")", "\n", "// TODO(smut): Validate required fields client-side.", "req", ":=", "&", "crimson", ".", "CreateDRACRequest", "{", "Drac", ":", "&", "c", ".", "drac", ",", "}", "\n", "client", ":=", "getClient", "(", "ctx", ")", "\n", "resp", ",", "err", ":=", "client", ".", "CreateDRAC", "(", "ctx", ",", "req", ")", "\n", "if", "err", "!=", "nil", "{", "errors", ".", "Log", "(", "ctx", ",", "err", ")", "\n", "return", "1", "\n", "}", "\n", "printDRACs", "(", "c", ".", "f", ".", "tsv", ",", "resp", ")", "\n", "return", "0", "\n", "}" ]
// Run runs the command to add a DRAC.
[ "Run", "runs", "the", "command", "to", "add", "a", "DRAC", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/dracs.go#L48-L62
8,948
luci/luci-go
machine-db/client/cli/dracs.go
addDRACCmd
func addDRACCmd(params *Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "add-drac -name <name> -machine <machine> -mac <mac address> -switch <switch> -port <port> -ip <ip address>", ShortDesc: "adds a DRAC", LongDesc: "Adds a DRAC to the database.\n\nExample:\ncrimson add-drac -name server01-yy-drac -machine xx1-07-720 -mac 00:00:b3:c0:00:11 -switch switch.lab0 -port 99 -ip 999.999.999.999", CommandRun: func() subcommands.CommandRun { cmd := &AddDRACCmd{} cmd.Initialize(params) cmd.Flags.StringVar(&cmd.drac.Name, "name", "", "The name of the DRAC. Required and must be unique per machine within the database.") cmd.Flags.StringVar(&cmd.drac.Machine, "machine", "", "The machine this DRAC belongs to. Required and must be the name of a machine returned by get-machines.") cmd.Flags.StringVar(&cmd.drac.MacAddress, "mac", "", "The MAC address of this DRAC. Required and must be a valid MAC-48 address.") cmd.Flags.StringVar(&cmd.drac.Switch, "switch", "", "The switch this DRAC is connected to. Required and must be the name of a switch returned by get-switches.") cmd.Flags.Var(flag.Int32(&cmd.drac.Switchport), "port", "The switchport this DRAC is connected to.") cmd.Flags.StringVar(&cmd.drac.Ipv4, "ip", "", "The IPv4 address assigned to this DRAC. Required and must be a free IP address returned by get-ips.") return cmd }, } }
go
func addDRACCmd(params *Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "add-drac -name <name> -machine <machine> -mac <mac address> -switch <switch> -port <port> -ip <ip address>", ShortDesc: "adds a DRAC", LongDesc: "Adds a DRAC to the database.\n\nExample:\ncrimson add-drac -name server01-yy-drac -machine xx1-07-720 -mac 00:00:b3:c0:00:11 -switch switch.lab0 -port 99 -ip 999.999.999.999", CommandRun: func() subcommands.CommandRun { cmd := &AddDRACCmd{} cmd.Initialize(params) cmd.Flags.StringVar(&cmd.drac.Name, "name", "", "The name of the DRAC. Required and must be unique per machine within the database.") cmd.Flags.StringVar(&cmd.drac.Machine, "machine", "", "The machine this DRAC belongs to. Required and must be the name of a machine returned by get-machines.") cmd.Flags.StringVar(&cmd.drac.MacAddress, "mac", "", "The MAC address of this DRAC. Required and must be a valid MAC-48 address.") cmd.Flags.StringVar(&cmd.drac.Switch, "switch", "", "The switch this DRAC is connected to. Required and must be the name of a switch returned by get-switches.") cmd.Flags.Var(flag.Int32(&cmd.drac.Switchport), "port", "The switchport this DRAC is connected to.") cmd.Flags.StringVar(&cmd.drac.Ipv4, "ip", "", "The IPv4 address assigned to this DRAC. Required and must be a free IP address returned by get-ips.") return cmd }, } }
[ "func", "addDRACCmd", "(", "params", "*", "Parameters", ")", "*", "subcommands", ".", "Command", "{", "return", "&", "subcommands", ".", "Command", "{", "UsageLine", ":", "\"", "\"", ",", "ShortDesc", ":", "\"", "\"", ",", "LongDesc", ":", "\"", "\\n", "\\n", "\\n", "\"", ",", "CommandRun", ":", "func", "(", ")", "subcommands", ".", "CommandRun", "{", "cmd", ":=", "&", "AddDRACCmd", "{", "}", "\n", "cmd", ".", "Initialize", "(", "params", ")", "\n", "cmd", ".", "Flags", ".", "StringVar", "(", "&", "cmd", ".", "drac", ".", "Name", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "StringVar", "(", "&", "cmd", ".", "drac", ".", "Machine", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "StringVar", "(", "&", "cmd", ".", "drac", ".", "MacAddress", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "StringVar", "(", "&", "cmd", ".", "drac", ".", "Switch", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "flag", ".", "Int32", "(", "&", "cmd", ".", "drac", ".", "Switchport", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "StringVar", "(", "&", "cmd", ".", "drac", ".", "Ipv4", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "cmd", "\n", "}", ",", "}", "\n", "}" ]
// addDRACCmd returns a command to add a DRAC.
[ "addDRACCmd", "returns", "a", "command", "to", "add", "a", "DRAC", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/dracs.go#L65-L82
8,949
luci/luci-go
machine-db/client/cli/dracs.go
Run
func (c *EditDRACCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int { ctx := cli.GetContext(app, c, env) // TODO(smut): Validate required fields client-side. req := &crimson.UpdateDRACRequest{ Drac: &c.drac, UpdateMask: getUpdateMask(&c.Flags, map[string]string{ "machine": "machine", "mac": "mac_address", "switch": "switch", "port": "switchport", }), } client := getClient(ctx) resp, err := client.UpdateDRAC(ctx, req) if err != nil { errors.Log(ctx, err) return 1 } printDRACs(c.f.tsv, resp) return 0 }
go
func (c *EditDRACCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int { ctx := cli.GetContext(app, c, env) // TODO(smut): Validate required fields client-side. req := &crimson.UpdateDRACRequest{ Drac: &c.drac, UpdateMask: getUpdateMask(&c.Flags, map[string]string{ "machine": "machine", "mac": "mac_address", "switch": "switch", "port": "switchport", }), } client := getClient(ctx) resp, err := client.UpdateDRAC(ctx, req) if err != nil { errors.Log(ctx, err) return 1 } printDRACs(c.f.tsv, resp) return 0 }
[ "func", "(", "c", "*", "EditDRACCmd", ")", "Run", "(", "app", "subcommands", ".", "Application", ",", "args", "[", "]", "string", ",", "env", "subcommands", ".", "Env", ")", "int", "{", "ctx", ":=", "cli", ".", "GetContext", "(", "app", ",", "c", ",", "env", ")", "\n", "// TODO(smut): Validate required fields client-side.", "req", ":=", "&", "crimson", ".", "UpdateDRACRequest", "{", "Drac", ":", "&", "c", ".", "drac", ",", "UpdateMask", ":", "getUpdateMask", "(", "&", "c", ".", "Flags", ",", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", ",", "}", ")", ",", "}", "\n", "client", ":=", "getClient", "(", "ctx", ")", "\n", "resp", ",", "err", ":=", "client", ".", "UpdateDRAC", "(", "ctx", ",", "req", ")", "\n", "if", "err", "!=", "nil", "{", "errors", ".", "Log", "(", "ctx", ",", "err", ")", "\n", "return", "1", "\n", "}", "\n", "printDRACs", "(", "c", ".", "f", ".", "tsv", ",", "resp", ")", "\n", "return", "0", "\n", "}" ]
// Run runs the command to edit a DRAC.
[ "Run", "runs", "the", "command", "to", "edit", "a", "DRAC", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/dracs.go#L91-L111
8,950
luci/luci-go
machine-db/client/cli/dracs.go
Run
func (c *GetDRACsCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int { ctx := cli.GetContext(app, c, env) client := getClient(ctx) resp, err := client.ListDRACs(ctx, &c.req) if err != nil { errors.Log(ctx, err) return 1 } printDRACs(c.f.tsv, resp.Dracs...) return 0 }
go
func (c *GetDRACsCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int { ctx := cli.GetContext(app, c, env) client := getClient(ctx) resp, err := client.ListDRACs(ctx, &c.req) if err != nil { errors.Log(ctx, err) return 1 } printDRACs(c.f.tsv, resp.Dracs...) return 0 }
[ "func", "(", "c", "*", "GetDRACsCmd", ")", "Run", "(", "app", "subcommands", ".", "Application", ",", "args", "[", "]", "string", ",", "env", "subcommands", ".", "Env", ")", "int", "{", "ctx", ":=", "cli", ".", "GetContext", "(", "app", ",", "c", ",", "env", ")", "\n", "client", ":=", "getClient", "(", "ctx", ")", "\n", "resp", ",", "err", ":=", "client", ".", "ListDRACs", "(", "ctx", ",", "&", "c", ".", "req", ")", "\n", "if", "err", "!=", "nil", "{", "errors", ".", "Log", "(", "ctx", ",", "err", ")", "\n", "return", "1", "\n", "}", "\n", "printDRACs", "(", "c", ".", "f", ".", "tsv", ",", "resp", ".", "Dracs", "...", ")", "\n", "return", "0", "\n", "}" ]
// Run runs the command to get DRACs.
[ "Run", "runs", "the", "command", "to", "get", "DRACs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/dracs.go#L139-L149
8,951
luci/luci-go
machine-db/client/cli/dracs.go
getDRACsCmd
func getDRACsCmd(params *Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "get-dracs [-name <name>]... [-machine <machine>]... [-mac <mac address>]... [-switch <switch>]... [-ip <ip address>]... [-vlan <id>]...", ShortDesc: "retrieves DRACs", LongDesc: "Retrieves DRACs matching the given names and machines, or all DRACs if names and machines are omitted.\n\nExample to get all DRACs:\ncrimson get-dracs\nExample to get all DRACs in VLAN 1:\ncrimson get-dracs -vlan 1", CommandRun: func() subcommands.CommandRun { cmd := &GetDRACsCmd{} cmd.Initialize(params) cmd.Flags.Var(flag.StringSlice(&cmd.req.Names), "name", "Name of a DRAC to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Machines), "machine", "Name of a machine to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.MacAddresses), "mac", "MAC address to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Switches), "switch", "Name of a switch to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Ipv4S), "ip", "IPv4 address to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.Int64Slice(&cmd.req.Vlans), "vlan", "ID of a VLAN to filter by. Can be specified multiple times.") return cmd }, } }
go
func getDRACsCmd(params *Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "get-dracs [-name <name>]... [-machine <machine>]... [-mac <mac address>]... [-switch <switch>]... [-ip <ip address>]... [-vlan <id>]...", ShortDesc: "retrieves DRACs", LongDesc: "Retrieves DRACs matching the given names and machines, or all DRACs if names and machines are omitted.\n\nExample to get all DRACs:\ncrimson get-dracs\nExample to get all DRACs in VLAN 1:\ncrimson get-dracs -vlan 1", CommandRun: func() subcommands.CommandRun { cmd := &GetDRACsCmd{} cmd.Initialize(params) cmd.Flags.Var(flag.StringSlice(&cmd.req.Names), "name", "Name of a DRAC to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Machines), "machine", "Name of a machine to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.MacAddresses), "mac", "MAC address to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Switches), "switch", "Name of a switch to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Ipv4S), "ip", "IPv4 address to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.Int64Slice(&cmd.req.Vlans), "vlan", "ID of a VLAN to filter by. Can be specified multiple times.") return cmd }, } }
[ "func", "getDRACsCmd", "(", "params", "*", "Parameters", ")", "*", "subcommands", ".", "Command", "{", "return", "&", "subcommands", ".", "Command", "{", "UsageLine", ":", "\"", "\"", ",", "ShortDesc", ":", "\"", "\"", ",", "LongDesc", ":", "\"", "\\n", "\\n", "\\n", "\\n", "\\n", "\"", ",", "CommandRun", ":", "func", "(", ")", "subcommands", ".", "CommandRun", "{", "cmd", ":=", "&", "GetDRACsCmd", "{", "}", "\n", "cmd", ".", "Initialize", "(", "params", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "flag", ".", "StringSlice", "(", "&", "cmd", ".", "req", ".", "Names", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "flag", ".", "StringSlice", "(", "&", "cmd", ".", "req", ".", "Machines", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "flag", ".", "StringSlice", "(", "&", "cmd", ".", "req", ".", "MacAddresses", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "flag", ".", "StringSlice", "(", "&", "cmd", ".", "req", ".", "Switches", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "flag", ".", "StringSlice", "(", "&", "cmd", ".", "req", ".", "Ipv4S", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "Var", "(", "flag", ".", "Int64Slice", "(", "&", "cmd", ".", "req", ".", "Vlans", ")", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "cmd", "\n", "}", ",", "}", "\n", "}" ]
// getDRACCmd returns a command to get DRACs.
[ "getDRACCmd", "returns", "a", "command", "to", "get", "DRACs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/dracs.go#L152-L169
8,952
luci/luci-go
common/clock/clockcontext.go
WithDeadline
func WithDeadline(parent context.Context, deadline time.Time) (context.Context, context.CancelFunc) { if cur, ok := parent.Deadline(); ok && cur.Before(deadline) { // The current deadline is already sooner than the new one. return context.WithCancel(parent) } parent, cancelFunc := context.WithCancel(parent) c := &clockContext{ Context: parent, deadline: deadline, } d := deadline.Sub(Now(c)) if d <= 0 { // Deadline has already passed. c.setError(context.DeadlineExceeded) cancelFunc() return c, cancelFunc } // Invoke our cancelFunc after the specified time. Register the timer now, so // it gets registered in the testclock heap right away (and not at some // undetermined later time when the goroutine starts). t := NewTimer(Tag(c, ContextDeadlineTag)) t.Reset(d) go func() { defer t.Stop() select { case ar := <-t.GetC(): if !ar.Incomplete() { // Timer expired naturally. c.setError(context.DeadlineExceeded) cancelFunc() } case <-c.Done(): // Context was canceled, can stop the timer / goroutine. break } }() return c, cancelFunc }
go
func WithDeadline(parent context.Context, deadline time.Time) (context.Context, context.CancelFunc) { if cur, ok := parent.Deadline(); ok && cur.Before(deadline) { // The current deadline is already sooner than the new one. return context.WithCancel(parent) } parent, cancelFunc := context.WithCancel(parent) c := &clockContext{ Context: parent, deadline: deadline, } d := deadline.Sub(Now(c)) if d <= 0 { // Deadline has already passed. c.setError(context.DeadlineExceeded) cancelFunc() return c, cancelFunc } // Invoke our cancelFunc after the specified time. Register the timer now, so // it gets registered in the testclock heap right away (and not at some // undetermined later time when the goroutine starts). t := NewTimer(Tag(c, ContextDeadlineTag)) t.Reset(d) go func() { defer t.Stop() select { case ar := <-t.GetC(): if !ar.Incomplete() { // Timer expired naturally. c.setError(context.DeadlineExceeded) cancelFunc() } case <-c.Done(): // Context was canceled, can stop the timer / goroutine. break } }() return c, cancelFunc }
[ "func", "WithDeadline", "(", "parent", "context", ".", "Context", ",", "deadline", "time", ".", "Time", ")", "(", "context", ".", "Context", ",", "context", ".", "CancelFunc", ")", "{", "if", "cur", ",", "ok", ":=", "parent", ".", "Deadline", "(", ")", ";", "ok", "&&", "cur", ".", "Before", "(", "deadline", ")", "{", "// The current deadline is already sooner than the new one.", "return", "context", ".", "WithCancel", "(", "parent", ")", "\n", "}", "\n\n", "parent", ",", "cancelFunc", ":=", "context", ".", "WithCancel", "(", "parent", ")", "\n", "c", ":=", "&", "clockContext", "{", "Context", ":", "parent", ",", "deadline", ":", "deadline", ",", "}", "\n\n", "d", ":=", "deadline", ".", "Sub", "(", "Now", "(", "c", ")", ")", "\n", "if", "d", "<=", "0", "{", "// Deadline has already passed.", "c", ".", "setError", "(", "context", ".", "DeadlineExceeded", ")", "\n", "cancelFunc", "(", ")", "\n", "return", "c", ",", "cancelFunc", "\n", "}", "\n\n", "// Invoke our cancelFunc after the specified time. Register the timer now, so", "// it gets registered in the testclock heap right away (and not at some", "// undetermined later time when the goroutine starts).", "t", ":=", "NewTimer", "(", "Tag", "(", "c", ",", "ContextDeadlineTag", ")", ")", "\n", "t", ".", "Reset", "(", "d", ")", "\n", "go", "func", "(", ")", "{", "defer", "t", ".", "Stop", "(", ")", "\n\n", "select", "{", "case", "ar", ":=", "<-", "t", ".", "GetC", "(", ")", ":", "if", "!", "ar", ".", "Incomplete", "(", ")", "{", "// Timer expired naturally.", "c", ".", "setError", "(", "context", ".", "DeadlineExceeded", ")", "\n", "cancelFunc", "(", ")", "\n", "}", "\n", "case", "<-", "c", ".", "Done", "(", ")", ":", "// Context was canceled, can stop the timer / goroutine.", "break", "\n", "}", "\n", "}", "(", ")", "\n", "return", "c", ",", "cancelFunc", "\n", "}" ]
// WithDeadline is a clock library implementation of context.WithDeadline that // uses the clock library's time features instead of the Go time library. // // For more information, see context.WithDeadline.
[ "WithDeadline", "is", "a", "clock", "library", "implementation", "of", "context", ".", "WithDeadline", "that", "uses", "the", "clock", "library", "s", "time", "features", "instead", "of", "the", "Go", "time", "library", ".", "For", "more", "information", "see", "context", ".", "WithDeadline", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/clock/clockcontext.go#L65-L106
8,953
luci/luci-go
machine-db/appengine/rpc/platforms.go
ListPlatforms
func (*Service) ListPlatforms(c context.Context, req *crimson.ListPlatformsRequest) (*crimson.ListPlatformsResponse, error) { platforms, err := listPlatforms(c, req) if err != nil { return nil, err } return &crimson.ListPlatformsResponse{ Platforms: platforms, }, nil }
go
func (*Service) ListPlatforms(c context.Context, req *crimson.ListPlatformsRequest) (*crimson.ListPlatformsResponse, error) { platforms, err := listPlatforms(c, req) if err != nil { return nil, err } return &crimson.ListPlatformsResponse{ Platforms: platforms, }, nil }
[ "func", "(", "*", "Service", ")", "ListPlatforms", "(", "c", "context", ".", "Context", ",", "req", "*", "crimson", ".", "ListPlatformsRequest", ")", "(", "*", "crimson", ".", "ListPlatformsResponse", ",", "error", ")", "{", "platforms", ",", "err", ":=", "listPlatforms", "(", "c", ",", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "crimson", ".", "ListPlatformsResponse", "{", "Platforms", ":", "platforms", ",", "}", ",", "nil", "\n", "}" ]
// ListPlatforms handles a request to retrieve platforms.
[ "ListPlatforms", "handles", "a", "request", "to", "retrieve", "platforms", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/platforms.go#L29-L37
8,954
luci/luci-go
machine-db/appengine/rpc/platforms.go
listPlatforms
func listPlatforms(c context.Context, req *crimson.ListPlatformsRequest) ([]*crimson.Platform, error) { stmt := squirrel.Select("name", "description", "manufacturer").From("platforms") stmt = selectInString(stmt, "name", req.Names) stmt = selectInString(stmt, "manufacturer", req.Manufacturers) query, args, err := stmt.ToSql() if err != nil { return nil, errors.Annotate(err, "failed to generate statement").Err() } db := database.Get(c) rows, err := db.QueryContext(c, query, args...) if err != nil { return nil, errors.Annotate(err, "failed to fetch platforms").Err() } defer rows.Close() var platforms []*crimson.Platform for rows.Next() { p := &crimson.Platform{} if err = rows.Scan(&p.Name, &p.Description, &p.Manufacturer); err != nil { return nil, errors.Annotate(err, "failed to fetch platform").Err() } platforms = append(platforms, p) } return platforms, nil }
go
func listPlatforms(c context.Context, req *crimson.ListPlatformsRequest) ([]*crimson.Platform, error) { stmt := squirrel.Select("name", "description", "manufacturer").From("platforms") stmt = selectInString(stmt, "name", req.Names) stmt = selectInString(stmt, "manufacturer", req.Manufacturers) query, args, err := stmt.ToSql() if err != nil { return nil, errors.Annotate(err, "failed to generate statement").Err() } db := database.Get(c) rows, err := db.QueryContext(c, query, args...) if err != nil { return nil, errors.Annotate(err, "failed to fetch platforms").Err() } defer rows.Close() var platforms []*crimson.Platform for rows.Next() { p := &crimson.Platform{} if err = rows.Scan(&p.Name, &p.Description, &p.Manufacturer); err != nil { return nil, errors.Annotate(err, "failed to fetch platform").Err() } platforms = append(platforms, p) } return platforms, nil }
[ "func", "listPlatforms", "(", "c", "context", ".", "Context", ",", "req", "*", "crimson", ".", "ListPlatformsRequest", ")", "(", "[", "]", "*", "crimson", ".", "Platform", ",", "error", ")", "{", "stmt", ":=", "squirrel", ".", "Select", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", ".", "From", "(", "\"", "\"", ")", "\n", "stmt", "=", "selectInString", "(", "stmt", ",", "\"", "\"", ",", "req", ".", "Names", ")", "\n", "stmt", "=", "selectInString", "(", "stmt", ",", "\"", "\"", ",", "req", ".", "Manufacturers", ")", "\n", "query", ",", "args", ",", "err", ":=", "stmt", ".", "ToSql", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "db", ":=", "database", ".", "Get", "(", "c", ")", "\n", "rows", ",", "err", ":=", "db", ".", "QueryContext", "(", "c", ",", "query", ",", "args", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "defer", "rows", ".", "Close", "(", ")", "\n\n", "var", "platforms", "[", "]", "*", "crimson", ".", "Platform", "\n", "for", "rows", ".", "Next", "(", ")", "{", "p", ":=", "&", "crimson", ".", "Platform", "{", "}", "\n", "if", "err", "=", "rows", ".", "Scan", "(", "&", "p", ".", "Name", ",", "&", "p", ".", "Description", ",", "&", "p", ".", "Manufacturer", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "platforms", "=", "append", "(", "platforms", ",", "p", ")", "\n", "}", "\n", "return", "platforms", ",", "nil", "\n", "}" ]
// listPlatforms returns a slice of platforms in the database.
[ "listPlatforms", "returns", "a", "slice", "of", "platforms", "in", "the", "database", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/platforms.go#L40-L65
8,955
luci/luci-go
config/impl/memory/memory.go
SetError
func SetError(impl config.Interface, err error) { impl.(*memoryImpl).err = err }
go
func SetError(impl config.Interface, err error) { impl.(*memoryImpl).err = err }
[ "func", "SetError", "(", "impl", "config", ".", "Interface", ",", "err", "error", ")", "{", "impl", ".", "(", "*", "memoryImpl", ")", ".", "err", "=", "err", "\n", "}" ]
// SetError artificially pins the error code returned by impl to err. If err is // nil, impl will behave normally. // // impl must be a memory config isntance created with New, else SetError will // panic.
[ "SetError", "artificially", "pins", "the", "error", "code", "returned", "by", "impl", "to", "err", ".", "If", "err", "is", "nil", "impl", "will", "behave", "normally", ".", "impl", "must", "be", "a", "memory", "config", "isntance", "created", "with", "New", "else", "SetError", "will", "panic", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/impl/memory/memory.go#L44-L46
8,956
luci/luci-go
config/impl/memory/memory.go
configMaybe
func (b Files) configMaybe(configSet config.Set, path string, metaOnly bool) *config.Config { if body, ok := b[path]; ok { cfg := &config.Config{ Meta: config.Meta{ ConfigSet: configSet, Path: path, ContentHash: hash(body), Revision: b.rev(), ViewURL: fmt.Sprintf("https://example.com/view/here/%s", path), }, } if !metaOnly { cfg.Content = body } return cfg } return nil }
go
func (b Files) configMaybe(configSet config.Set, path string, metaOnly bool) *config.Config { if body, ok := b[path]; ok { cfg := &config.Config{ Meta: config.Meta{ ConfigSet: configSet, Path: path, ContentHash: hash(body), Revision: b.rev(), ViewURL: fmt.Sprintf("https://example.com/view/here/%s", path), }, } if !metaOnly { cfg.Content = body } return cfg } return nil }
[ "func", "(", "b", "Files", ")", "configMaybe", "(", "configSet", "config", ".", "Set", ",", "path", "string", ",", "metaOnly", "bool", ")", "*", "config", ".", "Config", "{", "if", "body", ",", "ok", ":=", "b", "[", "path", "]", ";", "ok", "{", "cfg", ":=", "&", "config", ".", "Config", "{", "Meta", ":", "config", ".", "Meta", "{", "ConfigSet", ":", "configSet", ",", "Path", ":", "path", ",", "ContentHash", ":", "hash", "(", "body", ")", ",", "Revision", ":", "b", ".", "rev", "(", ")", ",", "ViewURL", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "path", ")", ",", "}", ",", "}", "\n", "if", "!", "metaOnly", "{", "cfg", ".", "Content", "=", "body", "\n", "}", "\n", "return", "cfg", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// configMaybe returns config.Config if such config is in the set, else nil.
[ "configMaybe", "returns", "config", ".", "Config", "if", "such", "config", "is", "in", "the", "set", "else", "nil", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/impl/memory/memory.go#L190-L207
8,957
luci/luci-go
config/impl/memory/memory.go
rev
func (b Files) rev() string { keys := make([]string, 0, len(b)) for k := range b { keys = append(keys, k) } sort.Strings(keys) buf := sha256.New() for _, k := range keys { buf.Write([]byte(k)) buf.Write([]byte{0}) buf.Write([]byte(b[k])) buf.Write([]byte{0}) } return hex.EncodeToString(buf.Sum(nil))[:40] }
go
func (b Files) rev() string { keys := make([]string, 0, len(b)) for k := range b { keys = append(keys, k) } sort.Strings(keys) buf := sha256.New() for _, k := range keys { buf.Write([]byte(k)) buf.Write([]byte{0}) buf.Write([]byte(b[k])) buf.Write([]byte{0}) } return hex.EncodeToString(buf.Sum(nil))[:40] }
[ "func", "(", "b", "Files", ")", "rev", "(", ")", "string", "{", "keys", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "b", ")", ")", "\n", "for", "k", ":=", "range", "b", "{", "keys", "=", "append", "(", "keys", ",", "k", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "keys", ")", "\n", "buf", ":=", "sha256", ".", "New", "(", ")", "\n", "for", "_", ",", "k", ":=", "range", "keys", "{", "buf", ".", "Write", "(", "[", "]", "byte", "(", "k", ")", ")", "\n", "buf", ".", "Write", "(", "[", "]", "byte", "{", "0", "}", ")", "\n", "buf", ".", "Write", "(", "[", "]", "byte", "(", "b", "[", "k", "]", ")", ")", "\n", "buf", ".", "Write", "(", "[", "]", "byte", "{", "0", "}", ")", "\n", "}", "\n", "return", "hex", ".", "EncodeToString", "(", "buf", ".", "Sum", "(", "nil", ")", ")", "[", ":", "40", "]", "\n", "}" ]
// rev returns fake revision of given config set.
[ "rev", "returns", "fake", "revision", "of", "given", "config", "set", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/impl/memory/memory.go#L210-L224
8,958
luci/luci-go
config/impl/memory/memory.go
hash
func hash(body string) string { buf := sha256.New() fmt.Fprintf(buf, "blob %d", len(body)) buf.Write([]byte{0}) buf.Write([]byte(body)) return "v2:" + hex.EncodeToString(buf.Sum(nil)) }
go
func hash(body string) string { buf := sha256.New() fmt.Fprintf(buf, "blob %d", len(body)) buf.Write([]byte{0}) buf.Write([]byte(body)) return "v2:" + hex.EncodeToString(buf.Sum(nil)) }
[ "func", "hash", "(", "body", "string", ")", "string", "{", "buf", ":=", "sha256", ".", "New", "(", ")", "\n", "fmt", ".", "Fprintf", "(", "buf", ",", "\"", "\"", ",", "len", "(", "body", ")", ")", "\n", "buf", ".", "Write", "(", "[", "]", "byte", "{", "0", "}", ")", "\n", "buf", ".", "Write", "(", "[", "]", "byte", "(", "body", ")", ")", "\n", "return", "\"", "\"", "+", "hex", ".", "EncodeToString", "(", "buf", ".", "Sum", "(", "nil", ")", ")", "\n", "}" ]
// hash returns generated ContentHash of a config file.
[ "hash", "returns", "generated", "ContentHash", "of", "a", "config", "file", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/impl/memory/memory.go#L227-L233
8,959
luci/luci-go
milo/git/gitacls/acls.go
FromConfig
func FromConfig(c context.Context, cfg []*config.Settings_SourceAcls) (*ACLs, error) { ctx := validation.Context{Context: c} ACLs := &ACLs{} ACLs.load(&ctx, cfg) if err := ctx.Finalize(); err != nil { return nil, err } return ACLs, nil }
go
func FromConfig(c context.Context, cfg []*config.Settings_SourceAcls) (*ACLs, error) { ctx := validation.Context{Context: c} ACLs := &ACLs{} ACLs.load(&ctx, cfg) if err := ctx.Finalize(); err != nil { return nil, err } return ACLs, nil }
[ "func", "FromConfig", "(", "c", "context", ".", "Context", ",", "cfg", "[", "]", "*", "config", ".", "Settings_SourceAcls", ")", "(", "*", "ACLs", ",", "error", ")", "{", "ctx", ":=", "validation", ".", "Context", "{", "Context", ":", "c", "}", "\n", "ACLs", ":=", "&", "ACLs", "{", "}", "\n", "ACLs", ".", "load", "(", "&", "ctx", ",", "cfg", ")", "\n", "if", "err", ":=", "ctx", ".", "Finalize", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "ACLs", ",", "nil", "\n", "}" ]
// FromConfig returns ACLs if config is valid.
[ "FromConfig", "returns", "ACLs", "if", "config", "is", "valid", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/git/gitacls/acls.go#L34-L42
8,960
luci/luci-go
milo/git/gitacls/acls.go
ValidateConfig
func ValidateConfig(ctx *validation.Context, cfg []*config.Settings_SourceAcls) { var ACLs ACLs ACLs.load(ctx, cfg) }
go
func ValidateConfig(ctx *validation.Context, cfg []*config.Settings_SourceAcls) { var ACLs ACLs ACLs.load(ctx, cfg) }
[ "func", "ValidateConfig", "(", "ctx", "*", "validation", ".", "Context", ",", "cfg", "[", "]", "*", "config", ".", "Settings_SourceAcls", ")", "{", "var", "ACLs", "ACLs", "\n", "ACLs", ".", "load", "(", "ctx", ",", "cfg", ")", "\n", "}" ]
// ValidateConfig passes all validation errors through validation context.
[ "ValidateConfig", "passes", "all", "validation", "errors", "through", "validation", "context", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/git/gitacls/acls.go#L45-L48
8,961
luci/luci-go
milo/git/gitacls/acls.go
belongsTo
func (a *ACLs) belongsTo(c context.Context, readerGroups ...[]string) (bool, error) { currentIdentity := auth.CurrentIdentity(c) groups := []string{} for _, readers := range readerGroups { for _, r := range readers { switch { case strings.HasPrefix(r, "group:"): // auth.IsMember expects group names w/o "group:" prefix. groups = append(groups, r[len("group:"):]) case currentIdentity == identity.Identity(r): return true, nil } } } isMember, err := auth.IsMember(c, groups...) if err != nil { return false, transient.Tag.Apply(err) } return isMember, nil }
go
func (a *ACLs) belongsTo(c context.Context, readerGroups ...[]string) (bool, error) { currentIdentity := auth.CurrentIdentity(c) groups := []string{} for _, readers := range readerGroups { for _, r := range readers { switch { case strings.HasPrefix(r, "group:"): // auth.IsMember expects group names w/o "group:" prefix. groups = append(groups, r[len("group:"):]) case currentIdentity == identity.Identity(r): return true, nil } } } isMember, err := auth.IsMember(c, groups...) if err != nil { return false, transient.Tag.Apply(err) } return isMember, nil }
[ "func", "(", "a", "*", "ACLs", ")", "belongsTo", "(", "c", "context", ".", "Context", ",", "readerGroups", "...", "[", "]", "string", ")", "(", "bool", ",", "error", ")", "{", "currentIdentity", ":=", "auth", ".", "CurrentIdentity", "(", "c", ")", "\n", "groups", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "readers", ":=", "range", "readerGroups", "{", "for", "_", ",", "r", ":=", "range", "readers", "{", "switch", "{", "case", "strings", ".", "HasPrefix", "(", "r", ",", "\"", "\"", ")", ":", "// auth.IsMember expects group names w/o \"group:\" prefix.", "groups", "=", "append", "(", "groups", ",", "r", "[", "len", "(", "\"", "\"", ")", ":", "]", ")", "\n", "case", "currentIdentity", "==", "identity", ".", "Identity", "(", "r", ")", ":", "return", "true", ",", "nil", "\n", "}", "\n", "}", "\n", "}", "\n", "isMember", ",", "err", ":=", "auth", ".", "IsMember", "(", "c", ",", "groups", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "transient", ".", "Tag", ".", "Apply", "(", "err", ")", "\n", "}", "\n", "return", "isMember", ",", "nil", "\n", "}" ]
// private implementation.
[ "private", "implementation", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/git/gitacls/acls.go#L74-L93
8,962
luci/luci-go
milo/git/gitacls/acls.go
load
func (a *ACLs) load(ctx *validation.Context, cfg []*config.Settings_SourceAcls) { a.hosts = map[string]*hostACLs{} for i, group := range cfg { ctx.Enter("source_acls #%d", i) if len(group.Readers) == 0 { ctx.Errorf("at least 1 reader required") } if len(group.Hosts)+len(group.Projects) == 0 { ctx.Errorf("at least 1 host or project required") } gReaders := a.loadReaders(ctx, group.Readers) for _, hostURL := range group.Hosts { ctx.Enter("host %q", hostURL) a.loadHost(ctx, i, hostURL, gReaders) ctx.Exit() } for _, projectURL := range group.Projects { ctx.Enter("project %q", projectURL) a.loadProject(ctx, i, projectURL, gReaders) ctx.Exit() } ctx.Exit() } }
go
func (a *ACLs) load(ctx *validation.Context, cfg []*config.Settings_SourceAcls) { a.hosts = map[string]*hostACLs{} for i, group := range cfg { ctx.Enter("source_acls #%d", i) if len(group.Readers) == 0 { ctx.Errorf("at least 1 reader required") } if len(group.Hosts)+len(group.Projects) == 0 { ctx.Errorf("at least 1 host or project required") } gReaders := a.loadReaders(ctx, group.Readers) for _, hostURL := range group.Hosts { ctx.Enter("host %q", hostURL) a.loadHost(ctx, i, hostURL, gReaders) ctx.Exit() } for _, projectURL := range group.Projects { ctx.Enter("project %q", projectURL) a.loadProject(ctx, i, projectURL, gReaders) ctx.Exit() } ctx.Exit() } }
[ "func", "(", "a", "*", "ACLs", ")", "load", "(", "ctx", "*", "validation", ".", "Context", ",", "cfg", "[", "]", "*", "config", ".", "Settings_SourceAcls", ")", "{", "a", ".", "hosts", "=", "map", "[", "string", "]", "*", "hostACLs", "{", "}", "\n", "for", "i", ",", "group", ":=", "range", "cfg", "{", "ctx", ".", "Enter", "(", "\"", "\"", ",", "i", ")", "\n\n", "if", "len", "(", "group", ".", "Readers", ")", "==", "0", "{", "ctx", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "group", ".", "Hosts", ")", "+", "len", "(", "group", ".", "Projects", ")", "==", "0", "{", "ctx", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "gReaders", ":=", "a", ".", "loadReaders", "(", "ctx", ",", "group", ".", "Readers", ")", "\n", "for", "_", ",", "hostURL", ":=", "range", "group", ".", "Hosts", "{", "ctx", ".", "Enter", "(", "\"", "\"", ",", "hostURL", ")", "\n", "a", ".", "loadHost", "(", "ctx", ",", "i", ",", "hostURL", ",", "gReaders", ")", "\n", "ctx", ".", "Exit", "(", ")", "\n", "}", "\n", "for", "_", ",", "projectURL", ":=", "range", "group", ".", "Projects", "{", "ctx", ".", "Enter", "(", "\"", "\"", ",", "projectURL", ")", "\n", "a", ".", "loadProject", "(", "ctx", ",", "i", ",", "projectURL", ",", "gReaders", ")", "\n", "ctx", ".", "Exit", "(", ")", "\n", "}", "\n", "ctx", ".", "Exit", "(", ")", "\n", "}", "\n", "}" ]
// load validates and loads ACLs from config.
[ "load", "validates", "and", "loads", "ACLs", "from", "config", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/git/gitacls/acls.go#L106-L131
8,963
luci/luci-go
milo/git/gitacls/acls.go
loadReaders
func (a *ACLs) loadReaders(ctx *validation.Context, readers []string) []string { known := stringset.New(len(readers)) for _, r := range readers { id := r switch { case strings.HasPrefix(r, "group:"): if r[len("group:"):] == "" { ctx.Errorf("invalid readers %q: needs a group name", r) } case !strings.ContainsRune(r, ':'): id = "user:" + r fallthrough default: if _, err := identity.MakeIdentity(id); err != nil { ctx.Error(errors.Annotate(err, "invalid readers %q", r).Err()) continue } } if !known.Add(id) { ctx.Errorf("duplicate readers %q", r) } } res := known.ToSlice() sort.Strings(res) return res }
go
func (a *ACLs) loadReaders(ctx *validation.Context, readers []string) []string { known := stringset.New(len(readers)) for _, r := range readers { id := r switch { case strings.HasPrefix(r, "group:"): if r[len("group:"):] == "" { ctx.Errorf("invalid readers %q: needs a group name", r) } case !strings.ContainsRune(r, ':'): id = "user:" + r fallthrough default: if _, err := identity.MakeIdentity(id); err != nil { ctx.Error(errors.Annotate(err, "invalid readers %q", r).Err()) continue } } if !known.Add(id) { ctx.Errorf("duplicate readers %q", r) } } res := known.ToSlice() sort.Strings(res) return res }
[ "func", "(", "a", "*", "ACLs", ")", "loadReaders", "(", "ctx", "*", "validation", ".", "Context", ",", "readers", "[", "]", "string", ")", "[", "]", "string", "{", "known", ":=", "stringset", ".", "New", "(", "len", "(", "readers", ")", ")", "\n", "for", "_", ",", "r", ":=", "range", "readers", "{", "id", ":=", "r", "\n", "switch", "{", "case", "strings", ".", "HasPrefix", "(", "r", ",", "\"", "\"", ")", ":", "if", "r", "[", "len", "(", "\"", "\"", ")", ":", "]", "==", "\"", "\"", "{", "ctx", ".", "Errorf", "(", "\"", "\"", ",", "r", ")", "\n", "}", "\n", "case", "!", "strings", ".", "ContainsRune", "(", "r", ",", "':'", ")", ":", "id", "=", "\"", "\"", "+", "r", "\n", "fallthrough", "\n", "default", ":", "if", "_", ",", "err", ":=", "identity", ".", "MakeIdentity", "(", "id", ")", ";", "err", "!=", "nil", "{", "ctx", ".", "Error", "(", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "r", ")", ".", "Err", "(", ")", ")", "\n", "continue", "\n", "}", "\n", "}", "\n", "if", "!", "known", ".", "Add", "(", "id", ")", "{", "ctx", ".", "Errorf", "(", "\"", "\"", ",", "r", ")", "\n", "}", "\n", "}", "\n", "res", ":=", "known", ".", "ToSlice", "(", ")", "\n", "sort", ".", "Strings", "(", "res", ")", "\n", "return", "res", "\n", "}" ]
// loadReaders validates readers and returns slice of valid identities.
[ "loadReaders", "validates", "readers", "and", "returns", "slice", "of", "valid", "identities", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/git/gitacls/acls.go#L134-L159
8,964
luci/luci-go
milo/git/gitacls/acls.go
validateURL
func validateURL(ctx *validation.Context, s string) (*url.URL, bool) { // url.Parse considers "example.com/a/b" to be a path, so ensure a scheme. if !strings.HasPrefix(s, "https://") { s = "https://" + s } u, err := url.Parse(s) if err != nil { ctx.Error(errors.Annotate(err, "not a valid URL").Err()) return nil, false } valid := true if !strings.HasSuffix(u.Host, ".googlesource.com") { ctx.Errorf("isn't at *.googlesource.com %q", u.Host) valid = false } if u.Scheme != "" && u.Scheme != "https" { ctx.Errorf("scheme must be https") valid = false } if strings.HasSuffix(u.Host, "-review.googlesource.com") { ctx.Errorf("must not be a Gerrit host (try without '-review')") valid = false } return u, valid }
go
func validateURL(ctx *validation.Context, s string) (*url.URL, bool) { // url.Parse considers "example.com/a/b" to be a path, so ensure a scheme. if !strings.HasPrefix(s, "https://") { s = "https://" + s } u, err := url.Parse(s) if err != nil { ctx.Error(errors.Annotate(err, "not a valid URL").Err()) return nil, false } valid := true if !strings.HasSuffix(u.Host, ".googlesource.com") { ctx.Errorf("isn't at *.googlesource.com %q", u.Host) valid = false } if u.Scheme != "" && u.Scheme != "https" { ctx.Errorf("scheme must be https") valid = false } if strings.HasSuffix(u.Host, "-review.googlesource.com") { ctx.Errorf("must not be a Gerrit host (try without '-review')") valid = false } return u, valid }
[ "func", "validateURL", "(", "ctx", "*", "validation", ".", "Context", ",", "s", "string", ")", "(", "*", "url", ".", "URL", ",", "bool", ")", "{", "// url.Parse considers \"example.com/a/b\" to be a path, so ensure a scheme.", "if", "!", "strings", ".", "HasPrefix", "(", "s", ",", "\"", "\"", ")", "{", "s", "=", "\"", "\"", "+", "s", "\n", "}", "\n", "u", ",", "err", ":=", "url", ".", "Parse", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "ctx", ".", "Error", "(", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", ")", "\n", "return", "nil", ",", "false", "\n", "}", "\n", "valid", ":=", "true", "\n", "if", "!", "strings", ".", "HasSuffix", "(", "u", ".", "Host", ",", "\"", "\"", ")", "{", "ctx", ".", "Errorf", "(", "\"", "\"", ",", "u", ".", "Host", ")", "\n", "valid", "=", "false", "\n", "}", "\n", "if", "u", ".", "Scheme", "!=", "\"", "\"", "&&", "u", ".", "Scheme", "!=", "\"", "\"", "{", "ctx", ".", "Errorf", "(", "\"", "\"", ")", "\n", "valid", "=", "false", "\n", "}", "\n", "if", "strings", ".", "HasSuffix", "(", "u", ".", "Host", ",", "\"", "\"", ")", "{", "ctx", ".", "Errorf", "(", "\"", "\"", ")", "\n", "valid", "=", "false", "\n", "}", "\n", "return", "u", ",", "valid", "\n", "}" ]
// validateURL returns parsed URL and whether it has passed validation.
[ "validateURL", "returns", "parsed", "URL", "and", "whether", "it", "has", "passed", "validation", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/git/gitacls/acls.go#L237-L261
8,965
luci/luci-go
lucicfg/protos.go
protoLoader
func protoLoader() interpreter.Loader { mapping := make(map[string]string, len(publicProtos)) for path, proto := range publicProtos { mapping[path] = proto.goPath } return interpreter.ProtoLoader(mapping) }
go
func protoLoader() interpreter.Loader { mapping := make(map[string]string, len(publicProtos)) for path, proto := range publicProtos { mapping[path] = proto.goPath } return interpreter.ProtoLoader(mapping) }
[ "func", "protoLoader", "(", ")", "interpreter", ".", "Loader", "{", "mapping", ":=", "make", "(", "map", "[", "string", "]", "string", ",", "len", "(", "publicProtos", ")", ")", "\n", "for", "path", ",", "proto", ":=", "range", "publicProtos", "{", "mapping", "[", "path", "]", "=", "proto", ".", "goPath", "\n", "}", "\n", "return", "interpreter", ".", "ProtoLoader", "(", "mapping", ")", "\n", "}" ]
// protoLoader returns a loader that is capable of loading publicProtos.
[ "protoLoader", "returns", "a", "loader", "that", "is", "capable", "of", "loading", "publicProtos", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/protos.go#L216-L222
8,966
luci/luci-go
lucicfg/protos.go
protoMessageDoc
func protoMessageDoc(msg proto.Message) (name, doc string) { withDesc, ok := msg.(descriptor.Message) if !ok { return "", "" } fd, md := descriptor.ForMessage(withDesc) if fd == nil || md == nil { return "", "" } for _, info := range publicProtos { // Find the exact same *.proto file within publicProtos struct. if info.goPath == fd.GetName() { if info.docURL == "" { return "", "" // no docs for it } return md.GetName(), info.docURL } } return "", "" // not a public proto }
go
func protoMessageDoc(msg proto.Message) (name, doc string) { withDesc, ok := msg.(descriptor.Message) if !ok { return "", "" } fd, md := descriptor.ForMessage(withDesc) if fd == nil || md == nil { return "", "" } for _, info := range publicProtos { // Find the exact same *.proto file within publicProtos struct. if info.goPath == fd.GetName() { if info.docURL == "" { return "", "" // no docs for it } return md.GetName(), info.docURL } } return "", "" // not a public proto }
[ "func", "protoMessageDoc", "(", "msg", "proto", ".", "Message", ")", "(", "name", ",", "doc", "string", ")", "{", "withDesc", ",", "ok", ":=", "msg", ".", "(", "descriptor", ".", "Message", ")", "\n", "if", "!", "ok", "{", "return", "\"", "\"", ",", "\"", "\"", "\n", "}", "\n\n", "fd", ",", "md", ":=", "descriptor", ".", "ForMessage", "(", "withDesc", ")", "\n", "if", "fd", "==", "nil", "||", "md", "==", "nil", "{", "return", "\"", "\"", ",", "\"", "\"", "\n", "}", "\n\n", "for", "_", ",", "info", ":=", "range", "publicProtos", "{", "// Find the exact same *.proto file within publicProtos struct.", "if", "info", ".", "goPath", "==", "fd", ".", "GetName", "(", ")", "{", "if", "info", ".", "docURL", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "\"", "\"", "// no docs for it", "\n", "}", "\n", "return", "md", ".", "GetName", "(", ")", ",", "info", ".", "docURL", "\n", "}", "\n", "}", "\n\n", "return", "\"", "\"", ",", "\"", "\"", "// not a public proto", "\n", "}" ]
// protoMessageDoc returns the message name and a link to its schema doc. // // If there's no documentation, returns two empty strings.
[ "protoMessageDoc", "returns", "the", "message", "name", "and", "a", "link", "to", "its", "schema", "doc", ".", "If", "there", "s", "no", "documentation", "returns", "two", "empty", "strings", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/protos.go#L227-L249
8,967
luci/luci-go
starlark/interpreter/loaders.go
FileSystemLoader
func FileSystemLoader(root string) Loader { root, err := filepath.Abs(root) if err != nil { panic(err) } return func(path string) (_ starlark.StringDict, src string, err error) { abs := filepath.Join(root, filepath.FromSlash(path)) rel, err := filepath.Rel(root, abs) if err != nil { return nil, "", errors.Annotate(err, "failed to calculate relative path").Err() } if strings.HasPrefix(rel, ".."+string(filepath.Separator)) { return nil, "", errors.New("outside the package root") } body, err := ioutil.ReadFile(abs) if os.IsNotExist(err) { return nil, "", ErrNoModule } return nil, string(body), err } }
go
func FileSystemLoader(root string) Loader { root, err := filepath.Abs(root) if err != nil { panic(err) } return func(path string) (_ starlark.StringDict, src string, err error) { abs := filepath.Join(root, filepath.FromSlash(path)) rel, err := filepath.Rel(root, abs) if err != nil { return nil, "", errors.Annotate(err, "failed to calculate relative path").Err() } if strings.HasPrefix(rel, ".."+string(filepath.Separator)) { return nil, "", errors.New("outside the package root") } body, err := ioutil.ReadFile(abs) if os.IsNotExist(err) { return nil, "", ErrNoModule } return nil, string(body), err } }
[ "func", "FileSystemLoader", "(", "root", "string", ")", "Loader", "{", "root", ",", "err", ":=", "filepath", ".", "Abs", "(", "root", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "func", "(", "path", "string", ")", "(", "_", "starlark", ".", "StringDict", ",", "src", "string", ",", "err", "error", ")", "{", "abs", ":=", "filepath", ".", "Join", "(", "root", ",", "filepath", ".", "FromSlash", "(", "path", ")", ")", "\n", "rel", ",", "err", ":=", "filepath", ".", "Rel", "(", "root", ",", "abs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"", "\"", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "if", "strings", ".", "HasPrefix", "(", "rel", ",", "\"", "\"", "+", "string", "(", "filepath", ".", "Separator", ")", ")", "{", "return", "nil", ",", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "body", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "abs", ")", "\n", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "nil", ",", "\"", "\"", ",", "ErrNoModule", "\n", "}", "\n", "return", "nil", ",", "string", "(", "body", ")", ",", "err", "\n", "}", "\n", "}" ]
// FileSystemLoader returns a loader that loads files from the file system.
[ "FileSystemLoader", "returns", "a", "loader", "that", "loads", "files", "from", "the", "file", "system", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/interpreter/loaders.go#L30-L50
8,968
luci/luci-go
starlark/interpreter/loaders.go
MemoryLoader
func MemoryLoader(files map[string]string) Loader { return func(path string) (_ starlark.StringDict, src string, err error) { body, ok := files[path] if !ok { return nil, "", ErrNoModule } return nil, body, nil } }
go
func MemoryLoader(files map[string]string) Loader { return func(path string) (_ starlark.StringDict, src string, err error) { body, ok := files[path] if !ok { return nil, "", ErrNoModule } return nil, body, nil } }
[ "func", "MemoryLoader", "(", "files", "map", "[", "string", "]", "string", ")", "Loader", "{", "return", "func", "(", "path", "string", ")", "(", "_", "starlark", ".", "StringDict", ",", "src", "string", ",", "err", "error", ")", "{", "body", ",", "ok", ":=", "files", "[", "path", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "\"", "\"", ",", "ErrNoModule", "\n", "}", "\n", "return", "nil", ",", "body", ",", "nil", "\n", "}", "\n", "}" ]
// MemoryLoader returns a loader that loads files from the given map. // // Useful together with 'assets' package to embed Starlark code into the // interpreter binary.
[ "MemoryLoader", "returns", "a", "loader", "that", "loads", "files", "from", "the", "given", "map", ".", "Useful", "together", "with", "assets", "package", "to", "embed", "Starlark", "code", "into", "the", "interpreter", "binary", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/interpreter/loaders.go#L56-L64
8,969
luci/luci-go
server/auth/xsrf/xsrf.go
Check
func Check(c context.Context, tok string) error { _, err := xsrfToken.Validate(c, tok, state(c)) return err }
go
func Check(c context.Context, tok string) error { _, err := xsrfToken.Validate(c, tok, state(c)) return err }
[ "func", "Check", "(", "c", "context", ".", "Context", ",", "tok", "string", ")", "error", "{", "_", ",", "err", ":=", "xsrfToken", ".", "Validate", "(", "c", ",", "tok", ",", "state", "(", "c", ")", ")", "\n", "return", "err", "\n", "}" ]
// Check returns nil if XSRF token is valid.
[ "Check", "returns", "nil", "if", "XSRF", "token", "is", "valid", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/xsrf/xsrf.go#L61-L64
8,970
luci/luci-go
server/auth/xsrf/xsrf.go
replyError
func replyError(c context.Context, rw http.ResponseWriter, code int, msg string, args ...interface{}) { text := fmt.Sprintf(msg, args...) logging.Errorf(c, "xsrf: %s", text) http.Error(rw, text, code) }
go
func replyError(c context.Context, rw http.ResponseWriter, code int, msg string, args ...interface{}) { text := fmt.Sprintf(msg, args...) logging.Errorf(c, "xsrf: %s", text) http.Error(rw, text, code) }
[ "func", "replyError", "(", "c", "context", ".", "Context", ",", "rw", "http", ".", "ResponseWriter", ",", "code", "int", ",", "msg", "string", ",", "args", "...", "interface", "{", "}", ")", "{", "text", ":=", "fmt", ".", "Sprintf", "(", "msg", ",", "args", "...", ")", "\n", "logging", ".", "Errorf", "(", "c", ",", "\"", "\"", ",", "text", ")", "\n", "http", ".", "Error", "(", "rw", ",", "text", ",", "code", ")", "\n", "}" ]
// replyError sends error response and logs it.
[ "replyError", "sends", "error", "response", "and", "logs", "it", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/xsrf/xsrf.go#L107-L111
8,971
luci/luci-go
logdog/client/cmd/logdog_butler/prefix.go
generateRandomUserPrefix
func generateRandomUserPrefix(ctx context.Context) (types.StreamName, error) { username, err := getCurrentUser() if err != nil { log.Warningf(log.SetError(ctx, err), "Failed to lookup current user name.") username = "user" } buf := make([]byte, userPrefixBytes) c, err := rand.Read(buf) if err != nil { return "", err } if c != len(buf) { return "", errors.New("main: failed to fill user prefix bytes") } streamName, err := types.MakeStreamName("s_", "butler", "users", username, base64.URLEncoding.EncodeToString(buf)) if err != nil { return "", fmt.Errorf("failed to generate user prefix: %s", err) } return streamName, nil }
go
func generateRandomUserPrefix(ctx context.Context) (types.StreamName, error) { username, err := getCurrentUser() if err != nil { log.Warningf(log.SetError(ctx, err), "Failed to lookup current user name.") username = "user" } buf := make([]byte, userPrefixBytes) c, err := rand.Read(buf) if err != nil { return "", err } if c != len(buf) { return "", errors.New("main: failed to fill user prefix bytes") } streamName, err := types.MakeStreamName("s_", "butler", "users", username, base64.URLEncoding.EncodeToString(buf)) if err != nil { return "", fmt.Errorf("failed to generate user prefix: %s", err) } return streamName, nil }
[ "func", "generateRandomUserPrefix", "(", "ctx", "context", ".", "Context", ")", "(", "types", ".", "StreamName", ",", "error", ")", "{", "username", ",", "err", ":=", "getCurrentUser", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Warningf", "(", "log", ".", "SetError", "(", "ctx", ",", "err", ")", ",", "\"", "\"", ")", "\n", "username", "=", "\"", "\"", "\n", "}", "\n\n", "buf", ":=", "make", "(", "[", "]", "byte", ",", "userPrefixBytes", ")", "\n", "c", ",", "err", ":=", "rand", ".", "Read", "(", "buf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "if", "c", "!=", "len", "(", "buf", ")", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "streamName", ",", "err", ":=", "types", ".", "MakeStreamName", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "username", ",", "base64", ".", "URLEncoding", ".", "EncodeToString", "(", "buf", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "streamName", ",", "nil", "\n", "}" ]
// generateRandomPrefix generates a new log prefix in the "user" space.
[ "generateRandomPrefix", "generates", "a", "new", "log", "prefix", "in", "the", "user", "space", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/cmd/logdog_butler/prefix.go#L46-L67
8,972
luci/luci-go
milo/frontend/view_console.go
validateFaviconURL
func validateFaviconURL(faviconURL string) error { parsedFaviconURL, err := url.Parse(faviconURL) if err != nil { return err } host := strings.SplitN(parsedFaviconURL.Host, ":", 2)[0] if host != "storage.googleapis.com" { return fmt.Errorf("%q is not a valid FaviconURL hostname", host) } return nil }
go
func validateFaviconURL(faviconURL string) error { parsedFaviconURL, err := url.Parse(faviconURL) if err != nil { return err } host := strings.SplitN(parsedFaviconURL.Host, ":", 2)[0] if host != "storage.googleapis.com" { return fmt.Errorf("%q is not a valid FaviconURL hostname", host) } return nil }
[ "func", "validateFaviconURL", "(", "faviconURL", "string", ")", "error", "{", "parsedFaviconURL", ",", "err", ":=", "url", ".", "Parse", "(", "faviconURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "host", ":=", "strings", ".", "SplitN", "(", "parsedFaviconURL", ".", "Host", ",", "\"", "\"", ",", "2", ")", "[", "0", "]", "\n", "if", "host", "!=", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "host", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// validateFaviconURL checks to see if the URL is well-formed and the host is in // the whitelist.
[ "validateFaviconURL", "checks", "to", "see", "if", "the", "URL", "is", "well", "-", "formed", "and", "the", "host", "is", "in", "the", "whitelist", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/view_console.go#L74-L84
8,973
luci/luci-go
milo/frontend/view_console.go
getConsoleGroups
func getConsoleGroups(def *config.Header, summaries map[common.ConsoleID]*ui.BuilderSummaryGroup) []ui.ConsoleGroup { if def == nil || len(def.GetConsoleGroups()) == 0 { // No header, no console groups. return nil } groups := def.GetConsoleGroups() consoleGroups := make([]ui.ConsoleGroup, len(groups)) for i, group := range groups { groupSummaries := make([]*ui.BuilderSummaryGroup, len(group.ConsoleIds)) for j, id := range group.ConsoleIds { cid, err := common.ParseConsoleID(id) if err != nil { // This should never happen, the consoleID was already validated further // upstream. panic(err) } if consoleSummary, ok := summaries[cid]; ok { groupSummaries[j] = consoleSummary } else { // This should never happen. panic(fmt.Sprintf("could not find console summary %s", id)) } } consoleGroups[i].Consoles = groupSummaries if group.Title != nil { ariaLabel := "console group " + group.Title.Text consoleGroups[i].Title = ui.NewLink(group.Title.Text, group.Title.Url, ariaLabel) consoleGroups[i].Title.Alt = group.Title.Alt } } return consoleGroups }
go
func getConsoleGroups(def *config.Header, summaries map[common.ConsoleID]*ui.BuilderSummaryGroup) []ui.ConsoleGroup { if def == nil || len(def.GetConsoleGroups()) == 0 { // No header, no console groups. return nil } groups := def.GetConsoleGroups() consoleGroups := make([]ui.ConsoleGroup, len(groups)) for i, group := range groups { groupSummaries := make([]*ui.BuilderSummaryGroup, len(group.ConsoleIds)) for j, id := range group.ConsoleIds { cid, err := common.ParseConsoleID(id) if err != nil { // This should never happen, the consoleID was already validated further // upstream. panic(err) } if consoleSummary, ok := summaries[cid]; ok { groupSummaries[j] = consoleSummary } else { // This should never happen. panic(fmt.Sprintf("could not find console summary %s", id)) } } consoleGroups[i].Consoles = groupSummaries if group.Title != nil { ariaLabel := "console group " + group.Title.Text consoleGroups[i].Title = ui.NewLink(group.Title.Text, group.Title.Url, ariaLabel) consoleGroups[i].Title.Alt = group.Title.Alt } } return consoleGroups }
[ "func", "getConsoleGroups", "(", "def", "*", "config", ".", "Header", ",", "summaries", "map", "[", "common", ".", "ConsoleID", "]", "*", "ui", ".", "BuilderSummaryGroup", ")", "[", "]", "ui", ".", "ConsoleGroup", "{", "if", "def", "==", "nil", "||", "len", "(", "def", ".", "GetConsoleGroups", "(", ")", ")", "==", "0", "{", "// No header, no console groups.", "return", "nil", "\n", "}", "\n", "groups", ":=", "def", ".", "GetConsoleGroups", "(", ")", "\n", "consoleGroups", ":=", "make", "(", "[", "]", "ui", ".", "ConsoleGroup", ",", "len", "(", "groups", ")", ")", "\n", "for", "i", ",", "group", ":=", "range", "groups", "{", "groupSummaries", ":=", "make", "(", "[", "]", "*", "ui", ".", "BuilderSummaryGroup", ",", "len", "(", "group", ".", "ConsoleIds", ")", ")", "\n", "for", "j", ",", "id", ":=", "range", "group", ".", "ConsoleIds", "{", "cid", ",", "err", ":=", "common", ".", "ParseConsoleID", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "// This should never happen, the consoleID was already validated further", "// upstream.", "panic", "(", "err", ")", "\n", "}", "\n", "if", "consoleSummary", ",", "ok", ":=", "summaries", "[", "cid", "]", ";", "ok", "{", "groupSummaries", "[", "j", "]", "=", "consoleSummary", "\n", "}", "else", "{", "// This should never happen.", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "id", ")", ")", "\n", "}", "\n", "}", "\n", "consoleGroups", "[", "i", "]", ".", "Consoles", "=", "groupSummaries", "\n", "if", "group", ".", "Title", "!=", "nil", "{", "ariaLabel", ":=", "\"", "\"", "+", "group", ".", "Title", ".", "Text", "\n", "consoleGroups", "[", "i", "]", ".", "Title", "=", "ui", ".", "NewLink", "(", "group", ".", "Title", ".", "Text", ",", "group", ".", "Title", ".", "Url", ",", "ariaLabel", ")", "\n", "consoleGroups", "[", "i", "]", ".", "Title", ".", "Alt", "=", "group", ".", "Title", ".", "Alt", "\n", "}", "\n", "}", "\n", "return", "consoleGroups", "\n", "}" ]
// getConsoleGroups extracts the console summaries for all header summaries // out of the summaries map into console groups for the header.
[ "getConsoleGroups", "extracts", "the", "console", "summaries", "for", "all", "header", "summaries", "out", "of", "the", "summaries", "map", "into", "console", "groups", "for", "the", "header", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/view_console.go#L131-L162
8,974
luci/luci-go
milo/frontend/view_console.go
getJSONData
func getJSONData(c context.Context, url string, expiration time.Duration, target interface{}) error { // Try memcache first. item := memcache.NewItem(c, "url:"+url) if err := memcache.Get(c, item); err == nil { if err = json.Unmarshal(item.Value(), target); err == nil { return nil } logging.WithError(err).Warningf(c, "couldn't load stored item from datastore") } else if err != memcache.ErrCacheMiss { logging.WithError(err).Errorf(c, "memcache is having issues") } // Fetch it from the app. transport := urlfetch.Get(c) response, err := (&http.Client{Transport: transport}).Get(url) if err != nil { return errors.Annotate(err, "failed to get data from %q", url).Err() } defer response.Body.Close() bytes, err := ioutil.ReadAll(response.Body) if err != nil { return errors.Annotate(err, "failed to read response body from %q", url).Err() } // Parse JSON into target. if err := json.Unmarshal(bytes, target); err != nil { return errors.Annotate( err, "failed to decode JSON %q from %q", bytes, url).Err() } // Save data into memcache on a best-effort basis. item.SetValue(bytes).SetExpiration(expiration) if err = memcache.Set(c, item); err != nil { logging.WithError(err).Warningf(c, "could not save url data %q into memcache", url) } return nil }
go
func getJSONData(c context.Context, url string, expiration time.Duration, target interface{}) error { // Try memcache first. item := memcache.NewItem(c, "url:"+url) if err := memcache.Get(c, item); err == nil { if err = json.Unmarshal(item.Value(), target); err == nil { return nil } logging.WithError(err).Warningf(c, "couldn't load stored item from datastore") } else if err != memcache.ErrCacheMiss { logging.WithError(err).Errorf(c, "memcache is having issues") } // Fetch it from the app. transport := urlfetch.Get(c) response, err := (&http.Client{Transport: transport}).Get(url) if err != nil { return errors.Annotate(err, "failed to get data from %q", url).Err() } defer response.Body.Close() bytes, err := ioutil.ReadAll(response.Body) if err != nil { return errors.Annotate(err, "failed to read response body from %q", url).Err() } // Parse JSON into target. if err := json.Unmarshal(bytes, target); err != nil { return errors.Annotate( err, "failed to decode JSON %q from %q", bytes, url).Err() } // Save data into memcache on a best-effort basis. item.SetValue(bytes).SetExpiration(expiration) if err = memcache.Set(c, item); err != nil { logging.WithError(err).Warningf(c, "could not save url data %q into memcache", url) } return nil }
[ "func", "getJSONData", "(", "c", "context", ".", "Context", ",", "url", "string", ",", "expiration", "time", ".", "Duration", ",", "target", "interface", "{", "}", ")", "error", "{", "// Try memcache first.", "item", ":=", "memcache", ".", "NewItem", "(", "c", ",", "\"", "\"", "+", "url", ")", "\n", "if", "err", ":=", "memcache", ".", "Get", "(", "c", ",", "item", ")", ";", "err", "==", "nil", "{", "if", "err", "=", "json", ".", "Unmarshal", "(", "item", ".", "Value", "(", ")", ",", "target", ")", ";", "err", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "logging", ".", "WithError", "(", "err", ")", ".", "Warningf", "(", "c", ",", "\"", "\"", ")", "\n", "}", "else", "if", "err", "!=", "memcache", ".", "ErrCacheMiss", "{", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Fetch it from the app.", "transport", ":=", "urlfetch", ".", "Get", "(", "c", ")", "\n", "response", ",", "err", ":=", "(", "&", "http", ".", "Client", "{", "Transport", ":", "transport", "}", ")", ".", "Get", "(", "url", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "url", ")", ".", "Err", "(", ")", "\n", "}", "\n", "defer", "response", ".", "Body", ".", "Close", "(", ")", "\n\n", "bytes", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "response", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "url", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "// Parse JSON into target.", "if", "err", ":=", "json", ".", "Unmarshal", "(", "bytes", ",", "target", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "bytes", ",", "url", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "// Save data into memcache on a best-effort basis.", "item", ".", "SetValue", "(", "bytes", ")", ".", "SetExpiration", "(", "expiration", ")", "\n", "if", "err", "=", "memcache", ".", "Set", "(", "c", ",", "item", ")", ";", "err", "!=", "nil", "{", "logging", ".", "WithError", "(", "err", ")", ".", "Warningf", "(", "c", ",", "\"", "\"", ",", "url", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// getJSONData fetches data from the given URL into the target, caching it // for expiration seconds in memcache.
[ "getJSONData", "fetches", "data", "from", "the", "given", "URL", "into", "the", "target", "caching", "it", "for", "expiration", "seconds", "in", "memcache", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/view_console.go#L291-L328
8,975
luci/luci-go
milo/frontend/view_console.go
getTreeStatus
func getTreeStatus(c context.Context, host string) *ui.TreeStatus { q := url.Values{} q.Add("format", "json") url := url.URL{ Scheme: "https", Host: host, Path: "current", RawQuery: q.Encode(), } status := &ui.TreeStatus{} if err := getJSONData(c, url.String(), 30*time.Second, status); err != nil { // Generate a fake tree status. logging.WithError(err).Errorf(c, "loading tree status") status = &ui.TreeStatus{ GeneralState: "maintenance", Message: "could not load tree status", } } return status }
go
func getTreeStatus(c context.Context, host string) *ui.TreeStatus { q := url.Values{} q.Add("format", "json") url := url.URL{ Scheme: "https", Host: host, Path: "current", RawQuery: q.Encode(), } status := &ui.TreeStatus{} if err := getJSONData(c, url.String(), 30*time.Second, status); err != nil { // Generate a fake tree status. logging.WithError(err).Errorf(c, "loading tree status") status = &ui.TreeStatus{ GeneralState: "maintenance", Message: "could not load tree status", } } return status }
[ "func", "getTreeStatus", "(", "c", "context", ".", "Context", ",", "host", "string", ")", "*", "ui", ".", "TreeStatus", "{", "q", ":=", "url", ".", "Values", "{", "}", "\n", "q", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "url", ":=", "url", ".", "URL", "{", "Scheme", ":", "\"", "\"", ",", "Host", ":", "host", ",", "Path", ":", "\"", "\"", ",", "RawQuery", ":", "q", ".", "Encode", "(", ")", ",", "}", "\n\n", "status", ":=", "&", "ui", ".", "TreeStatus", "{", "}", "\n", "if", "err", ":=", "getJSONData", "(", "c", ",", "url", ".", "String", "(", ")", ",", "30", "*", "time", ".", "Second", ",", "status", ")", ";", "err", "!=", "nil", "{", "// Generate a fake tree status.", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "status", "=", "&", "ui", ".", "TreeStatus", "{", "GeneralState", ":", "\"", "\"", ",", "Message", ":", "\"", "\"", ",", "}", "\n", "}", "\n\n", "return", "status", "\n", "}" ]
// getTreeStatus returns the current tree status from the chromium-status app. // This never errors, instead it constructs a fake purple TreeStatus
[ "getTreeStatus", "returns", "the", "current", "tree", "status", "from", "the", "chromium", "-", "status", "app", ".", "This", "never", "errors", "instead", "it", "constructs", "a", "fake", "purple", "TreeStatus" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/view_console.go#L332-L353
8,976
luci/luci-go
milo/frontend/view_console.go
getOncallData
func getOncallData(c context.Context, name, url string) (ui.Oncall, error) { result := ui.Oncall{} err := getJSONData(c, url, 10*time.Minute, &result) // Set the name, this is not loaded from the sheriff JSON. result.Name = name return result, err }
go
func getOncallData(c context.Context, name, url string) (ui.Oncall, error) { result := ui.Oncall{} err := getJSONData(c, url, 10*time.Minute, &result) // Set the name, this is not loaded from the sheriff JSON. result.Name = name return result, err }
[ "func", "getOncallData", "(", "c", "context", ".", "Context", ",", "name", ",", "url", "string", ")", "(", "ui", ".", "Oncall", ",", "error", ")", "{", "result", ":=", "ui", ".", "Oncall", "{", "}", "\n", "err", ":=", "getJSONData", "(", "c", ",", "url", ",", "10", "*", "time", ".", "Minute", ",", "&", "result", ")", "\n", "// Set the name, this is not loaded from the sheriff JSON.", "result", ".", "Name", "=", "name", "\n", "return", "result", ",", "err", "\n", "}" ]
// getOncallData fetches oncall data and caches it for 10 minutes.
[ "getOncallData", "fetches", "oncall", "data", "and", "caches", "it", "for", "10", "minutes", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/view_console.go#L356-L362
8,977
luci/luci-go
milo/frontend/view_console.go
ConsoleTable
func (c consoleRenderer) ConsoleTable() template.HTML { var buffer bytes.Buffer // The first node is a dummy node for _, column := range c.Table.Children() { column.RenderHTML(&buffer, 1, c.MaxDepth) } return template.HTML(buffer.String()) }
go
func (c consoleRenderer) ConsoleTable() template.HTML { var buffer bytes.Buffer // The first node is a dummy node for _, column := range c.Table.Children() { column.RenderHTML(&buffer, 1, c.MaxDepth) } return template.HTML(buffer.String()) }
[ "func", "(", "c", "consoleRenderer", ")", "ConsoleTable", "(", ")", "template", ".", "HTML", "{", "var", "buffer", "bytes", ".", "Buffer", "\n", "// The first node is a dummy node", "for", "_", ",", "column", ":=", "range", "c", ".", "Table", ".", "Children", "(", ")", "{", "column", ".", "RenderHTML", "(", "&", "buffer", ",", "1", ",", "c", ".", "MaxDepth", ")", "\n", "}", "\n", "return", "template", ".", "HTML", "(", "buffer", ".", "String", "(", ")", ")", "\n", "}" ]
// ConsoleTable generates the main console table html. // // This cannot be generated with templates due to the 'recursive' nature of // this layout.
[ "ConsoleTable", "generates", "the", "main", "console", "table", "html", ".", "This", "cannot", "be", "generated", "with", "templates", "due", "to", "the", "recursive", "nature", "of", "this", "layout", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/view_console.go#L447-L454
8,978
luci/luci-go
milo/frontend/view_console.go
consoleHeaderGroupIDs
func consoleHeaderGroupIDs(project string, config []*config.ConsoleSummaryGroup) ([]common.ConsoleID, error) { consoleIDSet := map[common.ConsoleID]struct{}{} for _, group := range config { for _, id := range group.ConsoleIds { if cid, err := common.ParseConsoleID(id); err != nil { return nil, err } else { consoleIDSet[cid] = struct{}{} } } } consoleIDs := make([]common.ConsoleID, 0, len(consoleIDSet)) for cid := range consoleIDSet { consoleIDs = append(consoleIDs, cid) } return consoleIDs, nil }
go
func consoleHeaderGroupIDs(project string, config []*config.ConsoleSummaryGroup) ([]common.ConsoleID, error) { consoleIDSet := map[common.ConsoleID]struct{}{} for _, group := range config { for _, id := range group.ConsoleIds { if cid, err := common.ParseConsoleID(id); err != nil { return nil, err } else { consoleIDSet[cid] = struct{}{} } } } consoleIDs := make([]common.ConsoleID, 0, len(consoleIDSet)) for cid := range consoleIDSet { consoleIDs = append(consoleIDs, cid) } return consoleIDs, nil }
[ "func", "consoleHeaderGroupIDs", "(", "project", "string", ",", "config", "[", "]", "*", "config", ".", "ConsoleSummaryGroup", ")", "(", "[", "]", "common", ".", "ConsoleID", ",", "error", ")", "{", "consoleIDSet", ":=", "map", "[", "common", ".", "ConsoleID", "]", "struct", "{", "}", "{", "}", "\n", "for", "_", ",", "group", ":=", "range", "config", "{", "for", "_", ",", "id", ":=", "range", "group", ".", "ConsoleIds", "{", "if", "cid", ",", "err", ":=", "common", ".", "ParseConsoleID", "(", "id", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "else", "{", "consoleIDSet", "[", "cid", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "consoleIDs", ":=", "make", "(", "[", "]", "common", ".", "ConsoleID", ",", "0", ",", "len", "(", "consoleIDSet", ")", ")", "\n", "for", "cid", ":=", "range", "consoleIDSet", "{", "consoleIDs", "=", "append", "(", "consoleIDs", ",", "cid", ")", "\n", "}", "\n", "return", "consoleIDs", ",", "nil", "\n", "}" ]
// consoleHeaderGroupIDs extracts the console group IDs out of the header config.
[ "consoleHeaderGroupIDs", "extracts", "the", "console", "group", "IDs", "out", "of", "the", "header", "config", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/view_console.go#L476-L492
8,979
luci/luci-go
milo/frontend/view_console.go
filterUnauthorizedBuildersFromConsoles
func filterUnauthorizedBuildersFromConsoles(c context.Context, cons []*common.Console) error { buckets := stringset.New(0) for _, con := range cons { buckets = buckets.Union(con.Buckets()) } perms, err := common.BucketPermissions(c, buckets.ToSlice()...) if err != nil { return err } for _, con := range cons { con.FilterBuilders(perms) } return nil }
go
func filterUnauthorizedBuildersFromConsoles(c context.Context, cons []*common.Console) error { buckets := stringset.New(0) for _, con := range cons { buckets = buckets.Union(con.Buckets()) } perms, err := common.BucketPermissions(c, buckets.ToSlice()...) if err != nil { return err } for _, con := range cons { con.FilterBuilders(perms) } return nil }
[ "func", "filterUnauthorizedBuildersFromConsoles", "(", "c", "context", ".", "Context", ",", "cons", "[", "]", "*", "common", ".", "Console", ")", "error", "{", "buckets", ":=", "stringset", ".", "New", "(", "0", ")", "\n", "for", "_", ",", "con", ":=", "range", "cons", "{", "buckets", "=", "buckets", ".", "Union", "(", "con", ".", "Buckets", "(", ")", ")", "\n", "}", "\n", "perms", ",", "err", ":=", "common", ".", "BucketPermissions", "(", "c", ",", "buckets", ".", "ToSlice", "(", ")", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "_", ",", "con", ":=", "range", "cons", "{", "con", ".", "FilterBuilders", "(", "perms", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// filterUnauthorizedBuildersFromConsoles filters out builders the user does not have access to.
[ "filterUnauthorizedBuildersFromConsoles", "filters", "out", "builders", "the", "user", "does", "not", "have", "access", "to", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/view_console.go#L495-L508
8,980
luci/luci-go
milo/frontend/view_console.go
ConsoleHandler
func ConsoleHandler(c *router.Context) error { project := c.Params.ByName("project") if project == "" { return errors.New("missing project", grpcutil.InvalidArgumentTag) } group := c.Params.ByName("group") // Get console from datastore and filter out builders from the definition. con, err := common.GetConsole(c.Context, project, group) switch { case err != nil: return err case con.Def.BuilderViewOnly: redirect("/p/:project/g/:group/builders", http.StatusFound)(c) return nil } defaultLimit := 50 if con.Def.DefaultCommitLimit > 0 { defaultLimit = int(con.Def.DefaultCommitLimit) } const maxLimit = 1000 limit := defaultLimit if tLimit := GetLimit(c.Request, -1); tLimit >= 0 { limit = tLimit } if limit > maxLimit { limit = maxLimit } var headerCons []*common.Console if con.Def.Header != nil { ids, err := consoleHeaderGroupIDs(project, con.Def.Header.GetConsoleGroups()) if err != nil { return err } headerCons, err = common.GetConsoles(c.Context, ids) if err != nil { return errors.Annotate(err, "error getting header consoles").Err() } } if err := filterUnauthorizedBuildersFromConsoles(c.Context, append(headerCons, con)); err != nil { return errors.Annotate(err, "error authorizing user").Err() } // Process the request and generate a renderable structure. result, err := console(c.Context, project, group, limit, con, headerCons) if err != nil { return err } var reload *int if tReload := GetReload(c.Request, -1); tReload >= 0 { reload = &tReload } templates.MustRender(c.Context, c.Writer, "pages/console.html", templates.Args{ "Console": consoleRenderer{result}, "Reload": reload, "Expand": con.Def.DefaultExpand, }) return nil }
go
func ConsoleHandler(c *router.Context) error { project := c.Params.ByName("project") if project == "" { return errors.New("missing project", grpcutil.InvalidArgumentTag) } group := c.Params.ByName("group") // Get console from datastore and filter out builders from the definition. con, err := common.GetConsole(c.Context, project, group) switch { case err != nil: return err case con.Def.BuilderViewOnly: redirect("/p/:project/g/:group/builders", http.StatusFound)(c) return nil } defaultLimit := 50 if con.Def.DefaultCommitLimit > 0 { defaultLimit = int(con.Def.DefaultCommitLimit) } const maxLimit = 1000 limit := defaultLimit if tLimit := GetLimit(c.Request, -1); tLimit >= 0 { limit = tLimit } if limit > maxLimit { limit = maxLimit } var headerCons []*common.Console if con.Def.Header != nil { ids, err := consoleHeaderGroupIDs(project, con.Def.Header.GetConsoleGroups()) if err != nil { return err } headerCons, err = common.GetConsoles(c.Context, ids) if err != nil { return errors.Annotate(err, "error getting header consoles").Err() } } if err := filterUnauthorizedBuildersFromConsoles(c.Context, append(headerCons, con)); err != nil { return errors.Annotate(err, "error authorizing user").Err() } // Process the request and generate a renderable structure. result, err := console(c.Context, project, group, limit, con, headerCons) if err != nil { return err } var reload *int if tReload := GetReload(c.Request, -1); tReload >= 0 { reload = &tReload } templates.MustRender(c.Context, c.Writer, "pages/console.html", templates.Args{ "Console": consoleRenderer{result}, "Reload": reload, "Expand": con.Def.DefaultExpand, }) return nil }
[ "func", "ConsoleHandler", "(", "c", "*", "router", ".", "Context", ")", "error", "{", "project", ":=", "c", ".", "Params", ".", "ByName", "(", "\"", "\"", ")", "\n", "if", "project", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ",", "grpcutil", ".", "InvalidArgumentTag", ")", "\n", "}", "\n", "group", ":=", "c", ".", "Params", ".", "ByName", "(", "\"", "\"", ")", "\n\n", "// Get console from datastore and filter out builders from the definition.", "con", ",", "err", ":=", "common", ".", "GetConsole", "(", "c", ".", "Context", ",", "project", ",", "group", ")", "\n", "switch", "{", "case", "err", "!=", "nil", ":", "return", "err", "\n", "case", "con", ".", "Def", ".", "BuilderViewOnly", ":", "redirect", "(", "\"", "\"", ",", "http", ".", "StatusFound", ")", "(", "c", ")", "\n", "return", "nil", "\n", "}", "\n\n", "defaultLimit", ":=", "50", "\n", "if", "con", ".", "Def", ".", "DefaultCommitLimit", ">", "0", "{", "defaultLimit", "=", "int", "(", "con", ".", "Def", ".", "DefaultCommitLimit", ")", "\n", "}", "\n", "const", "maxLimit", "=", "1000", "\n", "limit", ":=", "defaultLimit", "\n", "if", "tLimit", ":=", "GetLimit", "(", "c", ".", "Request", ",", "-", "1", ")", ";", "tLimit", ">=", "0", "{", "limit", "=", "tLimit", "\n", "}", "\n", "if", "limit", ">", "maxLimit", "{", "limit", "=", "maxLimit", "\n", "}", "\n\n", "var", "headerCons", "[", "]", "*", "common", ".", "Console", "\n", "if", "con", ".", "Def", ".", "Header", "!=", "nil", "{", "ids", ",", "err", ":=", "consoleHeaderGroupIDs", "(", "project", ",", "con", ".", "Def", ".", "Header", ".", "GetConsoleGroups", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "headerCons", ",", "err", "=", "common", ".", "GetConsoles", "(", "c", ".", "Context", ",", "ids", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "filterUnauthorizedBuildersFromConsoles", "(", "c", ".", "Context", ",", "append", "(", "headerCons", ",", "con", ")", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "// Process the request and generate a renderable structure.", "result", ",", "err", ":=", "console", "(", "c", ".", "Context", ",", "project", ",", "group", ",", "limit", ",", "con", ",", "headerCons", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "var", "reload", "*", "int", "\n", "if", "tReload", ":=", "GetReload", "(", "c", ".", "Request", ",", "-", "1", ")", ";", "tReload", ">=", "0", "{", "reload", "=", "&", "tReload", "\n", "}", "\n\n", "templates", ".", "MustRender", "(", "c", ".", "Context", ",", "c", ".", "Writer", ",", "\"", "\"", ",", "templates", ".", "Args", "{", "\"", "\"", ":", "consoleRenderer", "{", "result", "}", ",", "\"", "\"", ":", "reload", ",", "\"", "\"", ":", "con", ".", "Def", ".", "DefaultExpand", ",", "}", ")", "\n", "return", "nil", "\n", "}" ]
// ConsoleHandler renders the console page.
[ "ConsoleHandler", "renders", "the", "console", "page", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/view_console.go#L511-L573
8,981
luci/luci-go
milo/buildsource/swarming/memoryClient.go
addToStreams
func (c *memoryClient) addToStreams(s *rawpresentation.Streams, anno *miloProto.Step) error { if lds := anno.StdoutStream; lds != nil { if err := c.addLogDogTextStream(s, lds); err != nil { return fmt.Errorf( "Encountered error while processing step streams for STDOUT: %s", err) } } if lds := anno.StderrStream; lds != nil { if err := c.addLogDogTextStream(s, lds); err != nil { return fmt.Errorf( "Encountered error while processing step streams for STDERR: %s", err) } } // Look for substream. for _, link := range anno.GetOtherLinks() { lds := link.GetLogdogStream() // Not a logdog stream. if lds == nil { continue } if err := c.addLogDogTextStream(s, lds); err != nil { return fmt.Errorf( "Encountered error while processing step streams for '%s'\n%s", lds.Name, err) } } // Now do substeps. for _, subStepEntry := range anno.Substep { substep := subStepEntry.GetStep() if substep == nil { continue } if err := c.addToStreams(s, substep); err != nil { return err } } return nil }
go
func (c *memoryClient) addToStreams(s *rawpresentation.Streams, anno *miloProto.Step) error { if lds := anno.StdoutStream; lds != nil { if err := c.addLogDogTextStream(s, lds); err != nil { return fmt.Errorf( "Encountered error while processing step streams for STDOUT: %s", err) } } if lds := anno.StderrStream; lds != nil { if err := c.addLogDogTextStream(s, lds); err != nil { return fmt.Errorf( "Encountered error while processing step streams for STDERR: %s", err) } } // Look for substream. for _, link := range anno.GetOtherLinks() { lds := link.GetLogdogStream() // Not a logdog stream. if lds == nil { continue } if err := c.addLogDogTextStream(s, lds); err != nil { return fmt.Errorf( "Encountered error while processing step streams for '%s'\n%s", lds.Name, err) } } // Now do substeps. for _, subStepEntry := range anno.Substep { substep := subStepEntry.GetStep() if substep == nil { continue } if err := c.addToStreams(s, substep); err != nil { return err } } return nil }
[ "func", "(", "c", "*", "memoryClient", ")", "addToStreams", "(", "s", "*", "rawpresentation", ".", "Streams", ",", "anno", "*", "miloProto", ".", "Step", ")", "error", "{", "if", "lds", ":=", "anno", ".", "StdoutStream", ";", "lds", "!=", "nil", "{", "if", "err", ":=", "c", ".", "addLogDogTextStream", "(", "s", ",", "lds", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "if", "lds", ":=", "anno", ".", "StderrStream", ";", "lds", "!=", "nil", "{", "if", "err", ":=", "c", ".", "addLogDogTextStream", "(", "s", ",", "lds", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "// Look for substream.", "for", "_", ",", "link", ":=", "range", "anno", ".", "GetOtherLinks", "(", ")", "{", "lds", ":=", "link", ".", "GetLogdogStream", "(", ")", "\n", "// Not a logdog stream.", "if", "lds", "==", "nil", "{", "continue", "\n", "}", "\n\n", "if", "err", ":=", "c", ".", "addLogDogTextStream", "(", "s", ",", "lds", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "lds", ".", "Name", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "// Now do substeps.", "for", "_", ",", "subStepEntry", ":=", "range", "anno", ".", "Substep", "{", "substep", ":=", "subStepEntry", ".", "GetStep", "(", ")", "\n", "if", "substep", "==", "nil", "{", "continue", "\n", "}", "\n\n", "if", "err", ":=", "c", ".", "addToStreams", "(", "s", ",", "substep", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// addToStreams adds the set of stream with a given base path to the logdog // stream map. A base path is assumed to have a stream named "annotations".
[ "addToStreams", "adds", "the", "set", "of", "stream", "with", "a", "given", "base", "path", "to", "the", "logdog", "stream", "map", ".", "A", "base", "path", "is", "assumed", "to", "have", "a", "stream", "named", "annotations", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/swarming/memoryClient.go#L118-L159
8,982
luci/luci-go
vpython/spec/spec.go
NormalizeSpec
func NormalizeSpec(spec *vpython.Spec, tags []*vpython.PEP425Tag) error { // If we have a VirtualEnv package, validate and normalize it. if pkg := spec.Virtualenv; pkg != nil { if len(pkg.MatchTag) > 0 { // The VirtualEnv package may not specify a match tag. pkg.MatchTag = nil } } // Apply match filters, prune any entries that don't match, and clear the // MatchTag entries for those that do. // // Make sure the VirtualEnv package isn't listed in the wheels list. // // Track the versions for each package and assert that any duplicate packages // don't share a version. pos := 0 packageVersions := make(map[string]string, len(spec.Wheel)) for _, w := range spec.Wheel { if spec.Virtualenv != nil && spec.Virtualenv.Name == w.Name { return errors.Reason("wheel %q cannot be the VirtualEnv package", w.Name).Err() } // If this package has already been included, assert version consistency. if v, ok := packageVersions[w.Name]; ok { if v != w.Version { return errors.Reason("multiple versions for package %q: %q != %q", w.Name, w.Version, v).Err() } // This package has already been included, so we can ignore it. continue } // If this package doesn't match the tag set, skip it. if !PackageMatches(w, tags) { continue } // Mark that this package was included, so we can assert version consistency // and avoid duplicates. packageVersions[w.Name] = w.Version w.MatchTag = nil spec.Wheel[pos] = w pos++ } spec.Wheel = spec.Wheel[:pos] sort.Sort(specPackageSlice(spec.Wheel)) return nil }
go
func NormalizeSpec(spec *vpython.Spec, tags []*vpython.PEP425Tag) error { // If we have a VirtualEnv package, validate and normalize it. if pkg := spec.Virtualenv; pkg != nil { if len(pkg.MatchTag) > 0 { // The VirtualEnv package may not specify a match tag. pkg.MatchTag = nil } } // Apply match filters, prune any entries that don't match, and clear the // MatchTag entries for those that do. // // Make sure the VirtualEnv package isn't listed in the wheels list. // // Track the versions for each package and assert that any duplicate packages // don't share a version. pos := 0 packageVersions := make(map[string]string, len(spec.Wheel)) for _, w := range spec.Wheel { if spec.Virtualenv != nil && spec.Virtualenv.Name == w.Name { return errors.Reason("wheel %q cannot be the VirtualEnv package", w.Name).Err() } // If this package has already been included, assert version consistency. if v, ok := packageVersions[w.Name]; ok { if v != w.Version { return errors.Reason("multiple versions for package %q: %q != %q", w.Name, w.Version, v).Err() } // This package has already been included, so we can ignore it. continue } // If this package doesn't match the tag set, skip it. if !PackageMatches(w, tags) { continue } // Mark that this package was included, so we can assert version consistency // and avoid duplicates. packageVersions[w.Name] = w.Version w.MatchTag = nil spec.Wheel[pos] = w pos++ } spec.Wheel = spec.Wheel[:pos] sort.Sort(specPackageSlice(spec.Wheel)) return nil }
[ "func", "NormalizeSpec", "(", "spec", "*", "vpython", ".", "Spec", ",", "tags", "[", "]", "*", "vpython", ".", "PEP425Tag", ")", "error", "{", "// If we have a VirtualEnv package, validate and normalize it.", "if", "pkg", ":=", "spec", ".", "Virtualenv", ";", "pkg", "!=", "nil", "{", "if", "len", "(", "pkg", ".", "MatchTag", ")", ">", "0", "{", "// The VirtualEnv package may not specify a match tag.", "pkg", ".", "MatchTag", "=", "nil", "\n", "}", "\n", "}", "\n\n", "// Apply match filters, prune any entries that don't match, and clear the", "// MatchTag entries for those that do.", "//", "// Make sure the VirtualEnv package isn't listed in the wheels list.", "//", "// Track the versions for each package and assert that any duplicate packages", "// don't share a version.", "pos", ":=", "0", "\n", "packageVersions", ":=", "make", "(", "map", "[", "string", "]", "string", ",", "len", "(", "spec", ".", "Wheel", ")", ")", "\n", "for", "_", ",", "w", ":=", "range", "spec", ".", "Wheel", "{", "if", "spec", ".", "Virtualenv", "!=", "nil", "&&", "spec", ".", "Virtualenv", ".", "Name", "==", "w", ".", "Name", "{", "return", "errors", ".", "Reason", "(", "\"", "\"", ",", "w", ".", "Name", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "// If this package has already been included, assert version consistency.", "if", "v", ",", "ok", ":=", "packageVersions", "[", "w", ".", "Name", "]", ";", "ok", "{", "if", "v", "!=", "w", ".", "Version", "{", "return", "errors", ".", "Reason", "(", "\"", "\"", ",", "w", ".", "Name", ",", "w", ".", "Version", ",", "v", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "// This package has already been included, so we can ignore it.", "continue", "\n", "}", "\n\n", "// If this package doesn't match the tag set, skip it.", "if", "!", "PackageMatches", "(", "w", ",", "tags", ")", "{", "continue", "\n", "}", "\n\n", "// Mark that this package was included, so we can assert version consistency", "// and avoid duplicates.", "packageVersions", "[", "w", ".", "Name", "]", "=", "w", ".", "Version", "\n", "w", ".", "MatchTag", "=", "nil", "\n", "spec", ".", "Wheel", "[", "pos", "]", "=", "w", "\n", "pos", "++", "\n", "}", "\n", "spec", ".", "Wheel", "=", "spec", ".", "Wheel", "[", ":", "pos", "]", "\n", "sort", ".", "Sort", "(", "specPackageSlice", "(", "spec", ".", "Wheel", ")", ")", "\n", "return", "nil", "\n", "}" ]
// NormalizeSpec normalizes the specification Message such that two messages // with identical meaning will have identical representation. // // If multiple wheel entries exist for the same package name, they must also // share a version. If they don't, an error will be returned. Otherwise, they // will be merged into a single wheel entry. // // NormalizeSpec will prune any Wheel entries that don't match the specified // tags, and will remove the match entries from any remaining Wheel entries.
[ "NormalizeSpec", "normalizes", "the", "specification", "Message", "such", "that", "two", "messages", "with", "identical", "meaning", "will", "have", "identical", "representation", ".", "If", "multiple", "wheel", "entries", "exist", "for", "the", "same", "package", "name", "they", "must", "also", "share", "a", "version", ".", "If", "they", "don", "t", "an", "error", "will", "be", "returned", ".", "Otherwise", "they", "will", "be", "merged", "into", "a", "single", "wheel", "entry", ".", "NormalizeSpec", "will", "prune", "any", "Wheel", "entries", "that", "don", "t", "match", "the", "specified", "tags", "and", "will", "remove", "the", "match", "entries", "from", "any", "remaining", "Wheel", "entries", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/spec/spec.go#L43-L91
8,983
luci/luci-go
vpython/spec/spec.go
Hash
func Hash(spec *vpython.Spec, rt *vpython.Runtime, extra ...string) string { mustMarshal := func(msg proto.Message) []byte { data, err := proto.Marshal(msg) if err != nil { panic(fmt.Errorf("failed to marshal proto: %v", err)) } return data } specData := mustMarshal(spec) rtData := mustMarshal(rt) mustWrite := func(v int, err error) { if err != nil { panic(fmt.Errorf("impossible: %s", err)) } } hash := sha256.New() for _, s := range extra { mustWrite(fmt.Fprintf(hash, "%s:", s)) } mustWrite(fmt.Fprintf(hash, "%s:", vpython.Version)) mustWrite(hash.Write(specData)) mustWrite(hash.Write([]byte(":"))) mustWrite(hash.Write(rtData)) return hex.EncodeToString(hash.Sum(nil)) }
go
func Hash(spec *vpython.Spec, rt *vpython.Runtime, extra ...string) string { mustMarshal := func(msg proto.Message) []byte { data, err := proto.Marshal(msg) if err != nil { panic(fmt.Errorf("failed to marshal proto: %v", err)) } return data } specData := mustMarshal(spec) rtData := mustMarshal(rt) mustWrite := func(v int, err error) { if err != nil { panic(fmt.Errorf("impossible: %s", err)) } } hash := sha256.New() for _, s := range extra { mustWrite(fmt.Fprintf(hash, "%s:", s)) } mustWrite(fmt.Fprintf(hash, "%s:", vpython.Version)) mustWrite(hash.Write(specData)) mustWrite(hash.Write([]byte(":"))) mustWrite(hash.Write(rtData)) return hex.EncodeToString(hash.Sum(nil)) }
[ "func", "Hash", "(", "spec", "*", "vpython", ".", "Spec", ",", "rt", "*", "vpython", ".", "Runtime", ",", "extra", "...", "string", ")", "string", "{", "mustMarshal", ":=", "func", "(", "msg", "proto", ".", "Message", ")", "[", "]", "byte", "{", "data", ",", "err", ":=", "proto", ".", "Marshal", "(", "msg", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n", "return", "data", "\n", "}", "\n", "specData", ":=", "mustMarshal", "(", "spec", ")", "\n", "rtData", ":=", "mustMarshal", "(", "rt", ")", "\n\n", "mustWrite", ":=", "func", "(", "v", "int", ",", "err", "error", ")", "{", "if", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n", "}", "\n\n", "hash", ":=", "sha256", ".", "New", "(", ")", "\n", "for", "_", ",", "s", ":=", "range", "extra", "{", "mustWrite", "(", "fmt", ".", "Fprintf", "(", "hash", ",", "\"", "\"", ",", "s", ")", ")", "\n", "}", "\n", "mustWrite", "(", "fmt", ".", "Fprintf", "(", "hash", ",", "\"", "\"", ",", "vpython", ".", "Version", ")", ")", "\n", "mustWrite", "(", "hash", ".", "Write", "(", "specData", ")", ")", "\n", "mustWrite", "(", "hash", ".", "Write", "(", "[", "]", "byte", "(", "\"", "\"", ")", ")", ")", "\n", "mustWrite", "(", "hash", ".", "Write", "(", "rtData", ")", ")", "\n", "return", "hex", ".", "EncodeToString", "(", "hash", ".", "Sum", "(", "nil", ")", ")", "\n", "}" ]
// Hash hashes the contents of the supplied "spec" and "rt" and returns the // result as a hex-encoded string. // // If not empty, the contents of extra are prefixed to hash string. This can // be used to factor additional influences into the spec hash.
[ "Hash", "hashes", "the", "contents", "of", "the", "supplied", "spec", "and", "rt", "and", "returns", "the", "result", "as", "a", "hex", "-", "encoded", "string", ".", "If", "not", "empty", "the", "contents", "of", "extra", "are", "prefixed", "to", "hash", "string", ".", "This", "can", "be", "used", "to", "factor", "additional", "influences", "into", "the", "spec", "hash", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/spec/spec.go#L98-L124
8,984
luci/luci-go
client/cmd/swarming/collect.go
summarizeResultsPython
func summarizeResultsPython(results []taskResult) ([]byte, error) { var shards []map[string]interface{} for _, result := range results { buf, err := json.Marshal(result.result) if err != nil { return nil, err } var jsonResult map[string]interface{} if err := json.Unmarshal(buf, &jsonResult); err != nil { return nil, err } if jsonResult != nil { jsonResult["output"] = result.output } shards = append(shards, jsonResult) } return json.MarshalIndent(map[string]interface{}{ "shards": shards, }, "", " ") }
go
func summarizeResultsPython(results []taskResult) ([]byte, error) { var shards []map[string]interface{} for _, result := range results { buf, err := json.Marshal(result.result) if err != nil { return nil, err } var jsonResult map[string]interface{} if err := json.Unmarshal(buf, &jsonResult); err != nil { return nil, err } if jsonResult != nil { jsonResult["output"] = result.output } shards = append(shards, jsonResult) } return json.MarshalIndent(map[string]interface{}{ "shards": shards, }, "", " ") }
[ "func", "summarizeResultsPython", "(", "results", "[", "]", "taskResult", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "shards", "[", "]", "map", "[", "string", "]", "interface", "{", "}", "\n\n", "for", "_", ",", "result", ":=", "range", "results", "{", "buf", ",", "err", ":=", "json", ".", "Marshal", "(", "result", ".", "result", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "var", "jsonResult", "map", "[", "string", "]", "interface", "{", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "buf", ",", "&", "jsonResult", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "if", "jsonResult", "!=", "nil", "{", "jsonResult", "[", "\"", "\"", "]", "=", "result", ".", "output", "\n", "}", "\n", "shards", "=", "append", "(", "shards", ",", "jsonResult", ")", "\n", "}", "\n\n", "return", "json", ".", "MarshalIndent", "(", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "shards", ",", "}", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}" ]
// summarizeResultsPython generates summary JSON file compatible with python's // swarming client.
[ "summarizeResultsPython", "generates", "summary", "JSON", "file", "compatible", "with", "python", "s", "swarming", "client", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/cmd/swarming/collect.go#L317-L340
8,985
luci/luci-go
client/cmd/swarming/collect.go
summarizeResults
func (c *collectRun) summarizeResults(results []taskResult) ([]byte, error) { if c.taskSummaryPython { return summarizeResultsPython(results) } jsonResults := map[string]interface{}{} for _, result := range results { jsonResult := map[string]interface{}{} if result.err != nil { jsonResult["error"] = result.err.Error() } if result.result != nil { jsonResult["results"] = *result.result if c.taskOutput.includesJSON() { jsonResult["output"] = result.output } jsonResult["outputs"] = result.outputs } jsonResults[result.taskID] = jsonResult } return json.MarshalIndent(jsonResults, "", " ") }
go
func (c *collectRun) summarizeResults(results []taskResult) ([]byte, error) { if c.taskSummaryPython { return summarizeResultsPython(results) } jsonResults := map[string]interface{}{} for _, result := range results { jsonResult := map[string]interface{}{} if result.err != nil { jsonResult["error"] = result.err.Error() } if result.result != nil { jsonResult["results"] = *result.result if c.taskOutput.includesJSON() { jsonResult["output"] = result.output } jsonResult["outputs"] = result.outputs } jsonResults[result.taskID] = jsonResult } return json.MarshalIndent(jsonResults, "", " ") }
[ "func", "(", "c", "*", "collectRun", ")", "summarizeResults", "(", "results", "[", "]", "taskResult", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "c", ".", "taskSummaryPython", "{", "return", "summarizeResultsPython", "(", "results", ")", "\n", "}", "\n\n", "jsonResults", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "}", "\n", "for", "_", ",", "result", ":=", "range", "results", "{", "jsonResult", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "}", "\n", "if", "result", ".", "err", "!=", "nil", "{", "jsonResult", "[", "\"", "\"", "]", "=", "result", ".", "err", ".", "Error", "(", ")", "\n", "}", "\n", "if", "result", ".", "result", "!=", "nil", "{", "jsonResult", "[", "\"", "\"", "]", "=", "*", "result", ".", "result", "\n", "if", "c", ".", "taskOutput", ".", "includesJSON", "(", ")", "{", "jsonResult", "[", "\"", "\"", "]", "=", "result", ".", "output", "\n", "}", "\n", "jsonResult", "[", "\"", "\"", "]", "=", "result", ".", "outputs", "\n", "}", "\n", "jsonResults", "[", "result", ".", "taskID", "]", "=", "jsonResult", "\n", "}", "\n", "return", "json", ".", "MarshalIndent", "(", "jsonResults", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}" ]
// summarizeResults generate a marshalled JSON summary of the task results.
[ "summarizeResults", "generate", "a", "marshalled", "JSON", "summary", "of", "the", "task", "results", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/cmd/swarming/collect.go#L343-L364
8,986
luci/luci-go
cipd/appengine/impl/model/txn.go
Txn
func Txn(c context.Context, name string, cb func(context.Context) error) error { c = logging.SetField(c, "txn", name) var attempt int var innerErr error err := datastore.RunInTransaction(c, func(c context.Context) error { attempt++ if attempt != 1 { logging.Warningf(c, "Retrying the transaction: failed to commit") } innerErr = cb(c) return innerErr }, nil) if err != innerErr { return errors.Annotate(err, "failed to land %s transaction", name).Tag(transient.Tag).Err() } return innerErr }
go
func Txn(c context.Context, name string, cb func(context.Context) error) error { c = logging.SetField(c, "txn", name) var attempt int var innerErr error err := datastore.RunInTransaction(c, func(c context.Context) error { attempt++ if attempt != 1 { logging.Warningf(c, "Retrying the transaction: failed to commit") } innerErr = cb(c) return innerErr }, nil) if err != innerErr { return errors.Annotate(err, "failed to land %s transaction", name).Tag(transient.Tag).Err() } return innerErr }
[ "func", "Txn", "(", "c", "context", ".", "Context", ",", "name", "string", ",", "cb", "func", "(", "context", ".", "Context", ")", "error", ")", "error", "{", "c", "=", "logging", ".", "SetField", "(", "c", ",", "\"", "\"", ",", "name", ")", "\n\n", "var", "attempt", "int", "\n", "var", "innerErr", "error", "\n\n", "err", ":=", "datastore", ".", "RunInTransaction", "(", "c", ",", "func", "(", "c", "context", ".", "Context", ")", "error", "{", "attempt", "++", "\n", "if", "attempt", "!=", "1", "{", "logging", ".", "Warningf", "(", "c", ",", "\"", "\"", ")", "\n", "}", "\n", "innerErr", "=", "cb", "(", "c", ")", "\n", "return", "innerErr", "\n", "}", ",", "nil", ")", "\n\n", "if", "err", "!=", "innerErr", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "name", ")", ".", "Tag", "(", "transient", ".", "Tag", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "innerErr", "\n", "}" ]
// Txn runs the callback in a datastore transaction, marking commit errors with // transient tag. // // The given name will be used for logging and error messages.
[ "Txn", "runs", "the", "callback", "in", "a", "datastore", "transaction", "marking", "commit", "errors", "with", "transient", "tag", ".", "The", "given", "name", "will", "be", "used", "for", "logging", "and", "error", "messages", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/model/txn.go#L30-L49
8,987
luci/luci-go
logdog/server/service/config/poller.go
Run
func (p *ChangePoller) Run(c context.Context) { if p.Period <= 0 { return } for { // If our Context has been canceled, terminate. select { case <-c.Done(): log.WithError(c.Err()).Warningf(c, "Terminating poll loop: context has been cancelled.") return default: // Continue } log.Fields{ "timeout": p.Period, }.Debugf(c, "Entering change check poll loop...") if tr := clock.Sleep(c, p.Period); tr.Incomplete() { log.WithError(tr.Err).Debugf(c, "Context cancelled, shutting down change poller.") return } log.Infof(c, "Change check timeout triggered, checking configuration...") lastHash := p.ContentHash switch err := p.Refresh(c); { case err != nil: log.WithError(err).Errorf(c, "Failed to refresh config.") case lastHash != p.ContentHash: log.Fields{ "originalHash": lastHash, "newHash": p.ContentHash, }.Warningf(c, "Configuration content hash has changed.") if p.OnChange != nil { p.OnChange() } default: log.Fields{ "currentHash": lastHash, }.Debugf(c, "Content hash matches.") } } }
go
func (p *ChangePoller) Run(c context.Context) { if p.Period <= 0 { return } for { // If our Context has been canceled, terminate. select { case <-c.Done(): log.WithError(c.Err()).Warningf(c, "Terminating poll loop: context has been cancelled.") return default: // Continue } log.Fields{ "timeout": p.Period, }.Debugf(c, "Entering change check poll loop...") if tr := clock.Sleep(c, p.Period); tr.Incomplete() { log.WithError(tr.Err).Debugf(c, "Context cancelled, shutting down change poller.") return } log.Infof(c, "Change check timeout triggered, checking configuration...") lastHash := p.ContentHash switch err := p.Refresh(c); { case err != nil: log.WithError(err).Errorf(c, "Failed to refresh config.") case lastHash != p.ContentHash: log.Fields{ "originalHash": lastHash, "newHash": p.ContentHash, }.Warningf(c, "Configuration content hash has changed.") if p.OnChange != nil { p.OnChange() } default: log.Fields{ "currentHash": lastHash, }.Debugf(c, "Content hash matches.") } } }
[ "func", "(", "p", "*", "ChangePoller", ")", "Run", "(", "c", "context", ".", "Context", ")", "{", "if", "p", ".", "Period", "<=", "0", "{", "return", "\n", "}", "\n\n", "for", "{", "// If our Context has been canceled, terminate.", "select", "{", "case", "<-", "c", ".", "Done", "(", ")", ":", "log", ".", "WithError", "(", "c", ".", "Err", "(", ")", ")", ".", "Warningf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "\n", "default", ":", "// Continue", "}", "\n\n", "log", ".", "Fields", "{", "\"", "\"", ":", "p", ".", "Period", ",", "}", ".", "Debugf", "(", "c", ",", "\"", "\"", ")", "\n", "if", "tr", ":=", "clock", ".", "Sleep", "(", "c", ",", "p", ".", "Period", ")", ";", "tr", ".", "Incomplete", "(", ")", "{", "log", ".", "WithError", "(", "tr", ".", "Err", ")", ".", "Debugf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "log", ".", "Infof", "(", "c", ",", "\"", "\"", ")", "\n", "lastHash", ":=", "p", ".", "ContentHash", "\n", "switch", "err", ":=", "p", ".", "Refresh", "(", "c", ")", ";", "{", "case", "err", "!=", "nil", ":", "log", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n\n", "case", "lastHash", "!=", "p", ".", "ContentHash", ":", "log", ".", "Fields", "{", "\"", "\"", ":", "lastHash", ",", "\"", "\"", ":", "p", ".", "ContentHash", ",", "}", ".", "Warningf", "(", "c", ",", "\"", "\"", ")", "\n", "if", "p", ".", "OnChange", "!=", "nil", "{", "p", ".", "OnChange", "(", ")", "\n", "}", "\n\n", "default", ":", "log", ".", "Fields", "{", "\"", "\"", ":", "lastHash", ",", "}", ".", "Debugf", "(", "c", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Run starts polling for changes. It will stop when the Context is cancelled.
[ "Run", "starts", "polling", "for", "changes", ".", "It", "will", "stop", "when", "the", "Context", "is", "cancelled", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/server/service/config/poller.go#L54-L98
8,988
luci/luci-go
logdog/server/service/config/poller.go
Refresh
func (p *ChangePoller) Refresh(c context.Context) error { var meta config.Meta if err := cfgclient.Get(c, cfgclient.AsService, p.ConfigSet, p.Path, nil, &meta); err != nil { return errors.Annotate(err, "failed to reload config %s :: %s", p.ConfigSet, p.Path).Err() } p.ContentHash = meta.ContentHash return nil }
go
func (p *ChangePoller) Refresh(c context.Context) error { var meta config.Meta if err := cfgclient.Get(c, cfgclient.AsService, p.ConfigSet, p.Path, nil, &meta); err != nil { return errors.Annotate(err, "failed to reload config %s :: %s", p.ConfigSet, p.Path).Err() } p.ContentHash = meta.ContentHash return nil }
[ "func", "(", "p", "*", "ChangePoller", ")", "Refresh", "(", "c", "context", ".", "Context", ")", "error", "{", "var", "meta", "config", ".", "Meta", "\n", "if", "err", ":=", "cfgclient", ".", "Get", "(", "c", ",", "cfgclient", ".", "AsService", ",", "p", ".", "ConfigSet", ",", "p", ".", "Path", ",", "nil", ",", "&", "meta", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "p", ".", "ConfigSet", ",", "p", ".", "Path", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "p", ".", "ContentHash", "=", "meta", ".", "ContentHash", "\n", "return", "nil", "\n", "}" ]
// Refresh reloads the configuration value, updating ContentHash.
[ "Refresh", "reloads", "the", "configuration", "value", "updating", "ContentHash", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/server/service/config/poller.go#L101-L109
8,989
luci/luci-go
cipd/appengine/impl/settings/settings.go
Get
func Get(ctx context.Context) (*Settings, error) { s := &Settings{} if err := settings.Get(ctx, settingsKey, s); err != nil && err != settings.ErrNoSettings { return nil, errors.Annotate(err, "failed to fetch settings"). Tag(grpcutil.InternalTag, transient.Tag).Err() } if s.StorageGSPath == "" || s.TempGSPath == "" { return nil, errors.Reason("the backend is not configured"). Tag(grpcutil.InternalTag).Err() } return s, nil }
go
func Get(ctx context.Context) (*Settings, error) { s := &Settings{} if err := settings.Get(ctx, settingsKey, s); err != nil && err != settings.ErrNoSettings { return nil, errors.Annotate(err, "failed to fetch settings"). Tag(grpcutil.InternalTag, transient.Tag).Err() } if s.StorageGSPath == "" || s.TempGSPath == "" { return nil, errors.Reason("the backend is not configured"). Tag(grpcutil.InternalTag).Err() } return s, nil }
[ "func", "Get", "(", "ctx", "context", ".", "Context", ")", "(", "*", "Settings", ",", "error", ")", "{", "s", ":=", "&", "Settings", "{", "}", "\n", "if", "err", ":=", "settings", ".", "Get", "(", "ctx", ",", "settingsKey", ",", "s", ")", ";", "err", "!=", "nil", "&&", "err", "!=", "settings", ".", "ErrNoSettings", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Tag", "(", "grpcutil", ".", "InternalTag", ",", "transient", ".", "Tag", ")", ".", "Err", "(", ")", "\n", "}", "\n", "if", "s", ".", "StorageGSPath", "==", "\"", "\"", "||", "s", ".", "TempGSPath", "==", "\"", "\"", "{", "return", "nil", ",", "errors", ".", "Reason", "(", "\"", "\"", ")", ".", "Tag", "(", "grpcutil", ".", "InternalTag", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "s", ",", "nil", "\n", "}" ]
// Get returns the settings from the local cache, checking they are populated. // // Returns grpc-annotated Internal error if something is wrong.
[ "Get", "returns", "the", "settings", "from", "the", "local", "cache", "checking", "they", "are", "populated", ".", "Returns", "grpc", "-", "annotated", "Internal", "error", "if", "something", "is", "wrong", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/settings/settings.go#L63-L74
8,990
luci/luci-go
cipd/appengine/impl/settings/settings.go
ObjectPath
func (s *Settings) ObjectPath(obj *api.ObjectRef) string { return s.StorageGSPath + "/" + obj.HashAlgo.String() + "/" + obj.HexDigest }
go
func (s *Settings) ObjectPath(obj *api.ObjectRef) string { return s.StorageGSPath + "/" + obj.HashAlgo.String() + "/" + obj.HexDigest }
[ "func", "(", "s", "*", "Settings", ")", "ObjectPath", "(", "obj", "*", "api", ".", "ObjectRef", ")", "string", "{", "return", "s", ".", "StorageGSPath", "+", "\"", "\"", "+", "obj", ".", "HashAlgo", ".", "String", "(", ")", "+", "\"", "\"", "+", "obj", ".", "HexDigest", "\n", "}" ]
// ObjectPath constructs a path to the object in the Google Storage, starting // from StorageGSPath root.
[ "ObjectPath", "constructs", "a", "path", "to", "the", "object", "in", "the", "Google", "Storage", "starting", "from", "StorageGSPath", "root", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/settings/settings.go#L78-L80
8,991
luci/luci-go
auth/client/authcli/authcli.go
Register
func (fl *Flags) Register(f *flag.FlagSet, defaults auth.Options) { fl.defaults = defaults f.StringVar(&fl.serviceAccountJSON, "service-account-json", fl.defaults.ServiceAccountJSONPath, "Path to JSON file with service account credentials to use.") if fl.RegisterScopesFlag { defaultScopes := strings.Join(defaults.Scopes, " ") if defaultScopes == "" { defaultScopes = auth.OAuthScopeEmail } f.StringVar(&fl.scopes, "scopes", defaultScopes, "space-separated OAuth 2.0 scopes") } }
go
func (fl *Flags) Register(f *flag.FlagSet, defaults auth.Options) { fl.defaults = defaults f.StringVar(&fl.serviceAccountJSON, "service-account-json", fl.defaults.ServiceAccountJSONPath, "Path to JSON file with service account credentials to use.") if fl.RegisterScopesFlag { defaultScopes := strings.Join(defaults.Scopes, " ") if defaultScopes == "" { defaultScopes = auth.OAuthScopeEmail } f.StringVar(&fl.scopes, "scopes", defaultScopes, "space-separated OAuth 2.0 scopes") } }
[ "func", "(", "fl", "*", "Flags", ")", "Register", "(", "f", "*", "flag", ".", "FlagSet", ",", "defaults", "auth", ".", "Options", ")", "{", "fl", ".", "defaults", "=", "defaults", "\n", "f", ".", "StringVar", "(", "&", "fl", ".", "serviceAccountJSON", ",", "\"", "\"", ",", "fl", ".", "defaults", ".", "ServiceAccountJSONPath", ",", "\"", "\"", ")", "\n", "if", "fl", ".", "RegisterScopesFlag", "{", "defaultScopes", ":=", "strings", ".", "Join", "(", "defaults", ".", "Scopes", ",", "\"", "\"", ")", "\n", "if", "defaultScopes", "==", "\"", "\"", "{", "defaultScopes", "=", "auth", ".", "OAuthScopeEmail", "\n", "}", "\n", "f", ".", "StringVar", "(", "&", "fl", ".", "scopes", ",", "\"", "\"", ",", "defaultScopes", ",", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// Register adds auth related flags to a FlagSet.
[ "Register", "adds", "auth", "related", "flags", "to", "a", "FlagSet", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/client/authcli/authcli.go#L133-L143
8,992
luci/luci-go
auth/client/authcli/authcli.go
Options
func (fl *Flags) Options() (auth.Options, error) { opts := fl.defaults opts.ServiceAccountJSONPath = fl.serviceAccountJSON if fl.RegisterScopesFlag { opts.Scopes = strings.Split(fl.scopes, " ") sort.Strings(opts.Scopes) } return opts, nil }
go
func (fl *Flags) Options() (auth.Options, error) { opts := fl.defaults opts.ServiceAccountJSONPath = fl.serviceAccountJSON if fl.RegisterScopesFlag { opts.Scopes = strings.Split(fl.scopes, " ") sort.Strings(opts.Scopes) } return opts, nil }
[ "func", "(", "fl", "*", "Flags", ")", "Options", "(", ")", "(", "auth", ".", "Options", ",", "error", ")", "{", "opts", ":=", "fl", ".", "defaults", "\n", "opts", ".", "ServiceAccountJSONPath", "=", "fl", ".", "serviceAccountJSON", "\n", "if", "fl", ".", "RegisterScopesFlag", "{", "opts", ".", "Scopes", "=", "strings", ".", "Split", "(", "fl", ".", "scopes", ",", "\"", "\"", ")", "\n", "sort", ".", "Strings", "(", "opts", ".", "Scopes", ")", "\n", "}", "\n", "return", "opts", ",", "nil", "\n", "}" ]
// Options return instance of auth.Options struct with values set accordingly to // parsed command line flags.
[ "Options", "return", "instance", "of", "auth", ".", "Options", "struct", "with", "values", "set", "accordingly", "to", "parsed", "command", "line", "flags", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/client/authcli/authcli.go#L147-L155
8,993
luci/luci-go
auth/client/authcli/authcli.go
SubcommandLoginWithParams
func SubcommandLoginWithParams(params CommandParams) *subcommands.Command { return &subcommands.Command{ Advanced: params.Advanced, UsageLine: params.Name, ShortDesc: "performs interactive login flow", LongDesc: "Performs interactive login flow and caches obtained credentials", CommandRun: func() subcommands.CommandRun { c := &loginRun{} c.params = &params c.registerBaseFlags() return c }, } }
go
func SubcommandLoginWithParams(params CommandParams) *subcommands.Command { return &subcommands.Command{ Advanced: params.Advanced, UsageLine: params.Name, ShortDesc: "performs interactive login flow", LongDesc: "Performs interactive login flow and caches obtained credentials", CommandRun: func() subcommands.CommandRun { c := &loginRun{} c.params = &params c.registerBaseFlags() return c }, } }
[ "func", "SubcommandLoginWithParams", "(", "params", "CommandParams", ")", "*", "subcommands", ".", "Command", "{", "return", "&", "subcommands", ".", "Command", "{", "Advanced", ":", "params", ".", "Advanced", ",", "UsageLine", ":", "params", ".", "Name", ",", "ShortDesc", ":", "\"", "\"", ",", "LongDesc", ":", "\"", "\"", ",", "CommandRun", ":", "func", "(", ")", "subcommands", ".", "CommandRun", "{", "c", ":=", "&", "loginRun", "{", "}", "\n", "c", ".", "params", "=", "&", "params", "\n", "c", ".", "registerBaseFlags", "(", ")", "\n", "return", "c", "\n", "}", ",", "}", "\n", "}" ]
// SubcommandLoginWithParams returns subcommands.Command that can be used to // perform interactive login.
[ "SubcommandLoginWithParams", "returns", "subcommands", ".", "Command", "that", "can", "be", "used", "to", "perform", "interactive", "login", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/client/authcli/authcli.go#L187-L200
8,994
luci/luci-go
auth/client/authcli/authcli.go
SubcommandLogoutWithParams
func SubcommandLogoutWithParams(params CommandParams) *subcommands.Command { return &subcommands.Command{ Advanced: params.Advanced, UsageLine: params.Name, ShortDesc: "removes cached credentials", LongDesc: "Removes cached credentials from the disk", CommandRun: func() subcommands.CommandRun { c := &logoutRun{} c.params = &params c.registerBaseFlags() return c }, } }
go
func SubcommandLogoutWithParams(params CommandParams) *subcommands.Command { return &subcommands.Command{ Advanced: params.Advanced, UsageLine: params.Name, ShortDesc: "removes cached credentials", LongDesc: "Removes cached credentials from the disk", CommandRun: func() subcommands.CommandRun { c := &logoutRun{} c.params = &params c.registerBaseFlags() return c }, } }
[ "func", "SubcommandLogoutWithParams", "(", "params", "CommandParams", ")", "*", "subcommands", ".", "Command", "{", "return", "&", "subcommands", ".", "Command", "{", "Advanced", ":", "params", ".", "Advanced", ",", "UsageLine", ":", "params", ".", "Name", ",", "ShortDesc", ":", "\"", "\"", ",", "LongDesc", ":", "\"", "\"", ",", "CommandRun", ":", "func", "(", ")", "subcommands", ".", "CommandRun", "{", "c", ":=", "&", "logoutRun", "{", "}", "\n", "c", ".", "params", "=", "&", "params", "\n", "c", ".", "registerBaseFlags", "(", ")", "\n", "return", "c", "\n", "}", ",", "}", "\n", "}" ]
// SubcommandLogoutWithParams returns subcommands.Command that can be used to purge cached // credentials.
[ "SubcommandLogoutWithParams", "returns", "subcommands", ".", "Command", "that", "can", "be", "used", "to", "purge", "cached", "credentials", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/client/authcli/authcli.go#L231-L244
8,995
luci/luci-go
auth/client/authcli/authcli.go
SubcommandInfoWithParams
func SubcommandInfoWithParams(params CommandParams) *subcommands.Command { return &subcommands.Command{ Advanced: params.Advanced, UsageLine: params.Name, ShortDesc: "prints an email address associated with currently cached token", LongDesc: "Prints an email address associated with currently cached token", CommandRun: func() subcommands.CommandRun { c := &infoRun{} c.params = &params c.registerBaseFlags() return c }, } }
go
func SubcommandInfoWithParams(params CommandParams) *subcommands.Command { return &subcommands.Command{ Advanced: params.Advanced, UsageLine: params.Name, ShortDesc: "prints an email address associated with currently cached token", LongDesc: "Prints an email address associated with currently cached token", CommandRun: func() subcommands.CommandRun { c := &infoRun{} c.params = &params c.registerBaseFlags() return c }, } }
[ "func", "SubcommandInfoWithParams", "(", "params", "CommandParams", ")", "*", "subcommands", ".", "Command", "{", "return", "&", "subcommands", ".", "Command", "{", "Advanced", ":", "params", ".", "Advanced", ",", "UsageLine", ":", "params", ".", "Name", ",", "ShortDesc", ":", "\"", "\"", ",", "LongDesc", ":", "\"", "\"", ",", "CommandRun", ":", "func", "(", ")", "subcommands", ".", "CommandRun", "{", "c", ":=", "&", "infoRun", "{", "}", "\n", "c", ".", "params", "=", "&", "params", "\n", "c", ".", "registerBaseFlags", "(", ")", "\n", "return", "c", "\n", "}", ",", "}", "\n", "}" ]
// SubcommandInfoWithParams returns subcommand.Command that can be used to print // current cached credentials.
[ "SubcommandInfoWithParams", "returns", "subcommand", ".", "Command", "that", "can", "be", "used", "to", "print", "current", "cached", "credentials", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/client/authcli/authcli.go#L275-L288
8,996
luci/luci-go
auth/client/authcli/authcli.go
SubcommandTokenWithParams
func SubcommandTokenWithParams(params CommandParams) *subcommands.Command { return &subcommands.Command{ Advanced: params.Advanced, UsageLine: params.Name, ShortDesc: "prints an access token", LongDesc: "Generates an access token if requested and prints it.", CommandRun: func() subcommands.CommandRun { c := &tokenRun{} c.params = &params c.registerBaseFlags() c.Flags.DurationVar( &c.lifetime, "lifetime", time.Minute, "Minimum token lifetime. If existing token expired and refresh token or service account is not present, returns nothing.", ) c.Flags.StringVar( &c.jsonOutput, "json-output", "", "Destination file to print token and expiration time in JSON. \"-\" for standard output.") return c }, } }
go
func SubcommandTokenWithParams(params CommandParams) *subcommands.Command { return &subcommands.Command{ Advanced: params.Advanced, UsageLine: params.Name, ShortDesc: "prints an access token", LongDesc: "Generates an access token if requested and prints it.", CommandRun: func() subcommands.CommandRun { c := &tokenRun{} c.params = &params c.registerBaseFlags() c.Flags.DurationVar( &c.lifetime, "lifetime", time.Minute, "Minimum token lifetime. If existing token expired and refresh token or service account is not present, returns nothing.", ) c.Flags.StringVar( &c.jsonOutput, "json-output", "", "Destination file to print token and expiration time in JSON. \"-\" for standard output.") return c }, } }
[ "func", "SubcommandTokenWithParams", "(", "params", "CommandParams", ")", "*", "subcommands", ".", "Command", "{", "return", "&", "subcommands", ".", "Command", "{", "Advanced", ":", "params", ".", "Advanced", ",", "UsageLine", ":", "params", ".", "Name", ",", "ShortDesc", ":", "\"", "\"", ",", "LongDesc", ":", "\"", "\"", ",", "CommandRun", ":", "func", "(", ")", "subcommands", ".", "CommandRun", "{", "c", ":=", "&", "tokenRun", "{", "}", "\n", "c", ".", "params", "=", "&", "params", "\n", "c", ".", "registerBaseFlags", "(", ")", "\n", "c", ".", "Flags", ".", "DurationVar", "(", "&", "c", ".", "lifetime", ",", "\"", "\"", ",", "time", ".", "Minute", ",", "\"", "\"", ",", ")", "\n", "c", ".", "Flags", ".", "StringVar", "(", "&", "c", ".", "jsonOutput", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\\\"", "\\\"", "\"", ")", "\n", "return", "c", "\n", "}", ",", "}", "\n", "}" ]
// SubcommandTokenWithParams returns subcommand.Command that can be used to // print current access token.
[ "SubcommandTokenWithParams", "returns", "subcommand", ".", "Command", "that", "can", "be", "used", "to", "print", "current", "access", "token", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/client/authcli/authcli.go#L323-L343
8,997
luci/luci-go
auth/client/authcli/authcli.go
SubcommandContextWithParams
func SubcommandContextWithParams(params CommandParams) *subcommands.Command { // By default request all scopes used by authctx.Context. params.AuthOptions.Scopes = []string{ "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/firebase", "https://www.googleapis.com/auth/gerritcodereview", "https://www.googleapis.com/auth/userinfo.email", } return &subcommands.Command{ Advanced: params.Advanced, UsageLine: fmt.Sprintf("%s [flags] [--] <bin> [args]", params.Name), ShortDesc: "sets up new LUCI local auth context and launches a process in it", LongDesc: "Starts local RPC auth server, prepares LUCI_CONTEXT, launches a process in this environment.", CommandRun: func() subcommands.CommandRun { c := &contextRun{} c.params = &params c.registerBaseFlags() c.Flags.StringVar( &c.actAs, "act-as-service-account", "", "Act as a given service account (caller must have iam.serviceAccountActor role).") c.Flags.BoolVar(&c.verbose, "verbose", false, "More logging") return c }, } }
go
func SubcommandContextWithParams(params CommandParams) *subcommands.Command { // By default request all scopes used by authctx.Context. params.AuthOptions.Scopes = []string{ "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/firebase", "https://www.googleapis.com/auth/gerritcodereview", "https://www.googleapis.com/auth/userinfo.email", } return &subcommands.Command{ Advanced: params.Advanced, UsageLine: fmt.Sprintf("%s [flags] [--] <bin> [args]", params.Name), ShortDesc: "sets up new LUCI local auth context and launches a process in it", LongDesc: "Starts local RPC auth server, prepares LUCI_CONTEXT, launches a process in this environment.", CommandRun: func() subcommands.CommandRun { c := &contextRun{} c.params = &params c.registerBaseFlags() c.Flags.StringVar( &c.actAs, "act-as-service-account", "", "Act as a given service account (caller must have iam.serviceAccountActor role).") c.Flags.BoolVar(&c.verbose, "verbose", false, "More logging") return c }, } }
[ "func", "SubcommandContextWithParams", "(", "params", "CommandParams", ")", "*", "subcommands", ".", "Command", "{", "// By default request all scopes used by authctx.Context.", "params", ".", "AuthOptions", ".", "Scopes", "=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "}", "\n", "return", "&", "subcommands", ".", "Command", "{", "Advanced", ":", "params", ".", "Advanced", ",", "UsageLine", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "params", ".", "Name", ")", ",", "ShortDesc", ":", "\"", "\"", ",", "LongDesc", ":", "\"", "\"", ",", "CommandRun", ":", "func", "(", ")", "subcommands", ".", "CommandRun", "{", "c", ":=", "&", "contextRun", "{", "}", "\n", "c", ".", "params", "=", "&", "params", "\n", "c", ".", "registerBaseFlags", "(", ")", "\n", "c", ".", "Flags", ".", "StringVar", "(", "&", "c", ".", "actAs", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "c", ".", "Flags", ".", "BoolVar", "(", "&", "c", ".", "verbose", ",", "\"", "\"", ",", "false", ",", "\"", "\"", ")", "\n", "return", "c", "\n", "}", ",", "}", "\n", "}" ]
// SubcommandContextWithParams returns subcommand.Command that can be used to // setup new LUCI authentication context for a process tree.
[ "SubcommandContextWithParams", "returns", "subcommand", ".", "Command", "that", "can", "be", "used", "to", "setup", "new", "LUCI", "authentication", "context", "for", "a", "process", "tree", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/client/authcli/authcli.go#L416-L440
8,998
luci/luci-go
milo/api/buildbot/structs.go
ID
func (b *Build) ID() BuildID { return BuildID{ Master: b.Master, Builder: b.Buildername, Number: b.Number, } }
go
func (b *Build) ID() BuildID { return BuildID{ Master: b.Master, Builder: b.Buildername, Number: b.Number, } }
[ "func", "(", "b", "*", "Build", ")", "ID", "(", ")", "BuildID", "{", "return", "BuildID", "{", "Master", ":", "b", ".", "Master", ",", "Builder", ":", "b", ".", "Buildername", ",", "Number", ":", "b", ".", "Number", ",", "}", "\n", "}" ]
// ID returns b's BuildID.
[ "ID", "returns", "b", "s", "BuildID", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/api/buildbot/structs.go#L160-L166
8,999
luci/luci-go
milo/api/buildbot/structs.go
PropertyValue
func (b *Build) PropertyValue(name string) interface{} { for _, prop := range b.Properties { if prop.Name == name { return prop.Value } } // Not returning (nil, false) here because it would complicate all // practical usage of this function, which simply try to cast the // returned value. return PropertyNotFound }
go
func (b *Build) PropertyValue(name string) interface{} { for _, prop := range b.Properties { if prop.Name == name { return prop.Value } } // Not returning (nil, false) here because it would complicate all // practical usage of this function, which simply try to cast the // returned value. return PropertyNotFound }
[ "func", "(", "b", "*", "Build", ")", "PropertyValue", "(", "name", "string", ")", "interface", "{", "}", "{", "for", "_", ",", "prop", ":=", "range", "b", ".", "Properties", "{", "if", "prop", ".", "Name", "==", "name", "{", "return", "prop", ".", "Value", "\n", "}", "\n", "}", "\n\n", "// Not returning (nil, false) here because it would complicate all", "// practical usage of this function, which simply try to cast the", "// returned value.", "return", "PropertyNotFound", "\n", "}" ]
// PropertyValue returns the named property value. // If such property does not exist, returns PropertyNotFound.
[ "PropertyValue", "returns", "the", "named", "property", "value", ".", "If", "such", "property", "does", "not", "exist", "returns", "PropertyNotFound", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/api/buildbot/structs.go#L184-L195