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
7,100
luci/luci-go
dm/appengine/mutate/finish_execution.go
FinishExecutionFn
func FinishExecutionFn(c context.Context, eid *dm.Execution_ID, rslt *dm.Result) ([]tumble.Mutation, error) { if rslt.Data != nil { if normErr := rslt.Data.Normalize(); normErr != nil { logging.WithError(normErr).Errorf(c, "Could not normalize distributor Result!") rslt = &dm.Result{ AbnormalFinish: &dm.AbnormalFinish{ Status: dm.AbnormalFinish_RESULT_MALFORMED, Reason: fmt.Sprintf("distributor result malformed: %q in %q", normErr, rslt.Data.Object), }, } } } return []tumble.Mutation{&FinishExecution{EID: eid, Result: rslt}}, nil }
go
func FinishExecutionFn(c context.Context, eid *dm.Execution_ID, rslt *dm.Result) ([]tumble.Mutation, error) { if rslt.Data != nil { if normErr := rslt.Data.Normalize(); normErr != nil { logging.WithError(normErr).Errorf(c, "Could not normalize distributor Result!") rslt = &dm.Result{ AbnormalFinish: &dm.AbnormalFinish{ Status: dm.AbnormalFinish_RESULT_MALFORMED, Reason: fmt.Sprintf("distributor result malformed: %q in %q", normErr, rslt.Data.Object), }, } } } return []tumble.Mutation{&FinishExecution{EID: eid, Result: rslt}}, nil }
[ "func", "FinishExecutionFn", "(", "c", "context", ".", "Context", ",", "eid", "*", "dm", ".", "Execution_ID", ",", "rslt", "*", "dm", ".", "Result", ")", "(", "[", "]", "tumble", ".", "Mutation", ",", "error", ")", "{", "if", "rslt", ".", "Data", "!=", "nil", "{", "if", "normErr", ":=", "rslt", ".", "Data", ".", "Normalize", "(", ")", ";", "normErr", "!=", "nil", "{", "logging", ".", "WithError", "(", "normErr", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "rslt", "=", "&", "dm", ".", "Result", "{", "AbnormalFinish", ":", "&", "dm", ".", "AbnormalFinish", "{", "Status", ":", "dm", ".", "AbnormalFinish_RESULT_MALFORMED", ",", "Reason", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "normErr", ",", "rslt", ".", "Data", ".", "Object", ")", ",", "}", ",", "}", "\n", "}", "\n", "}", "\n\n", "return", "[", "]", "tumble", ".", "Mutation", "{", "&", "FinishExecution", "{", "EID", ":", "eid", ",", "Result", ":", "rslt", "}", "}", ",", "nil", "\n", "}" ]
// FinishExecutionFn is the implementation of distributor.FinishExecutionFn. // It's defined here to avoid a circular dependency.
[ "FinishExecutionFn", "is", "the", "implementation", "of", "distributor", ".", "FinishExecutionFn", ".", "It", "s", "defined", "here", "to", "avoid", "a", "circular", "dependency", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/mutate/finish_execution.go#L156-L170
7,101
luci/luci-go
dm/appengine/mutate/finish_execution.go
NewFinishExecutionAbnormal
func NewFinishExecutionAbnormal(eid *dm.Execution_ID, status dm.AbnormalFinish_Status, reason string) *FinishExecution { return &FinishExecution{ eid, &dm.Result{ AbnormalFinish: &dm.AbnormalFinish{Status: status, Reason: reason}}} }
go
func NewFinishExecutionAbnormal(eid *dm.Execution_ID, status dm.AbnormalFinish_Status, reason string) *FinishExecution { return &FinishExecution{ eid, &dm.Result{ AbnormalFinish: &dm.AbnormalFinish{Status: status, Reason: reason}}} }
[ "func", "NewFinishExecutionAbnormal", "(", "eid", "*", "dm", ".", "Execution_ID", ",", "status", "dm", ".", "AbnormalFinish_Status", ",", "reason", "string", ")", "*", "FinishExecution", "{", "return", "&", "FinishExecution", "{", "eid", ",", "&", "dm", ".", "Result", "{", "AbnormalFinish", ":", "&", "dm", ".", "AbnormalFinish", "{", "Status", ":", "status", ",", "Reason", ":", "reason", "}", "}", "}", "\n", "}" ]
// NewFinishExecutionAbnormal is a shorthand to make a FinishExecution mutation // with some abnomal result.
[ "NewFinishExecutionAbnormal", "is", "a", "shorthand", "to", "make", "a", "FinishExecution", "mutation", "with", "some", "abnomal", "result", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/mutate/finish_execution.go#L174-L178
7,102
luci/luci-go
common/data/caching/lru/lru.go
New
func New(size int) *Cache { c := Cache{ size: size, } c.Reset() return &c }
go
func New(size int) *Cache { c := Cache{ size: size, } c.Reset() return &c }
[ "func", "New", "(", "size", "int", ")", "*", "Cache", "{", "c", ":=", "Cache", "{", "size", ":", "size", ",", "}", "\n", "c", ".", "Reset", "(", ")", "\n", "return", "&", "c", "\n", "}" ]
// New creates a new, locking LRU cache with the specified size. // // If size is <= 0, the LRU cache will have infinite capacity, and will never // prune elements.
[ "New", "creates", "a", "new", "locking", "LRU", "cache", "with", "the", "specified", "size", ".", "If", "size", "is", "<", "=", "0", "the", "LRU", "cache", "will", "have", "infinite", "capacity", "and", "will", "never", "prune", "elements", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/caching/lru/lru.go#L111-L117
7,103
luci/luci-go
common/data/caching/lru/lru.go
Peek
func (c *Cache) Peek(ctx context.Context, key interface{}) (interface{}, bool) { now := clock.Now(ctx) c.lock.RLock() defer c.lock.RUnlock() if e := c.cache[key]; e != nil { ent := e.Value.(*cacheEntry) if !c.isEntryExpired(now, ent) { return ent.v, true } } return nil, false }
go
func (c *Cache) Peek(ctx context.Context, key interface{}) (interface{}, bool) { now := clock.Now(ctx) c.lock.RLock() defer c.lock.RUnlock() if e := c.cache[key]; e != nil { ent := e.Value.(*cacheEntry) if !c.isEntryExpired(now, ent) { return ent.v, true } } return nil, false }
[ "func", "(", "c", "*", "Cache", ")", "Peek", "(", "ctx", "context", ".", "Context", ",", "key", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "bool", ")", "{", "now", ":=", "clock", ".", "Now", "(", "ctx", ")", "\n\n", "c", ".", "lock", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "lock", ".", "RUnlock", "(", ")", "\n\n", "if", "e", ":=", "c", ".", "cache", "[", "key", "]", ";", "e", "!=", "nil", "{", "ent", ":=", "e", ".", "Value", ".", "(", "*", "cacheEntry", ")", "\n", "if", "!", "c", ".", "isEntryExpired", "(", "now", ",", "ent", ")", "{", "return", "ent", ".", "v", ",", "true", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "false", "\n", "}" ]
// Peek fetches the element associated with the supplied key without updating // the element's recently-used standing. // // Peek uses the cache read lock.
[ "Peek", "fetches", "the", "element", "associated", "with", "the", "supplied", "key", "without", "updating", "the", "element", "s", "recently", "-", "used", "standing", ".", "Peek", "uses", "the", "cache", "read", "lock", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/caching/lru/lru.go#L123-L136
7,104
luci/luci-go
common/data/caching/lru/lru.go
GetOrCreate
func (c *Cache) GetOrCreate(ctx context.Context, key interface{}, fn Maker) (v interface{}, err error) { // First, check if the value is the cache. We don't need to hold the item's // Mutex for this. var ok bool if v, ok = c.Get(ctx, key); ok { return v, nil } // The value is currently not cached, so we will generate it. c.mp.WithMutex(key, func() { // Has the value been cached since we obtained the key's lock? if v, ok = c.Get(ctx, key); ok { return } // Generate a new value. var exp time.Duration if v, exp, err = fn(); err != nil { // The Maker returned an error, so do not add the value to the cache. return } // Add the generated value to the cache. c.Put(ctx, key, v, exp) }) return }
go
func (c *Cache) GetOrCreate(ctx context.Context, key interface{}, fn Maker) (v interface{}, err error) { // First, check if the value is the cache. We don't need to hold the item's // Mutex for this. var ok bool if v, ok = c.Get(ctx, key); ok { return v, nil } // The value is currently not cached, so we will generate it. c.mp.WithMutex(key, func() { // Has the value been cached since we obtained the key's lock? if v, ok = c.Get(ctx, key); ok { return } // Generate a new value. var exp time.Duration if v, exp, err = fn(); err != nil { // The Maker returned an error, so do not add the value to the cache. return } // Add the generated value to the cache. c.Put(ctx, key, v, exp) }) return }
[ "func", "(", "c", "*", "Cache", ")", "GetOrCreate", "(", "ctx", "context", ".", "Context", ",", "key", "interface", "{", "}", ",", "fn", "Maker", ")", "(", "v", "interface", "{", "}", ",", "err", "error", ")", "{", "// First, check if the value is the cache. We don't need to hold the item's", "// Mutex for this.", "var", "ok", "bool", "\n", "if", "v", ",", "ok", "=", "c", ".", "Get", "(", "ctx", ",", "key", ")", ";", "ok", "{", "return", "v", ",", "nil", "\n", "}", "\n\n", "// The value is currently not cached, so we will generate it.", "c", ".", "mp", ".", "WithMutex", "(", "key", ",", "func", "(", ")", "{", "// Has the value been cached since we obtained the key's lock?", "if", "v", ",", "ok", "=", "c", ".", "Get", "(", "ctx", ",", "key", ")", ";", "ok", "{", "return", "\n", "}", "\n\n", "// Generate a new value.", "var", "exp", "time", ".", "Duration", "\n", "if", "v", ",", "exp", ",", "err", "=", "fn", "(", ")", ";", "err", "!=", "nil", "{", "// The Maker returned an error, so do not add the value to the cache.", "return", "\n", "}", "\n\n", "// Add the generated value to the cache.", "c", ".", "Put", "(", "ctx", ",", "key", ",", "v", ",", "exp", ")", "\n", "}", ")", "\n", "return", "\n", "}" ]
// GetOrCreate retrieves the current value of key. If no value exists for key, // GetOrCreate will lock around key and invoke the supplied Maker to generate // a new value. // // If multiple concurrent operations invoke GetOrCreate at the same time, they // will serialize, and at most one Maker will be invoked at a time. If the Maker // succeeds, it is more likely that the first operation will generate and // install a value, and the other operations will all quickly retrieve that // value once unblocked. // // If the Maker returns an error, the error will be returned by GetOrCreate and // no modifications will be made to the Cache. If Maker returns a nil error, the // value that it returns will be added into the Cache and returned to the // caller. // // Note that the Cache's lock will not be held while the Maker is running. // Operations on to the Cache using other methods will not lock around // key. This will not interfere with GetOrCreate.
[ "GetOrCreate", "retrieves", "the", "current", "value", "of", "key", ".", "If", "no", "value", "exists", "for", "key", "GetOrCreate", "will", "lock", "around", "key", "and", "invoke", "the", "supplied", "Maker", "to", "generate", "a", "new", "value", ".", "If", "multiple", "concurrent", "operations", "invoke", "GetOrCreate", "at", "the", "same", "time", "they", "will", "serialize", "and", "at", "most", "one", "Maker", "will", "be", "invoked", "at", "a", "time", ".", "If", "the", "Maker", "succeeds", "it", "is", "more", "likely", "that", "the", "first", "operation", "will", "generate", "and", "install", "a", "value", "and", "the", "other", "operations", "will", "all", "quickly", "retrieve", "that", "value", "once", "unblocked", ".", "If", "the", "Maker", "returns", "an", "error", "the", "error", "will", "be", "returned", "by", "GetOrCreate", "and", "no", "modifications", "will", "be", "made", "to", "the", "Cache", ".", "If", "Maker", "returns", "a", "nil", "error", "the", "value", "that", "it", "returns", "will", "be", "added", "into", "the", "Cache", "and", "returned", "to", "the", "caller", ".", "Note", "that", "the", "Cache", "s", "lock", "will", "not", "be", "held", "while", "the", "Maker", "is", "running", ".", "Operations", "on", "to", "the", "Cache", "using", "other", "methods", "will", "not", "lock", "around", "key", ".", "This", "will", "not", "interfere", "with", "GetOrCreate", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/caching/lru/lru.go#L299-L325
7,105
luci/luci-go
common/data/caching/lru/lru.go
Create
func (c *Cache) Create(ctx context.Context, key interface{}, fn Maker) (v interface{}, err error) { c.mp.WithMutex(key, func() { // Generate a new value. var exp time.Duration if v, exp, err = fn(); err != nil { // The Maker returned an error, so do not add the value to the cache. return } // Add the generated value to the cache. c.Put(ctx, key, v, exp) }) return }
go
func (c *Cache) Create(ctx context.Context, key interface{}, fn Maker) (v interface{}, err error) { c.mp.WithMutex(key, func() { // Generate a new value. var exp time.Duration if v, exp, err = fn(); err != nil { // The Maker returned an error, so do not add the value to the cache. return } // Add the generated value to the cache. c.Put(ctx, key, v, exp) }) return }
[ "func", "(", "c", "*", "Cache", ")", "Create", "(", "ctx", "context", ".", "Context", ",", "key", "interface", "{", "}", ",", "fn", "Maker", ")", "(", "v", "interface", "{", "}", ",", "err", "error", ")", "{", "c", ".", "mp", ".", "WithMutex", "(", "key", ",", "func", "(", ")", "{", "// Generate a new value.", "var", "exp", "time", ".", "Duration", "\n", "if", "v", ",", "exp", ",", "err", "=", "fn", "(", ")", ";", "err", "!=", "nil", "{", "// The Maker returned an error, so do not add the value to the cache.", "return", "\n", "}", "\n\n", "// Add the generated value to the cache.", "c", ".", "Put", "(", "ctx", ",", "key", ",", "v", ",", "exp", ")", "\n", "}", ")", "\n", "return", "\n", "}" ]
// Create write-locks around key and invokes the supplied Maker to generate a // new value. // // If multiple concurrent operations invoke GetOrCreate or Create at the same // time, they will serialize, and at most one Maker will be invoked at a time. // If the Maker succeeds, it is more likely that the first operation will // generate and install a value, and the other operations will all quickly // retrieve that value once unblocked. // // If the Maker returns an error, the error will be returned by Create and // no modifications will be made to the Cache. If Maker returns a nil error, the // value that it returns will be added into the Cache and returned to the // caller. // // Note that the Cache's lock will not be held while the Maker is running. // Operations on to the Cache using other methods will not lock around // key. This will not interfere with Create.
[ "Create", "write", "-", "locks", "around", "key", "and", "invokes", "the", "supplied", "Maker", "to", "generate", "a", "new", "value", ".", "If", "multiple", "concurrent", "operations", "invoke", "GetOrCreate", "or", "Create", "at", "the", "same", "time", "they", "will", "serialize", "and", "at", "most", "one", "Maker", "will", "be", "invoked", "at", "a", "time", ".", "If", "the", "Maker", "succeeds", "it", "is", "more", "likely", "that", "the", "first", "operation", "will", "generate", "and", "install", "a", "value", "and", "the", "other", "operations", "will", "all", "quickly", "retrieve", "that", "value", "once", "unblocked", ".", "If", "the", "Maker", "returns", "an", "error", "the", "error", "will", "be", "returned", "by", "Create", "and", "no", "modifications", "will", "be", "made", "to", "the", "Cache", ".", "If", "Maker", "returns", "a", "nil", "error", "the", "value", "that", "it", "returns", "will", "be", "added", "into", "the", "Cache", "and", "returned", "to", "the", "caller", ".", "Note", "that", "the", "Cache", "s", "lock", "will", "not", "be", "held", "while", "the", "Maker", "is", "running", ".", "Operations", "on", "to", "the", "Cache", "using", "other", "methods", "will", "not", "lock", "around", "key", ".", "This", "will", "not", "interfere", "with", "Create", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/caching/lru/lru.go#L344-L357
7,106
luci/luci-go
common/data/caching/lru/lru.go
Prune
func (c *Cache) Prune(ctx context.Context) { now := clock.Now(ctx) c.lock.Lock() defer c.lock.Unlock() c.pruneExpiryLocked(now) }
go
func (c *Cache) Prune(ctx context.Context) { now := clock.Now(ctx) c.lock.Lock() defer c.lock.Unlock() c.pruneExpiryLocked(now) }
[ "func", "(", "c", "*", "Cache", ")", "Prune", "(", "ctx", "context", ".", "Context", ")", "{", "now", ":=", "clock", ".", "Now", "(", "ctx", ")", "\n\n", "c", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "c", ".", "pruneExpiryLocked", "(", "now", ")", "\n", "}" ]
// Prune iterates through entries in the Cache and prunes any which are // expired.
[ "Prune", "iterates", "through", "entries", "in", "the", "Cache", "and", "prunes", "any", "which", "are", "expired", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/caching/lru/lru.go#L361-L368
7,107
luci/luci-go
common/data/caching/lru/lru.go
snapshot
func (c *Cache) snapshot() (ss snapshot) { c.lock.RLock() defer c.lock.RUnlock() if len(c.cache) > 0 { ss = make(snapshot) for k, e := range c.cache { ss[k] = e.Value.(*cacheEntry).v } } return }
go
func (c *Cache) snapshot() (ss snapshot) { c.lock.RLock() defer c.lock.RUnlock() if len(c.cache) > 0 { ss = make(snapshot) for k, e := range c.cache { ss[k] = e.Value.(*cacheEntry).v } } return }
[ "func", "(", "c", "*", "Cache", ")", "snapshot", "(", ")", "(", "ss", "snapshot", ")", "{", "c", ".", "lock", ".", "RLock", "(", ")", "\n", "defer", "c", ".", "lock", ".", "RUnlock", "(", ")", "\n\n", "if", "len", "(", "c", ".", "cache", ")", ">", "0", "{", "ss", "=", "make", "(", "snapshot", ")", "\n", "for", "k", ",", "e", ":=", "range", "c", ".", "cache", "{", "ss", "[", "k", "]", "=", "e", ".", "Value", ".", "(", "*", "cacheEntry", ")", ".", "v", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// snapshot returns a snapshot map of the cache's entries.
[ "snapshot", "returns", "a", "snapshot", "map", "of", "the", "cache", "s", "entries", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/caching/lru/lru.go#L392-L403
7,108
luci/luci-go
common/data/caching/lru/lru.go
pruneSizeLocked
func (c *Cache) pruneSizeLocked() { // There is no size constraint. if c.size <= 0 { return } // Prune the oldest entries until we're within our size constraint. for e := c.lru.Back(); e != nil; e = c.lru.Back() { if len(c.cache) <= c.size { return } c.evictEntryLocked(e) } }
go
func (c *Cache) pruneSizeLocked() { // There is no size constraint. if c.size <= 0 { return } // Prune the oldest entries until we're within our size constraint. for e := c.lru.Back(); e != nil; e = c.lru.Back() { if len(c.cache) <= c.size { return } c.evictEntryLocked(e) } }
[ "func", "(", "c", "*", "Cache", ")", "pruneSizeLocked", "(", ")", "{", "// There is no size constraint.", "if", "c", ".", "size", "<=", "0", "{", "return", "\n", "}", "\n\n", "// Prune the oldest entries until we're within our size constraint.", "for", "e", ":=", "c", ".", "lru", ".", "Back", "(", ")", ";", "e", "!=", "nil", ";", "e", "=", "c", ".", "lru", ".", "Back", "(", ")", "{", "if", "len", "(", "c", ".", "cache", ")", "<=", "c", ".", "size", "{", "return", "\n", "}", "\n", "c", ".", "evictEntryLocked", "(", "e", ")", "\n", "}", "\n", "}" ]
// pruneSizeLocked prunes LRU elements until its heuristic is satisfied. Its // write lock must be held by the caller.
[ "pruneSizeLocked", "prunes", "LRU", "elements", "until", "its", "heuristic", "is", "satisfied", ".", "Its", "write", "lock", "must", "be", "held", "by", "the", "caller", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/caching/lru/lru.go#L407-L420
7,109
luci/luci-go
common/data/caching/lru/lru.go
isEntryExpired
func (c *Cache) isEntryExpired(now time.Time, ent *cacheEntry) bool { return !(ent.expiry.IsZero() || now.Before(ent.expiry)) }
go
func (c *Cache) isEntryExpired(now time.Time, ent *cacheEntry) bool { return !(ent.expiry.IsZero() || now.Before(ent.expiry)) }
[ "func", "(", "c", "*", "Cache", ")", "isEntryExpired", "(", "now", "time", ".", "Time", ",", "ent", "*", "cacheEntry", ")", "bool", "{", "return", "!", "(", "ent", ".", "expiry", ".", "IsZero", "(", ")", "||", "now", ".", "Before", "(", "ent", ".", "expiry", ")", ")", "\n", "}" ]
// isEntryExpired returns whether this entry is expired given the current time. // // An entry is expired if it has an expiration time, and the current time is >= // the expiration time. // // Will return false if the entry has no expiration, or if the entry is not // expired.
[ "isEntryExpired", "returns", "whether", "this", "entry", "is", "expired", "given", "the", "current", "time", ".", "An", "entry", "is", "expired", "if", "it", "has", "an", "expiration", "time", "and", "the", "current", "time", "is", ">", "=", "the", "expiration", "time", ".", "Will", "return", "false", "if", "the", "entry", "has", "no", "expiration", "or", "if", "the", "entry", "is", "not", "expired", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/caching/lru/lru.go#L444-L446
7,110
luci/luci-go
cipd/client/cipd/digests/client_digests_file.go
Contains
func (d *ClientDigestsFile) Contains(plat string, ref *api.ObjectRef) bool { for _, e := range d.entries { if e.plat == plat && proto.Equal(ref, e.ref) { return true } } return false }
go
func (d *ClientDigestsFile) Contains(plat string, ref *api.ObjectRef) bool { for _, e := range d.entries { if e.plat == plat && proto.Equal(ref, e.ref) { return true } } return false }
[ "func", "(", "d", "*", "ClientDigestsFile", ")", "Contains", "(", "plat", "string", ",", "ref", "*", "api", ".", "ObjectRef", ")", "bool", "{", "for", "_", ",", "e", ":=", "range", "d", ".", "entries", "{", "if", "e", ".", "plat", "==", "plat", "&&", "proto", ".", "Equal", "(", "ref", ",", "e", ".", "ref", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Contains returns true if the given ref is among refs for the given platform. // // Compares 'ref' to all hashes corresponding to 'plat', not only the best one.
[ "Contains", "returns", "true", "if", "the", "given", "ref", "is", "among", "refs", "for", "the", "given", "platform", ".", "Compares", "ref", "to", "all", "hashes", "corresponding", "to", "plat", "not", "only", "the", "best", "one", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/digests/client_digests_file.go#L105-L112
7,111
luci/luci-go
cipd/client/cipd/digests/client_digests_file.go
Equal
func (d *ClientDigestsFile) Equal(a *ClientDigestsFile) bool { if len(d.entries) != len(a.entries) { return false } for i, l := range d.entries { if r := a.entries[i]; l.plat != r.plat || !proto.Equal(l.ref, r.ref) { return false } } return true }
go
func (d *ClientDigestsFile) Equal(a *ClientDigestsFile) bool { if len(d.entries) != len(a.entries) { return false } for i, l := range d.entries { if r := a.entries[i]; l.plat != r.plat || !proto.Equal(l.ref, r.ref) { return false } } return true }
[ "func", "(", "d", "*", "ClientDigestsFile", ")", "Equal", "(", "a", "*", "ClientDigestsFile", ")", "bool", "{", "if", "len", "(", "d", ".", "entries", ")", "!=", "len", "(", "a", ".", "entries", ")", "{", "return", "false", "\n", "}", "\n", "for", "i", ",", "l", ":=", "range", "d", ".", "entries", "{", "if", "r", ":=", "a", ".", "entries", "[", "i", "]", ";", "l", ".", "plat", "!=", "r", ".", "plat", "||", "!", "proto", ".", "Equal", "(", "l", ".", "ref", ",", "r", ".", "ref", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Equal returns true if files have same entries in same order.
[ "Equal", "returns", "true", "if", "files", "have", "same", "entries", "in", "same", "order", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/digests/client_digests_file.go#L126-L136
7,112
luci/luci-go
cipd/client/cipd/digests/client_digests_file.go
Serialize
func (d *ClientDigestsFile) Serialize(w io.Writer, version, versionFile string) error { _, err := iotools.WriteTracker(w, func(w io.Writer) error { fmt.Fprintf(w, "# This file was generated by\n") fmt.Fprintf(w, "#\n") fmt.Fprintf(w, "# cipd selfupdate-roll -version-file %s \\\n", versionFile) fmt.Fprintf(w, "# -version %s\n", version) fmt.Fprintf(w, "#\n") fmt.Fprintf(w, "# Do not modify manually. All changes will be overwritten.\n") fmt.Fprintf(w, "# Use 'cipd selfupdate-roll ...' to modify.\n\n") // Align fields nicely. max := []int{0, 0} for _, e := range d.entries { if l := len(e.plat); l > max[0] { max[0] = l } if l := len(e.ref.HashAlgo.String()); l > max[1] { max[1] = l } } for _, e := range d.entries { algo := strings.ToLower(e.ref.HashAlgo.String()) fmt.Fprintf(w, "%s%s%s%s%s\n", e.plat, strings.Repeat(" ", max[0]+2-len(e.plat)), algo, strings.Repeat(" ", max[1]+2-len(algo)), e.ref.HexDigest, ) } return nil }) return err }
go
func (d *ClientDigestsFile) Serialize(w io.Writer, version, versionFile string) error { _, err := iotools.WriteTracker(w, func(w io.Writer) error { fmt.Fprintf(w, "# This file was generated by\n") fmt.Fprintf(w, "#\n") fmt.Fprintf(w, "# cipd selfupdate-roll -version-file %s \\\n", versionFile) fmt.Fprintf(w, "# -version %s\n", version) fmt.Fprintf(w, "#\n") fmt.Fprintf(w, "# Do not modify manually. All changes will be overwritten.\n") fmt.Fprintf(w, "# Use 'cipd selfupdate-roll ...' to modify.\n\n") // Align fields nicely. max := []int{0, 0} for _, e := range d.entries { if l := len(e.plat); l > max[0] { max[0] = l } if l := len(e.ref.HashAlgo.String()); l > max[1] { max[1] = l } } for _, e := range d.entries { algo := strings.ToLower(e.ref.HashAlgo.String()) fmt.Fprintf(w, "%s%s%s%s%s\n", e.plat, strings.Repeat(" ", max[0]+2-len(e.plat)), algo, strings.Repeat(" ", max[1]+2-len(algo)), e.ref.HexDigest, ) } return nil }) return err }
[ "func", "(", "d", "*", "ClientDigestsFile", ")", "Serialize", "(", "w", "io", ".", "Writer", ",", "version", ",", "versionFile", "string", ")", "error", "{", "_", ",", "err", ":=", "iotools", ".", "WriteTracker", "(", "w", ",", "func", "(", "w", "io", ".", "Writer", ")", "error", "{", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ")", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ")", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\\\", "\\n", "\"", ",", "versionFile", ")", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "version", ")", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ")", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ")", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\\n", "\"", ")", "\n\n", "// Align fields nicely.", "max", ":=", "[", "]", "int", "{", "0", ",", "0", "}", "\n", "for", "_", ",", "e", ":=", "range", "d", ".", "entries", "{", "if", "l", ":=", "len", "(", "e", ".", "plat", ")", ";", "l", ">", "max", "[", "0", "]", "{", "max", "[", "0", "]", "=", "l", "\n", "}", "\n", "if", "l", ":=", "len", "(", "e", ".", "ref", ".", "HashAlgo", ".", "String", "(", ")", ")", ";", "l", ">", "max", "[", "1", "]", "{", "max", "[", "1", "]", "=", "l", "\n", "}", "\n", "}", "\n\n", "for", "_", ",", "e", ":=", "range", "d", ".", "entries", "{", "algo", ":=", "strings", ".", "ToLower", "(", "e", ".", "ref", ".", "HashAlgo", ".", "String", "(", ")", ")", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "e", ".", "plat", ",", "strings", ".", "Repeat", "(", "\"", "\"", ",", "max", "[", "0", "]", "+", "2", "-", "len", "(", "e", ".", "plat", ")", ")", ",", "algo", ",", "strings", ".", "Repeat", "(", "\"", "\"", ",", "max", "[", "1", "]", "+", "2", "-", "len", "(", "algo", ")", ")", ",", "e", ".", "ref", ".", "HexDigest", ",", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}", ")", "\n", "return", "err", "\n", "}" ]
// Serialize writes the ClientDigestsFile to an io.Writer. // // 'version' and 'versionFile' are used to construct a meaningful comment // footer.
[ "Serialize", "writes", "the", "ClientDigestsFile", "to", "an", "io", ".", "Writer", ".", "version", "and", "versionFile", "are", "used", "to", "construct", "a", "meaningful", "comment", "footer", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/digests/client_digests_file.go#L142-L175
7,113
luci/luci-go
cipd/client/cipd/digests/client_digests_file.go
ParseClientDigestsFile
func ParseClientDigestsFile(r io.Reader) (*ClientDigestsFile, error) { res := &ClientDigestsFile{} lineNo := 0 makeError := func(fmtStr string, args ...interface{}) error { args = append([]interface{}{lineNo}, args...) return fmt.Errorf("failed to parse client digests file (line %d): "+fmtStr, args...) } scanner := bufio.NewScanner(r) for scanner.Scan() { lineNo++ line := strings.TrimSpace(scanner.Text()) if line == "" || line[0] == '#' { continue } tokens := strings.Fields(line) if len(tokens) != 3 { return nil, makeError("each line must have format \"<platform> <algo> <digest>\"") } algoIdx := api.HashAlgo_value[strings.ToUpper(tokens[1])] if algoIdx == 0 { continue // skip unknown algorithms } ref := &api.ObjectRef{ HashAlgo: api.HashAlgo(algoIdx), HexDigest: tokens[2], } if err := common.ValidateObjectRef(ref, common.KnownHash); err != nil { return nil, makeError("%s", err) } if err := res.AddClientRef(tokens[0], ref); err != nil { return nil, makeError("%s", err) } } if err := scanner.Err(); err != nil { return nil, err } return res, nil }
go
func ParseClientDigestsFile(r io.Reader) (*ClientDigestsFile, error) { res := &ClientDigestsFile{} lineNo := 0 makeError := func(fmtStr string, args ...interface{}) error { args = append([]interface{}{lineNo}, args...) return fmt.Errorf("failed to parse client digests file (line %d): "+fmtStr, args...) } scanner := bufio.NewScanner(r) for scanner.Scan() { lineNo++ line := strings.TrimSpace(scanner.Text()) if line == "" || line[0] == '#' { continue } tokens := strings.Fields(line) if len(tokens) != 3 { return nil, makeError("each line must have format \"<platform> <algo> <digest>\"") } algoIdx := api.HashAlgo_value[strings.ToUpper(tokens[1])] if algoIdx == 0 { continue // skip unknown algorithms } ref := &api.ObjectRef{ HashAlgo: api.HashAlgo(algoIdx), HexDigest: tokens[2], } if err := common.ValidateObjectRef(ref, common.KnownHash); err != nil { return nil, makeError("%s", err) } if err := res.AddClientRef(tokens[0], ref); err != nil { return nil, makeError("%s", err) } } if err := scanner.Err(); err != nil { return nil, err } return res, nil }
[ "func", "ParseClientDigestsFile", "(", "r", "io", ".", "Reader", ")", "(", "*", "ClientDigestsFile", ",", "error", ")", "{", "res", ":=", "&", "ClientDigestsFile", "{", "}", "\n\n", "lineNo", ":=", "0", "\n", "makeError", ":=", "func", "(", "fmtStr", "string", ",", "args", "...", "interface", "{", "}", ")", "error", "{", "args", "=", "append", "(", "[", "]", "interface", "{", "}", "{", "lineNo", "}", ",", "args", "...", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "fmtStr", ",", "args", "...", ")", "\n", "}", "\n\n", "scanner", ":=", "bufio", ".", "NewScanner", "(", "r", ")", "\n", "for", "scanner", ".", "Scan", "(", ")", "{", "lineNo", "++", "\n\n", "line", ":=", "strings", ".", "TrimSpace", "(", "scanner", ".", "Text", "(", ")", ")", "\n", "if", "line", "==", "\"", "\"", "||", "line", "[", "0", "]", "==", "'#'", "{", "continue", "\n", "}", "\n\n", "tokens", ":=", "strings", ".", "Fields", "(", "line", ")", "\n", "if", "len", "(", "tokens", ")", "!=", "3", "{", "return", "nil", ",", "makeError", "(", "\"", "\\\"", "\\\"", "\"", ")", "\n", "}", "\n\n", "algoIdx", ":=", "api", ".", "HashAlgo_value", "[", "strings", ".", "ToUpper", "(", "tokens", "[", "1", "]", ")", "]", "\n", "if", "algoIdx", "==", "0", "{", "continue", "// skip unknown algorithms", "\n", "}", "\n", "ref", ":=", "&", "api", ".", "ObjectRef", "{", "HashAlgo", ":", "api", ".", "HashAlgo", "(", "algoIdx", ")", ",", "HexDigest", ":", "tokens", "[", "2", "]", ",", "}", "\n", "if", "err", ":=", "common", ".", "ValidateObjectRef", "(", "ref", ",", "common", ".", "KnownHash", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "makeError", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "res", ".", "AddClientRef", "(", "tokens", "[", "0", "]", ",", "ref", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "makeError", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "if", "err", ":=", "scanner", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "res", ",", "nil", "\n", "}" ]
// ParseClientDigestsFile parses previously serialized client digests file. // // Unrecognized algorithms are silently skipped, to be compatible with files // generated by the future versions of CIPD that may use different algorithms.
[ "ParseClientDigestsFile", "parses", "previously", "serialized", "client", "digests", "file", ".", "Unrecognized", "algorithms", "are", "silently", "skipped", "to", "be", "compatible", "with", "files", "generated", "by", "the", "future", "versions", "of", "CIPD", "that", "may", "use", "different", "algorithms", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/digests/client_digests_file.go#L181-L225
7,114
luci/luci-go
cipd/client/cipd/delete_on_close.go
Close
func (d deleteOnClose) Close(ctx context.Context, corrupt bool) (err error) { name := d.File.Name() defer func() { if rmErr := os.Remove(name); err == nil && rmErr != nil && !os.IsNotExist(rmErr) { err = rmErr } }() return d.File.Close() }
go
func (d deleteOnClose) Close(ctx context.Context, corrupt bool) (err error) { name := d.File.Name() defer func() { if rmErr := os.Remove(name); err == nil && rmErr != nil && !os.IsNotExist(rmErr) { err = rmErr } }() return d.File.Close() }
[ "func", "(", "d", "deleteOnClose", ")", "Close", "(", "ctx", "context", ".", "Context", ",", "corrupt", "bool", ")", "(", "err", "error", ")", "{", "name", ":=", "d", ".", "File", ".", "Name", "(", ")", "\n", "defer", "func", "(", ")", "{", "if", "rmErr", ":=", "os", ".", "Remove", "(", "name", ")", ";", "err", "==", "nil", "&&", "rmErr", "!=", "nil", "&&", "!", "os", ".", "IsNotExist", "(", "rmErr", ")", "{", "err", "=", "rmErr", "\n", "}", "\n", "}", "(", ")", "\n", "return", "d", ".", "File", ".", "Close", "(", ")", "\n", "}" ]
// Close closes the underlying file and then deletes it.
[ "Close", "closes", "the", "underlying", "file", "and", "then", "deletes", "it", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/delete_on_close.go#L32-L40
7,115
luci/luci-go
cipd/client/cipd/delete_on_close.go
underlyingFile
func underlyingFile(i pkg.Source) *os.File { return i.(interface { UnderlyingFile() *os.File }).UnderlyingFile() }
go
func underlyingFile(i pkg.Source) *os.File { return i.(interface { UnderlyingFile() *os.File }).UnderlyingFile() }
[ "func", "underlyingFile", "(", "i", "pkg", ".", "Source", ")", "*", "os", ".", "File", "{", "return", "i", ".", "(", "interface", "{", "UnderlyingFile", "(", ")", "*", "os", ".", "File", "\n", "}", ")", ".", "UnderlyingFile", "(", ")", "\n", "}" ]
// underlyingFile is only used by tests.
[ "underlyingFile", "is", "only", "used", "by", "tests", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/delete_on_close.go#L48-L52
7,116
luci/luci-go
common/gcloud/gs/path.go
MakePath
func MakePath(bucket, filename string) Path { var carr [2]string comps := carr[:0] if b := stripTrailingSlashes(bucket); b != "" { comps = append(comps, "gs://"+b) } if filename != "" { comps = append(comps, filename) } return Path(strings.Join(comps, "/")) }
go
func MakePath(bucket, filename string) Path { var carr [2]string comps := carr[:0] if b := stripTrailingSlashes(bucket); b != "" { comps = append(comps, "gs://"+b) } if filename != "" { comps = append(comps, filename) } return Path(strings.Join(comps, "/")) }
[ "func", "MakePath", "(", "bucket", ",", "filename", "string", ")", "Path", "{", "var", "carr", "[", "2", "]", "string", "\n\n", "comps", ":=", "carr", "[", ":", "0", "]", "\n", "if", "b", ":=", "stripTrailingSlashes", "(", "bucket", ")", ";", "b", "!=", "\"", "\"", "{", "comps", "=", "append", "(", "comps", ",", "\"", "\"", "+", "b", ")", "\n", "}", "\n", "if", "filename", "!=", "\"", "\"", "{", "comps", "=", "append", "(", "comps", ",", "filename", ")", "\n", "}", "\n", "return", "Path", "(", "strings", ".", "Join", "(", "comps", ",", "\"", "\"", ")", ")", "\n", "}" ]
// MakePath constructs a Google Storage path from optional bucket and filename // components. // // Trailing forward slashes will be removed from the bucket name, if present.
[ "MakePath", "constructs", "a", "Google", "Storage", "path", "from", "optional", "bucket", "and", "filename", "components", ".", "Trailing", "forward", "slashes", "will", "be", "removed", "from", "the", "bucket", "name", "if", "present", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/gcloud/gs/path.go#L32-L43
7,117
luci/luci-go
common/gcloud/gs/path.go
IsFullPath
func (p Path) IsFullPath() bool { bucket, filename := p.Split() return (bucket != "" && filename != "") }
go
func (p Path) IsFullPath() bool { bucket, filename := p.Split() return (bucket != "" && filename != "") }
[ "func", "(", "p", "Path", ")", "IsFullPath", "(", ")", "bool", "{", "bucket", ",", "filename", ":=", "p", ".", "Split", "(", ")", "\n", "return", "(", "bucket", "!=", "\"", "\"", "&&", "filename", "!=", "\"", "\"", ")", "\n", "}" ]
// IsFullPath returns true if the Path contains both a bucket and file name.
[ "IsFullPath", "returns", "true", "if", "the", "Path", "contains", "both", "a", "bucket", "and", "file", "name", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/gcloud/gs/path.go#L85-L88
7,118
luci/luci-go
common/proto/multiline.go
UnmarshalTextML
func UnmarshalTextML(s string, pb proto.Message) error { s, err := ParseMultilineStrings(s) if err != nil { return err } return proto.UnmarshalText(s, pb) }
go
func UnmarshalTextML(s string, pb proto.Message) error { s, err := ParseMultilineStrings(s) if err != nil { return err } return proto.UnmarshalText(s, pb) }
[ "func", "UnmarshalTextML", "(", "s", "string", ",", "pb", "proto", ".", "Message", ")", "error", "{", "s", ",", "err", ":=", "ParseMultilineStrings", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "proto", ".", "UnmarshalText", "(", "s", ",", "pb", ")", "\n", "}" ]
// UnmarshalTextML behaves the same as proto.UnmarshalText, except that it // allows for multiline strings in the manner of ParseMultilineStrings.
[ "UnmarshalTextML", "behaves", "the", "same", "as", "proto", ".", "UnmarshalText", "except", "that", "it", "allows", "for", "multiline", "strings", "in", "the", "manner", "of", "ParseMultilineStrings", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/proto/multiline.go#L195-L201
7,119
luci/luci-go
logdog/client/butler/output/logdog/output.go
Scopes
func Scopes() []string { // E-mail scope needed for Coordinator authentication. scopes := []string{auth.OAuthScopeEmail} // Publisher scope needed to publish to Pub/Sub transport. scopes = append(scopes, ps.PublisherScopes...) return scopes }
go
func Scopes() []string { // E-mail scope needed for Coordinator authentication. scopes := []string{auth.OAuthScopeEmail} // Publisher scope needed to publish to Pub/Sub transport. scopes = append(scopes, ps.PublisherScopes...) return scopes }
[ "func", "Scopes", "(", ")", "[", "]", "string", "{", "// E-mail scope needed for Coordinator authentication.", "scopes", ":=", "[", "]", "string", "{", "auth", ".", "OAuthScopeEmail", "}", "\n", "// Publisher scope needed to publish to Pub/Sub transport.", "scopes", "=", "append", "(", "scopes", ",", "ps", ".", "PublisherScopes", "...", ")", "\n\n", "return", "scopes", "\n", "}" ]
// Scopes returns the set of OAuth scopes required for this Output.
[ "Scopes", "returns", "the", "set", "of", "OAuth", "scopes", "required", "for", "this", "Output", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/output/logdog/output.go#L44-L51
7,120
luci/luci-go
client/archiver/archiver.go
TotalBytesHits
func (s *Stats) TotalBytesHits() units.Size { out := units.Size(0) for _, i := range s.Hits { out += i } return out }
go
func (s *Stats) TotalBytesHits() units.Size { out := units.Size(0) for _, i := range s.Hits { out += i } return out }
[ "func", "(", "s", "*", "Stats", ")", "TotalBytesHits", "(", ")", "units", ".", "Size", "{", "out", ":=", "units", ".", "Size", "(", "0", ")", "\n", "for", "_", ",", "i", ":=", "range", "s", ".", "Hits", "{", "out", "+=", "i", "\n", "}", "\n", "return", "out", "\n", "}" ]
// TotalBytesHits is the number of bytes not uploaded due to cache hits on the // server.
[ "TotalBytesHits", "is", "the", "number", "of", "bytes", "not", "uploaded", "due", "to", "cache", "hits", "on", "the", "server", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/archiver/archiver.go#L93-L99
7,121
luci/luci-go
client/archiver/archiver.go
TotalBytesPushed
func (s *Stats) TotalBytesPushed() units.Size { out := units.Size(0) for _, i := range s.Pushed { out += i.Size } return out }
go
func (s *Stats) TotalBytesPushed() units.Size { out := units.Size(0) for _, i := range s.Pushed { out += i.Size } return out }
[ "func", "(", "s", "*", "Stats", ")", "TotalBytesPushed", "(", ")", "units", ".", "Size", "{", "out", ":=", "units", ".", "Size", "(", "0", ")", "\n", "for", "_", ",", "i", ":=", "range", "s", ".", "Pushed", "{", "out", "+=", "i", ".", "Size", "\n", "}", "\n", "return", "out", "\n", "}" ]
// TotalBytesPushed returns the sum of bytes uploaded.
[ "TotalBytesPushed", "returns", "the", "sum", "of", "bytes", "uploaded", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/archiver/archiver.go#L107-L113
7,122
luci/luci-go
client/archiver/archiver.go
New
func New(ctx context.Context, c *isolatedclient.Client, out io.Writer) *Archiver { // TODO(maruel): Cache hashes and server cache presence. ctx2, cancel := context.WithCancel(common.CancelOnCtrlC(ctx)) a := &Archiver{ ctx: ctx2, cancel: cancel, progress: progress.New(headers, out), c: c, stage1: make(chan *PendingItem), } tracer.NewPID(a, "archiver") // Tuning parameters. // Stage 1 is single threaded. // Stage 2; Disk I/O bound. // TODO(maruel): Reduce to 1 or 2. const maxConcurrentHash = 5 // Stage 3; Control server overload due to parallelism (DDoS). const maxConcurrentContains = 64 const containsBatchingDelay = 100 * time.Millisecond const containsBatchSize = 50 // Stage 4; Network I/O bound. const maxConcurrentUpload = 8 stage2 := make(chan *PendingItem) stage3 := make(chan *PendingItem) stage4 := make(chan *PendingItem) a.wg.Add(1) go func() { defer func() { a.wg.Done() close(stage2) }() a.stage1DedupeLoop(a.stage1, stage2) }() // TODO(todd): Create on-disk cache in a new stage inserted between stages 1 // and 2. This should be a separate interface with its own implementation // that 'archiver' keeps a reference to as member. a.wg.Add(1) go func() { defer func() { a.wg.Done() close(stage3) }() a.stage2HashLoop(stage2, stage3, maxConcurrentHash) }() a.wg.Add(1) go func() { defer func() { a.wg.Done() close(stage4) }() a.stage3LookupLoop(stage3, stage4, maxConcurrentContains, containsBatchingDelay, containsBatchSize) }() a.wg.Add(1) go func() { defer a.wg.Done() a.stage4UploadLoop(stage4, maxConcurrentUpload) }() // Push an nil item to enforce stage1DedupeLoop() woke up. Otherwise this // could lead to a race condition if Close() is called too quickly. a.stage1 <- nil return a }
go
func New(ctx context.Context, c *isolatedclient.Client, out io.Writer) *Archiver { // TODO(maruel): Cache hashes and server cache presence. ctx2, cancel := context.WithCancel(common.CancelOnCtrlC(ctx)) a := &Archiver{ ctx: ctx2, cancel: cancel, progress: progress.New(headers, out), c: c, stage1: make(chan *PendingItem), } tracer.NewPID(a, "archiver") // Tuning parameters. // Stage 1 is single threaded. // Stage 2; Disk I/O bound. // TODO(maruel): Reduce to 1 or 2. const maxConcurrentHash = 5 // Stage 3; Control server overload due to parallelism (DDoS). const maxConcurrentContains = 64 const containsBatchingDelay = 100 * time.Millisecond const containsBatchSize = 50 // Stage 4; Network I/O bound. const maxConcurrentUpload = 8 stage2 := make(chan *PendingItem) stage3 := make(chan *PendingItem) stage4 := make(chan *PendingItem) a.wg.Add(1) go func() { defer func() { a.wg.Done() close(stage2) }() a.stage1DedupeLoop(a.stage1, stage2) }() // TODO(todd): Create on-disk cache in a new stage inserted between stages 1 // and 2. This should be a separate interface with its own implementation // that 'archiver' keeps a reference to as member. a.wg.Add(1) go func() { defer func() { a.wg.Done() close(stage3) }() a.stage2HashLoop(stage2, stage3, maxConcurrentHash) }() a.wg.Add(1) go func() { defer func() { a.wg.Done() close(stage4) }() a.stage3LookupLoop(stage3, stage4, maxConcurrentContains, containsBatchingDelay, containsBatchSize) }() a.wg.Add(1) go func() { defer a.wg.Done() a.stage4UploadLoop(stage4, maxConcurrentUpload) }() // Push an nil item to enforce stage1DedupeLoop() woke up. Otherwise this // could lead to a race condition if Close() is called too quickly. a.stage1 <- nil return a }
[ "func", "New", "(", "ctx", "context", ".", "Context", ",", "c", "*", "isolatedclient", ".", "Client", ",", "out", "io", ".", "Writer", ")", "*", "Archiver", "{", "// TODO(maruel): Cache hashes and server cache presence.", "ctx2", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "common", ".", "CancelOnCtrlC", "(", "ctx", ")", ")", "\n", "a", ":=", "&", "Archiver", "{", "ctx", ":", "ctx2", ",", "cancel", ":", "cancel", ",", "progress", ":", "progress", ".", "New", "(", "headers", ",", "out", ")", ",", "c", ":", "c", ",", "stage1", ":", "make", "(", "chan", "*", "PendingItem", ")", ",", "}", "\n", "tracer", ".", "NewPID", "(", "a", ",", "\"", "\"", ")", "\n\n", "// Tuning parameters.", "// Stage 1 is single threaded.", "// Stage 2; Disk I/O bound.", "// TODO(maruel): Reduce to 1 or 2.", "const", "maxConcurrentHash", "=", "5", "\n\n", "// Stage 3; Control server overload due to parallelism (DDoS).", "const", "maxConcurrentContains", "=", "64", "\n", "const", "containsBatchingDelay", "=", "100", "*", "time", ".", "Millisecond", "\n", "const", "containsBatchSize", "=", "50", "\n\n", "// Stage 4; Network I/O bound.", "const", "maxConcurrentUpload", "=", "8", "\n\n", "stage2", ":=", "make", "(", "chan", "*", "PendingItem", ")", "\n", "stage3", ":=", "make", "(", "chan", "*", "PendingItem", ")", "\n", "stage4", ":=", "make", "(", "chan", "*", "PendingItem", ")", "\n", "a", ".", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "defer", "func", "(", ")", "{", "a", ".", "wg", ".", "Done", "(", ")", "\n", "close", "(", "stage2", ")", "\n", "}", "(", ")", "\n", "a", ".", "stage1DedupeLoop", "(", "a", ".", "stage1", ",", "stage2", ")", "\n", "}", "(", ")", "\n\n", "// TODO(todd): Create on-disk cache in a new stage inserted between stages 1", "// and 2. This should be a separate interface with its own implementation", "// that 'archiver' keeps a reference to as member.", "a", ".", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "defer", "func", "(", ")", "{", "a", ".", "wg", ".", "Done", "(", ")", "\n", "close", "(", "stage3", ")", "\n", "}", "(", ")", "\n", "a", ".", "stage2HashLoop", "(", "stage2", ",", "stage3", ",", "maxConcurrentHash", ")", "\n", "}", "(", ")", "\n\n", "a", ".", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "defer", "func", "(", ")", "{", "a", ".", "wg", ".", "Done", "(", ")", "\n", "close", "(", "stage4", ")", "\n", "}", "(", ")", "\n", "a", ".", "stage3LookupLoop", "(", "stage3", ",", "stage4", ",", "maxConcurrentContains", ",", "containsBatchingDelay", ",", "containsBatchSize", ")", "\n", "}", "(", ")", "\n\n", "a", ".", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", ")", "{", "defer", "a", ".", "wg", ".", "Done", "(", ")", "\n", "a", ".", "stage4UploadLoop", "(", "stage4", ",", "maxConcurrentUpload", ")", "\n", "}", "(", ")", "\n\n", "// Push an nil item to enforce stage1DedupeLoop() woke up. Otherwise this", "// could lead to a race condition if Close() is called too quickly.", "a", ".", "stage1", "<-", "nil", "\n", "return", "a", "\n", "}" ]
// New returns a thread-safe Archiver instance. // // If not nil, out will contain tty-oriented progress information. // // ctx will be used for logging.
[ "New", "returns", "a", "thread", "-", "safe", "Archiver", "instance", ".", "If", "not", "nil", "out", "will", "contain", "tty", "-", "oriented", "progress", "information", ".", "ctx", "will", "be", "used", "for", "logging", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/archiver/archiver.go#L125-L197
7,123
luci/luci-go
client/archiver/archiver.go
done
func (i *PendingItem) done() error { tracer.CounterAdd(i.a, "itemsProcessing", -1) i.a = nil return nil }
go
func (i *PendingItem) done() error { tracer.CounterAdd(i.a, "itemsProcessing", -1) i.a = nil return nil }
[ "func", "(", "i", "*", "PendingItem", ")", "done", "(", ")", "error", "{", "tracer", ".", "CounterAdd", "(", "i", ".", "a", ",", "\"", "\"", ",", "-", "1", ")", "\n", "i", ".", "a", "=", "nil", "\n", "return", "nil", "\n", "}" ]
// done is called when the PendingItem processing is done. // // It can be because there was an error, it was linked to another item, it was // present on the server or finally it was uploaded successfully.
[ "done", "is", "called", "when", "the", "PendingItem", "processing", "is", "done", ".", "It", "can", "be", "because", "there", "was", "an", "error", "it", "was", "linked", "to", "another", "item", "it", "was", "present", "on", "the", "server", "or", "finally", "it", "was", "uploaded", "successfully", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/archiver/archiver.go#L232-L236
7,124
luci/luci-go
client/archiver/archiver.go
Error
func (i *PendingItem) Error() error { i.lock.Lock() defer i.lock.Unlock() return i.err }
go
func (i *PendingItem) Error() error { i.lock.Lock() defer i.lock.Unlock() return i.err }
[ "func", "(", "i", "*", "PendingItem", ")", "Error", "(", ")", "error", "{", "i", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "i", ".", "lock", ".", "Unlock", "(", ")", "\n", "return", "i", ".", "err", "\n", "}" ]
// Error returns any error that occurred for this item if any.
[ "Error", "returns", "any", "error", "that", "occurred", "for", "this", "item", "if", "any", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/archiver/archiver.go#L244-L248
7,125
luci/luci-go
client/archiver/archiver.go
Digest
func (i *PendingItem) Digest() isolated.HexDigest { i.lock.Lock() defer i.lock.Unlock() return isolated.HexDigest(i.digestItem.Digest) }
go
func (i *PendingItem) Digest() isolated.HexDigest { i.lock.Lock() defer i.lock.Unlock() return isolated.HexDigest(i.digestItem.Digest) }
[ "func", "(", "i", "*", "PendingItem", ")", "Digest", "(", ")", "isolated", ".", "HexDigest", "{", "i", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "i", ".", "lock", ".", "Unlock", "(", ")", "\n", "return", "isolated", ".", "HexDigest", "(", "i", ".", "digestItem", ".", "Digest", ")", "\n", "}" ]
// Digest returns the calculated digest once calculated, empty otherwise.
[ "Digest", "returns", "the", "calculated", "digest", "once", "calculated", "empty", "otherwise", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/archiver/archiver.go#L251-L255
7,126
luci/luci-go
client/archiver/archiver.go
SetErr
func (i *PendingItem) SetErr(err error) { if err == nil { panic("internal error") } i.lock.Lock() defer i.lock.Unlock() if i.err == nil { i.err = err for _, child := range i.linked { child.lock.Lock() child.err = err child.lock.Unlock() } } }
go
func (i *PendingItem) SetErr(err error) { if err == nil { panic("internal error") } i.lock.Lock() defer i.lock.Unlock() if i.err == nil { i.err = err for _, child := range i.linked { child.lock.Lock() child.err = err child.lock.Unlock() } } }
[ "func", "(", "i", "*", "PendingItem", ")", "SetErr", "(", "err", "error", ")", "{", "if", "err", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "i", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "i", ".", "lock", ".", "Unlock", "(", ")", "\n", "if", "i", ".", "err", "==", "nil", "{", "i", ".", "err", "=", "err", "\n", "for", "_", ",", "child", ":=", "range", "i", ".", "linked", "{", "child", ".", "lock", ".", "Lock", "(", ")", "\n", "child", ".", "err", "=", "err", "\n", "child", ".", "lock", ".", "Unlock", "(", ")", "\n", "}", "\n", "}", "\n", "}" ]
// SetErr forcibly set an item as failed. Normally not used by callers.
[ "SetErr", "forcibly", "set", "an", "item", "as", "failed", ".", "Normally", "not", "used", "by", "callers", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/archiver/archiver.go#L262-L276
7,127
luci/luci-go
client/archiver/archiver.go
Close
func (a *Archiver) Close() error { // This is done so asynchronously calling push() won't crash. a.closeLock.Lock() ok := false if a.stage1 != nil { close(a.stage1) a.stage1 = nil ok = true } a.closeLock.Unlock() if !ok { return errors.New("was already closed") } a.wg.Wait() _ = a.progress.Close() tracer.Instant(a, "done", tracer.Global, nil) err := a.ctx.Err() // Documentation says that not calling cancel() could cause a leak, so call // it, but not before taking the context's error, if any. a.cancel() return err }
go
func (a *Archiver) Close() error { // This is done so asynchronously calling push() won't crash. a.closeLock.Lock() ok := false if a.stage1 != nil { close(a.stage1) a.stage1 = nil ok = true } a.closeLock.Unlock() if !ok { return errors.New("was already closed") } a.wg.Wait() _ = a.progress.Close() tracer.Instant(a, "done", tracer.Global, nil) err := a.ctx.Err() // Documentation says that not calling cancel() could cause a leak, so call // it, but not before taking the context's error, if any. a.cancel() return err }
[ "func", "(", "a", "*", "Archiver", ")", "Close", "(", ")", "error", "{", "// This is done so asynchronously calling push() won't crash.", "a", ".", "closeLock", ".", "Lock", "(", ")", "\n", "ok", ":=", "false", "\n", "if", "a", ".", "stage1", "!=", "nil", "{", "close", "(", "a", ".", "stage1", ")", "\n", "a", ".", "stage1", "=", "nil", "\n", "ok", "=", "true", "\n", "}", "\n", "a", ".", "closeLock", ".", "Unlock", "(", ")", "\n\n", "if", "!", "ok", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "a", ".", "wg", ".", "Wait", "(", ")", "\n", "_", "=", "a", ".", "progress", ".", "Close", "(", ")", "\n", "tracer", ".", "Instant", "(", "a", ",", "\"", "\"", ",", "tracer", ".", "Global", ",", "nil", ")", "\n", "err", ":=", "a", ".", "ctx", ".", "Err", "(", ")", "\n", "// Documentation says that not calling cancel() could cause a leak, so call", "// it, but not before taking the context's error, if any.", "a", ".", "cancel", "(", ")", "\n", "return", "err", "\n", "}" ]
// Close waits for all pending files to be done. If an error occured during // processing, it is returned.
[ "Close", "waits", "for", "all", "pending", "files", "to", "be", "done", ".", "If", "an", "error", "occured", "during", "processing", "it", "is", "returned", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/archiver/archiver.go#L352-L375
7,128
luci/luci-go
client/archiver/archiver.go
Push
func (a *Archiver) Push(displayName string, source isolatedclient.Source, priority int64) *PendingItem { return a.push(newItem(a, displayName, "", source, priority)) }
go
func (a *Archiver) Push(displayName string, source isolatedclient.Source, priority int64) *PendingItem { return a.push(newItem(a, displayName, "", source, priority)) }
[ "func", "(", "a", "*", "Archiver", ")", "Push", "(", "displayName", "string", ",", "source", "isolatedclient", ".", "Source", ",", "priority", "int64", ")", "*", "PendingItem", "{", "return", "a", ".", "push", "(", "newItem", "(", "a", ",", "displayName", ",", "\"", "\"", ",", "source", ",", "priority", ")", ")", "\n", "}" ]
// Push schedules item upload to the isolate server. Smaller priority value // means earlier processing.
[ "Push", "schedules", "item", "upload", "to", "the", "isolate", "server", ".", "Smaller", "priority", "value", "means", "earlier", "processing", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/archiver/archiver.go#L384-L386
7,129
luci/luci-go
client/archiver/archiver.go
PushFile
func (a *Archiver) PushFile(displayName, path string, priority int64) *PendingItem { source := func() (io.ReadCloser, error) { return os.Open(path) } return a.push(newItem(a, displayName, path, source, priority)) }
go
func (a *Archiver) PushFile(displayName, path string, priority int64) *PendingItem { source := func() (io.ReadCloser, error) { return os.Open(path) } return a.push(newItem(a, displayName, path, source, priority)) }
[ "func", "(", "a", "*", "Archiver", ")", "PushFile", "(", "displayName", ",", "path", "string", ",", "priority", "int64", ")", "*", "PendingItem", "{", "source", ":=", "func", "(", ")", "(", "io", ".", "ReadCloser", ",", "error", ")", "{", "return", "os", ".", "Open", "(", "path", ")", "\n", "}", "\n", "return", "a", ".", "push", "(", "newItem", "(", "a", ",", "displayName", ",", "path", ",", "source", ",", "priority", ")", ")", "\n", "}" ]
// PushFile schedules file upload to the isolate server. Smaller priority // value means earlier processing.
[ "PushFile", "schedules", "file", "upload", "to", "the", "isolate", "server", ".", "Smaller", "priority", "value", "means", "earlier", "processing", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/archiver/archiver.go#L390-L395
7,130
luci/luci-go
client/archiver/archiver.go
Stats
func (a *Archiver) Stats() *Stats { a.statsLock.Lock() defer a.statsLock.Unlock() return a.stats.deepCopy() }
go
func (a *Archiver) Stats() *Stats { a.statsLock.Lock() defer a.statsLock.Unlock() return a.stats.deepCopy() }
[ "func", "(", "a", "*", "Archiver", ")", "Stats", "(", ")", "*", "Stats", "{", "a", ".", "statsLock", ".", "Lock", "(", ")", "\n", "defer", "a", ".", "statsLock", ".", "Unlock", "(", ")", "\n", "return", "a", ".", "stats", ".", "deepCopy", "(", ")", "\n", "}" ]
// Stats returns a copy of the statistics.
[ "Stats", "returns", "a", "copy", "of", "the", "statistics", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/archiver/archiver.go#L398-L402
7,131
luci/luci-go
client/archiver/archiver.go
doContains
func (a *Archiver) doContains(out chan<- *PendingItem, items []*PendingItem) { tmp := make([]*isolateservice.HandlersEndpointsV1Digest, len(items)) // No need to lock each item at that point, no mutation occurs on // PendingItem.digestItem after stage 2. for i, item := range items { tmp[i] = &item.digestItem } states, err := a.c.Contains(a.ctx, tmp) if err != nil { err = fmt.Errorf("contains(%d) failed: %s", len(items), err) // When an error occurs, early exit the process. a.cancel() for _, item := range items { item.SetErr(err) item.done() } return } a.progress.Update(groupLookup, groupLookupDone, int64(len(items))) for index, state := range states { size := items[index].digestItem.Size if state == nil { a.statsLock.Lock() a.stats.Hits = append(a.stats.Hits, units.Size(size)) a.statsLock.Unlock() items[index].done() } else { items[index].state = state a.progress.Update(groupUpload, groupUploadTodo, 1) a.progress.Update(groupUpload, groupUploadTodoSize, items[index].digestItem.Size) out <- items[index] } } logging.Infof(a.ctx, "Looked up %d items", len(items)) }
go
func (a *Archiver) doContains(out chan<- *PendingItem, items []*PendingItem) { tmp := make([]*isolateservice.HandlersEndpointsV1Digest, len(items)) // No need to lock each item at that point, no mutation occurs on // PendingItem.digestItem after stage 2. for i, item := range items { tmp[i] = &item.digestItem } states, err := a.c.Contains(a.ctx, tmp) if err != nil { err = fmt.Errorf("contains(%d) failed: %s", len(items), err) // When an error occurs, early exit the process. a.cancel() for _, item := range items { item.SetErr(err) item.done() } return } a.progress.Update(groupLookup, groupLookupDone, int64(len(items))) for index, state := range states { size := items[index].digestItem.Size if state == nil { a.statsLock.Lock() a.stats.Hits = append(a.stats.Hits, units.Size(size)) a.statsLock.Unlock() items[index].done() } else { items[index].state = state a.progress.Update(groupUpload, groupUploadTodo, 1) a.progress.Update(groupUpload, groupUploadTodoSize, items[index].digestItem.Size) out <- items[index] } } logging.Infof(a.ctx, "Looked up %d items", len(items)) }
[ "func", "(", "a", "*", "Archiver", ")", "doContains", "(", "out", "chan", "<-", "*", "PendingItem", ",", "items", "[", "]", "*", "PendingItem", ")", "{", "tmp", ":=", "make", "(", "[", "]", "*", "isolateservice", ".", "HandlersEndpointsV1Digest", ",", "len", "(", "items", ")", ")", "\n", "// No need to lock each item at that point, no mutation occurs on", "// PendingItem.digestItem after stage 2.", "for", "i", ",", "item", ":=", "range", "items", "{", "tmp", "[", "i", "]", "=", "&", "item", ".", "digestItem", "\n", "}", "\n", "states", ",", "err", ":=", "a", ".", "c", ".", "Contains", "(", "a", ".", "ctx", ",", "tmp", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "items", ")", ",", "err", ")", "\n", "// When an error occurs, early exit the process.", "a", ".", "cancel", "(", ")", "\n", "for", "_", ",", "item", ":=", "range", "items", "{", "item", ".", "SetErr", "(", "err", ")", "\n", "item", ".", "done", "(", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "a", ".", "progress", ".", "Update", "(", "groupLookup", ",", "groupLookupDone", ",", "int64", "(", "len", "(", "items", ")", ")", ")", "\n", "for", "index", ",", "state", ":=", "range", "states", "{", "size", ":=", "items", "[", "index", "]", ".", "digestItem", ".", "Size", "\n", "if", "state", "==", "nil", "{", "a", ".", "statsLock", ".", "Lock", "(", ")", "\n", "a", ".", "stats", ".", "Hits", "=", "append", "(", "a", ".", "stats", ".", "Hits", ",", "units", ".", "Size", "(", "size", ")", ")", "\n", "a", ".", "statsLock", ".", "Unlock", "(", ")", "\n", "items", "[", "index", "]", ".", "done", "(", ")", "\n", "}", "else", "{", "items", "[", "index", "]", ".", "state", "=", "state", "\n", "a", ".", "progress", ".", "Update", "(", "groupUpload", ",", "groupUploadTodo", ",", "1", ")", "\n", "a", ".", "progress", ".", "Update", "(", "groupUpload", ",", "groupUploadTodoSize", ",", "items", "[", "index", "]", ".", "digestItem", ".", "Size", ")", "\n", "out", "<-", "items", "[", "index", "]", "\n", "}", "\n", "}", "\n", "logging", ".", "Infof", "(", "a", ".", "ctx", ",", "\"", "\"", ",", "len", "(", "items", ")", ")", "\n", "}" ]
// doContains is called by stage 3.
[ "doContains", "is", "called", "by", "stage", "3", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/archiver/archiver.go#L582-L616
7,132
luci/luci-go
client/archiver/archiver.go
doUpload
func (a *Archiver) doUpload(item *PendingItem) { start := time.Now() if err := a.c.Push(a.ctx, item.state, item.source); err != nil { err = fmt.Errorf("push(%s) failed: %s", item.path, err) // When an error occurs, early exit the process. a.cancel() item.SetErr(err) item.done() return } a.progress.Update(groupUpload, groupUploadDone, 1) a.progress.Update(groupUpload, groupUploadDoneSize, item.digestItem.Size) item.done() size := units.Size(item.digestItem.Size) u := &UploadStat{time.Since(start), size, item.DisplayName} a.statsLock.Lock() a.stats.Pushed = append(a.stats.Pushed, u) a.statsLock.Unlock() logging.Infof(a.ctx, "Uploaded %7s: %s", size, item.DisplayName) }
go
func (a *Archiver) doUpload(item *PendingItem) { start := time.Now() if err := a.c.Push(a.ctx, item.state, item.source); err != nil { err = fmt.Errorf("push(%s) failed: %s", item.path, err) // When an error occurs, early exit the process. a.cancel() item.SetErr(err) item.done() return } a.progress.Update(groupUpload, groupUploadDone, 1) a.progress.Update(groupUpload, groupUploadDoneSize, item.digestItem.Size) item.done() size := units.Size(item.digestItem.Size) u := &UploadStat{time.Since(start), size, item.DisplayName} a.statsLock.Lock() a.stats.Pushed = append(a.stats.Pushed, u) a.statsLock.Unlock() logging.Infof(a.ctx, "Uploaded %7s: %s", size, item.DisplayName) }
[ "func", "(", "a", "*", "Archiver", ")", "doUpload", "(", "item", "*", "PendingItem", ")", "{", "start", ":=", "time", ".", "Now", "(", ")", "\n", "if", "err", ":=", "a", ".", "c", ".", "Push", "(", "a", ".", "ctx", ",", "item", ".", "state", ",", "item", ".", "source", ")", ";", "err", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "item", ".", "path", ",", "err", ")", "\n", "// When an error occurs, early exit the process.", "a", ".", "cancel", "(", ")", "\n", "item", ".", "SetErr", "(", "err", ")", "\n", "item", ".", "done", "(", ")", "\n", "return", "\n", "}", "\n", "a", ".", "progress", ".", "Update", "(", "groupUpload", ",", "groupUploadDone", ",", "1", ")", "\n", "a", ".", "progress", ".", "Update", "(", "groupUpload", ",", "groupUploadDoneSize", ",", "item", ".", "digestItem", ".", "Size", ")", "\n", "item", ".", "done", "(", ")", "\n", "size", ":=", "units", ".", "Size", "(", "item", ".", "digestItem", ".", "Size", ")", "\n", "u", ":=", "&", "UploadStat", "{", "time", ".", "Since", "(", "start", ")", ",", "size", ",", "item", ".", "DisplayName", "}", "\n", "a", ".", "statsLock", ".", "Lock", "(", ")", "\n", "a", ".", "stats", ".", "Pushed", "=", "append", "(", "a", ".", "stats", ".", "Pushed", ",", "u", ")", "\n", "a", ".", "statsLock", ".", "Unlock", "(", ")", "\n", "logging", ".", "Infof", "(", "a", ".", "ctx", ",", "\"", "\"", ",", "size", ",", "item", ".", "DisplayName", ")", "\n", "}" ]
// doUpload is called by stage 4.
[ "doUpload", "is", "called", "by", "stage", "4", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/archiver/archiver.go#L619-L638
7,133
luci/luci-go
common/iotools/countingWriter.go
WriteByte
func (c *CountingWriter) WriteByte(b byte) error { // If our underlying Writer is a ByteWriter, use its WriteByte directly. if bw, ok := c.Writer.(io.ByteWriter); ok { if err := bw.WriteByte(b); err != nil { return err } c.Count++ return nil } c.singleByteBuf[0] = b _, err := c.Write(c.singleByteBuf[:]) return err }
go
func (c *CountingWriter) WriteByte(b byte) error { // If our underlying Writer is a ByteWriter, use its WriteByte directly. if bw, ok := c.Writer.(io.ByteWriter); ok { if err := bw.WriteByte(b); err != nil { return err } c.Count++ return nil } c.singleByteBuf[0] = b _, err := c.Write(c.singleByteBuf[:]) return err }
[ "func", "(", "c", "*", "CountingWriter", ")", "WriteByte", "(", "b", "byte", ")", "error", "{", "// If our underlying Writer is a ByteWriter, use its WriteByte directly.", "if", "bw", ",", "ok", ":=", "c", ".", "Writer", ".", "(", "io", ".", "ByteWriter", ")", ";", "ok", "{", "if", "err", ":=", "bw", ".", "WriteByte", "(", "b", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "c", ".", "Count", "++", "\n", "return", "nil", "\n", "}", "\n\n", "c", ".", "singleByteBuf", "[", "0", "]", "=", "b", "\n", "_", ",", "err", ":=", "c", ".", "Write", "(", "c", ".", "singleByteBuf", "[", ":", "]", ")", "\n", "return", "err", "\n", "}" ]
// WriteByte implements io.ByteWriter.
[ "WriteByte", "implements", "io", ".", "ByteWriter", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/iotools/countingWriter.go#L42-L55
7,134
luci/luci-go
auth/client/luci_auth/luci_auth.go
GetApplication
func GetApplication(defaultAuthOpts auth.Options) *cli.Application { return &cli.Application{ Name: "luci-auth", Title: "LUCI Authentication Utility", Context: func(ctx context.Context) context.Context { return gologger.StdConfig.Use(ctx) }, Commands: []*subcommands.Command{ subcommands.CmdHelp, authcli.SubcommandInfoWithParams(authcli.CommandParams{ Name: "info", AuthOptions: defaultAuthOpts, ScopesFlag: true, }), authcli.SubcommandLoginWithParams(authcli.CommandParams{ Name: "login", AuthOptions: defaultAuthOpts, ScopesFlag: true, }), authcli.SubcommandLogoutWithParams(authcli.CommandParams{ Name: "logout", AuthOptions: defaultAuthOpts, ScopesFlag: true, }), authcli.SubcommandTokenWithParams(authcli.CommandParams{ Name: "token", AuthOptions: defaultAuthOpts, ScopesFlag: true, }), authcli.SubcommandContextWithParams(authcli.CommandParams{ Name: "context", Advanced: true, AuthOptions: defaultAuthOpts, ScopesFlag: true, }), }, } }
go
func GetApplication(defaultAuthOpts auth.Options) *cli.Application { return &cli.Application{ Name: "luci-auth", Title: "LUCI Authentication Utility", Context: func(ctx context.Context) context.Context { return gologger.StdConfig.Use(ctx) }, Commands: []*subcommands.Command{ subcommands.CmdHelp, authcli.SubcommandInfoWithParams(authcli.CommandParams{ Name: "info", AuthOptions: defaultAuthOpts, ScopesFlag: true, }), authcli.SubcommandLoginWithParams(authcli.CommandParams{ Name: "login", AuthOptions: defaultAuthOpts, ScopesFlag: true, }), authcli.SubcommandLogoutWithParams(authcli.CommandParams{ Name: "logout", AuthOptions: defaultAuthOpts, ScopesFlag: true, }), authcli.SubcommandTokenWithParams(authcli.CommandParams{ Name: "token", AuthOptions: defaultAuthOpts, ScopesFlag: true, }), authcli.SubcommandContextWithParams(authcli.CommandParams{ Name: "context", Advanced: true, AuthOptions: defaultAuthOpts, ScopesFlag: true, }), }, } }
[ "func", "GetApplication", "(", "defaultAuthOpts", "auth", ".", "Options", ")", "*", "cli", ".", "Application", "{", "return", "&", "cli", ".", "Application", "{", "Name", ":", "\"", "\"", ",", "Title", ":", "\"", "\"", ",", "Context", ":", "func", "(", "ctx", "context", ".", "Context", ")", "context", ".", "Context", "{", "return", "gologger", ".", "StdConfig", ".", "Use", "(", "ctx", ")", "\n", "}", ",", "Commands", ":", "[", "]", "*", "subcommands", ".", "Command", "{", "subcommands", ".", "CmdHelp", ",", "authcli", ".", "SubcommandInfoWithParams", "(", "authcli", ".", "CommandParams", "{", "Name", ":", "\"", "\"", ",", "AuthOptions", ":", "defaultAuthOpts", ",", "ScopesFlag", ":", "true", ",", "}", ")", ",", "authcli", ".", "SubcommandLoginWithParams", "(", "authcli", ".", "CommandParams", "{", "Name", ":", "\"", "\"", ",", "AuthOptions", ":", "defaultAuthOpts", ",", "ScopesFlag", ":", "true", ",", "}", ")", ",", "authcli", ".", "SubcommandLogoutWithParams", "(", "authcli", ".", "CommandParams", "{", "Name", ":", "\"", "\"", ",", "AuthOptions", ":", "defaultAuthOpts", ",", "ScopesFlag", ":", "true", ",", "}", ")", ",", "authcli", ".", "SubcommandTokenWithParams", "(", "authcli", ".", "CommandParams", "{", "Name", ":", "\"", "\"", ",", "AuthOptions", ":", "defaultAuthOpts", ",", "ScopesFlag", ":", "true", ",", "}", ")", ",", "authcli", ".", "SubcommandContextWithParams", "(", "authcli", ".", "CommandParams", "{", "Name", ":", "\"", "\"", ",", "Advanced", ":", "true", ",", "AuthOptions", ":", "defaultAuthOpts", ",", "ScopesFlag", ":", "true", ",", "}", ")", ",", "}", ",", "}", "\n", "}" ]
// GetApplication returns cli.Application that implements 'luci-auth'. // // It does NOT hardcode any default values. Defaults are hardcoded in // corresponding 'main' package.
[ "GetApplication", "returns", "cli", ".", "Application", "that", "implements", "luci", "-", "auth", ".", "It", "does", "NOT", "hardcode", "any", "default", "values", ".", "Defaults", "are", "hardcoded", "in", "corresponding", "main", "package", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/client/luci_auth/luci_auth.go#L32-L69
7,135
luci/luci-go
milo/buildsource/buildbot/buildstore/emulation.go
WithEmulation
func WithEmulation(c context.Context, enabled bool) context.Context { return context.WithValue(c, &emulationEnabledKey, enabled) }
go
func WithEmulation(c context.Context, enabled bool) context.Context { return context.WithValue(c, &emulationEnabledKey, enabled) }
[ "func", "WithEmulation", "(", "c", "context", ".", "Context", ",", "enabled", "bool", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "c", ",", "&", "emulationEnabledKey", ",", "enabled", ")", "\n", "}" ]
// WithEmulation enables or disables emulation.
[ "WithEmulation", "enables", "or", "disables", "emulation", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildstore/emulation.go#L37-L39
7,136
luci/luci-go
milo/buildsource/buildbot/buildstore/emulation.go
EmulationEnabled
func EmulationEnabled(c context.Context) bool { enabled, _ := c.Value(&emulationEnabledKey).(bool) return enabled }
go
func EmulationEnabled(c context.Context) bool { enabled, _ := c.Value(&emulationEnabledKey).(bool) return enabled }
[ "func", "EmulationEnabled", "(", "c", "context", ".", "Context", ")", "bool", "{", "enabled", ",", "_", ":=", "c", ".", "Value", "(", "&", "emulationEnabledKey", ")", ".", "(", "bool", ")", "\n", "return", "enabled", "\n", "}" ]
// EmulationEnabled returns true if emulation is enabled in c.
[ "EmulationEnabled", "returns", "true", "if", "emulation", "is", "enabled", "in", "c", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildstore/emulation.go#L42-L45
7,137
luci/luci-go
milo/buildsource/buildbot/buildstore/emulation.go
BucketOf
func BucketOf(c context.Context, master string) (string, error) { v, err := bucketCache.GetOrCreate(c, master, func() (v interface{}, exp time.Duration, err error) { transport, err := auth.GetRPCTransport(c, auth.AsSelf) if err != nil { return nil, 0, err } u := fmt.Sprintf("https://luci-migration.appspot.com/masters/%s/?format=json", url.PathEscape(master)) var bucket string err = retry.Retry(c, retry.Default, func() error { res, err := ctxhttp.Get(c, &http.Client{Transport: transport}, u) if err != nil { return err } defer res.Body.Close() switch { case res.StatusCode == http.StatusNotFound: return nil case res.StatusCode != http.StatusOK: return errors.Reason("migration app returned HTTP %d", res.StatusCode).Err() } var body struct { Bucket string } if err := json.NewDecoder(res.Body).Decode(&body); err != nil { return errors.Annotate(err, "could not decode migration app's response body").Err() } bucket = body.Bucket return nil }, retry.LogCallback(c, "luci-migration-get-master")) if err != nil { return nil, 0, err } // cache the result for 10min in process memory and memcache. return bucket, 10 * time.Minute, nil }) bucket, _ := v.(string) return bucket, err }
go
func BucketOf(c context.Context, master string) (string, error) { v, err := bucketCache.GetOrCreate(c, master, func() (v interface{}, exp time.Duration, err error) { transport, err := auth.GetRPCTransport(c, auth.AsSelf) if err != nil { return nil, 0, err } u := fmt.Sprintf("https://luci-migration.appspot.com/masters/%s/?format=json", url.PathEscape(master)) var bucket string err = retry.Retry(c, retry.Default, func() error { res, err := ctxhttp.Get(c, &http.Client{Transport: transport}, u) if err != nil { return err } defer res.Body.Close() switch { case res.StatusCode == http.StatusNotFound: return nil case res.StatusCode != http.StatusOK: return errors.Reason("migration app returned HTTP %d", res.StatusCode).Err() } var body struct { Bucket string } if err := json.NewDecoder(res.Body).Decode(&body); err != nil { return errors.Annotate(err, "could not decode migration app's response body").Err() } bucket = body.Bucket return nil }, retry.LogCallback(c, "luci-migration-get-master")) if err != nil { return nil, 0, err } // cache the result for 10min in process memory and memcache. return bucket, 10 * time.Minute, nil }) bucket, _ := v.(string) return bucket, err }
[ "func", "BucketOf", "(", "c", "context", ".", "Context", ",", "master", "string", ")", "(", "string", ",", "error", ")", "{", "v", ",", "err", ":=", "bucketCache", ".", "GetOrCreate", "(", "c", ",", "master", ",", "func", "(", ")", "(", "v", "interface", "{", "}", ",", "exp", "time", ".", "Duration", ",", "err", "error", ")", "{", "transport", ",", "err", ":=", "auth", ".", "GetRPCTransport", "(", "c", ",", "auth", ".", "AsSelf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "err", "\n", "}", "\n", "u", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "url", ".", "PathEscape", "(", "master", ")", ")", "\n", "var", "bucket", "string", "\n", "err", "=", "retry", ".", "Retry", "(", "c", ",", "retry", ".", "Default", ",", "func", "(", ")", "error", "{", "res", ",", "err", ":=", "ctxhttp", ".", "Get", "(", "c", ",", "&", "http", ".", "Client", "{", "Transport", ":", "transport", "}", ",", "u", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "res", ".", "Body", ".", "Close", "(", ")", "\n", "switch", "{", "case", "res", ".", "StatusCode", "==", "http", ".", "StatusNotFound", ":", "return", "nil", "\n", "case", "res", ".", "StatusCode", "!=", "http", ".", "StatusOK", ":", "return", "errors", ".", "Reason", "(", "\"", "\"", ",", "res", ".", "StatusCode", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "var", "body", "struct", "{", "Bucket", "string", "\n", "}", "\n", "if", "err", ":=", "json", ".", "NewDecoder", "(", "res", ".", "Body", ")", ".", "Decode", "(", "&", "body", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "bucket", "=", "body", ".", "Bucket", "\n", "return", "nil", "\n", "}", ",", "retry", ".", "LogCallback", "(", "c", ",", "\"", "\"", ")", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "err", "\n", "}", "\n", "// cache the result for 10min in process memory and memcache.", "return", "bucket", ",", "10", "*", "time", ".", "Minute", ",", "nil", "\n", "}", ")", "\n\n", "bucket", ",", "_", ":=", "v", ".", "(", "string", ")", "\n", "return", "bucket", ",", "err", "\n", "}" ]
// BucketOf returns LUCI bucket that the given buildbot master is migrating to. // Returns "" if it is unknown.
[ "BucketOf", "returns", "LUCI", "bucket", "that", "the", "given", "buildbot", "master", "is", "migrating", "to", ".", "Returns", "if", "it", "is", "unknown", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildstore/emulation.go#L60-L101
7,138
luci/luci-go
milo/buildsource/console.go
GetConsoleRows
func GetConsoleRows(c context.Context, project string, console *config.Console, commits []string) ([]*ConsoleRow, error) { rawCommits := make([][]byte, len(commits)) for i, c := range commits { var err error if rawCommits[i], err = hex.DecodeString(c); err != nil { return nil, errors.Annotate(err, "bad commit[%d]: %q", i, c).Err() } } // Maps all builderIDs to the indexes of the columns it appears in. columnMap := map[string][]int{} for columnIdx, b := range console.Builders { for _, name := range b.Name { columnMap[name] = append(columnMap[name], columnIdx) } } ret := make([]*ConsoleRow, len(commits)) url := console.RepoUrl // HACK(iannucci): This little hack should be removed when console definitions // no longer use a manifest name of "REVISION". REVISION was used to index the // 'got_revision' value before manifests were implemented. if console.ManifestName == "REVISION" { url = "" } partialKey := model.NewPartialManifestKey(project, console.Id, console.ManifestName, url) q := datastore.NewQuery("BuildSummary") err := parallel.WorkPool(16, func(ch chan<- func() error) { for i := range rawCommits { i := i r := &ConsoleRow{Commit: commits[i]} ret[i] = r ch <- func() error { fullQ := q.Eq("ManifestKeys", partialKey.AddRevision(rawCommits[i])) return datastore.Run(c, fullQ, func(bs *model.BuildSummary) { if bs.Experimental && !console.IncludeExperimentalBuilds { return } if columnIdxs, ok := columnMap[bs.BuilderID]; ok { if r.Builds == nil { r.Builds = map[int][]*model.BuildSummary{} } for _, columnIdx := range columnIdxs { r.Builds[columnIdx] = append(r.Builds[columnIdx], bs) } } }) } } }) return ret, err }
go
func GetConsoleRows(c context.Context, project string, console *config.Console, commits []string) ([]*ConsoleRow, error) { rawCommits := make([][]byte, len(commits)) for i, c := range commits { var err error if rawCommits[i], err = hex.DecodeString(c); err != nil { return nil, errors.Annotate(err, "bad commit[%d]: %q", i, c).Err() } } // Maps all builderIDs to the indexes of the columns it appears in. columnMap := map[string][]int{} for columnIdx, b := range console.Builders { for _, name := range b.Name { columnMap[name] = append(columnMap[name], columnIdx) } } ret := make([]*ConsoleRow, len(commits)) url := console.RepoUrl // HACK(iannucci): This little hack should be removed when console definitions // no longer use a manifest name of "REVISION". REVISION was used to index the // 'got_revision' value before manifests were implemented. if console.ManifestName == "REVISION" { url = "" } partialKey := model.NewPartialManifestKey(project, console.Id, console.ManifestName, url) q := datastore.NewQuery("BuildSummary") err := parallel.WorkPool(16, func(ch chan<- func() error) { for i := range rawCommits { i := i r := &ConsoleRow{Commit: commits[i]} ret[i] = r ch <- func() error { fullQ := q.Eq("ManifestKeys", partialKey.AddRevision(rawCommits[i])) return datastore.Run(c, fullQ, func(bs *model.BuildSummary) { if bs.Experimental && !console.IncludeExperimentalBuilds { return } if columnIdxs, ok := columnMap[bs.BuilderID]; ok { if r.Builds == nil { r.Builds = map[int][]*model.BuildSummary{} } for _, columnIdx := range columnIdxs { r.Builds[columnIdx] = append(r.Builds[columnIdx], bs) } } }) } } }) return ret, err }
[ "func", "GetConsoleRows", "(", "c", "context", ".", "Context", ",", "project", "string", ",", "console", "*", "config", ".", "Console", ",", "commits", "[", "]", "string", ")", "(", "[", "]", "*", "ConsoleRow", ",", "error", ")", "{", "rawCommits", ":=", "make", "(", "[", "]", "[", "]", "byte", ",", "len", "(", "commits", ")", ")", "\n", "for", "i", ",", "c", ":=", "range", "commits", "{", "var", "err", "error", "\n", "if", "rawCommits", "[", "i", "]", ",", "err", "=", "hex", ".", "DecodeString", "(", "c", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "i", ",", "c", ")", ".", "Err", "(", ")", "\n", "}", "\n", "}", "\n\n", "// Maps all builderIDs to the indexes of the columns it appears in.", "columnMap", ":=", "map", "[", "string", "]", "[", "]", "int", "{", "}", "\n", "for", "columnIdx", ",", "b", ":=", "range", "console", ".", "Builders", "{", "for", "_", ",", "name", ":=", "range", "b", ".", "Name", "{", "columnMap", "[", "name", "]", "=", "append", "(", "columnMap", "[", "name", "]", ",", "columnIdx", ")", "\n", "}", "\n", "}", "\n\n", "ret", ":=", "make", "(", "[", "]", "*", "ConsoleRow", ",", "len", "(", "commits", ")", ")", "\n", "url", ":=", "console", ".", "RepoUrl", "\n", "// HACK(iannucci): This little hack should be removed when console definitions", "// no longer use a manifest name of \"REVISION\". REVISION was used to index the", "// 'got_revision' value before manifests were implemented.", "if", "console", ".", "ManifestName", "==", "\"", "\"", "{", "url", "=", "\"", "\"", "\n", "}", "\n", "partialKey", ":=", "model", ".", "NewPartialManifestKey", "(", "project", ",", "console", ".", "Id", ",", "console", ".", "ManifestName", ",", "url", ")", "\n", "q", ":=", "datastore", ".", "NewQuery", "(", "\"", "\"", ")", "\n", "err", ":=", "parallel", ".", "WorkPool", "(", "16", ",", "func", "(", "ch", "chan", "<-", "func", "(", ")", "error", ")", "{", "for", "i", ":=", "range", "rawCommits", "{", "i", ":=", "i", "\n", "r", ":=", "&", "ConsoleRow", "{", "Commit", ":", "commits", "[", "i", "]", "}", "\n", "ret", "[", "i", "]", "=", "r", "\n", "ch", "<-", "func", "(", ")", "error", "{", "fullQ", ":=", "q", ".", "Eq", "(", "\"", "\"", ",", "partialKey", ".", "AddRevision", "(", "rawCommits", "[", "i", "]", ")", ")", "\n", "return", "datastore", ".", "Run", "(", "c", ",", "fullQ", ",", "func", "(", "bs", "*", "model", ".", "BuildSummary", ")", "{", "if", "bs", ".", "Experimental", "&&", "!", "console", ".", "IncludeExperimentalBuilds", "{", "return", "\n", "}", "\n", "if", "columnIdxs", ",", "ok", ":=", "columnMap", "[", "bs", ".", "BuilderID", "]", ";", "ok", "{", "if", "r", ".", "Builds", "==", "nil", "{", "r", ".", "Builds", "=", "map", "[", "int", "]", "[", "]", "*", "model", ".", "BuildSummary", "{", "}", "\n", "}", "\n", "for", "_", ",", "columnIdx", ":=", "range", "columnIdxs", "{", "r", ".", "Builds", "[", "columnIdx", "]", "=", "append", "(", "r", ".", "Builds", "[", "columnIdx", "]", ",", "bs", ")", "\n", "}", "\n", "}", "\n", "}", ")", "\n", "}", "\n", "}", "\n", "}", ")", "\n\n", "return", "ret", ",", "err", "\n", "}" ]
// GetConsoleRows returns a row-oriented collection of BuildSummary // objects. Each row corresponds to the similarly-indexed commit in the // `commits` slice.
[ "GetConsoleRows", "returns", "a", "row", "-", "oriented", "collection", "of", "BuildSummary", "objects", ".", "Each", "row", "corresponds", "to", "the", "similarly", "-", "indexed", "commit", "in", "the", "commits", "slice", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/console.go#L51-L103
7,139
luci/luci-go
dm/appengine/mutate/filter_existing.go
filterExisting
func filterExisting(c context.Context, fwdDeps []*model.FwdDep) ([]*model.FwdDep, error) { ret := make([]*model.FwdDep, 0, len(fwdDeps)) err := ds.Get(c, fwdDeps) if err == nil { return nil, nil } merr, ok := err.(errors.MultiError) if !ok { return nil, err } for i, err := range merr { if err == nil { continue } ret = append(ret, fwdDeps[i]) } return ret, nil }
go
func filterExisting(c context.Context, fwdDeps []*model.FwdDep) ([]*model.FwdDep, error) { ret := make([]*model.FwdDep, 0, len(fwdDeps)) err := ds.Get(c, fwdDeps) if err == nil { return nil, nil } merr, ok := err.(errors.MultiError) if !ok { return nil, err } for i, err := range merr { if err == nil { continue } ret = append(ret, fwdDeps[i]) } return ret, nil }
[ "func", "filterExisting", "(", "c", "context", ".", "Context", ",", "fwdDeps", "[", "]", "*", "model", ".", "FwdDep", ")", "(", "[", "]", "*", "model", ".", "FwdDep", ",", "error", ")", "{", "ret", ":=", "make", "(", "[", "]", "*", "model", ".", "FwdDep", ",", "0", ",", "len", "(", "fwdDeps", ")", ")", "\n\n", "err", ":=", "ds", ".", "Get", "(", "c", ",", "fwdDeps", ")", "\n", "if", "err", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "merr", ",", "ok", ":=", "err", ".", "(", "errors", ".", "MultiError", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "for", "i", ",", "err", ":=", "range", "merr", "{", "if", "err", "==", "nil", "{", "continue", "\n", "}", "\n", "ret", "=", "append", "(", "ret", ",", "fwdDeps", "[", "i", "]", ")", "\n", "}", "\n\n", "return", "ret", ",", "nil", "\n", "}" ]
// filterExisting removes the FwdDep objects which already exist. // // returns gRPC code error.
[ "filterExisting", "removes", "the", "FwdDep", "objects", "which", "already", "exist", ".", "returns", "gRPC", "code", "error", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/mutate/filter_existing.go#L28-L49
7,140
luci/luci-go
tumble/process.go
processShard
func processShard(c context.Context, cfg *Config, timestamp time.Time, shard uint64, loop bool) error { logging.Fields{ "shard": shard, }.Infof(c, "Processing tumble shard.") q := processShardQuery(c, cfg, shard) if q == nil { logging.Warningf(c, "dead shard, quitting") return nil } // Calculate our end itme. If we're not looping or we have a <= 0 duration, // we will perform a single loop. var endTime time.Time if cfg.ProcessLoopDuration > 0 { endTime = clock.Now(c).Add(time.Duration(cfg.ProcessLoopDuration)) logging.Debugf(c, "Process loop is configured to exit after [%s] at %s", cfg.ProcessLoopDuration.String(), endTime) } // Lock around the shard that we are trying to modify. // // Since memcache is namespaced, we don't need to include the namespace in our // lock name. task := makeProcessTask(timestamp, endTime, shard, loop) lockKey := fmt.Sprintf("%s.%d.lock", baseName, shard) clientID := fmt.Sprintf("%d_%d_%s", timestamp.Unix(), shard, info.RequestID(c)) err := memlock.TryWithLock(c, lockKey, clientID, func(c context.Context) error { return task.process(c, cfg, q) }) if err == memlock.ErrFailedToLock { logging.Infof(c, "Couldn't obtain lock (giving up): %s", err) return nil } return err }
go
func processShard(c context.Context, cfg *Config, timestamp time.Time, shard uint64, loop bool) error { logging.Fields{ "shard": shard, }.Infof(c, "Processing tumble shard.") q := processShardQuery(c, cfg, shard) if q == nil { logging.Warningf(c, "dead shard, quitting") return nil } // Calculate our end itme. If we're not looping or we have a <= 0 duration, // we will perform a single loop. var endTime time.Time if cfg.ProcessLoopDuration > 0 { endTime = clock.Now(c).Add(time.Duration(cfg.ProcessLoopDuration)) logging.Debugf(c, "Process loop is configured to exit after [%s] at %s", cfg.ProcessLoopDuration.String(), endTime) } // Lock around the shard that we are trying to modify. // // Since memcache is namespaced, we don't need to include the namespace in our // lock name. task := makeProcessTask(timestamp, endTime, shard, loop) lockKey := fmt.Sprintf("%s.%d.lock", baseName, shard) clientID := fmt.Sprintf("%d_%d_%s", timestamp.Unix(), shard, info.RequestID(c)) err := memlock.TryWithLock(c, lockKey, clientID, func(c context.Context) error { return task.process(c, cfg, q) }) if err == memlock.ErrFailedToLock { logging.Infof(c, "Couldn't obtain lock (giving up): %s", err) return nil } return err }
[ "func", "processShard", "(", "c", "context", ".", "Context", ",", "cfg", "*", "Config", ",", "timestamp", "time", ".", "Time", ",", "shard", "uint64", ",", "loop", "bool", ")", "error", "{", "logging", ".", "Fields", "{", "\"", "\"", ":", "shard", ",", "}", ".", "Infof", "(", "c", ",", "\"", "\"", ")", "\n\n", "q", ":=", "processShardQuery", "(", "c", ",", "cfg", ",", "shard", ")", "\n", "if", "q", "==", "nil", "{", "logging", ".", "Warningf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n\n", "// Calculate our end itme. If we're not looping or we have a <= 0 duration,", "// we will perform a single loop.", "var", "endTime", "time", ".", "Time", "\n", "if", "cfg", ".", "ProcessLoopDuration", ">", "0", "{", "endTime", "=", "clock", ".", "Now", "(", "c", ")", ".", "Add", "(", "time", ".", "Duration", "(", "cfg", ".", "ProcessLoopDuration", ")", ")", "\n", "logging", ".", "Debugf", "(", "c", ",", "\"", "\"", ",", "cfg", ".", "ProcessLoopDuration", ".", "String", "(", ")", ",", "endTime", ")", "\n", "}", "\n\n", "// Lock around the shard that we are trying to modify.", "//", "// Since memcache is namespaced, we don't need to include the namespace in our", "// lock name.", "task", ":=", "makeProcessTask", "(", "timestamp", ",", "endTime", ",", "shard", ",", "loop", ")", "\n", "lockKey", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "baseName", ",", "shard", ")", "\n", "clientID", ":=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "timestamp", ".", "Unix", "(", ")", ",", "shard", ",", "info", ".", "RequestID", "(", "c", ")", ")", "\n\n", "err", ":=", "memlock", ".", "TryWithLock", "(", "c", ",", "lockKey", ",", "clientID", ",", "func", "(", "c", "context", ".", "Context", ")", "error", "{", "return", "task", ".", "process", "(", "c", ",", "cfg", ",", "q", ")", "\n", "}", ")", "\n", "if", "err", "==", "memlock", ".", "ErrFailedToLock", "{", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "err", ")", "\n", "return", "nil", "\n", "}", "\n", "return", "err", "\n", "}" ]
// processShard is the tumble backend endpoint. This accepts a shard number // which is expected to be < GlobalConfig.NumShards.
[ "processShard", "is", "the", "tumble", "backend", "endpoint", ".", "This", "accepts", "a", "shard", "number", "which", "is", "expected", "to", "be", "<", "GlobalConfig", ".", "NumShards", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tumble/process.go#L106-L143
7,141
luci/luci-go
machine-db/client/cli/hosts.go
Run
func (c *DeleteHostCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int { ctx := cli.GetContext(app, c, env) // TODO(smut): Validate required fields client-side. client := getClient(ctx) _, err := client.DeleteHost(ctx, &c.req) if err != nil { errors.Log(ctx, err) return 1 } return 0 }
go
func (c *DeleteHostCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int { ctx := cli.GetContext(app, c, env) // TODO(smut): Validate required fields client-side. client := getClient(ctx) _, err := client.DeleteHost(ctx, &c.req) if err != nil { errors.Log(ctx, err) return 1 } return 0 }
[ "func", "(", "c", "*", "DeleteHostCmd", ")", "Run", "(", "app", "subcommands", ".", "Application", ",", "args", "[", "]", "string", ",", "env", "subcommands", ".", "Env", ")", "int", "{", "ctx", ":=", "cli", ".", "GetContext", "(", "app", ",", "c", ",", "env", ")", "\n", "// TODO(smut): Validate required fields client-side.", "client", ":=", "getClient", "(", "ctx", ")", "\n", "_", ",", "err", ":=", "client", ".", "DeleteHost", "(", "ctx", ",", "&", "c", ".", "req", ")", "\n", "if", "err", "!=", "nil", "{", "errors", ".", "Log", "(", "ctx", ",", "err", ")", "\n", "return", "1", "\n", "}", "\n", "return", "0", "\n", "}" ]
// Run runs the command to delete a host.
[ "Run", "runs", "the", "command", "to", "delete", "a", "host", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/hosts.go#L33-L43
7,142
luci/luci-go
machine-db/client/cli/hosts.go
deleteHostCmd
func deleteHostCmd(params *Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "del-host -name name", ShortDesc: "deletes a host", LongDesc: "Deletes a physical or virtual host from the database.\n\nExample:\ncrimson del-host -name vm100-y1", CommandRun: func() subcommands.CommandRun { cmd := &DeleteHostCmd{} cmd.Initialize(params) cmd.Flags.StringVar(&cmd.req.Name, "name", "", "The name of the host to delete.") cmd.Flags.Int64Var(&cmd.req.Vlan, "vlan", 0, "The VLAN the host belongs to.") return cmd }, } }
go
func deleteHostCmd(params *Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "del-host -name name", ShortDesc: "deletes a host", LongDesc: "Deletes a physical or virtual host from the database.\n\nExample:\ncrimson del-host -name vm100-y1", CommandRun: func() subcommands.CommandRun { cmd := &DeleteHostCmd{} cmd.Initialize(params) cmd.Flags.StringVar(&cmd.req.Name, "name", "", "The name of the host to delete.") cmd.Flags.Int64Var(&cmd.req.Vlan, "vlan", 0, "The VLAN the host belongs to.") return cmd }, } }
[ "func", "deleteHostCmd", "(", "params", "*", "Parameters", ")", "*", "subcommands", ".", "Command", "{", "return", "&", "subcommands", ".", "Command", "{", "UsageLine", ":", "\"", "\"", ",", "ShortDesc", ":", "\"", "\"", ",", "LongDesc", ":", "\"", "\\n", "\\n", "\\n", "\"", ",", "CommandRun", ":", "func", "(", ")", "subcommands", ".", "CommandRun", "{", "cmd", ":=", "&", "DeleteHostCmd", "{", "}", "\n", "cmd", ".", "Initialize", "(", "params", ")", "\n", "cmd", ".", "Flags", ".", "StringVar", "(", "&", "cmd", ".", "req", ".", "Name", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Flags", ".", "Int64Var", "(", "&", "cmd", ".", "req", ".", "Vlan", ",", "\"", "\"", ",", "0", ",", "\"", "\"", ")", "\n", "return", "cmd", "\n", "}", ",", "}", "\n", "}" ]
// deleteHostCmd returns a command to delete a host.
[ "deleteHostCmd", "returns", "a", "command", "to", "delete", "a", "host", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/hosts.go#L46-L59
7,143
luci/luci-go
logdog/api/endpoints/coordinator/logs/v1/fakelogs/client.go
Get
func (c *Client) Get(_ context.Context, in *logs_api.GetRequest, _ ...grpc.CallOption) (*logs_api.GetResponse, error) { realIn := *in realIn.Project = coordinatorTest.AllAccessProject return c.logsServ.Get(c.ctx, &realIn) }
go
func (c *Client) Get(_ context.Context, in *logs_api.GetRequest, _ ...grpc.CallOption) (*logs_api.GetResponse, error) { realIn := *in realIn.Project = coordinatorTest.AllAccessProject return c.logsServ.Get(c.ctx, &realIn) }
[ "func", "(", "c", "*", "Client", ")", "Get", "(", "_", "context", ".", "Context", ",", "in", "*", "logs_api", ".", "GetRequest", ",", "_", "...", "grpc", ".", "CallOption", ")", "(", "*", "logs_api", ".", "GetResponse", ",", "error", ")", "{", "realIn", ":=", "*", "in", "\n", "realIn", ".", "Project", "=", "coordinatorTest", ".", "AllAccessProject", "\n", "return", "c", ".", "logsServ", ".", "Get", "(", "c", ".", "ctx", ",", "&", "realIn", ")", "\n", "}" ]
// Get implements logs.Get.
[ "Get", "implements", "logs", ".", "Get", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/api/endpoints/coordinator/logs/v1/fakelogs/client.go#L89-L93
7,144
luci/luci-go
logdog/api/endpoints/coordinator/logs/v1/fakelogs/client.go
Query
func (c *Client) Query(_ context.Context, in *logs_api.QueryRequest, _ ...grpc.CallOption) (*logs_api.QueryResponse, error) { realIn := *in realIn.Project = coordinatorTest.AllAccessProject return c.logsServ.Query(c.ctx, &realIn) }
go
func (c *Client) Query(_ context.Context, in *logs_api.QueryRequest, _ ...grpc.CallOption) (*logs_api.QueryResponse, error) { realIn := *in realIn.Project = coordinatorTest.AllAccessProject return c.logsServ.Query(c.ctx, &realIn) }
[ "func", "(", "c", "*", "Client", ")", "Query", "(", "_", "context", ".", "Context", ",", "in", "*", "logs_api", ".", "QueryRequest", ",", "_", "...", "grpc", ".", "CallOption", ")", "(", "*", "logs_api", ".", "QueryResponse", ",", "error", ")", "{", "realIn", ":=", "*", "in", "\n", "realIn", ".", "Project", "=", "coordinatorTest", ".", "AllAccessProject", "\n", "return", "c", ".", "logsServ", ".", "Query", "(", "c", ".", "ctx", ",", "&", "realIn", ")", "\n", "}" ]
// Query implements logs.Query.
[ "Query", "implements", "logs", ".", "Query", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/api/endpoints/coordinator/logs/v1/fakelogs/client.go#L103-L107
7,145
luci/luci-go
logdog/api/endpoints/coordinator/logs/v1/fakelogs/client.go
OpenDatagramStream
func (c *Client) OpenDatagramStream(prefix, path logdog_types.StreamName, flags ...*streamproto.Flags) (*Stream, error) { return c.open(logpb.StreamType_DATAGRAM, prefix, path, flags...) }
go
func (c *Client) OpenDatagramStream(prefix, path logdog_types.StreamName, flags ...*streamproto.Flags) (*Stream, error) { return c.open(logpb.StreamType_DATAGRAM, prefix, path, flags...) }
[ "func", "(", "c", "*", "Client", ")", "OpenDatagramStream", "(", "prefix", ",", "path", "logdog_types", ".", "StreamName", ",", "flags", "...", "*", "streamproto", ".", "Flags", ")", "(", "*", "Stream", ",", "error", ")", "{", "return", "c", ".", "open", "(", "logpb", ".", "StreamType_DATAGRAM", ",", "prefix", ",", "path", ",", "flags", "...", ")", "\n", "}" ]
// OpenDatagramStream returns a stream for datagrams. // // Each Write will produce a single complete datagram in the stream.
[ "OpenDatagramStream", "returns", "a", "stream", "for", "datagrams", ".", "Each", "Write", "will", "produce", "a", "single", "complete", "datagram", "in", "the", "stream", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/api/endpoints/coordinator/logs/v1/fakelogs/client.go#L122-L124
7,146
luci/luci-go
logdog/api/endpoints/coordinator/logs/v1/fakelogs/client.go
OpenBinaryStream
func (c *Client) OpenBinaryStream(prefix, path logdog_types.StreamName, flags ...*streamproto.Flags) (*Stream, error) { return c.open(logpb.StreamType_BINARY, prefix, path, flags...) }
go
func (c *Client) OpenBinaryStream(prefix, path logdog_types.StreamName, flags ...*streamproto.Flags) (*Stream, error) { return c.open(logpb.StreamType_BINARY, prefix, path, flags...) }
[ "func", "(", "c", "*", "Client", ")", "OpenBinaryStream", "(", "prefix", ",", "path", "logdog_types", ".", "StreamName", ",", "flags", "...", "*", "streamproto", ".", "Flags", ")", "(", "*", "Stream", ",", "error", ")", "{", "return", "c", ".", "open", "(", "logpb", ".", "StreamType_BINARY", ",", "prefix", ",", "path", ",", "flags", "...", ")", "\n", "}" ]
// OpenBinaryStream returns a stream for binary data. // // Each Write will append to the binary data like a normal raw file.
[ "OpenBinaryStream", "returns", "a", "stream", "for", "binary", "data", ".", "Each", "Write", "will", "append", "to", "the", "binary", "data", "like", "a", "normal", "raw", "file", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/api/endpoints/coordinator/logs/v1/fakelogs/client.go#L129-L131
7,147
luci/luci-go
logdog/api/endpoints/coordinator/logs/v1/fakelogs/client.go
GetSignedURLs
func (s storageclient) GetSignedURLs(context.Context, *coordinator.URLSigningRequest) (*coordinator.URLSigningResponse, error) { return nil, errors.New("NOT IMPLEMENTED") }
go
func (s storageclient) GetSignedURLs(context.Context, *coordinator.URLSigningRequest) (*coordinator.URLSigningResponse, error) { return nil, errors.New("NOT IMPLEMENTED") }
[ "func", "(", "s", "storageclient", ")", "GetSignedURLs", "(", "context", ".", "Context", ",", "*", "coordinator", ".", "URLSigningRequest", ")", "(", "*", "coordinator", ".", "URLSigningResponse", ",", "error", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// GetSignedURLs is implemented to fill out the coordinator.Storage interface.
[ "GetSignedURLs", "is", "implemented", "to", "fill", "out", "the", "coordinator", ".", "Storage", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/api/endpoints/coordinator/logs/v1/fakelogs/client.go#L235-L237
7,148
luci/luci-go
grpc/cmd/prpc/descriptor.go
resolveInputMessage
func (d *serverDescription) resolveInputMessage(service, method string) (*descriptor.DescriptorProto, error) { _, obj, _ := descutil.Resolve(d.Description, service) serviceDesc, ok := obj.(*descriptor.ServiceDescriptorProto) if !ok { return nil, fmt.Errorf("service %q not found", service) } mi := descutil.FindMethodForService(serviceDesc, method) if mi == -1 { return nil, fmt.Errorf("method %q in service %q not found", method, service) } msgName := serviceDesc.Method[mi].GetInputType() msgName = strings.TrimPrefix(msgName, ".") return d.resolveMessage(msgName) }
go
func (d *serverDescription) resolveInputMessage(service, method string) (*descriptor.DescriptorProto, error) { _, obj, _ := descutil.Resolve(d.Description, service) serviceDesc, ok := obj.(*descriptor.ServiceDescriptorProto) if !ok { return nil, fmt.Errorf("service %q not found", service) } mi := descutil.FindMethodForService(serviceDesc, method) if mi == -1 { return nil, fmt.Errorf("method %q in service %q not found", method, service) } msgName := serviceDesc.Method[mi].GetInputType() msgName = strings.TrimPrefix(msgName, ".") return d.resolveMessage(msgName) }
[ "func", "(", "d", "*", "serverDescription", ")", "resolveInputMessage", "(", "service", ",", "method", "string", ")", "(", "*", "descriptor", ".", "DescriptorProto", ",", "error", ")", "{", "_", ",", "obj", ",", "_", ":=", "descutil", ".", "Resolve", "(", "d", ".", "Description", ",", "service", ")", "\n", "serviceDesc", ",", "ok", ":=", "obj", ".", "(", "*", "descriptor", ".", "ServiceDescriptorProto", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "service", ")", "\n", "}", "\n\n", "mi", ":=", "descutil", ".", "FindMethodForService", "(", "serviceDesc", ",", "method", ")", "\n", "if", "mi", "==", "-", "1", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "method", ",", "service", ")", "\n", "}", "\n\n", "msgName", ":=", "serviceDesc", ".", "Method", "[", "mi", "]", ".", "GetInputType", "(", ")", "\n", "msgName", "=", "strings", ".", "TrimPrefix", "(", "msgName", ",", "\"", "\"", ")", "\n", "return", "d", ".", "resolveMessage", "(", "msgName", ")", "\n", "}" ]
// resolveInputMessage resolves input message type of a method.
[ "resolveInputMessage", "resolves", "input", "message", "type", "of", "a", "method", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/cmd/prpc/descriptor.go#L44-L59
7,149
luci/luci-go
mmutex/lib/exclusive.go
RunExclusive
func RunExclusive(ctx context.Context, env subcommands.Env, command func(context.Context) error) error { lockFilePath, drainFilePath, err := computeMutexPaths(env) if err != nil { return err } if len(lockFilePath) == 0 { return command(ctx) } file, err := os.OpenFile(drainFilePath, os.O_RDONLY|os.O_CREATE, 0666) if err != nil { return err } if err = file.Close(); err != nil { return err } // Remove the drain file in case the lock can never be acquired. defer os.Remove(drainFilePath) blocker := createLockBlocker(ctx) return fslock.WithBlocking(lockFilePath, blocker, func() error { // Remove the drain file immediately after acquiring the lock in order // to decrease the likelihood that a crash occurs, leaving the drain // file sitting around indefinitely. if err := os.Remove(drainFilePath); err != nil { return err } return command(ctx) }) }
go
func RunExclusive(ctx context.Context, env subcommands.Env, command func(context.Context) error) error { lockFilePath, drainFilePath, err := computeMutexPaths(env) if err != nil { return err } if len(lockFilePath) == 0 { return command(ctx) } file, err := os.OpenFile(drainFilePath, os.O_RDONLY|os.O_CREATE, 0666) if err != nil { return err } if err = file.Close(); err != nil { return err } // Remove the drain file in case the lock can never be acquired. defer os.Remove(drainFilePath) blocker := createLockBlocker(ctx) return fslock.WithBlocking(lockFilePath, blocker, func() error { // Remove the drain file immediately after acquiring the lock in order // to decrease the likelihood that a crash occurs, leaving the drain // file sitting around indefinitely. if err := os.Remove(drainFilePath); err != nil { return err } return command(ctx) }) }
[ "func", "RunExclusive", "(", "ctx", "context", ".", "Context", ",", "env", "subcommands", ".", "Env", ",", "command", "func", "(", "context", ".", "Context", ")", "error", ")", "error", "{", "lockFilePath", ",", "drainFilePath", ",", "err", ":=", "computeMutexPaths", "(", "env", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "len", "(", "lockFilePath", ")", "==", "0", "{", "return", "command", "(", "ctx", ")", "\n", "}", "\n\n", "file", ",", "err", ":=", "os", ".", "OpenFile", "(", "drainFilePath", ",", "os", ".", "O_RDONLY", "|", "os", ".", "O_CREATE", ",", "0666", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", "=", "file", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Remove the drain file in case the lock can never be acquired.", "defer", "os", ".", "Remove", "(", "drainFilePath", ")", "\n\n", "blocker", ":=", "createLockBlocker", "(", "ctx", ")", "\n", "return", "fslock", ".", "WithBlocking", "(", "lockFilePath", ",", "blocker", ",", "func", "(", ")", "error", "{", "// Remove the drain file immediately after acquiring the lock in order", "// to decrease the likelihood that a crash occurs, leaving the drain", "// file sitting around indefinitely.", "if", "err", ":=", "os", ".", "Remove", "(", "drainFilePath", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "command", "(", "ctx", ")", "\n", "}", ")", "\n", "}" ]
// RunExclusive runs the command with the specified context and environment while // holding an exclusive mmutex lock.
[ "RunExclusive", "runs", "the", "command", "with", "the", "specified", "context", "and", "environment", "while", "holding", "an", "exclusive", "mmutex", "lock", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mmutex/lib/exclusive.go#L27-L59
7,150
luci/luci-go
dm/appengine/mutate/finish_attempt.go
RollForward
func (f *FinishAttempt) RollForward(c context.Context) (muts []tumble.Mutation, err error) { atmpt, ex, err := model.InvalidateExecution(c, f.Auth) if err != nil { logging.WithError(err).Errorf(c, "could not invalidate execution") return } if err = ResetExecutionTimeout(c, ex); err != nil { logging.WithError(err).Errorf(c, "could not reset timeout") return } ar := &model.AttemptResult{ Attempt: model.AttemptKeyFromID(c, &atmpt.ID), Data: *f.Data, } rslt := *f.Data atmpt.Result.Data = &rslt atmpt.Result.Data.Object = "" err = errors.Annotate(ds.Put(c, atmpt, ar), "during Put").Tag(grpcutil.Tag.With(codes.Internal)).Err() return }
go
func (f *FinishAttempt) RollForward(c context.Context) (muts []tumble.Mutation, err error) { atmpt, ex, err := model.InvalidateExecution(c, f.Auth) if err != nil { logging.WithError(err).Errorf(c, "could not invalidate execution") return } if err = ResetExecutionTimeout(c, ex); err != nil { logging.WithError(err).Errorf(c, "could not reset timeout") return } ar := &model.AttemptResult{ Attempt: model.AttemptKeyFromID(c, &atmpt.ID), Data: *f.Data, } rslt := *f.Data atmpt.Result.Data = &rslt atmpt.Result.Data.Object = "" err = errors.Annotate(ds.Put(c, atmpt, ar), "during Put").Tag(grpcutil.Tag.With(codes.Internal)).Err() return }
[ "func", "(", "f", "*", "FinishAttempt", ")", "RollForward", "(", "c", "context", ".", "Context", ")", "(", "muts", "[", "]", "tumble", ".", "Mutation", ",", "err", "error", ")", "{", "atmpt", ",", "ex", ",", "err", ":=", "model", ".", "InvalidateExecution", "(", "c", ",", "f", ".", "Auth", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "if", "err", "=", "ResetExecutionTimeout", "(", "c", ",", "ex", ")", ";", "err", "!=", "nil", "{", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "ar", ":=", "&", "model", ".", "AttemptResult", "{", "Attempt", ":", "model", ".", "AttemptKeyFromID", "(", "c", ",", "&", "atmpt", ".", "ID", ")", ",", "Data", ":", "*", "f", ".", "Data", ",", "}", "\n\n", "rslt", ":=", "*", "f", ".", "Data", "\n", "atmpt", ".", "Result", ".", "Data", "=", "&", "rslt", "\n", "atmpt", ".", "Result", ".", "Data", ".", "Object", "=", "\"", "\"", "\n\n", "err", "=", "errors", ".", "Annotate", "(", "ds", ".", "Put", "(", "c", ",", "atmpt", ",", "ar", ")", ",", "\"", "\"", ")", ".", "Tag", "(", "grpcutil", ".", "Tag", ".", "With", "(", "codes", ".", "Internal", ")", ")", ".", "Err", "(", ")", "\n", "return", "\n", "}" ]
// RollForward implements tumble.Mutation // // This mutation is called directly from FinishAttempt.
[ "RollForward", "implements", "tumble", ".", "Mutation", "This", "mutation", "is", "called", "directly", "from", "FinishAttempt", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/mutate/finish_attempt.go#L48-L71
7,151
luci/luci-go
config/server/cfgclient/textproto/resolver.go
Message
func Message(out proto.Message) interface { cfgclient.Resolver cfgclient.FormattingResolver } { if out == nil { panic("cannot pass a nil proto.Message instance") } return &resolver{ messageName: proto.MessageName(out), single: out, singleType: reflect.TypeOf(out), } }
go
func Message(out proto.Message) interface { cfgclient.Resolver cfgclient.FormattingResolver } { if out == nil { panic("cannot pass a nil proto.Message instance") } return &resolver{ messageName: proto.MessageName(out), single: out, singleType: reflect.TypeOf(out), } }
[ "func", "Message", "(", "out", "proto", ".", "Message", ")", "interface", "{", "cfgclient", ".", "Resolver", "\n", "cfgclient", ".", "FormattingResolver", "\n", "}", "{", "if", "out", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "&", "resolver", "{", "messageName", ":", "proto", ".", "MessageName", "(", "out", ")", ",", "single", ":", "out", ",", "singleType", ":", "reflect", ".", "TypeOf", "(", "out", ")", ",", "}", "\n", "}" ]
// Message is a cfgclient.Resolver that resolves config data into proto.Message // instances by parsing the config data as a text protobuf.
[ "Message", "is", "a", "cfgclient", ".", "Resolver", "that", "resolves", "config", "data", "into", "proto", ".", "Message", "instances", "by", "parsing", "the", "config", "data", "as", "a", "text", "protobuf", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/textproto/resolver.go#L62-L74
7,152
luci/luci-go
config/server/cfgclient/textproto/resolver.go
Resolve
func (r *resolver) Resolve(it *config.Config) error { return r.resolveItem(r.single, it.Content, it.FormatSpec.Formatter) }
go
func (r *resolver) Resolve(it *config.Config) error { return r.resolveItem(r.single, it.Content, it.FormatSpec.Formatter) }
[ "func", "(", "r", "*", "resolver", ")", "Resolve", "(", "it", "*", "config", ".", "Config", ")", "error", "{", "return", "r", ".", "resolveItem", "(", "r", ".", "single", ",", "it", ".", "Content", ",", "it", ".", "FormatSpec", ".", "Formatter", ")", "\n", "}" ]
// Resolve implements cfgclient.MultiResolver.
[ "Resolve", "implements", "cfgclient", ".", "MultiResolver", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/textproto/resolver.go#L132-L134
7,153
luci/luci-go
config/server/cfgclient/textproto/resolver.go
PrepareMulti
func (r *resolver) PrepareMulti(size int) { slice := reflect.MakeSlice(r.multiDest.Type(), size, size) r.multiDest.Set(slice) }
go
func (r *resolver) PrepareMulti(size int) { slice := reflect.MakeSlice(r.multiDest.Type(), size, size) r.multiDest.Set(slice) }
[ "func", "(", "r", "*", "resolver", ")", "PrepareMulti", "(", "size", "int", ")", "{", "slice", ":=", "reflect", ".", "MakeSlice", "(", "r", ".", "multiDest", ".", "Type", "(", ")", ",", "size", ",", "size", ")", "\n", "r", ".", "multiDest", ".", "Set", "(", "slice", ")", "\n", "}" ]
// PrepareMulti implements cfgclient.MultiResolver.
[ "PrepareMulti", "implements", "cfgclient", ".", "MultiResolver", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/textproto/resolver.go#L137-L140
7,154
luci/luci-go
config/server/cfgclient/textproto/resolver.go
ResolveItemAt
func (r *resolver) ResolveItemAt(i int, it *config.Config) error { msgV := archetypeInstance(r.singleType) if err := r.resolveItem(msgV.Interface().(proto.Message), it.Content, it.FormatSpec.Formatter); err != nil { return err } r.multiDest.Index(i).Set(msgV) return nil }
go
func (r *resolver) ResolveItemAt(i int, it *config.Config) error { msgV := archetypeInstance(r.singleType) if err := r.resolveItem(msgV.Interface().(proto.Message), it.Content, it.FormatSpec.Formatter); err != nil { return err } r.multiDest.Index(i).Set(msgV) return nil }
[ "func", "(", "r", "*", "resolver", ")", "ResolveItemAt", "(", "i", "int", ",", "it", "*", "config", ".", "Config", ")", "error", "{", "msgV", ":=", "archetypeInstance", "(", "r", ".", "singleType", ")", "\n", "if", "err", ":=", "r", ".", "resolveItem", "(", "msgV", ".", "Interface", "(", ")", ".", "(", "proto", ".", "Message", ")", ",", "it", ".", "Content", ",", "it", ".", "FormatSpec", ".", "Formatter", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "r", ".", "multiDest", ".", "Index", "(", "i", ")", ".", "Set", "(", "msgV", ")", "\n", "return", "nil", "\n", "}" ]
// ResolveItemAt implements cfgclient.MultiResolver.
[ "ResolveItemAt", "implements", "cfgclient", ".", "MultiResolver", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/textproto/resolver.go#L143-L150
7,155
luci/luci-go
config/server/cfgclient/textproto/resolver.go
FormatItem
func (f *Formatter) FormatItem(c, fd string) (string, error) { archetype := proto.MessageType(fd) if archetype == nil { return "", errors.Reason("unknown proto.Message type %q in formatter data", fd).Err() } msg := archetypeMessage(archetype) // Convert from config to protobuf. if err := luciProto.UnmarshalTextML(c, msg); err != nil { return "", errors.Annotate(err, "failed to unmarshal text protobuf content").Err() } // Binary format. bc, err := makeBinaryContent(msg) if err != nil { return "", errors.Annotate(err, "").Err() } return bc, nil }
go
func (f *Formatter) FormatItem(c, fd string) (string, error) { archetype := proto.MessageType(fd) if archetype == nil { return "", errors.Reason("unknown proto.Message type %q in formatter data", fd).Err() } msg := archetypeMessage(archetype) // Convert from config to protobuf. if err := luciProto.UnmarshalTextML(c, msg); err != nil { return "", errors.Annotate(err, "failed to unmarshal text protobuf content").Err() } // Binary format. bc, err := makeBinaryContent(msg) if err != nil { return "", errors.Annotate(err, "").Err() } return bc, nil }
[ "func", "(", "f", "*", "Formatter", ")", "FormatItem", "(", "c", ",", "fd", "string", ")", "(", "string", ",", "error", ")", "{", "archetype", ":=", "proto", ".", "MessageType", "(", "fd", ")", "\n", "if", "archetype", "==", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Reason", "(", "\"", "\"", ",", "fd", ")", ".", "Err", "(", ")", "\n", "}", "\n", "msg", ":=", "archetypeMessage", "(", "archetype", ")", "\n\n", "// Convert from config to protobuf.", "if", "err", ":=", "luciProto", ".", "UnmarshalTextML", "(", "c", ",", "msg", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "// Binary format.", "bc", ",", "err", ":=", "makeBinaryContent", "(", "msg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "bc", ",", "nil", "\n", "}" ]
// FormatItem implements cfgclient.Formatter.
[ "FormatItem", "implements", "cfgclient", ".", "Formatter", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/textproto/resolver.go#L184-L202
7,156
luci/luci-go
config/server/cfgclient/textproto/resolver.go
archetypeInstance
func archetypeInstance(t reflect.Type) reflect.Value { return reflect.New(t.Elem()) }
go
func archetypeInstance(t reflect.Type) reflect.Value { return reflect.New(t.Elem()) }
[ "func", "archetypeInstance", "(", "t", "reflect", ".", "Type", ")", "reflect", ".", "Value", "{", "return", "reflect", ".", "New", "(", "t", ".", "Elem", "(", ")", ")", "\n", "}" ]
// t is a pointer to a proto.Message instance.
[ "t", "is", "a", "pointer", "to", "a", "proto", ".", "Message", "instance", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/textproto/resolver.go#L205-L207
7,157
luci/luci-go
config/server/cfgclient/textproto/resolver.go
parseBinaryContent
func parseBinaryContent(v string, msg proto.Message) error { r := strings.NewReader(v) encName, _, err := cmpbin.ReadString(r) if err != nil { return errors.Annotate(err, "failed to read message name").Err() } // Construct a message for this. if name := proto.MessageName(msg); name != encName { return errors.Reason("message name %q doesn't match encoded name %q", name, encName).Err() } // We have the right message, unmarshal. d, _, err := cmpbin.ReadBytes(r) if err != nil { return errors.Annotate(err, "failed to read binary message content").Err() } if err := proto.Unmarshal(d, msg); err != nil { return errors.Annotate(err, "failed to unmarshal message").Err() } return nil }
go
func parseBinaryContent(v string, msg proto.Message) error { r := strings.NewReader(v) encName, _, err := cmpbin.ReadString(r) if err != nil { return errors.Annotate(err, "failed to read message name").Err() } // Construct a message for this. if name := proto.MessageName(msg); name != encName { return errors.Reason("message name %q doesn't match encoded name %q", name, encName).Err() } // We have the right message, unmarshal. d, _, err := cmpbin.ReadBytes(r) if err != nil { return errors.Annotate(err, "failed to read binary message content").Err() } if err := proto.Unmarshal(d, msg); err != nil { return errors.Annotate(err, "failed to unmarshal message").Err() } return nil }
[ "func", "parseBinaryContent", "(", "v", "string", ",", "msg", "proto", ".", "Message", ")", "error", "{", "r", ":=", "strings", ".", "NewReader", "(", "v", ")", "\n", "encName", ",", "_", ",", "err", ":=", "cmpbin", ".", "ReadString", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "// Construct a message for this.", "if", "name", ":=", "proto", ".", "MessageName", "(", "msg", ")", ";", "name", "!=", "encName", "{", "return", "errors", ".", "Reason", "(", "\"", "\"", ",", "name", ",", "encName", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "// We have the right message, unmarshal.", "d", ",", "_", ",", "err", ":=", "cmpbin", ".", "ReadBytes", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "d", ",", "msg", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// parseBinaryContent parses a binary content string, pulling out the message // type and marshalled message data. It then unmarshals the specified type into // a new message based on the archetype. // // If the binary content's declared type doesn't match the archetype, or if the // binary content is invalid, an error will be returned.
[ "parseBinaryContent", "parses", "a", "binary", "content", "string", "pulling", "out", "the", "message", "type", "and", "marshalled", "message", "data", ".", "It", "then", "unmarshals", "the", "specified", "type", "into", "a", "new", "message", "based", "on", "the", "archetype", ".", "If", "the", "binary", "content", "s", "declared", "type", "doesn", "t", "match", "the", "archetype", "or", "if", "the", "binary", "content", "is", "invalid", "an", "error", "will", "be", "returned", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/textproto/resolver.go#L241-L262
7,158
luci/luci-go
common/runtime/paniccatcher/catch.go
Catch
func Catch(cb func(p *Panic)) { if reason := recover(); reason != nil && cb != nil { stack := make([]byte, maxStackBufferSize) count := runtime.Stack(stack, true) cb(&Panic{ Reason: reason, Stack: string(stack[:count]), }) } }
go
func Catch(cb func(p *Panic)) { if reason := recover(); reason != nil && cb != nil { stack := make([]byte, maxStackBufferSize) count := runtime.Stack(stack, true) cb(&Panic{ Reason: reason, Stack: string(stack[:count]), }) } }
[ "func", "Catch", "(", "cb", "func", "(", "p", "*", "Panic", ")", ")", "{", "if", "reason", ":=", "recover", "(", ")", ";", "reason", "!=", "nil", "&&", "cb", "!=", "nil", "{", "stack", ":=", "make", "(", "[", "]", "byte", ",", "maxStackBufferSize", ")", "\n", "count", ":=", "runtime", ".", "Stack", "(", "stack", ",", "true", ")", "\n", "cb", "(", "&", "Panic", "{", "Reason", ":", "reason", ",", "Stack", ":", "string", "(", "stack", "[", ":", "count", "]", ")", ",", "}", ")", "\n", "}", "\n", "}" ]
// Catch recovers from panic. It should be used as a deferred call. // // If the supplied panic callback is nil, the panic will be silently discarded. // Otherwise, the callback will be invoked with the panic's information.
[ "Catch", "recovers", "from", "panic", ".", "It", "should", "be", "used", "as", "a", "deferred", "call", ".", "If", "the", "supplied", "panic", "callback", "is", "nil", "the", "panic", "will", "be", "silently", "discarded", ".", "Otherwise", "the", "callback", "will", "be", "invoked", "with", "the", "panic", "s", "information", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/runtime/paniccatcher/catch.go#L38-L47
7,159
luci/luci-go
milo/git/log.go
Log
func (p *implementation) Log(c context.Context, host, project, commitish string, inputOptions *LogOptions) (commits []*gitpb.Commit, err error) { defer func() { err = common.TagGRPC(c, err) }() allowed, err := p.acls.IsAllowed(c, host, project) switch { case err != nil: return case !allowed: logging.Warningf(c, "%q not allowed for host %q project %q", auth.CurrentIdentity(c), host, project) err = status.Errorf(codes.NotFound, "not found") return } return p.log(c, host, project, commitish, "", inputOptions) }
go
func (p *implementation) Log(c context.Context, host, project, commitish string, inputOptions *LogOptions) (commits []*gitpb.Commit, err error) { defer func() { err = common.TagGRPC(c, err) }() allowed, err := p.acls.IsAllowed(c, host, project) switch { case err != nil: return case !allowed: logging.Warningf(c, "%q not allowed for host %q project %q", auth.CurrentIdentity(c), host, project) err = status.Errorf(codes.NotFound, "not found") return } return p.log(c, host, project, commitish, "", inputOptions) }
[ "func", "(", "p", "*", "implementation", ")", "Log", "(", "c", "context", ".", "Context", ",", "host", ",", "project", ",", "commitish", "string", ",", "inputOptions", "*", "LogOptions", ")", "(", "commits", "[", "]", "*", "gitpb", ".", "Commit", ",", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "err", "=", "common", ".", "TagGRPC", "(", "c", ",", "err", ")", "}", "(", ")", "\n\n", "allowed", ",", "err", ":=", "p", ".", "acls", ".", "IsAllowed", "(", "c", ",", "host", ",", "project", ")", "\n", "switch", "{", "case", "err", "!=", "nil", ":", "return", "\n", "case", "!", "allowed", ":", "logging", ".", "Warningf", "(", "c", ",", "\"", "\"", ",", "auth", ".", "CurrentIdentity", "(", "c", ")", ",", "host", ",", "project", ")", "\n", "err", "=", "status", ".", "Errorf", "(", "codes", ".", "NotFound", ",", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "return", "p", ".", "log", "(", "c", ",", "host", ",", "project", ",", "commitish", ",", "\"", "\"", ",", "inputOptions", ")", "\n", "}" ]
// Log implements Client interface.
[ "Log", "implements", "Client", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/git/log.go#L50-L64
7,160
luci/luci-go
cipd/client/cipd/ensure/versions_file.go
ResolveVersion
func (v VersionsFile) ResolveVersion(pkg, ver string) (common.Pin, error) { if common.ValidateInstanceID(ver, common.AnyHash) == nil { return common.Pin{PackageName: pkg, InstanceID: ver}, nil } if iid, ok := v[unresolvedVer{pkg, ver}]; ok { return common.Pin{PackageName: pkg, InstanceID: iid}, nil } return common.Pin{}, errors.Reason("not in the versions file").Err() }
go
func (v VersionsFile) ResolveVersion(pkg, ver string) (common.Pin, error) { if common.ValidateInstanceID(ver, common.AnyHash) == nil { return common.Pin{PackageName: pkg, InstanceID: ver}, nil } if iid, ok := v[unresolvedVer{pkg, ver}]; ok { return common.Pin{PackageName: pkg, InstanceID: iid}, nil } return common.Pin{}, errors.Reason("not in the versions file").Err() }
[ "func", "(", "v", "VersionsFile", ")", "ResolveVersion", "(", "pkg", ",", "ver", "string", ")", "(", "common", ".", "Pin", ",", "error", ")", "{", "if", "common", ".", "ValidateInstanceID", "(", "ver", ",", "common", ".", "AnyHash", ")", "==", "nil", "{", "return", "common", ".", "Pin", "{", "PackageName", ":", "pkg", ",", "InstanceID", ":", "ver", "}", ",", "nil", "\n", "}", "\n", "if", "iid", ",", "ok", ":=", "v", "[", "unresolvedVer", "{", "pkg", ",", "ver", "}", "]", ";", "ok", "{", "return", "common", ".", "Pin", "{", "PackageName", ":", "pkg", ",", "InstanceID", ":", "iid", "}", ",", "nil", "\n", "}", "\n", "return", "common", ".", "Pin", "{", "}", ",", "errors", ".", "Reason", "(", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}" ]
// ResolveVersion returns a pin matching the given version or an error if such // version is not in the map. // // If 'ver' is already an instance ID, returns it right away.
[ "ResolveVersion", "returns", "a", "pin", "matching", "the", "given", "version", "or", "an", "error", "if", "such", "version", "is", "not", "in", "the", "map", ".", "If", "ver", "is", "already", "an", "instance", "ID", "returns", "it", "right", "away", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/ensure/versions_file.go#L95-L103
7,161
luci/luci-go
cipd/client/cipd/ensure/versions_file.go
Equal
func (v VersionsFile) Equal(a VersionsFile) bool { if len(v) != len(a) { return false } for ver, iid := range v { if a[ver] != iid { return false } } return true }
go
func (v VersionsFile) Equal(a VersionsFile) bool { if len(v) != len(a) { return false } for ver, iid := range v { if a[ver] != iid { return false } } return true }
[ "func", "(", "v", "VersionsFile", ")", "Equal", "(", "a", "VersionsFile", ")", "bool", "{", "if", "len", "(", "v", ")", "!=", "len", "(", "a", ")", "{", "return", "false", "\n", "}", "\n", "for", "ver", ",", "iid", ":=", "range", "v", "{", "if", "a", "[", "ver", "]", "!=", "iid", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// Equal returns true if version files have same entries.
[ "Equal", "returns", "true", "if", "version", "files", "have", "same", "entries", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/ensure/versions_file.go#L106-L116
7,162
luci/luci-go
cipd/client/cipd/ensure/versions_file.go
Serialize
func (v VersionsFile) Serialize(w io.Writer) error { keys := make([]unresolvedVer, 0, len(v)) for k := range v { keys = append(keys, k) } sort.Slice(keys, func(i, j int) bool { l, r := keys[i], keys[j] if l.pkg != r.pkg { return l.pkg < r.pkg } return l.ver < r.ver }) _, err := iotools.WriteTracker(w, func(w io.Writer) error { fmt.Fprintf(w, "# This file is auto-generated by 'cipd ensure-file-resolve'.\n") fmt.Fprintf(w, "# Do not modify manually. All changes will be overwritten.\n") for _, key := range keys { fmt.Fprintf(w, "\n%s\n\t%s\n\t%s\n", key.pkg, key.ver, v[key]) } return nil }) return err }
go
func (v VersionsFile) Serialize(w io.Writer) error { keys := make([]unresolvedVer, 0, len(v)) for k := range v { keys = append(keys, k) } sort.Slice(keys, func(i, j int) bool { l, r := keys[i], keys[j] if l.pkg != r.pkg { return l.pkg < r.pkg } return l.ver < r.ver }) _, err := iotools.WriteTracker(w, func(w io.Writer) error { fmt.Fprintf(w, "# This file is auto-generated by 'cipd ensure-file-resolve'.\n") fmt.Fprintf(w, "# Do not modify manually. All changes will be overwritten.\n") for _, key := range keys { fmt.Fprintf(w, "\n%s\n\t%s\n\t%s\n", key.pkg, key.ver, v[key]) } return nil }) return err }
[ "func", "(", "v", "VersionsFile", ")", "Serialize", "(", "w", "io", ".", "Writer", ")", "error", "{", "keys", ":=", "make", "(", "[", "]", "unresolvedVer", ",", "0", ",", "len", "(", "v", ")", ")", "\n", "for", "k", ":=", "range", "v", "{", "keys", "=", "append", "(", "keys", ",", "k", ")", "\n", "}", "\n", "sort", ".", "Slice", "(", "keys", ",", "func", "(", "i", ",", "j", "int", ")", "bool", "{", "l", ",", "r", ":=", "keys", "[", "i", "]", ",", "keys", "[", "j", "]", "\n", "if", "l", ".", "pkg", "!=", "r", ".", "pkg", "{", "return", "l", ".", "pkg", "<", "r", ".", "pkg", "\n", "}", "\n", "return", "l", ".", "ver", "<", "r", ".", "ver", "\n", "}", ")", "\n\n", "_", ",", "err", ":=", "iotools", ".", "WriteTracker", "(", "w", ",", "func", "(", "w", "io", ".", "Writer", ")", "error", "{", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ")", "\n", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ")", "\n", "for", "_", ",", "key", ":=", "range", "keys", "{", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\\n", "\\t", "\\n", "\\t", "\\n", "\"", ",", "key", ".", "pkg", ",", "key", ".", "ver", ",", "v", "[", "key", "]", ")", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "return", "err", "\n", "}" ]
// Serialize writes the VersionsFile to an io.Writer in canonical order.
[ "Serialize", "writes", "the", "VersionsFile", "to", "an", "io", ".", "Writer", "in", "canonical", "order", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/ensure/versions_file.go#L119-L141
7,163
luci/luci-go
cipd/client/cipd/ensure/versions_file.go
ParseVersionsFile
func ParseVersionsFile(r io.Reader) (VersionsFile, error) { res := VersionsFile{} lineNo := 0 makeError := func(fmtStr string, args ...interface{}) error { args = append([]interface{}{lineNo}, args...) return fmt.Errorf("failed to parse versions file (line %d): "+fmtStr, args...) } const ( stWaitingPkg = "a package name" stWaitingVer = "a package version" stWaitingIID = "an instance ID" stWaitingNL = "a new line" ) state := stWaitingPkg pkg := "" ver := "" iid := "" scanner := bufio.NewScanner(r) for scanner.Scan() { lineNo++ line := strings.TrimSpace(scanner.Text()) // Comments are grammatically insignificant (unlike empty lines), so skip // the completely. if len(line) > 0 && line[0] == '#' { continue } switch state { case stWaitingPkg: if line == "" { continue // can have more than one empty line between triples } pkg = line if err := common.ValidatePackageName(pkg); err != nil { return nil, makeError("%s", err) } state = stWaitingVer case stWaitingVer: if line == "" { return nil, makeError("expecting a version name, not a new line") } ver = line if err := common.ValidateInstanceVersion(ver); err != nil { return nil, makeError("%s", err) } state = stWaitingIID case stWaitingIID: if line == "" { return nil, makeError("expecting an instance ID, not a new line") } iid = line if err := common.ValidateInstanceID(iid, common.AnyHash); err != nil { return nil, makeError("%s", err) } if err := res.AddVersion(pkg, ver, iid); err != nil { panic(err) // impossible, everything has been validated already } pkg, ver, iid = "", "", "" state = stWaitingNL case stWaitingNL: if line == "" { state = stWaitingPkg continue } return nil, makeError("expecting an empty line between each version definition triple") } } if state != stWaitingPkg && state != stWaitingNL { return nil, makeError("unexpected EOF, expecting %s", state) } if err := scanner.Err(); err != nil { return nil, err } return res, nil }
go
func ParseVersionsFile(r io.Reader) (VersionsFile, error) { res := VersionsFile{} lineNo := 0 makeError := func(fmtStr string, args ...interface{}) error { args = append([]interface{}{lineNo}, args...) return fmt.Errorf("failed to parse versions file (line %d): "+fmtStr, args...) } const ( stWaitingPkg = "a package name" stWaitingVer = "a package version" stWaitingIID = "an instance ID" stWaitingNL = "a new line" ) state := stWaitingPkg pkg := "" ver := "" iid := "" scanner := bufio.NewScanner(r) for scanner.Scan() { lineNo++ line := strings.TrimSpace(scanner.Text()) // Comments are grammatically insignificant (unlike empty lines), so skip // the completely. if len(line) > 0 && line[0] == '#' { continue } switch state { case stWaitingPkg: if line == "" { continue // can have more than one empty line between triples } pkg = line if err := common.ValidatePackageName(pkg); err != nil { return nil, makeError("%s", err) } state = stWaitingVer case stWaitingVer: if line == "" { return nil, makeError("expecting a version name, not a new line") } ver = line if err := common.ValidateInstanceVersion(ver); err != nil { return nil, makeError("%s", err) } state = stWaitingIID case stWaitingIID: if line == "" { return nil, makeError("expecting an instance ID, not a new line") } iid = line if err := common.ValidateInstanceID(iid, common.AnyHash); err != nil { return nil, makeError("%s", err) } if err := res.AddVersion(pkg, ver, iid); err != nil { panic(err) // impossible, everything has been validated already } pkg, ver, iid = "", "", "" state = stWaitingNL case stWaitingNL: if line == "" { state = stWaitingPkg continue } return nil, makeError("expecting an empty line between each version definition triple") } } if state != stWaitingPkg && state != stWaitingNL { return nil, makeError("unexpected EOF, expecting %s", state) } if err := scanner.Err(); err != nil { return nil, err } return res, nil }
[ "func", "ParseVersionsFile", "(", "r", "io", ".", "Reader", ")", "(", "VersionsFile", ",", "error", ")", "{", "res", ":=", "VersionsFile", "{", "}", "\n\n", "lineNo", ":=", "0", "\n", "makeError", ":=", "func", "(", "fmtStr", "string", ",", "args", "...", "interface", "{", "}", ")", "error", "{", "args", "=", "append", "(", "[", "]", "interface", "{", "}", "{", "lineNo", "}", ",", "args", "...", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", "+", "fmtStr", ",", "args", "...", ")", "\n", "}", "\n\n", "const", "(", "stWaitingPkg", "=", "\"", "\"", "\n", "stWaitingVer", "=", "\"", "\"", "\n", "stWaitingIID", "=", "\"", "\"", "\n", "stWaitingNL", "=", "\"", "\"", "\n", ")", "\n", "state", ":=", "stWaitingPkg", "\n", "pkg", ":=", "\"", "\"", "\n", "ver", ":=", "\"", "\"", "\n", "iid", ":=", "\"", "\"", "\n\n", "scanner", ":=", "bufio", ".", "NewScanner", "(", "r", ")", "\n", "for", "scanner", ".", "Scan", "(", ")", "{", "lineNo", "++", "\n\n", "line", ":=", "strings", ".", "TrimSpace", "(", "scanner", ".", "Text", "(", ")", ")", "\n\n", "// Comments are grammatically insignificant (unlike empty lines), so skip", "// the completely.", "if", "len", "(", "line", ")", ">", "0", "&&", "line", "[", "0", "]", "==", "'#'", "{", "continue", "\n", "}", "\n\n", "switch", "state", "{", "case", "stWaitingPkg", ":", "if", "line", "==", "\"", "\"", "{", "continue", "// can have more than one empty line between triples", "\n", "}", "\n", "pkg", "=", "line", "\n", "if", "err", ":=", "common", ".", "ValidatePackageName", "(", "pkg", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "makeError", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "state", "=", "stWaitingVer", "\n\n", "case", "stWaitingVer", ":", "if", "line", "==", "\"", "\"", "{", "return", "nil", ",", "makeError", "(", "\"", "\"", ")", "\n", "}", "\n", "ver", "=", "line", "\n", "if", "err", ":=", "common", ".", "ValidateInstanceVersion", "(", "ver", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "makeError", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "state", "=", "stWaitingIID", "\n\n", "case", "stWaitingIID", ":", "if", "line", "==", "\"", "\"", "{", "return", "nil", ",", "makeError", "(", "\"", "\"", ")", "\n", "}", "\n", "iid", "=", "line", "\n", "if", "err", ":=", "common", ".", "ValidateInstanceID", "(", "iid", ",", "common", ".", "AnyHash", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "makeError", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "res", ".", "AddVersion", "(", "pkg", ",", "ver", ",", "iid", ")", ";", "err", "!=", "nil", "{", "panic", "(", "err", ")", "// impossible, everything has been validated already", "\n", "}", "\n", "pkg", ",", "ver", ",", "iid", "=", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "\n", "state", "=", "stWaitingNL", "\n\n", "case", "stWaitingNL", ":", "if", "line", "==", "\"", "\"", "{", "state", "=", "stWaitingPkg", "\n", "continue", "\n", "}", "\n", "return", "nil", ",", "makeError", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "if", "state", "!=", "stWaitingPkg", "&&", "state", "!=", "stWaitingNL", "{", "return", "nil", ",", "makeError", "(", "\"", "\"", ",", "state", ")", "\n", "}", "\n\n", "if", "err", ":=", "scanner", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "res", ",", "nil", "\n", "}" ]
// ParseVersionsFile parses previously serialized versions file.
[ "ParseVersionsFile", "parses", "previously", "serialized", "versions", "file", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/ensure/versions_file.go#L144-L228
7,164
luci/luci-go
logdog/api/endpoints/coordinator/services/v1/util.go
Complete
func (ar *ArchiveStreamRequest) Complete() bool { tidx := ar.TerminalIndex if tidx < 0 { tidx = -1 } return (ar.LogEntryCount == (tidx + 1)) }
go
func (ar *ArchiveStreamRequest) Complete() bool { tidx := ar.TerminalIndex if tidx < 0 { tidx = -1 } return (ar.LogEntryCount == (tidx + 1)) }
[ "func", "(", "ar", "*", "ArchiveStreamRequest", ")", "Complete", "(", ")", "bool", "{", "tidx", ":=", "ar", ".", "TerminalIndex", "\n", "if", "tidx", "<", "0", "{", "tidx", "=", "-", "1", "\n", "}", "\n", "return", "(", "ar", ".", "LogEntryCount", "==", "(", "tidx", "+", "1", ")", ")", "\n", "}" ]
// Complete returns true if the archive request expresses that the archived // log stream was complete. // // A log stream is complete if every entry between zero and its terminal index // is included.
[ "Complete", "returns", "true", "if", "the", "archive", "request", "expresses", "that", "the", "archived", "log", "stream", "was", "complete", ".", "A", "log", "stream", "is", "complete", "if", "every", "entry", "between", "zero", "and", "its", "terminal", "index", "is", "included", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/api/endpoints/coordinator/services/v1/util.go#L42-L48
7,165
luci/luci-go
logdog/api/endpoints/coordinator/services/v1/util.go
MakeError
func MakeError(err error) *Error { if err == nil { return nil } return &Error{ GrpcCode: int32(grpcutil.Code(err)), Transient: transient.Tag.In(err), } }
go
func MakeError(err error) *Error { if err == nil { return nil } return &Error{ GrpcCode: int32(grpcutil.Code(err)), Transient: transient.Tag.In(err), } }
[ "func", "MakeError", "(", "err", "error", ")", "*", "Error", "{", "if", "err", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "return", "&", "Error", "{", "GrpcCode", ":", "int32", "(", "grpcutil", ".", "Code", "(", "err", ")", ")", ",", "Transient", ":", "transient", ".", "Tag", ".", "In", "(", "err", ")", ",", "}", "\n", "}" ]
// MakeError returns an Error object for err. If err is a wrapped gRPC error, // its code will be extracted and embedded in the returned Error. // // The Msg field will not be populated.
[ "MakeError", "returns", "an", "Error", "object", "for", "err", ".", "If", "err", "is", "a", "wrapped", "gRPC", "error", "its", "code", "will", "be", "extracted", "and", "embedded", "in", "the", "returned", "Error", ".", "The", "Msg", "field", "will", "not", "be", "populated", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/api/endpoints/coordinator/services/v1/util.go#L54-L63
7,166
luci/luci-go
logdog/api/endpoints/coordinator/services/v1/util.go
ToError
func (e *Error) ToError() error { if e == nil { return nil } code := codes.Code(e.GrpcCode) err := status.Errorf(code, "%s", e.Msg) if e.Transient || grpcutil.IsTransientCode(code) { err = transient.Tag.Apply(err) } return err }
go
func (e *Error) ToError() error { if e == nil { return nil } code := codes.Code(e.GrpcCode) err := status.Errorf(code, "%s", e.Msg) if e.Transient || grpcutil.IsTransientCode(code) { err = transient.Tag.Apply(err) } return err }
[ "func", "(", "e", "*", "Error", ")", "ToError", "(", ")", "error", "{", "if", "e", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "code", ":=", "codes", ".", "Code", "(", "e", ".", "GrpcCode", ")", "\n", "err", ":=", "status", ".", "Errorf", "(", "code", ",", "\"", "\"", ",", "e", ".", "Msg", ")", "\n", "if", "e", ".", "Transient", "||", "grpcutil", ".", "IsTransientCode", "(", "code", ")", "{", "err", "=", "transient", ".", "Tag", ".", "Apply", "(", "err", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// ToError converts an Error into a gRPC error. If e is nil, a nil error will // be returned.
[ "ToError", "converts", "an", "Error", "into", "a", "gRPC", "error", ".", "If", "e", "is", "nil", "a", "nil", "error", "will", "be", "returned", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/api/endpoints/coordinator/services/v1/util.go#L67-L78
7,167
luci/luci-go
common/errors/walk.go
Walk
func Walk(err error, fn func(error) bool) { _ = walkVisit(err, fn, false) }
go
func Walk(err error, fn func(error) bool) { _ = walkVisit(err, fn, false) }
[ "func", "Walk", "(", "err", "error", ",", "fn", "func", "(", "error", ")", "bool", ")", "{", "_", "=", "walkVisit", "(", "err", ",", "fn", ",", "false", ")", "\n", "}" ]
// Walk performs a depth-first traversal of the supplied error, unfolding it and // invoke the supplied callback for each layered error recursively. If the // callback returns true, Walk will continue its traversal. // // - If walk encounters a MultiError, the callback is called once for the // outer MultiError, then once for each inner error. // - If walk encounters a Wrapped error, the callback is called for the outer // and inner error. // - If an inner error is, itself, a container, Walk will recurse into it. // // If err is nil, the callback will not be invoked.
[ "Walk", "performs", "a", "depth", "-", "first", "traversal", "of", "the", "supplied", "error", "unfolding", "it", "and", "invoke", "the", "supplied", "callback", "for", "each", "layered", "error", "recursively", ".", "If", "the", "callback", "returns", "true", "Walk", "will", "continue", "its", "traversal", ".", "-", "If", "walk", "encounters", "a", "MultiError", "the", "callback", "is", "called", "once", "for", "the", "outer", "MultiError", "then", "once", "for", "each", "inner", "error", ".", "-", "If", "walk", "encounters", "a", "Wrapped", "error", "the", "callback", "is", "called", "for", "the", "outer", "and", "inner", "error", ".", "-", "If", "an", "inner", "error", "is", "itself", "a", "container", "Walk", "will", "recurse", "into", "it", ".", "If", "err", "is", "nil", "the", "callback", "will", "not", "be", "invoked", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/errors/walk.go#L28-L30
7,168
luci/luci-go
common/errors/walk.go
WalkLeaves
func WalkLeaves(err error, fn func(error) bool) { _ = walkVisit(err, fn, true) }
go
func WalkLeaves(err error, fn func(error) bool) { _ = walkVisit(err, fn, true) }
[ "func", "WalkLeaves", "(", "err", "error", ",", "fn", "func", "(", "error", ")", "bool", ")", "{", "_", "=", "walkVisit", "(", "err", ",", "fn", ",", "true", ")", "\n", "}" ]
// WalkLeaves is like Walk, but only calls fn on leaf nodes.
[ "WalkLeaves", "is", "like", "Walk", "but", "only", "calls", "fn", "on", "leaf", "nodes", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/errors/walk.go#L33-L35
7,169
luci/luci-go
logdog/common/storage/entry.go
MakeEntry
func MakeEntry(d []byte, idx types.MessageIndex) *Entry { return &Entry{ D: d, streamIndex: idx, } }
go
func MakeEntry(d []byte, idx types.MessageIndex) *Entry { return &Entry{ D: d, streamIndex: idx, } }
[ "func", "MakeEntry", "(", "d", "[", "]", "byte", ",", "idx", "types", ".", "MessageIndex", ")", "*", "Entry", "{", "return", "&", "Entry", "{", "D", ":", "d", ",", "streamIndex", ":", "idx", ",", "}", "\n", "}" ]
// MakeEntry creates a new Entry. // // All Entry must be backed by data. The index, "idx", is optional. If <0, it // will be calculated by unmarshalling the data into a LogEntry and pulling the // value from there.
[ "MakeEntry", "creates", "a", "new", "Entry", ".", "All", "Entry", "must", "be", "backed", "by", "data", ".", "The", "index", "idx", "is", "optional", ".", "If", "<0", "it", "will", "be", "calculated", "by", "unmarshalling", "the", "data", "into", "a", "LogEntry", "and", "pulling", "the", "value", "from", "there", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/storage/entry.go#L41-L46
7,170
luci/luci-go
logdog/common/storage/entry.go
GetStreamIndex
func (e *Entry) GetStreamIndex() (types.MessageIndex, error) { if e.streamIndex < 0 { le, err := e.GetLogEntry() if err != nil { return -1, err } e.streamIndex = types.MessageIndex(le.StreamIndex) } return e.streamIndex, nil }
go
func (e *Entry) GetStreamIndex() (types.MessageIndex, error) { if e.streamIndex < 0 { le, err := e.GetLogEntry() if err != nil { return -1, err } e.streamIndex = types.MessageIndex(le.StreamIndex) } return e.streamIndex, nil }
[ "func", "(", "e", "*", "Entry", ")", "GetStreamIndex", "(", ")", "(", "types", ".", "MessageIndex", ",", "error", ")", "{", "if", "e", ".", "streamIndex", "<", "0", "{", "le", ",", "err", ":=", "e", ".", "GetLogEntry", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "err", "\n", "}", "\n\n", "e", ".", "streamIndex", "=", "types", ".", "MessageIndex", "(", "le", ".", "StreamIndex", ")", "\n", "}", "\n\n", "return", "e", ".", "streamIndex", ",", "nil", "\n", "}" ]
// GetStreamIndex returns the LogEntry's stream index. // // If this needs to be calculated by unmarshalling the LogEntry, this will be // done. If this fails, an error will be returned. // // If GetLogEntry has succeeded, subsequent GetStreamIndex calls will always // be fast and succeed.
[ "GetStreamIndex", "returns", "the", "LogEntry", "s", "stream", "index", ".", "If", "this", "needs", "to", "be", "calculated", "by", "unmarshalling", "the", "LogEntry", "this", "will", "be", "done", ".", "If", "this", "fails", "an", "error", "will", "be", "returned", ".", "If", "GetLogEntry", "has", "succeeded", "subsequent", "GetStreamIndex", "calls", "will", "always", "be", "fast", "and", "succeed", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/storage/entry.go#L55-L66
7,171
luci/luci-go
logdog/common/storage/entry.go
GetLogEntry
func (e *Entry) GetLogEntry() (*logpb.LogEntry, error) { if e.le == nil { if e.D == nil { // This can happen with keys-only results. return nil, errors.New("no log entry data") } var le logpb.LogEntry if err := proto.Unmarshal(e.D, &le); err != nil { return nil, errors.Annotate(err, "failed to unmarshal").Err() } e.le = &le } return e.le, nil }
go
func (e *Entry) GetLogEntry() (*logpb.LogEntry, error) { if e.le == nil { if e.D == nil { // This can happen with keys-only results. return nil, errors.New("no log entry data") } var le logpb.LogEntry if err := proto.Unmarshal(e.D, &le); err != nil { return nil, errors.Annotate(err, "failed to unmarshal").Err() } e.le = &le } return e.le, nil }
[ "func", "(", "e", "*", "Entry", ")", "GetLogEntry", "(", ")", "(", "*", "logpb", ".", "LogEntry", ",", "error", ")", "{", "if", "e", ".", "le", "==", "nil", "{", "if", "e", ".", "D", "==", "nil", "{", "// This can happen with keys-only results.", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "var", "le", "logpb", ".", "LogEntry", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "e", ".", "D", ",", "&", "le", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "e", ".", "le", "=", "&", "le", "\n", "}", "\n\n", "return", "e", ".", "le", ",", "nil", "\n", "}" ]
// GetLogEntry returns the unmarshalled LogEntry data. // // The first time this is called, the LogEntry will be unmarshalled from its // underlying data.
[ "GetLogEntry", "returns", "the", "unmarshalled", "LogEntry", "data", ".", "The", "first", "time", "this", "is", "called", "the", "LogEntry", "will", "be", "unmarshalled", "from", "its", "underlying", "data", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/storage/entry.go#L72-L87
7,172
luci/luci-go
tumble/tumble.go
RunUnbuffered
func RunUnbuffered(c context.Context, root *ds.Key, fn func(context.Context) ([]Mutation, error)) error { cfg := getConfig(c) shardSet, _, _, err := enterTransactionInternal(c, cfg, root, fn, 0) if err != nil { return err } fireTasks(c, cfg, shardSet, true) return nil }
go
func RunUnbuffered(c context.Context, root *ds.Key, fn func(context.Context) ([]Mutation, error)) error { cfg := getConfig(c) shardSet, _, _, err := enterTransactionInternal(c, cfg, root, fn, 0) if err != nil { return err } fireTasks(c, cfg, shardSet, true) return nil }
[ "func", "RunUnbuffered", "(", "c", "context", ".", "Context", ",", "root", "*", "ds", ".", "Key", ",", "fn", "func", "(", "context", ".", "Context", ")", "(", "[", "]", "Mutation", ",", "error", ")", ")", "error", "{", "cfg", ":=", "getConfig", "(", "c", ")", "\n", "shardSet", ",", "_", ",", "_", ",", "err", ":=", "enterTransactionInternal", "(", "c", ",", "cfg", ",", "root", ",", "fn", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "fireTasks", "(", "c", ",", "cfg", ",", "shardSet", ",", "true", ")", "\n", "return", "nil", "\n", "}" ]
// RunUnbuffered opens a lightweight unbuffered transaction on "root" // runs "fn" inside of it. Any mutations returned by "fn" will be registered // at the end of the transaction if "fn" doesn't return an error. // // This is useful as an initial starting point without incurring any of the // overhead of spinning up a new buffered transaction. // // During "fn"'s execution, standard Tumble operations such as PutNamedMutation // and CancelNamedMutation may be performed.
[ "RunUnbuffered", "opens", "a", "lightweight", "unbuffered", "transaction", "on", "root", "runs", "fn", "inside", "of", "it", ".", "Any", "mutations", "returned", "by", "fn", "will", "be", "registered", "at", "the", "end", "of", "the", "transaction", "if", "fn", "doesn", "t", "return", "an", "error", ".", "This", "is", "useful", "as", "an", "initial", "starting", "point", "without", "incurring", "any", "of", "the", "overhead", "of", "spinning", "up", "a", "new", "buffered", "transaction", ".", "During", "fn", "s", "execution", "standard", "Tumble", "operations", "such", "as", "PutNamedMutation", "and", "CancelNamedMutation", "may", "be", "performed", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tumble/tumble.go#L55-L63
7,173
luci/luci-go
tumble/tumble.go
CancelNamedMutations
func CancelNamedMutations(c context.Context, parent *ds.Key, names ...string) error { toDel := make([]*ds.Key, 0, len(names)) nameSet := stringset.NewFromSlice(names...) nameSet.Iter(func(name string) bool { toDel = append(toDel, ds.NewKey(c, "tumble.Mutation", "n:"+name, 0, parent)) return true }) err := ds.Delete(c, toDel) numFailed := int64(0) if me, ok := err.(errors.MultiError); ok { numFailed = int64(len(me)) } metricDeleted.Add(c, int64(len(toDel))-numFailed, parent.Namespace()) return errors.Filter(err, ds.ErrNoSuchEntity) }
go
func CancelNamedMutations(c context.Context, parent *ds.Key, names ...string) error { toDel := make([]*ds.Key, 0, len(names)) nameSet := stringset.NewFromSlice(names...) nameSet.Iter(func(name string) bool { toDel = append(toDel, ds.NewKey(c, "tumble.Mutation", "n:"+name, 0, parent)) return true }) err := ds.Delete(c, toDel) numFailed := int64(0) if me, ok := err.(errors.MultiError); ok { numFailed = int64(len(me)) } metricDeleted.Add(c, int64(len(toDel))-numFailed, parent.Namespace()) return errors.Filter(err, ds.ErrNoSuchEntity) }
[ "func", "CancelNamedMutations", "(", "c", "context", ".", "Context", ",", "parent", "*", "ds", ".", "Key", ",", "names", "...", "string", ")", "error", "{", "toDel", ":=", "make", "(", "[", "]", "*", "ds", ".", "Key", ",", "0", ",", "len", "(", "names", ")", ")", "\n", "nameSet", ":=", "stringset", ".", "NewFromSlice", "(", "names", "...", ")", "\n", "nameSet", ".", "Iter", "(", "func", "(", "name", "string", ")", "bool", "{", "toDel", "=", "append", "(", "toDel", ",", "ds", ".", "NewKey", "(", "c", ",", "\"", "\"", ",", "\"", "\"", "+", "name", ",", "0", ",", "parent", ")", ")", "\n", "return", "true", "\n", "}", ")", "\n", "err", ":=", "ds", ".", "Delete", "(", "c", ",", "toDel", ")", "\n", "numFailed", ":=", "int64", "(", "0", ")", "\n", "if", "me", ",", "ok", ":=", "err", ".", "(", "errors", ".", "MultiError", ")", ";", "ok", "{", "numFailed", "=", "int64", "(", "len", "(", "me", ")", ")", "\n", "}", "\n", "metricDeleted", ".", "Add", "(", "c", ",", "int64", "(", "len", "(", "toDel", ")", ")", "-", "numFailed", ",", "parent", ".", "Namespace", "(", ")", ")", "\n", "return", "errors", ".", "Filter", "(", "err", ",", "ds", ".", "ErrNoSuchEntity", ")", "\n", "}" ]
// CancelNamedMutations does a best-effort cancellation of the named mutations.
[ "CancelNamedMutations", "does", "a", "best", "-", "effort", "cancellation", "of", "the", "named", "mutations", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tumble/tumble.go#L152-L166
7,174
luci/luci-go
buildbucket/deprecated/build.go
RunDuration
func (b *Build) RunDuration() (duration time.Duration, ok bool) { if b.StartTime.IsZero() || b.CompletionTime.IsZero() { return 0, false } return b.CompletionTime.Sub(b.StartTime), true }
go
func (b *Build) RunDuration() (duration time.Duration, ok bool) { if b.StartTime.IsZero() || b.CompletionTime.IsZero() { return 0, false } return b.CompletionTime.Sub(b.StartTime), true }
[ "func", "(", "b", "*", "Build", ")", "RunDuration", "(", ")", "(", "duration", "time", ".", "Duration", ",", "ok", "bool", ")", "{", "if", "b", ".", "StartTime", ".", "IsZero", "(", ")", "||", "b", ".", "CompletionTime", ".", "IsZero", "(", ")", "{", "return", "0", ",", "false", "\n", "}", "\n", "return", "b", ".", "CompletionTime", ".", "Sub", "(", "b", ".", "StartTime", ")", ",", "true", "\n", "}" ]
// RunDuration returns duration between build start and completion.
[ "RunDuration", "returns", "duration", "between", "build", "start", "and", "completion", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/deprecated/build.go#L85-L90
7,175
luci/luci-go
buildbucket/deprecated/build.go
PutRequest
func (b *Build) PutRequest() (*v1.ApiPutRequestMessage, error) { tags := b.Tags.Copy() tags.Del(v1.TagBuilder) // buildbucket adds it automatically for _, bs := range b.Tags[v1.TagBuildSet] { if !tags.Contains(v1.TagBuildSet, bs) { tags.Add(v1.TagBuildSet, bs) } } msg := &v1.ApiPutRequestMessage{ Bucket: b.Bucket, Tags: tags.Format(), } parameters := map[string]interface{}{ "builder_name": b.Builder, "properties": b.Input.Properties, // keep this synced with marshaling error annotation } if data, err := json.Marshal(parameters); err != nil { // realistically, only properties may cause this. return nil, errors.Annotate(err, "marshaling properties").Err() } else { msg.ParametersJson = string(data) } return msg, nil }
go
func (b *Build) PutRequest() (*v1.ApiPutRequestMessage, error) { tags := b.Tags.Copy() tags.Del(v1.TagBuilder) // buildbucket adds it automatically for _, bs := range b.Tags[v1.TagBuildSet] { if !tags.Contains(v1.TagBuildSet, bs) { tags.Add(v1.TagBuildSet, bs) } } msg := &v1.ApiPutRequestMessage{ Bucket: b.Bucket, Tags: tags.Format(), } parameters := map[string]interface{}{ "builder_name": b.Builder, "properties": b.Input.Properties, // keep this synced with marshaling error annotation } if data, err := json.Marshal(parameters); err != nil { // realistically, only properties may cause this. return nil, errors.Annotate(err, "marshaling properties").Err() } else { msg.ParametersJson = string(data) } return msg, nil }
[ "func", "(", "b", "*", "Build", ")", "PutRequest", "(", ")", "(", "*", "v1", ".", "ApiPutRequestMessage", ",", "error", ")", "{", "tags", ":=", "b", ".", "Tags", ".", "Copy", "(", ")", "\n", "tags", ".", "Del", "(", "v1", ".", "TagBuilder", ")", "// buildbucket adds it automatically", "\n", "for", "_", ",", "bs", ":=", "range", "b", ".", "Tags", "[", "v1", ".", "TagBuildSet", "]", "{", "if", "!", "tags", ".", "Contains", "(", "v1", ".", "TagBuildSet", ",", "bs", ")", "{", "tags", ".", "Add", "(", "v1", ".", "TagBuildSet", ",", "bs", ")", "\n", "}", "\n", "}", "\n\n", "msg", ":=", "&", "v1", ".", "ApiPutRequestMessage", "{", "Bucket", ":", "b", ".", "Bucket", ",", "Tags", ":", "tags", ".", "Format", "(", ")", ",", "}", "\n\n", "parameters", ":=", "map", "[", "string", "]", "interface", "{", "}", "{", "\"", "\"", ":", "b", ".", "Builder", ",", "\"", "\"", ":", "b", ".", "Input", ".", "Properties", ",", "// keep this synced with marshaling error annotation", "}", "\n", "if", "data", ",", "err", ":=", "json", ".", "Marshal", "(", "parameters", ")", ";", "err", "!=", "nil", "{", "// realistically, only properties may cause this.", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "else", "{", "msg", ".", "ParametersJson", "=", "string", "(", "data", ")", "\n", "}", "\n\n", "return", "msg", ",", "nil", "\n", "}" ]
// PutRequest converts b to a build creation request. // // If a buildset is present in both b.BuildSets and b.Map, it is deduped. // Returned value has zero ClientOperationId. // Returns an error if properties could not be marshaled to JSON.
[ "PutRequest", "converts", "b", "to", "a", "build", "creation", "request", ".", "If", "a", "buildset", "is", "present", "in", "both", "b", ".", "BuildSets", "and", "b", ".", "Map", "it", "is", "deduped", ".", "Returned", "value", "has", "zero", "ClientOperationId", ".", "Returns", "an", "error", "if", "properties", "could", "not", "be", "marshaled", "to", "JSON", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/deprecated/build.go#L258-L285
7,176
luci/luci-go
config/server/cfgclient/config.go
Refs
func Refs(c context.Context, a Authority, path string, r MultiResolver, meta *[]*config.Meta) error { return getAll(c, a, backend.GetAllRef, path, r, meta) }
go
func Refs(c context.Context, a Authority, path string, r MultiResolver, meta *[]*config.Meta) error { return getAll(c, a, backend.GetAllRef, path, r, meta) }
[ "func", "Refs", "(", "c", "context", ".", "Context", ",", "a", "Authority", ",", "path", "string", ",", "r", "MultiResolver", ",", "meta", "*", "[", "]", "*", "config", ".", "Meta", ")", "error", "{", "return", "getAll", "(", "c", ",", "a", ",", "backend", ".", "GetAllRef", ",", "path", ",", "r", ",", "meta", ")", "\n", "}" ]
// Refs retrieves all named ref configurations. // // See Projects for individual argument descriptions.
[ "Refs", "retrieves", "all", "named", "ref", "configurations", ".", "See", "Projects", "for", "individual", "argument", "descriptions", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/config.go#L109-L111
7,177
luci/luci-go
dm/api/service/v1/id_helpers.go
Equals
func (q *Quest_ID) Equals(o *Quest_ID) bool { return q.Id == o.Id }
go
func (q *Quest_ID) Equals(o *Quest_ID) bool { return q.Id == o.Id }
[ "func", "(", "q", "*", "Quest_ID", ")", "Equals", "(", "o", "*", "Quest_ID", ")", "bool", "{", "return", "q", ".", "Id", "==", "o", ".", "Id", "\n", "}" ]
// Equals returns true iff the two Quest_IDs are equivalent.
[ "Equals", "returns", "true", "iff", "the", "two", "Quest_IDs", "are", "equivalent", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/id_helpers.go#L18-L20
7,178
luci/luci-go
dm/api/service/v1/id_helpers.go
Equals
func (a *Attempt_ID) Equals(o *Attempt_ID) bool { return a.Quest == o.Quest && a.Id == o.Id }
go
func (a *Attempt_ID) Equals(o *Attempt_ID) bool { return a.Quest == o.Quest && a.Id == o.Id }
[ "func", "(", "a", "*", "Attempt_ID", ")", "Equals", "(", "o", "*", "Attempt_ID", ")", "bool", "{", "return", "a", ".", "Quest", "==", "o", ".", "Quest", "&&", "a", ".", "Id", "==", "o", ".", "Id", "\n", "}" ]
// Equals returns true iff the two Attempt_IDs are equivalent.
[ "Equals", "returns", "true", "iff", "the", "two", "Attempt_IDs", "are", "equivalent", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/id_helpers.go#L28-L30
7,179
luci/luci-go
dm/api/service/v1/id_helpers.go
Execution
func (a *Attempt_ID) Execution(eid uint32) *Execution_ID { return &Execution_ID{Quest: a.Quest, Attempt: a.Id, Id: eid} }
go
func (a *Attempt_ID) Execution(eid uint32) *Execution_ID { return &Execution_ID{Quest: a.Quest, Attempt: a.Id, Id: eid} }
[ "func", "(", "a", "*", "Attempt_ID", ")", "Execution", "(", "eid", "uint32", ")", "*", "Execution_ID", "{", "return", "&", "Execution_ID", "{", "Quest", ":", "a", ".", "Quest", ",", "Attempt", ":", "a", ".", "Id", ",", "Id", ":", "eid", "}", "\n", "}" ]
// Execution returns an Execution_ID for this Attempt.
[ "Execution", "returns", "an", "Execution_ID", "for", "this", "Attempt", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/id_helpers.go#L33-L35
7,180
luci/luci-go
dm/api/service/v1/id_helpers.go
Equals
func (e *Execution_ID) Equals(o *Execution_ID) bool { return e.Quest == o.Quest && e.Attempt == o.Attempt && e.Id == o.Id }
go
func (e *Execution_ID) Equals(o *Execution_ID) bool { return e.Quest == o.Quest && e.Attempt == o.Attempt && e.Id == o.Id }
[ "func", "(", "e", "*", "Execution_ID", ")", "Equals", "(", "o", "*", "Execution_ID", ")", "bool", "{", "return", "e", ".", "Quest", "==", "o", ".", "Quest", "&&", "e", ".", "Attempt", "==", "o", ".", "Attempt", "&&", "e", ".", "Id", "==", "o", ".", "Id", "\n", "}" ]
// Equals returns true iff the two Execution_IDs are equivalent.
[ "Equals", "returns", "true", "iff", "the", "two", "Execution_IDs", "are", "equivalent", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/id_helpers.go#L49-L51
7,181
luci/luci-go
cipd/client/cipd/internal/tagcache.go
makeFileKey
func makeFileKey(pkg, instance, file string) fileKey { return fileKey(pkg + ":" + instance + ":" + file) }
go
func makeFileKey(pkg, instance, file string) fileKey { return fileKey(pkg + ":" + instance + ":" + file) }
[ "func", "makeFileKey", "(", "pkg", ",", "instance", ",", "file", "string", ")", "fileKey", "{", "return", "fileKey", "(", "pkg", "+", "\"", "\"", "+", "instance", "+", "\"", "\"", "+", "file", ")", "\n", "}" ]
// makeFileKey constructs key for the TagCache.addedFiles map. // // It is distinct from tagKey structurally, thus uses different type.
[ "makeFileKey", "constructs", "key", "for", "the", "TagCache", ".", "addedFiles", "map", ".", "It", "is", "distinct", "from", "tagKey", "structurally", "thus", "uses", "different", "type", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/internal/tagcache.go#L83-L85
7,182
luci/luci-go
cipd/client/cipd/internal/tagcache.go
NewTagCache
func NewTagCache(fs fs.FileSystem, service string) *TagCache { return &TagCache{fs: fs, service: service} }
go
func NewTagCache(fs fs.FileSystem, service string) *TagCache { return &TagCache{fs: fs, service: service} }
[ "func", "NewTagCache", "(", "fs", "fs", ".", "FileSystem", ",", "service", "string", ")", "*", "TagCache", "{", "return", "&", "TagCache", "{", "fs", ":", "fs", ",", "service", ":", "service", "}", "\n", "}" ]
// NewTagCache initializes TagCache. // // fs will be the root of the cache. It will be searched for tagcache.db file.
[ "NewTagCache", "initializes", "TagCache", ".", "fs", "will", "be", "the", "root", "of", "the", "cache", ".", "It", "will", "be", "searched", "for", "tagcache", ".", "db", "file", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/internal/tagcache.go#L90-L92
7,183
luci/luci-go
cipd/client/cipd/internal/tagcache.go
ResolveExtractedObjectRef
func (c *TagCache) ResolveExtractedObjectRef(ctx context.Context, pin common.Pin, fileName string) (*api.ObjectRef, error) { if err := common.ValidatePin(pin, common.AnyHash); err != nil { return nil, err } ignoreBrokenObjectRef := func(iid string) *api.ObjectRef { if err := common.ValidateInstanceID(iid, common.AnyHash); err != nil { logging.Errorf(ctx, "Stored object_ref %q for %q in %s is invalid, ignoring it - %s", iid, fileName, pin, err) return nil } return common.InstanceIDToObjectRef(iid) } c.lock.Lock() defer c.lock.Unlock() key := makeFileKey(pin.PackageName, pin.InstanceID, fileName) if e := c.addedFiles[key]; e != nil { return ignoreBrokenObjectRef(e.ObjectRef), nil } if err := c.lazyLoadLocked(ctx); err != nil { return nil, err } // Most recently used entries are usually at the end, search in reverse as a // silly optimization. for i := len(c.cache.FileEntries) - 1; i >= 0; i-- { e := c.cache.FileEntries[i] if e.Package == pin.PackageName && e.InstanceId == pin.InstanceID && e.FileName == fileName { return ignoreBrokenObjectRef(e.ObjectRef), nil } } return nil, nil }
go
func (c *TagCache) ResolveExtractedObjectRef(ctx context.Context, pin common.Pin, fileName string) (*api.ObjectRef, error) { if err := common.ValidatePin(pin, common.AnyHash); err != nil { return nil, err } ignoreBrokenObjectRef := func(iid string) *api.ObjectRef { if err := common.ValidateInstanceID(iid, common.AnyHash); err != nil { logging.Errorf(ctx, "Stored object_ref %q for %q in %s is invalid, ignoring it - %s", iid, fileName, pin, err) return nil } return common.InstanceIDToObjectRef(iid) } c.lock.Lock() defer c.lock.Unlock() key := makeFileKey(pin.PackageName, pin.InstanceID, fileName) if e := c.addedFiles[key]; e != nil { return ignoreBrokenObjectRef(e.ObjectRef), nil } if err := c.lazyLoadLocked(ctx); err != nil { return nil, err } // Most recently used entries are usually at the end, search in reverse as a // silly optimization. for i := len(c.cache.FileEntries) - 1; i >= 0; i-- { e := c.cache.FileEntries[i] if e.Package == pin.PackageName && e.InstanceId == pin.InstanceID && e.FileName == fileName { return ignoreBrokenObjectRef(e.ObjectRef), nil } } return nil, nil }
[ "func", "(", "c", "*", "TagCache", ")", "ResolveExtractedObjectRef", "(", "ctx", "context", ".", "Context", ",", "pin", "common", ".", "Pin", ",", "fileName", "string", ")", "(", "*", "api", ".", "ObjectRef", ",", "error", ")", "{", "if", "err", ":=", "common", ".", "ValidatePin", "(", "pin", ",", "common", ".", "AnyHash", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "ignoreBrokenObjectRef", ":=", "func", "(", "iid", "string", ")", "*", "api", ".", "ObjectRef", "{", "if", "err", ":=", "common", ".", "ValidateInstanceID", "(", "iid", ",", "common", ".", "AnyHash", ")", ";", "err", "!=", "nil", "{", "logging", ".", "Errorf", "(", "ctx", ",", "\"", "\"", ",", "iid", ",", "fileName", ",", "pin", ",", "err", ")", "\n", "return", "nil", "\n", "}", "\n", "return", "common", ".", "InstanceIDToObjectRef", "(", "iid", ")", "\n", "}", "\n\n", "c", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "key", ":=", "makeFileKey", "(", "pin", ".", "PackageName", ",", "pin", ".", "InstanceID", ",", "fileName", ")", "\n", "if", "e", ":=", "c", ".", "addedFiles", "[", "key", "]", ";", "e", "!=", "nil", "{", "return", "ignoreBrokenObjectRef", "(", "e", ".", "ObjectRef", ")", ",", "nil", "\n", "}", "\n\n", "if", "err", ":=", "c", ".", "lazyLoadLocked", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Most recently used entries are usually at the end, search in reverse as a", "// silly optimization.", "for", "i", ":=", "len", "(", "c", ".", "cache", ".", "FileEntries", ")", "-", "1", ";", "i", ">=", "0", ";", "i", "--", "{", "e", ":=", "c", ".", "cache", ".", "FileEntries", "[", "i", "]", "\n", "if", "e", ".", "Package", "==", "pin", ".", "PackageName", "&&", "e", ".", "InstanceId", "==", "pin", ".", "InstanceID", "&&", "e", ".", "FileName", "==", "fileName", "{", "return", "ignoreBrokenObjectRef", "(", "e", ".", "ObjectRef", ")", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "nil", "\n", "}" ]
// ResolveExtractedObjectRef returns ObjectRef or nil if that file is not in the // cache. // // Returns error if the cache can't be read.
[ "ResolveExtractedObjectRef", "returns", "ObjectRef", "or", "nil", "if", "that", "file", "is", "not", "in", "the", "cache", ".", "Returns", "error", "if", "the", "cache", "can", "t", "be", "read", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/internal/tagcache.go#L152-L186
7,184
luci/luci-go
cipd/client/cipd/internal/tagcache.go
Save
func (c *TagCache) Save(ctx context.Context) error { c.lock.Lock() defer c.lock.Unlock() // Nothing to store? Just clean the state, so that ResolveTag can fetch the // up-to-date cache from disk later if needed. if len(c.addedTags) == 0 && len(c.addedFiles) == 0 { c.cache = nil return nil } // Sort all new entries, for consistency. sortedTags := make([]string, 0, len(c.addedTags)) for k := range c.addedTags { sortedTags = append(sortedTags, string(k)) } sort.Strings(sortedTags) sortedFiles := make([]string, 0, len(c.addedFiles)) for k := range c.addedFiles { sortedFiles = append(sortedFiles, string(k)) } sort.Strings(sortedFiles) // Load the most recent data to avoid overwriting it. Load ALL entries, even // if they belong to different service: we have one global cache file and // should preserve all entries there. recent, err := c.loadFromDisk(ctx, true) if err != nil { return err } // Copy existing entries, except the ones we are moving to the tail. Carefully // copy entries belonging to other services too, we must not overwrite them. mergedTags := make([]*messages.TagCache_Entry, 0, len(recent.Entries)+len(c.addedTags)) for _, e := range recent.Entries { key := makeTagKey(e.Package, e.Tag) if e.Service != c.service || c.addedTags[key] == nil { mergedTags = append(mergedTags, e) } } // Add new entries to the tail. for _, k := range sortedTags { mergedTags = append(mergedTags, c.addedTags[tagKey(k)]) } // Trim the end result, discard the head: it's where old items are. if len(mergedTags) > tagCacheMaxSize { mergedTags = mergedTags[len(mergedTags)-tagCacheMaxSize:] } // Do the same for file entries. mergedFiles := make([]*messages.TagCache_FileEntry, 0, len(recent.FileEntries)+len(c.addedFiles)) for _, e := range recent.FileEntries { key := makeFileKey(e.Package, e.InstanceId, e.FileName) if e.Service != c.service || c.addedFiles[key] == nil { mergedFiles = append(mergedFiles, e) } } for _, k := range sortedFiles { mergedFiles = append(mergedFiles, c.addedFiles[fileKey(k)]) } if len(mergedFiles) > tagCacheMaxExeSize { mergedFiles = mergedFiles[len(mergedFiles)-tagCacheMaxExeSize:] } // Serialize and write to disk. We still can accidentally replace someone // else's changes, but the probability should be relatively low. It can happen // only if two processes call 'Save' at the exact same time. updated := &messages.TagCache{Entries: mergedTags, FileEntries: mergedFiles} if err := c.dumpToDisk(ctx, updated); err != nil { return err } // The state is persisted now. c.cache = updated c.addedTags = nil c.addedFiles = nil return nil }
go
func (c *TagCache) Save(ctx context.Context) error { c.lock.Lock() defer c.lock.Unlock() // Nothing to store? Just clean the state, so that ResolveTag can fetch the // up-to-date cache from disk later if needed. if len(c.addedTags) == 0 && len(c.addedFiles) == 0 { c.cache = nil return nil } // Sort all new entries, for consistency. sortedTags := make([]string, 0, len(c.addedTags)) for k := range c.addedTags { sortedTags = append(sortedTags, string(k)) } sort.Strings(sortedTags) sortedFiles := make([]string, 0, len(c.addedFiles)) for k := range c.addedFiles { sortedFiles = append(sortedFiles, string(k)) } sort.Strings(sortedFiles) // Load the most recent data to avoid overwriting it. Load ALL entries, even // if they belong to different service: we have one global cache file and // should preserve all entries there. recent, err := c.loadFromDisk(ctx, true) if err != nil { return err } // Copy existing entries, except the ones we are moving to the tail. Carefully // copy entries belonging to other services too, we must not overwrite them. mergedTags := make([]*messages.TagCache_Entry, 0, len(recent.Entries)+len(c.addedTags)) for _, e := range recent.Entries { key := makeTagKey(e.Package, e.Tag) if e.Service != c.service || c.addedTags[key] == nil { mergedTags = append(mergedTags, e) } } // Add new entries to the tail. for _, k := range sortedTags { mergedTags = append(mergedTags, c.addedTags[tagKey(k)]) } // Trim the end result, discard the head: it's where old items are. if len(mergedTags) > tagCacheMaxSize { mergedTags = mergedTags[len(mergedTags)-tagCacheMaxSize:] } // Do the same for file entries. mergedFiles := make([]*messages.TagCache_FileEntry, 0, len(recent.FileEntries)+len(c.addedFiles)) for _, e := range recent.FileEntries { key := makeFileKey(e.Package, e.InstanceId, e.FileName) if e.Service != c.service || c.addedFiles[key] == nil { mergedFiles = append(mergedFiles, e) } } for _, k := range sortedFiles { mergedFiles = append(mergedFiles, c.addedFiles[fileKey(k)]) } if len(mergedFiles) > tagCacheMaxExeSize { mergedFiles = mergedFiles[len(mergedFiles)-tagCacheMaxExeSize:] } // Serialize and write to disk. We still can accidentally replace someone // else's changes, but the probability should be relatively low. It can happen // only if two processes call 'Save' at the exact same time. updated := &messages.TagCache{Entries: mergedTags, FileEntries: mergedFiles} if err := c.dumpToDisk(ctx, updated); err != nil { return err } // The state is persisted now. c.cache = updated c.addedTags = nil c.addedFiles = nil return nil }
[ "func", "(", "c", "*", "TagCache", ")", "Save", "(", "ctx", "context", ".", "Context", ")", "error", "{", "c", ".", "lock", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "lock", ".", "Unlock", "(", ")", "\n\n", "// Nothing to store? Just clean the state, so that ResolveTag can fetch the", "// up-to-date cache from disk later if needed.", "if", "len", "(", "c", ".", "addedTags", ")", "==", "0", "&&", "len", "(", "c", ".", "addedFiles", ")", "==", "0", "{", "c", ".", "cache", "=", "nil", "\n", "return", "nil", "\n", "}", "\n\n", "// Sort all new entries, for consistency.", "sortedTags", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "c", ".", "addedTags", ")", ")", "\n", "for", "k", ":=", "range", "c", ".", "addedTags", "{", "sortedTags", "=", "append", "(", "sortedTags", ",", "string", "(", "k", ")", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "sortedTags", ")", "\n", "sortedFiles", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "c", ".", "addedFiles", ")", ")", "\n", "for", "k", ":=", "range", "c", ".", "addedFiles", "{", "sortedFiles", "=", "append", "(", "sortedFiles", ",", "string", "(", "k", ")", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "sortedFiles", ")", "\n\n", "// Load the most recent data to avoid overwriting it. Load ALL entries, even", "// if they belong to different service: we have one global cache file and", "// should preserve all entries there.", "recent", ",", "err", ":=", "c", ".", "loadFromDisk", "(", "ctx", ",", "true", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Copy existing entries, except the ones we are moving to the tail. Carefully", "// copy entries belonging to other services too, we must not overwrite them.", "mergedTags", ":=", "make", "(", "[", "]", "*", "messages", ".", "TagCache_Entry", ",", "0", ",", "len", "(", "recent", ".", "Entries", ")", "+", "len", "(", "c", ".", "addedTags", ")", ")", "\n", "for", "_", ",", "e", ":=", "range", "recent", ".", "Entries", "{", "key", ":=", "makeTagKey", "(", "e", ".", "Package", ",", "e", ".", "Tag", ")", "\n", "if", "e", ".", "Service", "!=", "c", ".", "service", "||", "c", ".", "addedTags", "[", "key", "]", "==", "nil", "{", "mergedTags", "=", "append", "(", "mergedTags", ",", "e", ")", "\n", "}", "\n", "}", "\n\n", "// Add new entries to the tail.", "for", "_", ",", "k", ":=", "range", "sortedTags", "{", "mergedTags", "=", "append", "(", "mergedTags", ",", "c", ".", "addedTags", "[", "tagKey", "(", "k", ")", "]", ")", "\n", "}", "\n\n", "// Trim the end result, discard the head: it's where old items are.", "if", "len", "(", "mergedTags", ")", ">", "tagCacheMaxSize", "{", "mergedTags", "=", "mergedTags", "[", "len", "(", "mergedTags", ")", "-", "tagCacheMaxSize", ":", "]", "\n", "}", "\n\n", "// Do the same for file entries.", "mergedFiles", ":=", "make", "(", "[", "]", "*", "messages", ".", "TagCache_FileEntry", ",", "0", ",", "len", "(", "recent", ".", "FileEntries", ")", "+", "len", "(", "c", ".", "addedFiles", ")", ")", "\n", "for", "_", ",", "e", ":=", "range", "recent", ".", "FileEntries", "{", "key", ":=", "makeFileKey", "(", "e", ".", "Package", ",", "e", ".", "InstanceId", ",", "e", ".", "FileName", ")", "\n", "if", "e", ".", "Service", "!=", "c", ".", "service", "||", "c", ".", "addedFiles", "[", "key", "]", "==", "nil", "{", "mergedFiles", "=", "append", "(", "mergedFiles", ",", "e", ")", "\n", "}", "\n", "}", "\n", "for", "_", ",", "k", ":=", "range", "sortedFiles", "{", "mergedFiles", "=", "append", "(", "mergedFiles", ",", "c", ".", "addedFiles", "[", "fileKey", "(", "k", ")", "]", ")", "\n", "}", "\n", "if", "len", "(", "mergedFiles", ")", ">", "tagCacheMaxExeSize", "{", "mergedFiles", "=", "mergedFiles", "[", "len", "(", "mergedFiles", ")", "-", "tagCacheMaxExeSize", ":", "]", "\n", "}", "\n\n", "// Serialize and write to disk. We still can accidentally replace someone", "// else's changes, but the probability should be relatively low. It can happen", "// only if two processes call 'Save' at the exact same time.", "updated", ":=", "&", "messages", ".", "TagCache", "{", "Entries", ":", "mergedTags", ",", "FileEntries", ":", "mergedFiles", "}", "\n", "if", "err", ":=", "c", ".", "dumpToDisk", "(", "ctx", ",", "updated", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// The state is persisted now.", "c", ".", "cache", "=", "updated", "\n", "c", ".", "addedTags", "=", "nil", "\n", "c", ".", "addedFiles", "=", "nil", "\n\n", "return", "nil", "\n", "}" ]
// Save stores all pending cache updates to the file system. // // It effectively resets the object to the initial state.
[ "Save", "stores", "all", "pending", "cache", "updates", "to", "the", "file", "system", ".", "It", "effectively", "resets", "the", "object", "to", "the", "initial", "state", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/internal/tagcache.go#L251-L331
7,185
luci/luci-go
cipd/client/cipd/internal/tagcache.go
dumpToDisk
func (c *TagCache) dumpToDisk(ctx context.Context, msg *messages.TagCache) error { path, err := c.fs.RootRelToAbs(tagCacheFilename) if err != nil { return err } blob, err := MarshalWithSHA256(msg) if err != nil { return err } return fs.EnsureFile(ctx, c.fs, path, bytes.NewReader(blob)) }
go
func (c *TagCache) dumpToDisk(ctx context.Context, msg *messages.TagCache) error { path, err := c.fs.RootRelToAbs(tagCacheFilename) if err != nil { return err } blob, err := MarshalWithSHA256(msg) if err != nil { return err } return fs.EnsureFile(ctx, c.fs, path, bytes.NewReader(blob)) }
[ "func", "(", "c", "*", "TagCache", ")", "dumpToDisk", "(", "ctx", "context", ".", "Context", ",", "msg", "*", "messages", ".", "TagCache", ")", "error", "{", "path", ",", "err", ":=", "c", ".", "fs", ".", "RootRelToAbs", "(", "tagCacheFilename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "blob", ",", "err", ":=", "MarshalWithSHA256", "(", "msg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "fs", ".", "EnsureFile", "(", "ctx", ",", "c", ".", "fs", ",", "path", ",", "bytes", ".", "NewReader", "(", "blob", ")", ")", "\n", "}" ]
// dumpToDisk serializes the tag cache and writes it to the file system.
[ "dumpToDisk", "serializes", "the", "tag", "cache", "and", "writes", "it", "to", "the", "file", "system", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/internal/tagcache.go#L380-L392
7,186
luci/luci-go
machine-db/common/mac_addresses.go
String
func (m MAC48) String() string { mac := make(net.HardwareAddr, 8) binary.BigEndian.PutUint64(mac, uint64(m)) return mac[2:].String() }
go
func (m MAC48) String() string { mac := make(net.HardwareAddr, 8) binary.BigEndian.PutUint64(mac, uint64(m)) return mac[2:].String() }
[ "func", "(", "m", "MAC48", ")", "String", "(", ")", "string", "{", "mac", ":=", "make", "(", "net", ".", "HardwareAddr", ",", "8", ")", "\n", "binary", ".", "BigEndian", ".", "PutUint64", "(", "mac", ",", "uint64", "(", "m", ")", ")", "\n", "return", "mac", "[", "2", ":", "]", ".", "String", "(", ")", "\n", "}" ]
// String returns a string representation of this MAC-48 address.
[ "String", "returns", "a", "string", "representation", "of", "this", "MAC", "-", "48", "address", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/common/mac_addresses.go#L32-L36
7,187
luci/luci-go
machine-db/common/mac_addresses.go
ParseMAC48
func ParseMAC48(mac48 string) (MAC48, error) { m, err := net.ParseMAC(mac48) if err != nil || len(m) != 6 { return 0, errors.Reason("invalid MAC-48 address %q", mac48).Err() } bytes := make([]byte, 8) copy(bytes[2:], m) return MAC48(binary.BigEndian.Uint64(bytes)), nil }
go
func ParseMAC48(mac48 string) (MAC48, error) { m, err := net.ParseMAC(mac48) if err != nil || len(m) != 6 { return 0, errors.Reason("invalid MAC-48 address %q", mac48).Err() } bytes := make([]byte, 8) copy(bytes[2:], m) return MAC48(binary.BigEndian.Uint64(bytes)), nil }
[ "func", "ParseMAC48", "(", "mac48", "string", ")", "(", "MAC48", ",", "error", ")", "{", "m", ",", "err", ":=", "net", ".", "ParseMAC", "(", "mac48", ")", "\n", "if", "err", "!=", "nil", "||", "len", "(", "m", ")", "!=", "6", "{", "return", "0", ",", "errors", ".", "Reason", "(", "\"", "\"", ",", "mac48", ")", ".", "Err", "(", ")", "\n", "}", "\n", "bytes", ":=", "make", "(", "[", "]", "byte", ",", "8", ")", "\n", "copy", "(", "bytes", "[", "2", ":", "]", ",", "m", ")", "\n", "return", "MAC48", "(", "binary", ".", "BigEndian", ".", "Uint64", "(", "bytes", ")", ")", ",", "nil", "\n", "}" ]
// ParseMAC48 returns a MAC-48 address from the given string.
[ "ParseMAC48", "returns", "a", "MAC", "-", "48", "address", "from", "the", "given", "string", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/common/mac_addresses.go#L39-L47
7,188
luci/luci-go
common/api/buildbucket/swarmbucket/v1/swarmbucket-gen.go
NewService
func NewService(ctx context.Context, opts ...option.ClientOption) (*Service, error) { scopesOption := option.WithScopes( "https://www.googleapis.com/auth/userinfo.email", ) // NOTE: prepend, so we don't override user-specified scopes. opts = append([]option.ClientOption{scopesOption}, opts...) client, endpoint, err := htransport.NewClient(ctx, opts...) if err != nil { return nil, err } s, err := New(client) if err != nil { return nil, err } if endpoint != "" { s.BasePath = endpoint } return s, nil }
go
func NewService(ctx context.Context, opts ...option.ClientOption) (*Service, error) { scopesOption := option.WithScopes( "https://www.googleapis.com/auth/userinfo.email", ) // NOTE: prepend, so we don't override user-specified scopes. opts = append([]option.ClientOption{scopesOption}, opts...) client, endpoint, err := htransport.NewClient(ctx, opts...) if err != nil { return nil, err } s, err := New(client) if err != nil { return nil, err } if endpoint != "" { s.BasePath = endpoint } return s, nil }
[ "func", "NewService", "(", "ctx", "context", ".", "Context", ",", "opts", "...", "option", ".", "ClientOption", ")", "(", "*", "Service", ",", "error", ")", "{", "scopesOption", ":=", "option", ".", "WithScopes", "(", "\"", "\"", ",", ")", "\n", "// NOTE: prepend, so we don't override user-specified scopes.", "opts", "=", "append", "(", "[", "]", "option", ".", "ClientOption", "{", "scopesOption", "}", ",", "opts", "...", ")", "\n", "client", ",", "endpoint", ",", "err", ":=", "htransport", ".", "NewClient", "(", "ctx", ",", "opts", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "s", ",", "err", ":=", "New", "(", "client", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "endpoint", "!=", "\"", "\"", "{", "s", ".", "BasePath", "=", "endpoint", "\n", "}", "\n", "return", "s", ",", "nil", "\n", "}" ]
// NewService creates a new Service.
[ "NewService", "creates", "a", "new", "Service", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/api/buildbucket/swarmbucket/v1/swarmbucket-gen.go#L92-L110
7,189
luci/luci-go
logdog/common/types/streamaddr.go
Validate
func (s *StreamAddr) Validate() error { if s.Host == "" { return errors.New("cannot have empty Host") } if err := s.Project.Validate(); err != nil { return err } if err := s.Path.Validate(); err != nil { return err } return nil }
go
func (s *StreamAddr) Validate() error { if s.Host == "" { return errors.New("cannot have empty Host") } if err := s.Project.Validate(); err != nil { return err } if err := s.Path.Validate(); err != nil { return err } return nil }
[ "func", "(", "s", "*", "StreamAddr", ")", "Validate", "(", ")", "error", "{", "if", "s", ".", "Host", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "err", ":=", "s", ".", "Project", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "s", ".", "Path", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Validate returns an error if the supplied StreamAddr is not valid.
[ "Validate", "returns", "an", "error", "if", "the", "supplied", "StreamAddr", "is", "not", "valid", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/types/streamaddr.go#L52-L63
7,190
luci/luci-go
logdog/common/types/streamaddr.go
IsZero
func (s *StreamAddr) IsZero() bool { return s.Host == "" && s.Path == "" && s.Project == "" }
go
func (s *StreamAddr) IsZero() bool { return s.Host == "" && s.Path == "" && s.Project == "" }
[ "func", "(", "s", "*", "StreamAddr", ")", "IsZero", "(", ")", "bool", "{", "return", "s", ".", "Host", "==", "\"", "\"", "&&", "s", ".", "Path", "==", "\"", "\"", "&&", "s", ".", "Project", "==", "\"", "\"", "\n", "}" ]
// IsZero returns true iff all fields are empty.
[ "IsZero", "returns", "true", "iff", "all", "fields", "are", "empty", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/types/streamaddr.go#L66-L68
7,191
luci/luci-go
logdog/common/types/streamaddr.go
URL
func (s *StreamAddr) URL() *url.URL { return &url.URL{ Scheme: logDogURLScheme, Host: s.Host, Path: strings.Join([]string{"", string(s.Project), string(s.Path)}, "/"), } }
go
func (s *StreamAddr) URL() *url.URL { return &url.URL{ Scheme: logDogURLScheme, Host: s.Host, Path: strings.Join([]string{"", string(s.Project), string(s.Path)}, "/"), } }
[ "func", "(", "s", "*", "StreamAddr", ")", "URL", "(", ")", "*", "url", ".", "URL", "{", "return", "&", "url", ".", "URL", "{", "Scheme", ":", "logDogURLScheme", ",", "Host", ":", "s", ".", "Host", ",", "Path", ":", "strings", ".", "Join", "(", "[", "]", "string", "{", "\"", "\"", ",", "string", "(", "s", ".", "Project", ")", ",", "string", "(", "s", ".", "Path", ")", "}", ",", "\"", "\"", ")", ",", "}", "\n", "}" ]
// URL returns a LogDog URL that represents this Stream.
[ "URL", "returns", "a", "LogDog", "URL", "that", "represents", "this", "Stream", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/types/streamaddr.go#L74-L80
7,192
luci/luci-go
scheduler/appengine/ui/presentation.go
makeJob
func makeJob(c context.Context, j *engine.Job, log *engine.JobTriageLog) *schedulerJob { traits, err := presentation.GetJobTraits(c, config(c).Catalog, j) if err != nil { logging.WithError(err).Warningf(c, "Failed to get task traits for %s", j.JobID) } now := clock.Now(c).UTC() nextRun := "" switch ts := j.CronTickTime(); { case ts == schedule.DistantFuture: nextRun = "-" case !ts.IsZero(): nextRun = humanize.RelTime(ts, now, "ago", "from now") default: nextRun = "not scheduled yet" } // Internal state names aren't very user friendly. Introduce some aliases. state := presentation.GetPublicStateKind(j, traits) labelClass := stateToLabelClass[state] // Put triggers after regular jobs. sortGroup := "A" if j.Flavor == catalog.JobFlavorTrigger { sortGroup = "B" } out := &schedulerJob{ ProjectID: j.ProjectID, JobName: j.JobName(), Schedule: j.Schedule, Definition: taskToText(j.Task), Policy: policyToText(j.TriggeringPolicyRaw), Revision: j.Revision, RevisionURL: j.RevisionURL, State: string(state), NextRun: nextRun, Paused: j.Paused, LabelClass: labelClass, JobFlavorIcon: flavorToIconClass[j.Flavor], JobFlavorTitle: flavorToTitle[j.Flavor], sortGroup: sortGroup, now: now, traits: traits, } // Fill in job triage log details if available. They are not available in // job listings, for example. if log != nil { out.TriageLog.Available = true out.TriageLog.LastTriage = humanize.RelTime(log.LastTriage, now, "ago", "") out.TriageLog.Stale = log.Stale() out.TriageLog.Staleness = j.LastTriage.Sub(log.LastTriage) out.TriageLog.DebugLog = log.DebugLog } return out }
go
func makeJob(c context.Context, j *engine.Job, log *engine.JobTriageLog) *schedulerJob { traits, err := presentation.GetJobTraits(c, config(c).Catalog, j) if err != nil { logging.WithError(err).Warningf(c, "Failed to get task traits for %s", j.JobID) } now := clock.Now(c).UTC() nextRun := "" switch ts := j.CronTickTime(); { case ts == schedule.DistantFuture: nextRun = "-" case !ts.IsZero(): nextRun = humanize.RelTime(ts, now, "ago", "from now") default: nextRun = "not scheduled yet" } // Internal state names aren't very user friendly. Introduce some aliases. state := presentation.GetPublicStateKind(j, traits) labelClass := stateToLabelClass[state] // Put triggers after regular jobs. sortGroup := "A" if j.Flavor == catalog.JobFlavorTrigger { sortGroup = "B" } out := &schedulerJob{ ProjectID: j.ProjectID, JobName: j.JobName(), Schedule: j.Schedule, Definition: taskToText(j.Task), Policy: policyToText(j.TriggeringPolicyRaw), Revision: j.Revision, RevisionURL: j.RevisionURL, State: string(state), NextRun: nextRun, Paused: j.Paused, LabelClass: labelClass, JobFlavorIcon: flavorToIconClass[j.Flavor], JobFlavorTitle: flavorToTitle[j.Flavor], sortGroup: sortGroup, now: now, traits: traits, } // Fill in job triage log details if available. They are not available in // job listings, for example. if log != nil { out.TriageLog.Available = true out.TriageLog.LastTriage = humanize.RelTime(log.LastTriage, now, "ago", "") out.TriageLog.Stale = log.Stale() out.TriageLog.Staleness = j.LastTriage.Sub(log.LastTriage) out.TriageLog.DebugLog = log.DebugLog } return out }
[ "func", "makeJob", "(", "c", "context", ".", "Context", ",", "j", "*", "engine", ".", "Job", ",", "log", "*", "engine", ".", "JobTriageLog", ")", "*", "schedulerJob", "{", "traits", ",", "err", ":=", "presentation", ".", "GetJobTraits", "(", "c", ",", "config", "(", "c", ")", ".", "Catalog", ",", "j", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "WithError", "(", "err", ")", ".", "Warningf", "(", "c", ",", "\"", "\"", ",", "j", ".", "JobID", ")", "\n", "}", "\n\n", "now", ":=", "clock", ".", "Now", "(", "c", ")", ".", "UTC", "(", ")", "\n", "nextRun", ":=", "\"", "\"", "\n", "switch", "ts", ":=", "j", ".", "CronTickTime", "(", ")", ";", "{", "case", "ts", "==", "schedule", ".", "DistantFuture", ":", "nextRun", "=", "\"", "\"", "\n", "case", "!", "ts", ".", "IsZero", "(", ")", ":", "nextRun", "=", "humanize", ".", "RelTime", "(", "ts", ",", "now", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "default", ":", "nextRun", "=", "\"", "\"", "\n", "}", "\n\n", "// Internal state names aren't very user friendly. Introduce some aliases.", "state", ":=", "presentation", ".", "GetPublicStateKind", "(", "j", ",", "traits", ")", "\n", "labelClass", ":=", "stateToLabelClass", "[", "state", "]", "\n\n", "// Put triggers after regular jobs.", "sortGroup", ":=", "\"", "\"", "\n", "if", "j", ".", "Flavor", "==", "catalog", ".", "JobFlavorTrigger", "{", "sortGroup", "=", "\"", "\"", "\n", "}", "\n\n", "out", ":=", "&", "schedulerJob", "{", "ProjectID", ":", "j", ".", "ProjectID", ",", "JobName", ":", "j", ".", "JobName", "(", ")", ",", "Schedule", ":", "j", ".", "Schedule", ",", "Definition", ":", "taskToText", "(", "j", ".", "Task", ")", ",", "Policy", ":", "policyToText", "(", "j", ".", "TriggeringPolicyRaw", ")", ",", "Revision", ":", "j", ".", "Revision", ",", "RevisionURL", ":", "j", ".", "RevisionURL", ",", "State", ":", "string", "(", "state", ")", ",", "NextRun", ":", "nextRun", ",", "Paused", ":", "j", ".", "Paused", ",", "LabelClass", ":", "labelClass", ",", "JobFlavorIcon", ":", "flavorToIconClass", "[", "j", ".", "Flavor", "]", ",", "JobFlavorTitle", ":", "flavorToTitle", "[", "j", ".", "Flavor", "]", ",", "sortGroup", ":", "sortGroup", ",", "now", ":", "now", ",", "traits", ":", "traits", ",", "}", "\n\n", "// Fill in job triage log details if available. They are not available in", "// job listings, for example.", "if", "log", "!=", "nil", "{", "out", ".", "TriageLog", ".", "Available", "=", "true", "\n", "out", ".", "TriageLog", ".", "LastTriage", "=", "humanize", ".", "RelTime", "(", "log", ".", "LastTriage", ",", "now", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "out", ".", "TriageLog", ".", "Stale", "=", "log", ".", "Stale", "(", ")", "\n", "out", ".", "TriageLog", ".", "Staleness", "=", "j", ".", "LastTriage", ".", "Sub", "(", "log", ".", "LastTriage", ")", "\n", "out", ".", "TriageLog", ".", "DebugLog", "=", "log", ".", "DebugLog", "\n", "}", "\n\n", "return", "out", "\n", "}" ]
// makeJob builds UI presentation for engine.Job.
[ "makeJob", "builds", "UI", "presentation", "for", "engine", ".", "Job", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/ui/presentation.go#L95-L153
7,193
luci/luci-go
scheduler/appengine/ui/presentation.go
sortJobs
func sortJobs(c context.Context, jobs []*engine.Job) sortedJobs { out := make(sortedJobs, len(jobs)) for i, job := range jobs { out[i] = makeJob(c, job, nil) } sort.Sort(out) return out }
go
func sortJobs(c context.Context, jobs []*engine.Job) sortedJobs { out := make(sortedJobs, len(jobs)) for i, job := range jobs { out[i] = makeJob(c, job, nil) } sort.Sort(out) return out }
[ "func", "sortJobs", "(", "c", "context", ".", "Context", ",", "jobs", "[", "]", "*", "engine", ".", "Job", ")", "sortedJobs", "{", "out", ":=", "make", "(", "sortedJobs", ",", "len", "(", "jobs", ")", ")", "\n", "for", "i", ",", "job", ":=", "range", "jobs", "{", "out", "[", "i", "]", "=", "makeJob", "(", "c", ",", "job", ",", "nil", ")", "\n", "}", "\n", "sort", ".", "Sort", "(", "out", ")", "\n", "return", "out", "\n", "}" ]
// sortJobs instantiate a bunch of schedulerJob objects and sorts them in // display order.
[ "sortJobs", "instantiate", "a", "bunch", "of", "schedulerJob", "objects", "and", "sorts", "them", "in", "display", "order", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/ui/presentation.go#L188-L195
7,194
luci/luci-go
scheduler/appengine/ui/presentation.go
makeInvocation
func makeInvocation(j *schedulerJob, i *engine.Invocation) *invocation { // Invocations with Multistage == false trait are never in "RUNNING" state, // they perform all their work in 'LaunchTask' while technically being in // "STARTING" state. We display them as "RUNNING" instead. See comment for // task.Traits.Multistage for more info. status := i.Status if !j.traits.Multistage && status == task.StatusStarting { status = task.StatusRunning } triggeredBy := "-" if i.TriggeredBy != "" { triggeredBy = string(i.TriggeredBy) if i.TriggeredBy.Email() != "" { triggeredBy = i.TriggeredBy.Email() // triggered by a user (not a service) } } finished := i.Finished if finished.IsZero() { finished = j.now } duration := humanize.RelTime(i.Started, finished, "", "") if duration == "now" { duration = "1 second" // "now" looks weird for durations } incTriggers, err := i.IncomingTriggers() if err != nil { panic(errors.Annotate(err, "failed to deserialize incoming triggers").Err()) } outTriggers, err := i.OutgoingTriggers() if err != nil { panic(errors.Annotate(err, "failed to deserialize outgoing triggers").Err()) } return &invocation{ ProjectID: j.ProjectID, JobName: j.JobName, InvID: i.ID, Attempt: i.RetryCount + 1, Revision: i.Revision, RevisionURL: i.RevisionURL, Definition: taskToText(i.Task), TriggeredBy: triggeredBy, Properties: makeJSONFromProtoStruct(i.PropertiesRaw), Tags: i.Tags, IncomingTriggers: makeTriggerList(j.now, incTriggers), OutgoingTriggers: makeTriggerList(j.now, outTriggers), Started: humanize.RelTime(i.Started, j.now, "ago", "from now"), Duration: duration, Status: string(status), DebugLog: i.DebugLog, RowClass: statusToRowClass[status], LabelClass: statusToLabelClass[status], ViewURL: i.ViewURL, } }
go
func makeInvocation(j *schedulerJob, i *engine.Invocation) *invocation { // Invocations with Multistage == false trait are never in "RUNNING" state, // they perform all their work in 'LaunchTask' while technically being in // "STARTING" state. We display them as "RUNNING" instead. See comment for // task.Traits.Multistage for more info. status := i.Status if !j.traits.Multistage && status == task.StatusStarting { status = task.StatusRunning } triggeredBy := "-" if i.TriggeredBy != "" { triggeredBy = string(i.TriggeredBy) if i.TriggeredBy.Email() != "" { triggeredBy = i.TriggeredBy.Email() // triggered by a user (not a service) } } finished := i.Finished if finished.IsZero() { finished = j.now } duration := humanize.RelTime(i.Started, finished, "", "") if duration == "now" { duration = "1 second" // "now" looks weird for durations } incTriggers, err := i.IncomingTriggers() if err != nil { panic(errors.Annotate(err, "failed to deserialize incoming triggers").Err()) } outTriggers, err := i.OutgoingTriggers() if err != nil { panic(errors.Annotate(err, "failed to deserialize outgoing triggers").Err()) } return &invocation{ ProjectID: j.ProjectID, JobName: j.JobName, InvID: i.ID, Attempt: i.RetryCount + 1, Revision: i.Revision, RevisionURL: i.RevisionURL, Definition: taskToText(i.Task), TriggeredBy: triggeredBy, Properties: makeJSONFromProtoStruct(i.PropertiesRaw), Tags: i.Tags, IncomingTriggers: makeTriggerList(j.now, incTriggers), OutgoingTriggers: makeTriggerList(j.now, outTriggers), Started: humanize.RelTime(i.Started, j.now, "ago", "from now"), Duration: duration, Status: string(status), DebugLog: i.DebugLog, RowClass: statusToRowClass[status], LabelClass: statusToLabelClass[status], ViewURL: i.ViewURL, } }
[ "func", "makeInvocation", "(", "j", "*", "schedulerJob", ",", "i", "*", "engine", ".", "Invocation", ")", "*", "invocation", "{", "// Invocations with Multistage == false trait are never in \"RUNNING\" state,", "// they perform all their work in 'LaunchTask' while technically being in", "// \"STARTING\" state. We display them as \"RUNNING\" instead. See comment for", "// task.Traits.Multistage for more info.", "status", ":=", "i", ".", "Status", "\n", "if", "!", "j", ".", "traits", ".", "Multistage", "&&", "status", "==", "task", ".", "StatusStarting", "{", "status", "=", "task", ".", "StatusRunning", "\n", "}", "\n\n", "triggeredBy", ":=", "\"", "\"", "\n", "if", "i", ".", "TriggeredBy", "!=", "\"", "\"", "{", "triggeredBy", "=", "string", "(", "i", ".", "TriggeredBy", ")", "\n", "if", "i", ".", "TriggeredBy", ".", "Email", "(", ")", "!=", "\"", "\"", "{", "triggeredBy", "=", "i", ".", "TriggeredBy", ".", "Email", "(", ")", "// triggered by a user (not a service)", "\n", "}", "\n", "}", "\n\n", "finished", ":=", "i", ".", "Finished", "\n", "if", "finished", ".", "IsZero", "(", ")", "{", "finished", "=", "j", ".", "now", "\n", "}", "\n", "duration", ":=", "humanize", ".", "RelTime", "(", "i", ".", "Started", ",", "finished", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "duration", "==", "\"", "\"", "{", "duration", "=", "\"", "\"", "// \"now\" looks weird for durations", "\n", "}", "\n\n", "incTriggers", ",", "err", ":=", "i", ".", "IncomingTriggers", "(", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", ")", "\n", "}", "\n", "outTriggers", ",", "err", ":=", "i", ".", "OutgoingTriggers", "(", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", ")", "\n", "}", "\n\n", "return", "&", "invocation", "{", "ProjectID", ":", "j", ".", "ProjectID", ",", "JobName", ":", "j", ".", "JobName", ",", "InvID", ":", "i", ".", "ID", ",", "Attempt", ":", "i", ".", "RetryCount", "+", "1", ",", "Revision", ":", "i", ".", "Revision", ",", "RevisionURL", ":", "i", ".", "RevisionURL", ",", "Definition", ":", "taskToText", "(", "i", ".", "Task", ")", ",", "TriggeredBy", ":", "triggeredBy", ",", "Properties", ":", "makeJSONFromProtoStruct", "(", "i", ".", "PropertiesRaw", ")", ",", "Tags", ":", "i", ".", "Tags", ",", "IncomingTriggers", ":", "makeTriggerList", "(", "j", ".", "now", ",", "incTriggers", ")", ",", "OutgoingTriggers", ":", "makeTriggerList", "(", "j", ".", "now", ",", "outTriggers", ")", ",", "Started", ":", "humanize", ".", "RelTime", "(", "i", ".", "Started", ",", "j", ".", "now", ",", "\"", "\"", ",", "\"", "\"", ")", ",", "Duration", ":", "duration", ",", "Status", ":", "string", "(", "status", ")", ",", "DebugLog", ":", "i", ".", "DebugLog", ",", "RowClass", ":", "statusToRowClass", "[", "status", "]", ",", "LabelClass", ":", "statusToLabelClass", "[", "status", "]", ",", "ViewURL", ":", "i", ".", "ViewURL", ",", "}", "\n", "}" ]
// makeInvocation builds UI presentation of some Invocation of a job.
[ "makeInvocation", "builds", "UI", "presentation", "of", "some", "Invocation", "of", "a", "job", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/ui/presentation.go#L241-L298
7,195
luci/luci-go
scheduler/appengine/ui/presentation.go
makeTrigger
func makeTrigger(t *internal.Trigger, now time.Time) trigger { out := trigger{ Title: t.Title, URL: t.Url, EmittedBy: strings.TrimPrefix(t.EmittedByUser, "user:"), } if out.Title == "" { out.Title = t.Id } if t.Created != nil { out.RelTime = humanize.RelTime(google.TimeFromProto(t.Created), now, "ago", "from now") } return out }
go
func makeTrigger(t *internal.Trigger, now time.Time) trigger { out := trigger{ Title: t.Title, URL: t.Url, EmittedBy: strings.TrimPrefix(t.EmittedByUser, "user:"), } if out.Title == "" { out.Title = t.Id } if t.Created != nil { out.RelTime = humanize.RelTime(google.TimeFromProto(t.Created), now, "ago", "from now") } return out }
[ "func", "makeTrigger", "(", "t", "*", "internal", ".", "Trigger", ",", "now", "time", ".", "Time", ")", "trigger", "{", "out", ":=", "trigger", "{", "Title", ":", "t", ".", "Title", ",", "URL", ":", "t", ".", "Url", ",", "EmittedBy", ":", "strings", ".", "TrimPrefix", "(", "t", ".", "EmittedByUser", ",", "\"", "\"", ")", ",", "}", "\n", "if", "out", ".", "Title", "==", "\"", "\"", "{", "out", ".", "Title", "=", "t", ".", "Id", "\n", "}", "\n", "if", "t", ".", "Created", "!=", "nil", "{", "out", ".", "RelTime", "=", "humanize", ".", "RelTime", "(", "google", ".", "TimeFromProto", "(", "t", ".", "Created", ")", ",", "now", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "out", "\n", "}" ]
// makeTrigger builds UI presentation of some internal.Trigger.
[ "makeTrigger", "builds", "UI", "presentation", "of", "some", "internal", ".", "Trigger", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/ui/presentation.go#L309-L322
7,196
luci/luci-go
scheduler/appengine/ui/presentation.go
makeTriggerList
func makeTriggerList(now time.Time, list []*internal.Trigger) []trigger { out := make([]trigger, len(list)) for i, t := range list { out[i] = makeTrigger(t, now) } return out }
go
func makeTriggerList(now time.Time, list []*internal.Trigger) []trigger { out := make([]trigger, len(list)) for i, t := range list { out[i] = makeTrigger(t, now) } return out }
[ "func", "makeTriggerList", "(", "now", "time", ".", "Time", ",", "list", "[", "]", "*", "internal", ".", "Trigger", ")", "[", "]", "trigger", "{", "out", ":=", "make", "(", "[", "]", "trigger", ",", "len", "(", "list", ")", ")", "\n", "for", "i", ",", "t", ":=", "range", "list", "{", "out", "[", "i", "]", "=", "makeTrigger", "(", "t", ",", "now", ")", "\n", "}", "\n", "return", "out", "\n", "}" ]
// makeTriggerList builds UI presentation of a bunch of triggers.
[ "makeTriggerList", "builds", "UI", "presentation", "of", "a", "bunch", "of", "triggers", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/ui/presentation.go#L325-L331
7,197
luci/luci-go
scheduler/appengine/ui/presentation.go
makeJSONFromProtoStruct
func makeJSONFromProtoStruct(blob []byte) string { if len(blob) == 0 { return "" } // Binary proto => internal representation. obj := structpb.Struct{} if err := proto.Unmarshal(blob, &obj); err != nil { return fmt.Sprintf("<not a valid protobuf.Struct - %s>", err) } // Internal representation => JSON. But JSONPB produces very ugly JSON when // using Ident. So we are not done yet... ugly, err := (&jsonpb.Marshaler{}).MarshalToString(&obj) if err != nil { return fmt.Sprintf("<failed to marshal to JSON - %s>", err) } // JSON => internal representation 2, sigh. Because there's no existing // structpb.Struct => map converter and writing one just for the sake of // JSON pretty printing is kind of annoying. var obj2 map[string]interface{} if err := json.Unmarshal([]byte(ugly), &obj2); err != nil { return fmt.Sprintf("<internal error when unmarshaling JSON - %s>", err) } // Internal representation 2 => pretty (well, prettier) JSON. pretty, err := json.MarshalIndent(obj2, "", " ") if err != nil { return fmt.Sprintf("<internal error when marshaling JSON - %s>", err) } return string(pretty) }
go
func makeJSONFromProtoStruct(blob []byte) string { if len(blob) == 0 { return "" } // Binary proto => internal representation. obj := structpb.Struct{} if err := proto.Unmarshal(blob, &obj); err != nil { return fmt.Sprintf("<not a valid protobuf.Struct - %s>", err) } // Internal representation => JSON. But JSONPB produces very ugly JSON when // using Ident. So we are not done yet... ugly, err := (&jsonpb.Marshaler{}).MarshalToString(&obj) if err != nil { return fmt.Sprintf("<failed to marshal to JSON - %s>", err) } // JSON => internal representation 2, sigh. Because there's no existing // structpb.Struct => map converter and writing one just for the sake of // JSON pretty printing is kind of annoying. var obj2 map[string]interface{} if err := json.Unmarshal([]byte(ugly), &obj2); err != nil { return fmt.Sprintf("<internal error when unmarshaling JSON - %s>", err) } // Internal representation 2 => pretty (well, prettier) JSON. pretty, err := json.MarshalIndent(obj2, "", " ") if err != nil { return fmt.Sprintf("<internal error when marshaling JSON - %s>", err) } return string(pretty) }
[ "func", "makeJSONFromProtoStruct", "(", "blob", "[", "]", "byte", ")", "string", "{", "if", "len", "(", "blob", ")", "==", "0", "{", "return", "\"", "\"", "\n", "}", "\n\n", "// Binary proto => internal representation.", "obj", ":=", "structpb", ".", "Struct", "{", "}", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "blob", ",", "&", "obj", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Internal representation => JSON. But JSONPB produces very ugly JSON when", "// using Ident. So we are not done yet...", "ugly", ",", "err", ":=", "(", "&", "jsonpb", ".", "Marshaler", "{", "}", ")", ".", "MarshalToString", "(", "&", "obj", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// JSON => internal representation 2, sigh. Because there's no existing", "// structpb.Struct => map converter and writing one just for the sake of", "// JSON pretty printing is kind of annoying.", "var", "obj2", "map", "[", "string", "]", "interface", "{", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "[", "]", "byte", "(", "ugly", ")", ",", "&", "obj2", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Internal representation 2 => pretty (well, prettier) JSON.", "pretty", ",", "err", ":=", "json", ".", "MarshalIndent", "(", "obj2", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "string", "(", "pretty", ")", "\n", "}" ]
// makeJSONFromProtoStruct reformats serialized protobuf.Struct as JSON. // // If the blob is empty, returns empty string. If the blob is not valid proto // message, returns a string with error message instead. This is exclusively for // UI after all.
[ "makeJSONFromProtoStruct", "reformats", "serialized", "protobuf", ".", "Struct", "as", "JSON", ".", "If", "the", "blob", "is", "empty", "returns", "empty", "string", ".", "If", "the", "blob", "is", "not", "valid", "proto", "message", "returns", "a", "string", "with", "error", "message", "instead", ".", "This", "is", "exclusively", "for", "UI", "after", "all", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/ui/presentation.go#L338-L370
7,198
luci/luci-go
milo/common/model/bots.go
Dimensions
func (d PoolDescriptor) Dimensions() strpair.Map { m := strpair.ParseMap(d) m.Del(SwarmingHostnameKey) return m }
go
func (d PoolDescriptor) Dimensions() strpair.Map { m := strpair.ParseMap(d) m.Del(SwarmingHostnameKey) return m }
[ "func", "(", "d", "PoolDescriptor", ")", "Dimensions", "(", ")", "strpair", ".", "Map", "{", "m", ":=", "strpair", ".", "ParseMap", "(", "d", ")", "\n", "m", ".", "Del", "(", "SwarmingHostnameKey", ")", "\n", "return", "m", "\n", "}" ]
// Dimensions returns a copy of the PoolDescriptor without the swarming_hostname item // in strpair.Map format.
[ "Dimensions", "returns", "a", "copy", "of", "the", "PoolDescriptor", "without", "the", "swarming_hostname", "item", "in", "strpair", ".", "Map", "format", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/model/bots.go#L64-L68
7,199
luci/luci-go
config/server/cfgclient/access/access.go
Check
func Check(c context.Context, a backend.Authority, configSet config.Set) error { if a == backend.AsService { return nil } project := configSet.Project() if project == "" { // Not a project config set, so neither remaining Authority can access. return ErrNoAccess } // Root project config set, contains project.cfg file that has project ACL // definitions. projectConfigSet := config.ProjectSet(project) // Load the project config. We execute this RPC as the service, not the user, // so while this will recurse (and hopefully take advantage of the cache), it // will not trigger an infinite access check loop. var pcfg configPB.ProjectCfg if err := cfgclient.Get(c, cfgclient.AsService, projectConfigSet, cfgclient.ProjectConfigPath, textproto.Message(&pcfg), nil); err != nil { return errors.Annotate(err, "failed to load %q in %q", cfgclient.ProjectConfigPath, projectConfigSet).Err() } id := identity.AnonymousIdentity if a == backend.AsUser { id = auth.CurrentIdentity(c) } checkGroups := make([]string, 0, len(pcfg.Access)) for _, access := range pcfg.Access { if group, ok := trimPrefix(access, "group:"); ok { // Check group membership. checkGroups = append(checkGroups, group) } else { // If there is no ":" in the access string, this is a user ACL. if strings.IndexRune(access, ':') < 0 { access = "user:" + access } if identity.Identity(access) == id { return nil } } } // No individual accesses, check groups. if len(checkGroups) > 0 { switch canAccess, err := auth.IsMember(c, checkGroups...); { case err != nil: return errors.Annotate(err, "failed to check group membership").Err() case canAccess: return nil } } return ErrNoAccess }
go
func Check(c context.Context, a backend.Authority, configSet config.Set) error { if a == backend.AsService { return nil } project := configSet.Project() if project == "" { // Not a project config set, so neither remaining Authority can access. return ErrNoAccess } // Root project config set, contains project.cfg file that has project ACL // definitions. projectConfigSet := config.ProjectSet(project) // Load the project config. We execute this RPC as the service, not the user, // so while this will recurse (and hopefully take advantage of the cache), it // will not trigger an infinite access check loop. var pcfg configPB.ProjectCfg if err := cfgclient.Get(c, cfgclient.AsService, projectConfigSet, cfgclient.ProjectConfigPath, textproto.Message(&pcfg), nil); err != nil { return errors.Annotate(err, "failed to load %q in %q", cfgclient.ProjectConfigPath, projectConfigSet).Err() } id := identity.AnonymousIdentity if a == backend.AsUser { id = auth.CurrentIdentity(c) } checkGroups := make([]string, 0, len(pcfg.Access)) for _, access := range pcfg.Access { if group, ok := trimPrefix(access, "group:"); ok { // Check group membership. checkGroups = append(checkGroups, group) } else { // If there is no ":" in the access string, this is a user ACL. if strings.IndexRune(access, ':') < 0 { access = "user:" + access } if identity.Identity(access) == id { return nil } } } // No individual accesses, check groups. if len(checkGroups) > 0 { switch canAccess, err := auth.IsMember(c, checkGroups...); { case err != nil: return errors.Annotate(err, "failed to check group membership").Err() case canAccess: return nil } } return ErrNoAccess }
[ "func", "Check", "(", "c", "context", ".", "Context", ",", "a", "backend", ".", "Authority", ",", "configSet", "config", ".", "Set", ")", "error", "{", "if", "a", "==", "backend", ".", "AsService", "{", "return", "nil", "\n", "}", "\n\n", "project", ":=", "configSet", ".", "Project", "(", ")", "\n", "if", "project", "==", "\"", "\"", "{", "// Not a project config set, so neither remaining Authority can access.", "return", "ErrNoAccess", "\n", "}", "\n\n", "// Root project config set, contains project.cfg file that has project ACL", "// definitions.", "projectConfigSet", ":=", "config", ".", "ProjectSet", "(", "project", ")", "\n\n", "// Load the project config. We execute this RPC as the service, not the user,", "// so while this will recurse (and hopefully take advantage of the cache), it", "// will not trigger an infinite access check loop.", "var", "pcfg", "configPB", ".", "ProjectCfg", "\n", "if", "err", ":=", "cfgclient", ".", "Get", "(", "c", ",", "cfgclient", ".", "AsService", ",", "projectConfigSet", ",", "cfgclient", ".", "ProjectConfigPath", ",", "textproto", ".", "Message", "(", "&", "pcfg", ")", ",", "nil", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "cfgclient", ".", "ProjectConfigPath", ",", "projectConfigSet", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "id", ":=", "identity", ".", "AnonymousIdentity", "\n", "if", "a", "==", "backend", ".", "AsUser", "{", "id", "=", "auth", ".", "CurrentIdentity", "(", "c", ")", "\n", "}", "\n", "checkGroups", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "pcfg", ".", "Access", ")", ")", "\n", "for", "_", ",", "access", ":=", "range", "pcfg", ".", "Access", "{", "if", "group", ",", "ok", ":=", "trimPrefix", "(", "access", ",", "\"", "\"", ")", ";", "ok", "{", "// Check group membership.", "checkGroups", "=", "append", "(", "checkGroups", ",", "group", ")", "\n", "}", "else", "{", "// If there is no \":\" in the access string, this is a user ACL.", "if", "strings", ".", "IndexRune", "(", "access", ",", "':'", ")", "<", "0", "{", "access", "=", "\"", "\"", "+", "access", "\n", "}", "\n", "if", "identity", ".", "Identity", "(", "access", ")", "==", "id", "{", "return", "nil", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// No individual accesses, check groups.", "if", "len", "(", "checkGroups", ")", ">", "0", "{", "switch", "canAccess", ",", "err", ":=", "auth", ".", "IsMember", "(", "c", ",", "checkGroups", "...", ")", ";", "{", "case", "err", "!=", "nil", ":", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "case", "canAccess", ":", "return", "nil", "\n", "}", "\n", "}", "\n", "return", "ErrNoAccess", "\n", "}" ]
// Check tests if a given Authority can access the named config set.
[ "Check", "tests", "if", "a", "given", "Authority", "can", "access", "the", "named", "config", "set", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/access/access.go#L47-L102