id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
8,000
luci/luci-go
cipd/client/cipd/internal/instancecache.go
readState
func (c *InstanceCache) readState(ctx context.Context, state *messages.InstanceCache, now time.Time) { statePath, err := c.fs.RootRelToAbs(instanceCacheStateFilename) if err != nil { panic("impossible") } stateBytes, err := ioutil.ReadFile(statePath) sync := false switch { case os.IsNotExist(err): sync = true case err != nil: logging.Warningf(ctx, "cipd: could not read instance cache - %s", err) sync = true default: if err := UnmarshalWithSHA256(stateBytes, state); err != nil { if err == ErrUnknownSHA256 { logging.Warningf(ctx, "cipd: need to rebuild instance cache index file") } else { logging.Warningf(ctx, "cipd: instance cache file is corrupted - %s", err) } *state = messages.InstanceCache{} sync = true } else { cutOff := now. Add(-instanceCacheSyncInterval). Add(time.Duration(rand.Int63n(int64(5 * time.Minute)))) sync = google.TimeFromProto(state.LastSynced).Before(cutOff) } } if sync { if err := c.syncState(ctx, state, now); err != nil { logging.Warningf(ctx, "cipd: failed to sync instance cache - %s", err) } c.gc(ctx, state, now) } }
go
func (c *InstanceCache) readState(ctx context.Context, state *messages.InstanceCache, now time.Time) { statePath, err := c.fs.RootRelToAbs(instanceCacheStateFilename) if err != nil { panic("impossible") } stateBytes, err := ioutil.ReadFile(statePath) sync := false switch { case os.IsNotExist(err): sync = true case err != nil: logging.Warningf(ctx, "cipd: could not read instance cache - %s", err) sync = true default: if err := UnmarshalWithSHA256(stateBytes, state); err != nil { if err == ErrUnknownSHA256 { logging.Warningf(ctx, "cipd: need to rebuild instance cache index file") } else { logging.Warningf(ctx, "cipd: instance cache file is corrupted - %s", err) } *state = messages.InstanceCache{} sync = true } else { cutOff := now. Add(-instanceCacheSyncInterval). Add(time.Duration(rand.Int63n(int64(5 * time.Minute)))) sync = google.TimeFromProto(state.LastSynced).Before(cutOff) } } if sync { if err := c.syncState(ctx, state, now); err != nil { logging.Warningf(ctx, "cipd: failed to sync instance cache - %s", err) } c.gc(ctx, state, now) } }
[ "func", "(", "c", "*", "InstanceCache", ")", "readState", "(", "ctx", "context", ".", "Context", ",", "state", "*", "messages", ".", "InstanceCache", ",", "now", "time", ".", "Time", ")", "{", "statePath", ",", "err", ":=", "c", ".", "fs", ".", "RootRelToAbs", "(", "instanceCacheStateFilename", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "stateBytes", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "statePath", ")", "\n", "sync", ":=", "false", "\n", "switch", "{", "case", "os", ".", "IsNotExist", "(", "err", ")", ":", "sync", "=", "true", "\n\n", "case", "err", "!=", "nil", ":", "logging", ".", "Warningf", "(", "ctx", ",", "\"", "\"", ",", "err", ")", "\n", "sync", "=", "true", "\n\n", "default", ":", "if", "err", ":=", "UnmarshalWithSHA256", "(", "stateBytes", ",", "state", ")", ";", "err", "!=", "nil", "{", "if", "err", "==", "ErrUnknownSHA256", "{", "logging", ".", "Warningf", "(", "ctx", ",", "\"", "\"", ")", "\n", "}", "else", "{", "logging", ".", "Warningf", "(", "ctx", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "*", "state", "=", "messages", ".", "InstanceCache", "{", "}", "\n", "sync", "=", "true", "\n", "}", "else", "{", "cutOff", ":=", "now", ".", "Add", "(", "-", "instanceCacheSyncInterval", ")", ".", "Add", "(", "time", ".", "Duration", "(", "rand", ".", "Int63n", "(", "int64", "(", "5", "*", "time", ".", "Minute", ")", ")", ")", ")", "\n", "sync", "=", "google", ".", "TimeFromProto", "(", "state", ".", "LastSynced", ")", ".", "Before", "(", "cutOff", ")", "\n", "}", "\n", "}", "\n\n", "if", "sync", "{", "if", "err", ":=", "c", ".", "syncState", "(", "ctx", ",", "state", ",", "now", ")", ";", "err", "!=", "nil", "{", "logging", ".", "Warningf", "(", "ctx", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "c", ".", "gc", "(", "ctx", ",", "state", ",", "now", ")", "\n", "}", "\n", "}" ]
// readState loads cache state from the state file. // If the file does not exist, corrupted or its state was not synchronized // with the instance files for a long time, synchronizes it. // Newly discovered files are considered last accessed at zero time. // If synchronization fails, then the state is considered empty.
[ "readState", "loads", "cache", "state", "from", "the", "state", "file", ".", "If", "the", "file", "does", "not", "exist", "corrupted", "or", "its", "state", "was", "not", "synchronized", "with", "the", "instance", "files", "for", "a", "long", "time", "synchronizes", "it", ".", "Newly", "discovered", "files", "are", "considered", "last", "accessed", "at", "zero", "time", ".", "If", "synchronization", "fails", "then", "the", "state", "is", "considered", "empty", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/internal/instancecache.go#L259-L298
8,001
luci/luci-go
cipd/client/cipd/internal/instancecache.go
syncState
func (c *InstanceCache) syncState(ctx context.Context, state *messages.InstanceCache, now time.Time) error { root, err := os.Open(c.fs.Root()) switch { case os.IsNotExist(err): state.Entries = nil case err != nil: return err default: instanceIDs, err := root.Readdirnames(0) if err != nil { return err } existingIDs := stringset.New(len(instanceIDs)) for _, id := range instanceIDs { if common.ValidateInstanceID(id, common.AnyHash) != nil { continue } existingIDs.Add(id) if _, ok := state.Entries[id]; !ok { if state.Entries == nil { state.Entries = map[string]*messages.InstanceCache_Entry{} } state.Entries[id] = &messages.InstanceCache_Entry{ LastAccess: google.NewTimestamp(now), } } } for id := range state.Entries { if !existingIDs.Has(id) { delete(state.Entries, id) } } } state.LastSynced = google.NewTimestamp(now) logging.Infof(ctx, "cipd: synchronized instance cache with instance files") return nil }
go
func (c *InstanceCache) syncState(ctx context.Context, state *messages.InstanceCache, now time.Time) error { root, err := os.Open(c.fs.Root()) switch { case os.IsNotExist(err): state.Entries = nil case err != nil: return err default: instanceIDs, err := root.Readdirnames(0) if err != nil { return err } existingIDs := stringset.New(len(instanceIDs)) for _, id := range instanceIDs { if common.ValidateInstanceID(id, common.AnyHash) != nil { continue } existingIDs.Add(id) if _, ok := state.Entries[id]; !ok { if state.Entries == nil { state.Entries = map[string]*messages.InstanceCache_Entry{} } state.Entries[id] = &messages.InstanceCache_Entry{ LastAccess: google.NewTimestamp(now), } } } for id := range state.Entries { if !existingIDs.Has(id) { delete(state.Entries, id) } } } state.LastSynced = google.NewTimestamp(now) logging.Infof(ctx, "cipd: synchronized instance cache with instance files") return nil }
[ "func", "(", "c", "*", "InstanceCache", ")", "syncState", "(", "ctx", "context", ".", "Context", ",", "state", "*", "messages", ".", "InstanceCache", ",", "now", "time", ".", "Time", ")", "error", "{", "root", ",", "err", ":=", "os", ".", "Open", "(", "c", ".", "fs", ".", "Root", "(", ")", ")", "\n", "switch", "{", "case", "os", ".", "IsNotExist", "(", "err", ")", ":", "state", ".", "Entries", "=", "nil", "\n\n", "case", "err", "!=", "nil", ":", "return", "err", "\n\n", "default", ":", "instanceIDs", ",", "err", ":=", "root", ".", "Readdirnames", "(", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "existingIDs", ":=", "stringset", ".", "New", "(", "len", "(", "instanceIDs", ")", ")", "\n", "for", "_", ",", "id", ":=", "range", "instanceIDs", "{", "if", "common", ".", "ValidateInstanceID", "(", "id", ",", "common", ".", "AnyHash", ")", "!=", "nil", "{", "continue", "\n", "}", "\n", "existingIDs", ".", "Add", "(", "id", ")", "\n\n", "if", "_", ",", "ok", ":=", "state", ".", "Entries", "[", "id", "]", ";", "!", "ok", "{", "if", "state", ".", "Entries", "==", "nil", "{", "state", ".", "Entries", "=", "map", "[", "string", "]", "*", "messages", ".", "InstanceCache_Entry", "{", "}", "\n", "}", "\n", "state", ".", "Entries", "[", "id", "]", "=", "&", "messages", ".", "InstanceCache_Entry", "{", "LastAccess", ":", "google", ".", "NewTimestamp", "(", "now", ")", ",", "}", "\n", "}", "\n", "}", "\n\n", "for", "id", ":=", "range", "state", ".", "Entries", "{", "if", "!", "existingIDs", ".", "Has", "(", "id", ")", "{", "delete", "(", "state", ".", "Entries", ",", "id", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "state", ".", "LastSynced", "=", "google", ".", "NewTimestamp", "(", "now", ")", "\n", "logging", ".", "Infof", "(", "ctx", ",", "\"", "\"", ")", "\n", "return", "nil", "\n", "}" ]
// syncState synchronizes the list of instances in the state file with instance // files. // // Preserves lastAccess of existing instances. Newly discovered files are // considered last accessed now.
[ "syncState", "synchronizes", "the", "list", "of", "instances", "in", "the", "state", "file", "with", "instance", "files", ".", "Preserves", "lastAccess", "of", "existing", "instances", ".", "Newly", "discovered", "files", "are", "considered", "last", "accessed", "now", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/internal/instancecache.go#L305-L347
8,002
luci/luci-go
cipd/client/cipd/internal/instancecache.go
saveState
func (c *InstanceCache) saveState(ctx context.Context, state *messages.InstanceCache) error { stateBytes, err := MarshalWithSHA256(state) if err != nil { return err } statePath, err := c.fs.RootRelToAbs(instanceCacheStateFilename) if err != nil { panic("impossible") } return fs.EnsureFile(ctx, c.fs, statePath, bytes.NewReader(stateBytes)) }
go
func (c *InstanceCache) saveState(ctx context.Context, state *messages.InstanceCache) error { stateBytes, err := MarshalWithSHA256(state) if err != nil { return err } statePath, err := c.fs.RootRelToAbs(instanceCacheStateFilename) if err != nil { panic("impossible") } return fs.EnsureFile(ctx, c.fs, statePath, bytes.NewReader(stateBytes)) }
[ "func", "(", "c", "*", "InstanceCache", ")", "saveState", "(", "ctx", "context", ".", "Context", ",", "state", "*", "messages", ".", "InstanceCache", ")", "error", "{", "stateBytes", ",", "err", ":=", "MarshalWithSHA256", "(", "state", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "statePath", ",", "err", ":=", "c", ".", "fs", ".", "RootRelToAbs", "(", "instanceCacheStateFilename", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "return", "fs", ".", "EnsureFile", "(", "ctx", ",", "c", ".", "fs", ",", "statePath", ",", "bytes", ".", "NewReader", "(", "stateBytes", ")", ")", "\n", "}" ]
// saveState persists the cache state.
[ "saveState", "persists", "the", "cache", "state", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/internal/instancecache.go#L350-L362
8,003
luci/luci-go
cipd/client/cipd/internal/instancecache.go
withState
func (c *InstanceCache) withState(ctx context.Context, now time.Time, f func(*messages.InstanceCache)) { state := &messages.InstanceCache{} start := clock.Now(ctx) defer func() { totalTime := clock.Since(ctx, start) if totalTime > 2*time.Second { logging.Warningf( ctx, "cipd: instance cache state update took %s (%d entries)", totalTime, len(state.Entries)) } }() c.stateLock.Lock() defer c.stateLock.Unlock() c.readState(ctx, state, now) f(state) if err := c.saveState(ctx, state); err != nil { logging.Warningf(ctx, "cipd: could not save instance cache - %s", err) } }
go
func (c *InstanceCache) withState(ctx context.Context, now time.Time, f func(*messages.InstanceCache)) { state := &messages.InstanceCache{} start := clock.Now(ctx) defer func() { totalTime := clock.Since(ctx, start) if totalTime > 2*time.Second { logging.Warningf( ctx, "cipd: instance cache state update took %s (%d entries)", totalTime, len(state.Entries)) } }() c.stateLock.Lock() defer c.stateLock.Unlock() c.readState(ctx, state, now) f(state) if err := c.saveState(ctx, state); err != nil { logging.Warningf(ctx, "cipd: could not save instance cache - %s", err) } }
[ "func", "(", "c", "*", "InstanceCache", ")", "withState", "(", "ctx", "context", ".", "Context", ",", "now", "time", ".", "Time", ",", "f", "func", "(", "*", "messages", ".", "InstanceCache", ")", ")", "{", "state", ":=", "&", "messages", ".", "InstanceCache", "{", "}", "\n\n", "start", ":=", "clock", ".", "Now", "(", "ctx", ")", "\n", "defer", "func", "(", ")", "{", "totalTime", ":=", "clock", ".", "Since", "(", "ctx", ",", "start", ")", "\n", "if", "totalTime", ">", "2", "*", "time", ".", "Second", "{", "logging", ".", "Warningf", "(", "ctx", ",", "\"", "\"", ",", "totalTime", ",", "len", "(", "state", ".", "Entries", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "c", ".", "stateLock", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "stateLock", ".", "Unlock", "(", ")", "\n\n", "c", ".", "readState", "(", "ctx", ",", "state", ",", "now", ")", "\n", "f", "(", "state", ")", "\n", "if", "err", ":=", "c", ".", "saveState", "(", "ctx", ",", "state", ")", ";", "err", "!=", "nil", "{", "logging", ".", "Warningf", "(", "ctx", ",", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}" ]
// withState loads cache state from the state file, calls f and saves it back. // See also readState.
[ "withState", "loads", "cache", "state", "from", "the", "state", "file", "calls", "f", "and", "saves", "it", "back", ".", "See", "also", "readState", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/internal/instancecache.go#L366-L387
8,004
luci/luci-go
cipd/client/cipd/internal/instancecache.go
getAccessTime
func (c *InstanceCache) getAccessTime(ctx context.Context, now time.Time, pin common.Pin) (lastAccess time.Time, ok bool) { c.withState(ctx, now, func(s *messages.InstanceCache) { var entry *messages.InstanceCache_Entry if entry, ok = s.Entries[pin.InstanceID]; ok { lastAccess = google.TimeFromProto(entry.LastAccess) } }) return }
go
func (c *InstanceCache) getAccessTime(ctx context.Context, now time.Time, pin common.Pin) (lastAccess time.Time, ok bool) { c.withState(ctx, now, func(s *messages.InstanceCache) { var entry *messages.InstanceCache_Entry if entry, ok = s.Entries[pin.InstanceID]; ok { lastAccess = google.TimeFromProto(entry.LastAccess) } }) return }
[ "func", "(", "c", "*", "InstanceCache", ")", "getAccessTime", "(", "ctx", "context", ".", "Context", ",", "now", "time", ".", "Time", ",", "pin", "common", ".", "Pin", ")", "(", "lastAccess", "time", ".", "Time", ",", "ok", "bool", ")", "{", "c", ".", "withState", "(", "ctx", ",", "now", ",", "func", "(", "s", "*", "messages", ".", "InstanceCache", ")", "{", "var", "entry", "*", "messages", ".", "InstanceCache_Entry", "\n", "if", "entry", ",", "ok", "=", "s", ".", "Entries", "[", "pin", ".", "InstanceID", "]", ";", "ok", "{", "lastAccess", "=", "google", ".", "TimeFromProto", "(", "entry", ".", "LastAccess", ")", "\n", "}", "\n", "}", ")", "\n", "return", "\n", "}" ]
// getAccessTime returns last access time of an instance. // Used for testing.
[ "getAccessTime", "returns", "last", "access", "time", "of", "an", "instance", ".", "Used", "for", "testing", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/internal/instancecache.go#L391-L399
8,005
luci/luci-go
tokenserver/auth/machine/auth_method.go
Authenticate
func (m *MachineTokenAuthMethod) Authenticate(c context.Context, r *http.Request) (*auth.User, error) { token := r.Header.Get(MachineTokenHeader) if token == "" { return nil, nil // no token -> the auth method is not applicable } // Deserialize both envelope and the body. envelope, body, err := deserialize(token) if err != nil { logTokenError(c, r, body, err, "Failed to deserialize the token") return nil, ErrBadToken } // Construct an identity of a token server that signed the token to check that // it belongs to "auth-token-servers" group. signerServiceAccount, err := identity.MakeIdentity("user:" + body.IssuedBy) if err != nil { logTokenError(c, r, body, err, "Bad issued_by field - %q", body.IssuedBy) return nil, ErrBadToken } // Reject tokens from unknown token servers right away. db, err := auth.GetDB(c) if err != nil { return nil, transient.Tag.Apply(err) } ok, err := db.IsMember(c, signerServiceAccount, []string{TokenServersGroup}) if err != nil { return nil, transient.Tag.Apply(err) } if !ok { logTokenError(c, r, body, nil, "Unknown token issuer - %q", body.IssuedBy) return nil, ErrBadToken } // Check the expiration time before doing any heavier checks. if err = checkExpiration(body, clock.Now(c)); err != nil { logTokenError(c, r, body, err, "Token has expired or not yet valid") return nil, ErrBadToken } // Check the token was actually signed by the server. if err = m.checkSignature(c, body.IssuedBy, envelope); err != nil { if transient.Tag.In(err) { return nil, err } logTokenError(c, r, body, err, "Bad signature") return nil, ErrBadToken } // The token is valid. Construct the bot identity. botIdent, err := identity.MakeIdentity("bot:" + body.MachineFqdn) if err != nil { logTokenError(c, r, body, err, "Bad machine_fqdn - %q", body.MachineFqdn) return nil, ErrBadToken } return &auth.User{Identity: botIdent}, nil }
go
func (m *MachineTokenAuthMethod) Authenticate(c context.Context, r *http.Request) (*auth.User, error) { token := r.Header.Get(MachineTokenHeader) if token == "" { return nil, nil // no token -> the auth method is not applicable } // Deserialize both envelope and the body. envelope, body, err := deserialize(token) if err != nil { logTokenError(c, r, body, err, "Failed to deserialize the token") return nil, ErrBadToken } // Construct an identity of a token server that signed the token to check that // it belongs to "auth-token-servers" group. signerServiceAccount, err := identity.MakeIdentity("user:" + body.IssuedBy) if err != nil { logTokenError(c, r, body, err, "Bad issued_by field - %q", body.IssuedBy) return nil, ErrBadToken } // Reject tokens from unknown token servers right away. db, err := auth.GetDB(c) if err != nil { return nil, transient.Tag.Apply(err) } ok, err := db.IsMember(c, signerServiceAccount, []string{TokenServersGroup}) if err != nil { return nil, transient.Tag.Apply(err) } if !ok { logTokenError(c, r, body, nil, "Unknown token issuer - %q", body.IssuedBy) return nil, ErrBadToken } // Check the expiration time before doing any heavier checks. if err = checkExpiration(body, clock.Now(c)); err != nil { logTokenError(c, r, body, err, "Token has expired or not yet valid") return nil, ErrBadToken } // Check the token was actually signed by the server. if err = m.checkSignature(c, body.IssuedBy, envelope); err != nil { if transient.Tag.In(err) { return nil, err } logTokenError(c, r, body, err, "Bad signature") return nil, ErrBadToken } // The token is valid. Construct the bot identity. botIdent, err := identity.MakeIdentity("bot:" + body.MachineFqdn) if err != nil { logTokenError(c, r, body, err, "Bad machine_fqdn - %q", body.MachineFqdn) return nil, ErrBadToken } return &auth.User{Identity: botIdent}, nil }
[ "func", "(", "m", "*", "MachineTokenAuthMethod", ")", "Authenticate", "(", "c", "context", ".", "Context", ",", "r", "*", "http", ".", "Request", ")", "(", "*", "auth", ".", "User", ",", "error", ")", "{", "token", ":=", "r", ".", "Header", ".", "Get", "(", "MachineTokenHeader", ")", "\n", "if", "token", "==", "\"", "\"", "{", "return", "nil", ",", "nil", "// no token -> the auth method is not applicable", "\n", "}", "\n\n", "// Deserialize both envelope and the body.", "envelope", ",", "body", ",", "err", ":=", "deserialize", "(", "token", ")", "\n", "if", "err", "!=", "nil", "{", "logTokenError", "(", "c", ",", "r", ",", "body", ",", "err", ",", "\"", "\"", ")", "\n", "return", "nil", ",", "ErrBadToken", "\n", "}", "\n\n", "// Construct an identity of a token server that signed the token to check that", "// it belongs to \"auth-token-servers\" group.", "signerServiceAccount", ",", "err", ":=", "identity", ".", "MakeIdentity", "(", "\"", "\"", "+", "body", ".", "IssuedBy", ")", "\n", "if", "err", "!=", "nil", "{", "logTokenError", "(", "c", ",", "r", ",", "body", ",", "err", ",", "\"", "\"", ",", "body", ".", "IssuedBy", ")", "\n", "return", "nil", ",", "ErrBadToken", "\n", "}", "\n\n", "// Reject tokens from unknown token servers right away.", "db", ",", "err", ":=", "auth", ".", "GetDB", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "transient", ".", "Tag", ".", "Apply", "(", "err", ")", "\n", "}", "\n", "ok", ",", "err", ":=", "db", ".", "IsMember", "(", "c", ",", "signerServiceAccount", ",", "[", "]", "string", "{", "TokenServersGroup", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "transient", ".", "Tag", ".", "Apply", "(", "err", ")", "\n", "}", "\n", "if", "!", "ok", "{", "logTokenError", "(", "c", ",", "r", ",", "body", ",", "nil", ",", "\"", "\"", ",", "body", ".", "IssuedBy", ")", "\n", "return", "nil", ",", "ErrBadToken", "\n", "}", "\n\n", "// Check the expiration time before doing any heavier checks.", "if", "err", "=", "checkExpiration", "(", "body", ",", "clock", ".", "Now", "(", "c", ")", ")", ";", "err", "!=", "nil", "{", "logTokenError", "(", "c", ",", "r", ",", "body", ",", "err", ",", "\"", "\"", ")", "\n", "return", "nil", ",", "ErrBadToken", "\n", "}", "\n\n", "// Check the token was actually signed by the server.", "if", "err", "=", "m", ".", "checkSignature", "(", "c", ",", "body", ".", "IssuedBy", ",", "envelope", ")", ";", "err", "!=", "nil", "{", "if", "transient", ".", "Tag", ".", "In", "(", "err", ")", "{", "return", "nil", ",", "err", "\n", "}", "\n", "logTokenError", "(", "c", ",", "r", ",", "body", ",", "err", ",", "\"", "\"", ")", "\n", "return", "nil", ",", "ErrBadToken", "\n", "}", "\n\n", "// The token is valid. Construct the bot identity.", "botIdent", ",", "err", ":=", "identity", ".", "MakeIdentity", "(", "\"", "\"", "+", "body", ".", "MachineFqdn", ")", "\n", "if", "err", "!=", "nil", "{", "logTokenError", "(", "c", ",", "r", ",", "body", ",", "err", ",", "\"", "\"", ",", "body", ".", "MachineFqdn", ")", "\n", "return", "nil", ",", "ErrBadToken", "\n", "}", "\n", "return", "&", "auth", ".", "User", "{", "Identity", ":", "botIdent", "}", ",", "nil", "\n", "}" ]
// Authenticate extracts peer's identity from the incoming request. // // It logs detailed errors in log, but returns only generic "bad credential" // error to the caller, to avoid leaking unnecessary information.
[ "Authenticate", "extracts", "peer", "s", "identity", "from", "the", "incoming", "request", ".", "It", "logs", "detailed", "errors", "in", "log", "but", "returns", "only", "generic", "bad", "credential", "error", "to", "the", "caller", "to", "avoid", "leaking", "unnecessary", "information", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/auth/machine/auth_method.go#L80-L137
8,006
luci/luci-go
tokenserver/auth/machine/auth_method.go
logTokenError
func logTokenError(c context.Context, r *http.Request, tok *tokenserver.MachineTokenBody, err error, msg string, args ...string) { fields := logging.Fields{"remoteAddr": r.RemoteAddr} if tok != nil { // Note that if token wasn't properly signed, these fields may contain // garbage. fields["machineFqdn"] = tok.MachineFqdn fields["issuedBy"] = tok.IssuedBy fields["issuedAt"] = tok.IssuedAt fields["lifetime"] = tok.Lifetime fields["caId"] = tok.CaId fields["certSn"] = tok.CertSn } if err != nil { fields[logging.ErrorKey] = err } fields.Warningf(c, msg, args) }
go
func logTokenError(c context.Context, r *http.Request, tok *tokenserver.MachineTokenBody, err error, msg string, args ...string) { fields := logging.Fields{"remoteAddr": r.RemoteAddr} if tok != nil { // Note that if token wasn't properly signed, these fields may contain // garbage. fields["machineFqdn"] = tok.MachineFqdn fields["issuedBy"] = tok.IssuedBy fields["issuedAt"] = tok.IssuedAt fields["lifetime"] = tok.Lifetime fields["caId"] = tok.CaId fields["certSn"] = tok.CertSn } if err != nil { fields[logging.ErrorKey] = err } fields.Warningf(c, msg, args) }
[ "func", "logTokenError", "(", "c", "context", ".", "Context", ",", "r", "*", "http", ".", "Request", ",", "tok", "*", "tokenserver", ".", "MachineTokenBody", ",", "err", "error", ",", "msg", "string", ",", "args", "...", "string", ")", "{", "fields", ":=", "logging", ".", "Fields", "{", "\"", "\"", ":", "r", ".", "RemoteAddr", "}", "\n", "if", "tok", "!=", "nil", "{", "// Note that if token wasn't properly signed, these fields may contain", "// garbage.", "fields", "[", "\"", "\"", "]", "=", "tok", ".", "MachineFqdn", "\n", "fields", "[", "\"", "\"", "]", "=", "tok", ".", "IssuedBy", "\n", "fields", "[", "\"", "\"", "]", "=", "tok", ".", "IssuedAt", "\n", "fields", "[", "\"", "\"", "]", "=", "tok", ".", "Lifetime", "\n", "fields", "[", "\"", "\"", "]", "=", "tok", ".", "CaId", "\n", "fields", "[", "\"", "\"", "]", "=", "tok", ".", "CertSn", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "fields", "[", "logging", ".", "ErrorKey", "]", "=", "err", "\n", "}", "\n", "fields", ".", "Warningf", "(", "c", ",", "msg", ",", "args", ")", "\n", "}" ]
// logTokenError adds a warning-level log entry with details about the request.
[ "logTokenError", "adds", "a", "warning", "-", "level", "log", "entry", "with", "details", "about", "the", "request", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/auth/machine/auth_method.go#L140-L156
8,007
luci/luci-go
tokenserver/auth/machine/auth_method.go
deserialize
func deserialize(token string) (*tokenserver.MachineTokenEnvelope, *tokenserver.MachineTokenBody, error) { tokenBinBlob, err := base64.RawStdEncoding.DecodeString(token) if err != nil { return nil, nil, err } envelope := &tokenserver.MachineTokenEnvelope{} if err := proto.Unmarshal(tokenBinBlob, envelope); err != nil { return nil, nil, err } body := &tokenserver.MachineTokenBody{} if err := proto.Unmarshal(envelope.TokenBody, body); err != nil { return envelope, nil, err } return envelope, body, nil }
go
func deserialize(token string) (*tokenserver.MachineTokenEnvelope, *tokenserver.MachineTokenBody, error) { tokenBinBlob, err := base64.RawStdEncoding.DecodeString(token) if err != nil { return nil, nil, err } envelope := &tokenserver.MachineTokenEnvelope{} if err := proto.Unmarshal(tokenBinBlob, envelope); err != nil { return nil, nil, err } body := &tokenserver.MachineTokenBody{} if err := proto.Unmarshal(envelope.TokenBody, body); err != nil { return envelope, nil, err } return envelope, body, nil }
[ "func", "deserialize", "(", "token", "string", ")", "(", "*", "tokenserver", ".", "MachineTokenEnvelope", ",", "*", "tokenserver", ".", "MachineTokenBody", ",", "error", ")", "{", "tokenBinBlob", ",", "err", ":=", "base64", ".", "RawStdEncoding", ".", "DecodeString", "(", "token", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "envelope", ":=", "&", "tokenserver", ".", "MachineTokenEnvelope", "{", "}", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "tokenBinBlob", ",", "envelope", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "body", ":=", "&", "tokenserver", ".", "MachineTokenBody", "{", "}", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "envelope", ".", "TokenBody", ",", "body", ")", ";", "err", "!=", "nil", "{", "return", "envelope", ",", "nil", ",", "err", "\n", "}", "\n", "return", "envelope", ",", "body", ",", "nil", "\n", "}" ]
// deserialize parses MachineTokenEnvelope and MachineTokenBody.
[ "deserialize", "parses", "MachineTokenEnvelope", "and", "MachineTokenBody", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/auth/machine/auth_method.go#L159-L173
8,008
luci/luci-go
tokenserver/auth/machine/auth_method.go
checkExpiration
func checkExpiration(body *tokenserver.MachineTokenBody, now time.Time) error { notBefore := time.Unix(int64(body.IssuedAt), 0) notAfter := notBefore.Add(time.Duration(body.Lifetime) * time.Second) if now.Before(notBefore.Add(-allowedClockDrift)) { diff := notBefore.Sub(now) return fmt.Errorf("token is not valid yet, will be valid in %s", diff) } if now.After(notAfter.Add(allowedClockDrift)) { diff := now.Sub(notAfter) return fmt.Errorf("token expired %s ago", diff) } return nil }
go
func checkExpiration(body *tokenserver.MachineTokenBody, now time.Time) error { notBefore := time.Unix(int64(body.IssuedAt), 0) notAfter := notBefore.Add(time.Duration(body.Lifetime) * time.Second) if now.Before(notBefore.Add(-allowedClockDrift)) { diff := notBefore.Sub(now) return fmt.Errorf("token is not valid yet, will be valid in %s", diff) } if now.After(notAfter.Add(allowedClockDrift)) { diff := now.Sub(notAfter) return fmt.Errorf("token expired %s ago", diff) } return nil }
[ "func", "checkExpiration", "(", "body", "*", "tokenserver", ".", "MachineTokenBody", ",", "now", "time", ".", "Time", ")", "error", "{", "notBefore", ":=", "time", ".", "Unix", "(", "int64", "(", "body", ".", "IssuedAt", ")", ",", "0", ")", "\n", "notAfter", ":=", "notBefore", ".", "Add", "(", "time", ".", "Duration", "(", "body", ".", "Lifetime", ")", "*", "time", ".", "Second", ")", "\n", "if", "now", ".", "Before", "(", "notBefore", ".", "Add", "(", "-", "allowedClockDrift", ")", ")", "{", "diff", ":=", "notBefore", ".", "Sub", "(", "now", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "diff", ")", "\n", "}", "\n", "if", "now", ".", "After", "(", "notAfter", ".", "Add", "(", "allowedClockDrift", ")", ")", "{", "diff", ":=", "now", ".", "Sub", "(", "notAfter", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "diff", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// checkExpiration returns nil if the token is non-expired yet. // // Allows some clock drift, see allowedClockDrift.
[ "checkExpiration", "returns", "nil", "if", "the", "token", "is", "non", "-", "expired", "yet", ".", "Allows", "some", "clock", "drift", "see", "allowedClockDrift", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/auth/machine/auth_method.go#L178-L190
8,009
luci/luci-go
tokenserver/auth/machine/auth_method.go
checkSignature
func (m *MachineTokenAuthMethod) checkSignature(c context.Context, signerEmail string, envelope *tokenserver.MachineTokenEnvelope) error { // Note that FetchCertificatesForServiceAccount implements caching inside. fetcher := m.certsFetcher if fetcher == nil { fetcher = signing.FetchCertificatesForServiceAccount } certs, err := fetcher(c, signerEmail) if err != nil { return transient.Tag.Apply(err) } return certs.CheckSignature(envelope.KeyId, envelope.TokenBody, envelope.RsaSha256) }
go
func (m *MachineTokenAuthMethod) checkSignature(c context.Context, signerEmail string, envelope *tokenserver.MachineTokenEnvelope) error { // Note that FetchCertificatesForServiceAccount implements caching inside. fetcher := m.certsFetcher if fetcher == nil { fetcher = signing.FetchCertificatesForServiceAccount } certs, err := fetcher(c, signerEmail) if err != nil { return transient.Tag.Apply(err) } return certs.CheckSignature(envelope.KeyId, envelope.TokenBody, envelope.RsaSha256) }
[ "func", "(", "m", "*", "MachineTokenAuthMethod", ")", "checkSignature", "(", "c", "context", ".", "Context", ",", "signerEmail", "string", ",", "envelope", "*", "tokenserver", ".", "MachineTokenEnvelope", ")", "error", "{", "// Note that FetchCertificatesForServiceAccount implements caching inside.", "fetcher", ":=", "m", ".", "certsFetcher", "\n", "if", "fetcher", "==", "nil", "{", "fetcher", "=", "signing", ".", "FetchCertificatesForServiceAccount", "\n", "}", "\n", "certs", ",", "err", ":=", "fetcher", "(", "c", ",", "signerEmail", ")", "\n", "if", "err", "!=", "nil", "{", "return", "transient", ".", "Tag", ".", "Apply", "(", "err", ")", "\n", "}", "\n", "return", "certs", ".", "CheckSignature", "(", "envelope", ".", "KeyId", ",", "envelope", ".", "TokenBody", ",", "envelope", ".", "RsaSha256", ")", "\n", "}" ]
// checkSignature verifies the token signature.
[ "checkSignature", "verifies", "the", "token", "signature", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/auth/machine/auth_method.go#L193-L204
8,010
luci/luci-go
tools/internal/apigen/main.go
AddToFlagSet
func (a *Application) AddToFlagSet(fs *flag.FlagSet) { flag.StringVar(&a.servicePath, "service", ".", "Path to the AppEngine service to generate from.") flag.StringVar(&a.serviceAPIRoot, "service-api-root", "/_ah/api/", "The service's API root path.") flag.StringVar(&a.genPath, "generator", "google-api-go-generator", "Path to the `google-api-go-generator` binary to use.") flag.StringVar(&a.apiPackage, "api-package", defaultPackageBase, "Name of the root API package on GOPATH.") flag.StringVar(&a.apiSubproject, "api-subproject", "", "If supplied, place APIs in an additional subdirectory under -api-package.") flag.Var(&a.apiWhitelist, "api", "If supplied, limit the emitted APIs to those named. Can be specified "+ "multiple times.") flag.StringVar(&a.baseURL, "base-url", "http://localhost:8080", "Use this as the default base service client URL.") }
go
func (a *Application) AddToFlagSet(fs *flag.FlagSet) { flag.StringVar(&a.servicePath, "service", ".", "Path to the AppEngine service to generate from.") flag.StringVar(&a.serviceAPIRoot, "service-api-root", "/_ah/api/", "The service's API root path.") flag.StringVar(&a.genPath, "generator", "google-api-go-generator", "Path to the `google-api-go-generator` binary to use.") flag.StringVar(&a.apiPackage, "api-package", defaultPackageBase, "Name of the root API package on GOPATH.") flag.StringVar(&a.apiSubproject, "api-subproject", "", "If supplied, place APIs in an additional subdirectory under -api-package.") flag.Var(&a.apiWhitelist, "api", "If supplied, limit the emitted APIs to those named. Can be specified "+ "multiple times.") flag.StringVar(&a.baseURL, "base-url", "http://localhost:8080", "Use this as the default base service client URL.") }
[ "func", "(", "a", "*", "Application", ")", "AddToFlagSet", "(", "fs", "*", "flag", ".", "FlagSet", ")", "{", "flag", ".", "StringVar", "(", "&", "a", ".", "servicePath", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "flag", ".", "StringVar", "(", "&", "a", ".", "serviceAPIRoot", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "flag", ".", "StringVar", "(", "&", "a", ".", "genPath", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "flag", ".", "StringVar", "(", "&", "a", ".", "apiPackage", ",", "\"", "\"", ",", "defaultPackageBase", ",", "\"", "\"", ")", "\n", "flag", ".", "StringVar", "(", "&", "a", ".", "apiSubproject", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "flag", ".", "Var", "(", "&", "a", ".", "apiWhitelist", ",", "\"", "\"", ",", "\"", "\"", "+", "\"", "\"", ")", "\n", "flag", ".", "StringVar", "(", "&", "a", ".", "baseURL", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}" ]
// AddToFlagSet adds application-level flags to the supplied FlagSet.
[ "AddToFlagSet", "adds", "application", "-", "level", "flags", "to", "the", "supplied", "FlagSet", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tools/internal/apigen/main.go#L97-L113
8,011
luci/luci-go
tools/internal/apigen/main.go
retryHTTP
func retryHTTP(c context.Context, u url.URL, method, body string) ([]byte, error) { client := http.Client{} gen := func() retry.Iterator { return &retry.Limited{ Delay: 2 * time.Second, Retries: 20, } } output := []byte(nil) err := retry.Retry(c, gen, func() error { req := http.Request{ Method: method, URL: &u, Header: http.Header{}, } if len(body) > 0 { req.Body = ioutil.NopCloser(bytes.NewBuffer([]byte(body))) req.ContentLength = int64(len(body)) req.Header.Add("Content-Type", "application/json") } resp, err := client.Do(&req) if err != nil { return err } if resp.Body != nil { defer resp.Body.Close() output, err = ioutil.ReadAll(resp.Body) if err != nil { return err } } switch resp.StatusCode { case http.StatusOK, http.StatusNoContent: return nil default: return fmt.Errorf("unsuccessful status code (%d): %s", resp.StatusCode, resp.Status) } }, func(err error, d time.Duration) { log.Fields{ log.ErrorKey: err, "url": u.String(), "delay": d, }.Infof(c, "Service is not up yet; retrying.") }) if err != nil { return nil, err } log.Fields{ "url": u.String(), }.Infof(c, "Service is alive!") return output, nil }
go
func retryHTTP(c context.Context, u url.URL, method, body string) ([]byte, error) { client := http.Client{} gen := func() retry.Iterator { return &retry.Limited{ Delay: 2 * time.Second, Retries: 20, } } output := []byte(nil) err := retry.Retry(c, gen, func() error { req := http.Request{ Method: method, URL: &u, Header: http.Header{}, } if len(body) > 0 { req.Body = ioutil.NopCloser(bytes.NewBuffer([]byte(body))) req.ContentLength = int64(len(body)) req.Header.Add("Content-Type", "application/json") } resp, err := client.Do(&req) if err != nil { return err } if resp.Body != nil { defer resp.Body.Close() output, err = ioutil.ReadAll(resp.Body) if err != nil { return err } } switch resp.StatusCode { case http.StatusOK, http.StatusNoContent: return nil default: return fmt.Errorf("unsuccessful status code (%d): %s", resp.StatusCode, resp.Status) } }, func(err error, d time.Duration) { log.Fields{ log.ErrorKey: err, "url": u.String(), "delay": d, }.Infof(c, "Service is not up yet; retrying.") }) if err != nil { return nil, err } log.Fields{ "url": u.String(), }.Infof(c, "Service is alive!") return output, nil }
[ "func", "retryHTTP", "(", "c", "context", ".", "Context", ",", "u", "url", ".", "URL", ",", "method", ",", "body", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "client", ":=", "http", ".", "Client", "{", "}", "\n\n", "gen", ":=", "func", "(", ")", "retry", ".", "Iterator", "{", "return", "&", "retry", ".", "Limited", "{", "Delay", ":", "2", "*", "time", ".", "Second", ",", "Retries", ":", "20", ",", "}", "\n", "}", "\n\n", "output", ":=", "[", "]", "byte", "(", "nil", ")", "\n", "err", ":=", "retry", ".", "Retry", "(", "c", ",", "gen", ",", "func", "(", ")", "error", "{", "req", ":=", "http", ".", "Request", "{", "Method", ":", "method", ",", "URL", ":", "&", "u", ",", "Header", ":", "http", ".", "Header", "{", "}", ",", "}", "\n", "if", "len", "(", "body", ")", ">", "0", "{", "req", ".", "Body", "=", "ioutil", ".", "NopCloser", "(", "bytes", ".", "NewBuffer", "(", "[", "]", "byte", "(", "body", ")", ")", ")", "\n", "req", ".", "ContentLength", "=", "int64", "(", "len", "(", "body", ")", ")", "\n", "req", ".", "Header", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n\n", "resp", ",", "err", ":=", "client", ".", "Do", "(", "&", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "resp", ".", "Body", "!=", "nil", "{", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "output", ",", "err", "=", "ioutil", ".", "ReadAll", "(", "resp", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "switch", "resp", ".", "StatusCode", "{", "case", "http", ".", "StatusOK", ",", "http", ".", "StatusNoContent", ":", "return", "nil", "\n\n", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "resp", ".", "StatusCode", ",", "resp", ".", "Status", ")", "\n", "}", "\n", "}", ",", "func", "(", "err", "error", ",", "d", "time", ".", "Duration", ")", "{", "log", ".", "Fields", "{", "log", ".", "ErrorKey", ":", "err", ",", "\"", "\"", ":", "u", ".", "String", "(", ")", ",", "\"", "\"", ":", "d", ",", "}", ".", "Infof", "(", "c", ",", "\"", "\"", ")", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "log", ".", "Fields", "{", "\"", "\"", ":", "u", ".", "String", "(", ")", ",", "}", ".", "Infof", "(", "c", ",", "\"", "\"", ")", "\n", "return", "output", ",", "nil", "\n", "}" ]
// retryHTTP executes an HTTP call to the specified URL, retrying if it fails. // // It will return an error if no successful HTTP results were returned. // Otherwise, it will return the body of the successful HTTP response.
[ "retryHTTP", "executes", "an", "HTTP", "call", "to", "the", "specified", "URL", "retrying", "if", "it", "fails", ".", "It", "will", "return", "an", "error", "if", "no", "successful", "HTTP", "results", "were", "returned", ".", "Otherwise", "it", "will", "return", "the", "body", "of", "the", "successful", "HTTP", "response", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tools/internal/apigen/main.go#L139-L196
8,012
luci/luci-go
tools/internal/apigen/main.go
generateAPI
func (a *Application) generateAPI(c context.Context, item *directoryItem, discoveryURL *url.URL, dst string) error { tmpdir, err := ioutil.TempDir(os.TempDir(), "apigen") if err != nil { return err } defer func() { os.RemoveAll(tmpdir) }() gendir := augPath(tmpdir, "gen") headerPath := augPath(tmpdir, "header.txt") if err := ioutil.WriteFile(headerPath, []byte(a.license), 0644); err != nil { return err } args := []string{ "-cache=false", // Apparently the form {"-cache", "false"} is ignored. "-discoveryurl", discoveryURL.String(), "-api", item.ID, "-gendir", gendir, "-api_pkg_base", a.apiPackage, "-base_url", a.baseURL, "-header_path", headerPath, } log.Fields{ "command": a.genPath, "args": args, }.Debugf(c, "Executing google-api-go-generator.") out, err := exec.Command(a.genPath, args...).CombinedOutput() log.Infof(c, "Output:\n%s", out) if err != nil { return fmt.Errorf("error executing google-api-go-generator: %s", err) } err = installSource(gendir, dst, func(relpath string, data []byte) ([]byte, error) { // Skip the root "api-list.json" file. This is generated only for the subset // of APIs that this installation is handling, and is not representative of // the full discovery (much less installation) API set. if relpath == "api-list.json" { return nil, nil } if !strings.HasSuffix(relpath, "-gen.go") { return data, nil } log.Fields{ "relpath": relpath, }.Infof(c, "Fixing up generated Go file.") // Remove copyright header added by google-api-go-generator. We have our own // already. filtered := strings.Builder{} alreadySkippedHeader := false scanner := bufio.NewScanner(bytes.NewReader(data)) for scanner.Scan() { if line := scanner.Text(); alreadySkippedHeader || !apiGoGenLicenseHdr.MatchString(line) { filtered.WriteString(line) filtered.WriteRune('\n') continue } // Found the start of the comment block with the header. Skip it all. for scanner.Scan() { if line := scanner.Text(); !strings.HasPrefix(line, "//") { // The comment block is usually followed by an empty line which we // also skip. But be careful in case it's not. if line != "" { filtered.WriteString(line) filtered.WriteRune('\n') } break } } // Carry on copying the rest of lines unchanged. alreadySkippedHeader = true } if err := scanner.Err(); err != nil { return nil, err } return []byte(filtered.String()), nil }) if err != nil { return fmt.Errorf("failed to install [%s]: %s", item.ID, err) } return nil }
go
func (a *Application) generateAPI(c context.Context, item *directoryItem, discoveryURL *url.URL, dst string) error { tmpdir, err := ioutil.TempDir(os.TempDir(), "apigen") if err != nil { return err } defer func() { os.RemoveAll(tmpdir) }() gendir := augPath(tmpdir, "gen") headerPath := augPath(tmpdir, "header.txt") if err := ioutil.WriteFile(headerPath, []byte(a.license), 0644); err != nil { return err } args := []string{ "-cache=false", // Apparently the form {"-cache", "false"} is ignored. "-discoveryurl", discoveryURL.String(), "-api", item.ID, "-gendir", gendir, "-api_pkg_base", a.apiPackage, "-base_url", a.baseURL, "-header_path", headerPath, } log.Fields{ "command": a.genPath, "args": args, }.Debugf(c, "Executing google-api-go-generator.") out, err := exec.Command(a.genPath, args...).CombinedOutput() log.Infof(c, "Output:\n%s", out) if err != nil { return fmt.Errorf("error executing google-api-go-generator: %s", err) } err = installSource(gendir, dst, func(relpath string, data []byte) ([]byte, error) { // Skip the root "api-list.json" file. This is generated only for the subset // of APIs that this installation is handling, and is not representative of // the full discovery (much less installation) API set. if relpath == "api-list.json" { return nil, nil } if !strings.HasSuffix(relpath, "-gen.go") { return data, nil } log.Fields{ "relpath": relpath, }.Infof(c, "Fixing up generated Go file.") // Remove copyright header added by google-api-go-generator. We have our own // already. filtered := strings.Builder{} alreadySkippedHeader := false scanner := bufio.NewScanner(bytes.NewReader(data)) for scanner.Scan() { if line := scanner.Text(); alreadySkippedHeader || !apiGoGenLicenseHdr.MatchString(line) { filtered.WriteString(line) filtered.WriteRune('\n') continue } // Found the start of the comment block with the header. Skip it all. for scanner.Scan() { if line := scanner.Text(); !strings.HasPrefix(line, "//") { // The comment block is usually followed by an empty line which we // also skip. But be careful in case it's not. if line != "" { filtered.WriteString(line) filtered.WriteRune('\n') } break } } // Carry on copying the rest of lines unchanged. alreadySkippedHeader = true } if err := scanner.Err(); err != nil { return nil, err } return []byte(filtered.String()), nil }) if err != nil { return fmt.Errorf("failed to install [%s]: %s", item.ID, err) } return nil }
[ "func", "(", "a", "*", "Application", ")", "generateAPI", "(", "c", "context", ".", "Context", ",", "item", "*", "directoryItem", ",", "discoveryURL", "*", "url", ".", "URL", ",", "dst", "string", ")", "error", "{", "tmpdir", ",", "err", ":=", "ioutil", ".", "TempDir", "(", "os", ".", "TempDir", "(", ")", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "func", "(", ")", "{", "os", ".", "RemoveAll", "(", "tmpdir", ")", "\n", "}", "(", ")", "\n\n", "gendir", ":=", "augPath", "(", "tmpdir", ",", "\"", "\"", ")", "\n", "headerPath", ":=", "augPath", "(", "tmpdir", ",", "\"", "\"", ")", "\n", "if", "err", ":=", "ioutil", ".", "WriteFile", "(", "headerPath", ",", "[", "]", "byte", "(", "a", ".", "license", ")", ",", "0644", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "args", ":=", "[", "]", "string", "{", "\"", "\"", ",", "// Apparently the form {\"-cache\", \"false\"} is ignored.", "\"", "\"", ",", "discoveryURL", ".", "String", "(", ")", ",", "\"", "\"", ",", "item", ".", "ID", ",", "\"", "\"", ",", "gendir", ",", "\"", "\"", ",", "a", ".", "apiPackage", ",", "\"", "\"", ",", "a", ".", "baseURL", ",", "\"", "\"", ",", "headerPath", ",", "}", "\n", "log", ".", "Fields", "{", "\"", "\"", ":", "a", ".", "genPath", ",", "\"", "\"", ":", "args", ",", "}", ".", "Debugf", "(", "c", ",", "\"", "\"", ")", "\n", "out", ",", "err", ":=", "exec", ".", "Command", "(", "a", ".", "genPath", ",", "args", "...", ")", ".", "CombinedOutput", "(", ")", "\n", "log", ".", "Infof", "(", "c", ",", "\"", "\\n", "\"", ",", "out", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "err", "=", "installSource", "(", "gendir", ",", "dst", ",", "func", "(", "relpath", "string", ",", "data", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// Skip the root \"api-list.json\" file. This is generated only for the subset", "// of APIs that this installation is handling, and is not representative of", "// the full discovery (much less installation) API set.", "if", "relpath", "==", "\"", "\"", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "if", "!", "strings", ".", "HasSuffix", "(", "relpath", ",", "\"", "\"", ")", "{", "return", "data", ",", "nil", "\n", "}", "\n\n", "log", ".", "Fields", "{", "\"", "\"", ":", "relpath", ",", "}", ".", "Infof", "(", "c", ",", "\"", "\"", ")", "\n\n", "// Remove copyright header added by google-api-go-generator. We have our own", "// already.", "filtered", ":=", "strings", ".", "Builder", "{", "}", "\n", "alreadySkippedHeader", ":=", "false", "\n", "scanner", ":=", "bufio", ".", "NewScanner", "(", "bytes", ".", "NewReader", "(", "data", ")", ")", "\n", "for", "scanner", ".", "Scan", "(", ")", "{", "if", "line", ":=", "scanner", ".", "Text", "(", ")", ";", "alreadySkippedHeader", "||", "!", "apiGoGenLicenseHdr", ".", "MatchString", "(", "line", ")", "{", "filtered", ".", "WriteString", "(", "line", ")", "\n", "filtered", ".", "WriteRune", "(", "'\\n'", ")", "\n", "continue", "\n", "}", "\n\n", "// Found the start of the comment block with the header. Skip it all.", "for", "scanner", ".", "Scan", "(", ")", "{", "if", "line", ":=", "scanner", ".", "Text", "(", ")", ";", "!", "strings", ".", "HasPrefix", "(", "line", ",", "\"", "\"", ")", "{", "// The comment block is usually followed by an empty line which we", "// also skip. But be careful in case it's not.", "if", "line", "!=", "\"", "\"", "{", "filtered", ".", "WriteString", "(", "line", ")", "\n", "filtered", ".", "WriteRune", "(", "'\\n'", ")", "\n", "}", "\n", "break", "\n", "}", "\n", "}", "\n\n", "// Carry on copying the rest of lines unchanged.", "alreadySkippedHeader", "=", "true", "\n", "}", "\n", "if", "err", ":=", "scanner", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "[", "]", "byte", "(", "filtered", ".", "String", "(", ")", ")", ",", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "item", ".", "ID", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// generateAPI generates and installs a single directory item's API.
[ "generateAPI", "generates", "and", "installs", "a", "single", "directory", "item", "s", "API", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tools/internal/apigen/main.go#L294-L381
8,013
luci/luci-go
starlark/interpreter/interpreter.go
String
func (key moduleKey) String() string { pkg := "" if key.pkg != MainPkg { pkg = "@" + key.pkg } return pkg + "//" + key.path }
go
func (key moduleKey) String() string { pkg := "" if key.pkg != MainPkg { pkg = "@" + key.pkg } return pkg + "//" + key.path }
[ "func", "(", "key", "moduleKey", ")", "String", "(", ")", "string", "{", "pkg", ":=", "\"", "\"", "\n", "if", "key", ".", "pkg", "!=", "MainPkg", "{", "pkg", "=", "\"", "\"", "+", "key", ".", "pkg", "\n", "}", "\n", "return", "pkg", "+", "\"", "\"", "+", "key", ".", "path", "\n", "}" ]
// String returns a fully-qualified module name to use in error messages. // // If is either "@pkg//path" or just "//path" if pkg is "__main__". We omit the // name of the top-level package with user-supplied code ("__main__") to avoid // confusing users who are oblivious of packages.
[ "String", "returns", "a", "fully", "-", "qualified", "module", "name", "to", "use", "in", "error", "messages", ".", "If", "is", "either" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/interpreter/interpreter.go#L271-L277
8,014
luci/luci-go
starlark/interpreter/interpreter.go
makeModuleKey
func makeModuleKey(ref string, th *starlark.Thread) (key moduleKey, err error) { defer func() { if err == nil && (strings.HasPrefix(key.path, "../") || key.path == "..") { err = errors.New("outside the package root") } }() // 'th' can be nil here if makeModuleKey is called by LoadModule or // ExecModule: they are entry points into Starlark code, there's no thread // yet when they start. var current *moduleKey if th != nil { if modKey, ok := th.Local(threadModKey).(moduleKey); ok { current = &modKey } } // Absolute paths start with '//' or '@'. Everything else is a relative path. hasPkg := strings.HasPrefix(ref, "@") isAbs := hasPkg || strings.HasPrefix(ref, "//") if !isAbs { if current == nil { err = errors.New("can't resolve relative module path: no current module information in thread locals") } else { key = moduleKey{ pkg: current.pkg, path: path.Join(path.Dir(current.path), ref), } } return } idx := strings.Index(ref, "//") if idx == -1 || (!hasPkg && idx != 0) { err = errors.New("a module path should be either '//<path>', '<path>' or '@<package>//<path>'") return } if hasPkg { if key.pkg = ref[1:idx]; key.pkg == "" { err = errors.New("a package alias can't be empty") return } } key.path = path.Clean(ref[idx+2:]) // Grab the package name from thread locals, if given. if !hasPkg { if current == nil { err = errors.New("no current package name in thread locals") } else { key.pkg = current.pkg } } return }
go
func makeModuleKey(ref string, th *starlark.Thread) (key moduleKey, err error) { defer func() { if err == nil && (strings.HasPrefix(key.path, "../") || key.path == "..") { err = errors.New("outside the package root") } }() // 'th' can be nil here if makeModuleKey is called by LoadModule or // ExecModule: they are entry points into Starlark code, there's no thread // yet when they start. var current *moduleKey if th != nil { if modKey, ok := th.Local(threadModKey).(moduleKey); ok { current = &modKey } } // Absolute paths start with '//' or '@'. Everything else is a relative path. hasPkg := strings.HasPrefix(ref, "@") isAbs := hasPkg || strings.HasPrefix(ref, "//") if !isAbs { if current == nil { err = errors.New("can't resolve relative module path: no current module information in thread locals") } else { key = moduleKey{ pkg: current.pkg, path: path.Join(path.Dir(current.path), ref), } } return } idx := strings.Index(ref, "//") if idx == -1 || (!hasPkg && idx != 0) { err = errors.New("a module path should be either '//<path>', '<path>' or '@<package>//<path>'") return } if hasPkg { if key.pkg = ref[1:idx]; key.pkg == "" { err = errors.New("a package alias can't be empty") return } } key.path = path.Clean(ref[idx+2:]) // Grab the package name from thread locals, if given. if !hasPkg { if current == nil { err = errors.New("no current package name in thread locals") } else { key.pkg = current.pkg } } return }
[ "func", "makeModuleKey", "(", "ref", "string", ",", "th", "*", "starlark", ".", "Thread", ")", "(", "key", "moduleKey", ",", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "if", "err", "==", "nil", "&&", "(", "strings", ".", "HasPrefix", "(", "key", ".", "path", ",", "\"", "\"", ")", "||", "key", ".", "path", "==", "\"", "\"", ")", "{", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "// 'th' can be nil here if makeModuleKey is called by LoadModule or", "// ExecModule: they are entry points into Starlark code, there's no thread", "// yet when they start.", "var", "current", "*", "moduleKey", "\n", "if", "th", "!=", "nil", "{", "if", "modKey", ",", "ok", ":=", "th", ".", "Local", "(", "threadModKey", ")", ".", "(", "moduleKey", ")", ";", "ok", "{", "current", "=", "&", "modKey", "\n", "}", "\n", "}", "\n\n", "// Absolute paths start with '//' or '@'. Everything else is a relative path.", "hasPkg", ":=", "strings", ".", "HasPrefix", "(", "ref", ",", "\"", "\"", ")", "\n", "isAbs", ":=", "hasPkg", "||", "strings", ".", "HasPrefix", "(", "ref", ",", "\"", "\"", ")", "\n\n", "if", "!", "isAbs", "{", "if", "current", "==", "nil", "{", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "else", "{", "key", "=", "moduleKey", "{", "pkg", ":", "current", ".", "pkg", ",", "path", ":", "path", ".", "Join", "(", "path", ".", "Dir", "(", "current", ".", "path", ")", ",", "ref", ")", ",", "}", "\n", "}", "\n", "return", "\n", "}", "\n\n", "idx", ":=", "strings", ".", "Index", "(", "ref", ",", "\"", "\"", ")", "\n", "if", "idx", "==", "-", "1", "||", "(", "!", "hasPkg", "&&", "idx", "!=", "0", ")", "{", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "if", "hasPkg", "{", "if", "key", ".", "pkg", "=", "ref", "[", "1", ":", "idx", "]", ";", "key", ".", "pkg", "==", "\"", "\"", "{", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "key", ".", "path", "=", "path", ".", "Clean", "(", "ref", "[", "idx", "+", "2", ":", "]", ")", "\n\n", "// Grab the package name from thread locals, if given.", "if", "!", "hasPkg", "{", "if", "current", "==", "nil", "{", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "else", "{", "key", ".", "pkg", "=", "current", ".", "pkg", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// makeModuleKey takes '[@pkg]//<path>' or '<path>', parses and normalizes it. // // Converts the path to be relative to the package root. Does some light // validation, in particular checking the resulting path is doesn't star with // '../'. Module loaders are expected to validate module paths more rigorously // (since they interpret them anyway). // // 'th' is used to get the name of the currently executing package and a path to // the currently executing module within it. It is required if 'ref' is not // given as an absolute path (i.e. does NOT look like '@pkg//path').
[ "makeModuleKey", "takes", "[" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/interpreter/interpreter.go#L289-L345
8,015
luci/luci-go
starlark/interpreter/interpreter.go
Init
func (intr *Interpreter) Init(ctx context.Context) error { intr.modules = map[moduleKey]*loadedModule{} intr.execed = map[moduleKey]struct{}{} intr.globals = make(starlark.StringDict, len(intr.Predeclared)+1) for k, v := range intr.Predeclared { intr.globals[k] = v } intr.globals["exec"] = intr.execBuiltin() // Load the stdlib, if any. top, err := intr.LoadModule(ctx, StdlibPkg, "builtins.star") if err != nil && err != ErrNoModule && err != ErrNoPackage { return err } for k, v := range top { if !strings.HasPrefix(k, "_") { intr.globals[k] = v } } return nil }
go
func (intr *Interpreter) Init(ctx context.Context) error { intr.modules = map[moduleKey]*loadedModule{} intr.execed = map[moduleKey]struct{}{} intr.globals = make(starlark.StringDict, len(intr.Predeclared)+1) for k, v := range intr.Predeclared { intr.globals[k] = v } intr.globals["exec"] = intr.execBuiltin() // Load the stdlib, if any. top, err := intr.LoadModule(ctx, StdlibPkg, "builtins.star") if err != nil && err != ErrNoModule && err != ErrNoPackage { return err } for k, v := range top { if !strings.HasPrefix(k, "_") { intr.globals[k] = v } } return nil }
[ "func", "(", "intr", "*", "Interpreter", ")", "Init", "(", "ctx", "context", ".", "Context", ")", "error", "{", "intr", ".", "modules", "=", "map", "[", "moduleKey", "]", "*", "loadedModule", "{", "}", "\n", "intr", ".", "execed", "=", "map", "[", "moduleKey", "]", "struct", "{", "}", "{", "}", "\n\n", "intr", ".", "globals", "=", "make", "(", "starlark", ".", "StringDict", ",", "len", "(", "intr", ".", "Predeclared", ")", "+", "1", ")", "\n", "for", "k", ",", "v", ":=", "range", "intr", ".", "Predeclared", "{", "intr", ".", "globals", "[", "k", "]", "=", "v", "\n", "}", "\n", "intr", ".", "globals", "[", "\"", "\"", "]", "=", "intr", ".", "execBuiltin", "(", ")", "\n\n", "// Load the stdlib, if any.", "top", ",", "err", ":=", "intr", ".", "LoadModule", "(", "ctx", ",", "StdlibPkg", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "&&", "err", "!=", "ErrNoModule", "&&", "err", "!=", "ErrNoPackage", "{", "return", "err", "\n", "}", "\n", "for", "k", ",", "v", ":=", "range", "top", "{", "if", "!", "strings", ".", "HasPrefix", "(", "k", ",", "\"", "\"", ")", "{", "intr", ".", "globals", "[", "k", "]", "=", "v", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Init initializes the interpreter and loads '@stdlib//builtins.star'. // // Registers whatever was passed via Predeclared plus 'exec'. Then loads // '@stdlib//builtins.star', which may define more symbols or override already // defined ones. Whatever symbols not starting with '_' end up in the global // dict of '@stdlib//builtins.star' module will become available as global // symbols in all modules. // // The context ends up available to builtins through Context(...).
[ "Init", "initializes", "the", "interpreter", "and", "loads" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/interpreter/interpreter.go#L362-L383
8,016
luci/luci-go
starlark/interpreter/interpreter.go
LoadSource
func (intr *Interpreter) LoadSource(th *starlark.Thread, ref string) (string, error) { if kind := GetThreadKind(th); kind != ThreadLoading && kind != ThreadExecing { return "", errors.New("wrong kind of thread (not enough information to " + "resolve the file reference), only threads that do 'load' and 'exec' can call this function") } target, err := makeModuleKey(ref, th) if err != nil { return "", err } dict, src, err := intr.invokeLoader(target) if err == nil && dict != nil { err = fmt.Errorf("it is a native Go module") } if err != nil { // Avoid term "module" since LoadSource is often used to load non-star // files. if err == ErrNoModule { err = fmt.Errorf("no such file") } return "", fmt.Errorf("cannot load %s: %s", target, err) } return src, nil }
go
func (intr *Interpreter) LoadSource(th *starlark.Thread, ref string) (string, error) { if kind := GetThreadKind(th); kind != ThreadLoading && kind != ThreadExecing { return "", errors.New("wrong kind of thread (not enough information to " + "resolve the file reference), only threads that do 'load' and 'exec' can call this function") } target, err := makeModuleKey(ref, th) if err != nil { return "", err } dict, src, err := intr.invokeLoader(target) if err == nil && dict != nil { err = fmt.Errorf("it is a native Go module") } if err != nil { // Avoid term "module" since LoadSource is often used to load non-star // files. if err == ErrNoModule { err = fmt.Errorf("no such file") } return "", fmt.Errorf("cannot load %s: %s", target, err) } return src, nil }
[ "func", "(", "intr", "*", "Interpreter", ")", "LoadSource", "(", "th", "*", "starlark", ".", "Thread", ",", "ref", "string", ")", "(", "string", ",", "error", ")", "{", "if", "kind", ":=", "GetThreadKind", "(", "th", ")", ";", "kind", "!=", "ThreadLoading", "&&", "kind", "!=", "ThreadExecing", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", "+", "\"", "\"", ")", "\n", "}", "\n\n", "target", ",", "err", ":=", "makeModuleKey", "(", "ref", ",", "th", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "dict", ",", "src", ",", "err", ":=", "intr", ".", "invokeLoader", "(", "target", ")", "\n", "if", "err", "==", "nil", "&&", "dict", "!=", "nil", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "// Avoid term \"module\" since LoadSource is often used to load non-star", "// files.", "if", "err", "==", "ErrNoModule", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "target", ",", "err", ")", "\n", "}", "\n", "return", "src", ",", "nil", "\n", "}" ]
// LoadSource returns a body of a file inside a package. // // It doesn't have to be a Starlark file, can be any text file as long as // the corresponding package Loader can find it. // // 'ref' is either an absolute reference to the file, in the same format as // accepted by 'load' and 'exec' (i.e. "[@pkg]//path"), or a path relative to // the currently executing module (i.e. just "path"). // // Only Starlark threads started via LoadModule or ExecModule can be used with // this function. Other threads don't have enough context to resolve paths // correctly.
[ "LoadSource", "returns", "a", "body", "of", "a", "file", "inside", "a", "package", ".", "It", "doesn", "t", "have", "to", "be", "a", "Starlark", "file", "can", "be", "any", "text", "file", "as", "long", "as", "the", "corresponding", "package", "Loader", "can", "find", "it", ".", "ref", "is", "either", "an", "absolute", "reference", "to", "the", "file", "in", "the", "same", "format", "as", "accepted", "by", "load", "and", "exec", "(", "i", ".", "e", ".", "[" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/interpreter/interpreter.go#L471-L495
8,017
luci/luci-go
starlark/interpreter/interpreter.go
invokeLoader
func (intr *Interpreter) invokeLoader(key moduleKey) (dict starlark.StringDict, src string, err error) { loader, ok := intr.Packages[key.pkg] if !ok { return nil, "", ErrNoPackage } return loader(key.path) }
go
func (intr *Interpreter) invokeLoader(key moduleKey) (dict starlark.StringDict, src string, err error) { loader, ok := intr.Packages[key.pkg] if !ok { return nil, "", ErrNoPackage } return loader(key.path) }
[ "func", "(", "intr", "*", "Interpreter", ")", "invokeLoader", "(", "key", "moduleKey", ")", "(", "dict", "starlark", ".", "StringDict", ",", "src", "string", ",", "err", "error", ")", "{", "loader", ",", "ok", ":=", "intr", ".", "Packages", "[", "key", ".", "pkg", "]", "\n", "if", "!", "ok", "{", "return", "nil", ",", "\"", "\"", ",", "ErrNoPackage", "\n", "}", "\n", "return", "loader", "(", "key", ".", "path", ")", "\n", "}" ]
// invokeLoader loads the module via the loader associated with the package.
[ "invokeLoader", "loads", "the", "module", "via", "the", "loader", "associated", "with", "the", "package", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/interpreter/interpreter.go#L571-L577
8,018
luci/luci-go
starlark/interpreter/interpreter.go
runModule
func (intr *Interpreter) runModule(ctx context.Context, key moduleKey, kind ThreadKind) (starlark.StringDict, error) { // Grab the source code. dict, src, err := intr.invokeLoader(key) switch { case err != nil: return nil, err case dict != nil: // This is a native module constructed in Go, no need to interpret it. return dict, nil } // Otherwise make a thread for executing the code. We do not reuse threads // between modules. All global state is passed through intr.globals, // intr.modules and ctx. th := intr.Thread(ctx) th.Load = func(th *starlark.Thread, module string) (starlark.StringDict, error) { key, err := makeModuleKey(module, th) if err != nil { return nil, err } dict, err := intr.LoadModule(ctx, key.pkg, key.path) // See comment in execBuiltin about why we extract EvalError backtrace into // new error. if evalErr, ok := err.(*starlark.EvalError); ok { err = fmt.Errorf("%s", evalErr.Backtrace()) } return dict, err } // Let builtins know what this thread is doing. Some calls (most notably Exec // itself) are allowed only from exec'ing threads, not from load'ing ones. th.SetLocal(threadKindKey, kind) // Let builtins (and in particular makeModuleKey and LoadSource) know the // package and the module that the thread executes. th.SetLocal(threadModKey, key) if kind == ThreadExecing { if intr.PreExec != nil { intr.PreExec(th, key.pkg, key.path) } if intr.PostExec != nil { defer intr.PostExec(th, key.pkg, key.path) } } // Execute the module. It may 'load' or 'exec' other modules inside, which // will either call LoadModule or ExecModule. // // Use user-friendly module name (with omitted "@__main__") for error messages // and stack traces to avoid confusing the user. return starlark.ExecFile(th, key.String(), src, intr.globals) }
go
func (intr *Interpreter) runModule(ctx context.Context, key moduleKey, kind ThreadKind) (starlark.StringDict, error) { // Grab the source code. dict, src, err := intr.invokeLoader(key) switch { case err != nil: return nil, err case dict != nil: // This is a native module constructed in Go, no need to interpret it. return dict, nil } // Otherwise make a thread for executing the code. We do not reuse threads // between modules. All global state is passed through intr.globals, // intr.modules and ctx. th := intr.Thread(ctx) th.Load = func(th *starlark.Thread, module string) (starlark.StringDict, error) { key, err := makeModuleKey(module, th) if err != nil { return nil, err } dict, err := intr.LoadModule(ctx, key.pkg, key.path) // See comment in execBuiltin about why we extract EvalError backtrace into // new error. if evalErr, ok := err.(*starlark.EvalError); ok { err = fmt.Errorf("%s", evalErr.Backtrace()) } return dict, err } // Let builtins know what this thread is doing. Some calls (most notably Exec // itself) are allowed only from exec'ing threads, not from load'ing ones. th.SetLocal(threadKindKey, kind) // Let builtins (and in particular makeModuleKey and LoadSource) know the // package and the module that the thread executes. th.SetLocal(threadModKey, key) if kind == ThreadExecing { if intr.PreExec != nil { intr.PreExec(th, key.pkg, key.path) } if intr.PostExec != nil { defer intr.PostExec(th, key.pkg, key.path) } } // Execute the module. It may 'load' or 'exec' other modules inside, which // will either call LoadModule or ExecModule. // // Use user-friendly module name (with omitted "@__main__") for error messages // and stack traces to avoid confusing the user. return starlark.ExecFile(th, key.String(), src, intr.globals) }
[ "func", "(", "intr", "*", "Interpreter", ")", "runModule", "(", "ctx", "context", ".", "Context", ",", "key", "moduleKey", ",", "kind", "ThreadKind", ")", "(", "starlark", ".", "StringDict", ",", "error", ")", "{", "// Grab the source code.", "dict", ",", "src", ",", "err", ":=", "intr", ".", "invokeLoader", "(", "key", ")", "\n", "switch", "{", "case", "err", "!=", "nil", ":", "return", "nil", ",", "err", "\n", "case", "dict", "!=", "nil", ":", "// This is a native module constructed in Go, no need to interpret it.", "return", "dict", ",", "nil", "\n", "}", "\n\n", "// Otherwise make a thread for executing the code. We do not reuse threads", "// between modules. All global state is passed through intr.globals,", "// intr.modules and ctx.", "th", ":=", "intr", ".", "Thread", "(", "ctx", ")", "\n", "th", ".", "Load", "=", "func", "(", "th", "*", "starlark", ".", "Thread", ",", "module", "string", ")", "(", "starlark", ".", "StringDict", ",", "error", ")", "{", "key", ",", "err", ":=", "makeModuleKey", "(", "module", ",", "th", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "dict", ",", "err", ":=", "intr", ".", "LoadModule", "(", "ctx", ",", "key", ".", "pkg", ",", "key", ".", "path", ")", "\n", "// See comment in execBuiltin about why we extract EvalError backtrace into", "// new error.", "if", "evalErr", ",", "ok", ":=", "err", ".", "(", "*", "starlark", ".", "EvalError", ")", ";", "ok", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "evalErr", ".", "Backtrace", "(", ")", ")", "\n", "}", "\n", "return", "dict", ",", "err", "\n", "}", "\n\n", "// Let builtins know what this thread is doing. Some calls (most notably Exec", "// itself) are allowed only from exec'ing threads, not from load'ing ones.", "th", ".", "SetLocal", "(", "threadKindKey", ",", "kind", ")", "\n", "// Let builtins (and in particular makeModuleKey and LoadSource) know the", "// package and the module that the thread executes.", "th", ".", "SetLocal", "(", "threadModKey", ",", "key", ")", "\n\n", "if", "kind", "==", "ThreadExecing", "{", "if", "intr", ".", "PreExec", "!=", "nil", "{", "intr", ".", "PreExec", "(", "th", ",", "key", ".", "pkg", ",", "key", ".", "path", ")", "\n", "}", "\n", "if", "intr", ".", "PostExec", "!=", "nil", "{", "defer", "intr", ".", "PostExec", "(", "th", ",", "key", ".", "pkg", ",", "key", ".", "path", ")", "\n", "}", "\n", "}", "\n\n", "// Execute the module. It may 'load' or 'exec' other modules inside, which", "// will either call LoadModule or ExecModule.", "//", "// Use user-friendly module name (with omitted \"@__main__\") for error messages", "// and stack traces to avoid confusing the user.", "return", "starlark", ".", "ExecFile", "(", "th", ",", "key", ".", "String", "(", ")", ",", "src", ",", "intr", ".", "globals", ")", "\n", "}" ]
// runModule really loads and executes the module, used by both LoadModule and // ExecModule.
[ "runModule", "really", "loads", "and", "executes", "the", "module", "used", "by", "both", "LoadModule", "and", "ExecModule", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/interpreter/interpreter.go#L581-L632
8,019
luci/luci-go
milo/buildsource/buildbot/buildstore/build.go
summarizeBuild
func summarizeBuild(c context.Context, b *buildbot.Build) (*model.BuildSummary, error) { bs := &model.BuildSummary{ BuildKey: datastore.KeyForObj(c, (*buildEntity)(b)), BuilderID: fmt.Sprintf("buildbot/%s/%s", b.Master, b.Buildername), BuildID: fmt.Sprintf("buildbot/%s/%s/%d", b.Master, b.Buildername, b.Number), } bs.Experimental = b.Experimental() bs.ContextURI = []string{ fmt.Sprintf("buildbot://%s/build/%s/%d", b.Master, b.Buildername, b.Number), fmt.Sprintf("buildbot://%s/bot/%s", b.Master, b.Slave), } // Try to extract the Buildbucket URL, if available. if uri, ok := getBuildbucketURI(b); ok { bs.ContextURI = append(bs.ContextURI, uri) } bs.Summary.Start = b.Times.Start.Time bs.Summary.End = b.Times.Finish.Time bs.Summary.Status = b.Status() // Start time acts as a proxy for creation time. bs.Created = b.Times.Start.Time // Populates BuildSet and ManifestKey if err := attachRevisionInfo(c, b, bs); err != nil { return nil, err } bs.AnnotationURL, _ = b.PropertyValue("log_location").(string) // we use the number of steps as the top bits, and the status (Finished // > other) as the low bits as a very dumb version number. bs.Version = int64(len(b.Steps)) << 1 if b.Finished { bs.Version |= 1 } return bs, nil }
go
func summarizeBuild(c context.Context, b *buildbot.Build) (*model.BuildSummary, error) { bs := &model.BuildSummary{ BuildKey: datastore.KeyForObj(c, (*buildEntity)(b)), BuilderID: fmt.Sprintf("buildbot/%s/%s", b.Master, b.Buildername), BuildID: fmt.Sprintf("buildbot/%s/%s/%d", b.Master, b.Buildername, b.Number), } bs.Experimental = b.Experimental() bs.ContextURI = []string{ fmt.Sprintf("buildbot://%s/build/%s/%d", b.Master, b.Buildername, b.Number), fmt.Sprintf("buildbot://%s/bot/%s", b.Master, b.Slave), } // Try to extract the Buildbucket URL, if available. if uri, ok := getBuildbucketURI(b); ok { bs.ContextURI = append(bs.ContextURI, uri) } bs.Summary.Start = b.Times.Start.Time bs.Summary.End = b.Times.Finish.Time bs.Summary.Status = b.Status() // Start time acts as a proxy for creation time. bs.Created = b.Times.Start.Time // Populates BuildSet and ManifestKey if err := attachRevisionInfo(c, b, bs); err != nil { return nil, err } bs.AnnotationURL, _ = b.PropertyValue("log_location").(string) // we use the number of steps as the top bits, and the status (Finished // > other) as the low bits as a very dumb version number. bs.Version = int64(len(b.Steps)) << 1 if b.Finished { bs.Version |= 1 } return bs, nil }
[ "func", "summarizeBuild", "(", "c", "context", ".", "Context", ",", "b", "*", "buildbot", ".", "Build", ")", "(", "*", "model", ".", "BuildSummary", ",", "error", ")", "{", "bs", ":=", "&", "model", ".", "BuildSummary", "{", "BuildKey", ":", "datastore", ".", "KeyForObj", "(", "c", ",", "(", "*", "buildEntity", ")", "(", "b", ")", ")", ",", "BuilderID", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "b", ".", "Master", ",", "b", ".", "Buildername", ")", ",", "BuildID", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "b", ".", "Master", ",", "b", ".", "Buildername", ",", "b", ".", "Number", ")", ",", "}", "\n\n", "bs", ".", "Experimental", "=", "b", ".", "Experimental", "(", ")", "\n\n", "bs", ".", "ContextURI", "=", "[", "]", "string", "{", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "b", ".", "Master", ",", "b", ".", "Buildername", ",", "b", ".", "Number", ")", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "b", ".", "Master", ",", "b", ".", "Slave", ")", ",", "}", "\n\n", "// Try to extract the Buildbucket URL, if available.", "if", "uri", ",", "ok", ":=", "getBuildbucketURI", "(", "b", ")", ";", "ok", "{", "bs", ".", "ContextURI", "=", "append", "(", "bs", ".", "ContextURI", ",", "uri", ")", "\n", "}", "\n\n", "bs", ".", "Summary", ".", "Start", "=", "b", ".", "Times", ".", "Start", ".", "Time", "\n", "bs", ".", "Summary", ".", "End", "=", "b", ".", "Times", ".", "Finish", ".", "Time", "\n", "bs", ".", "Summary", ".", "Status", "=", "b", ".", "Status", "(", ")", "\n\n", "// Start time acts as a proxy for creation time.", "bs", ".", "Created", "=", "b", ".", "Times", ".", "Start", ".", "Time", "\n\n", "// Populates BuildSet and ManifestKey", "if", "err", ":=", "attachRevisionInfo", "(", "c", ",", "b", ",", "bs", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "bs", ".", "AnnotationURL", ",", "_", "=", "b", ".", "PropertyValue", "(", "\"", "\"", ")", ".", "(", "string", ")", "\n\n", "// we use the number of steps as the top bits, and the status (Finished", "// > other) as the low bits as a very dumb version number.", "bs", ".", "Version", "=", "int64", "(", "len", "(", "b", ".", "Steps", ")", ")", "<<", "1", "\n", "if", "b", ".", "Finished", "{", "bs", ".", "Version", "|=", "1", "\n", "}", "\n\n", "return", "bs", ",", "nil", "\n", "}" ]
// summarizeBuild creates a build summary from the buildbot build.
[ "summarizeBuild", "creates", "a", "build", "summary", "from", "the", "buildbot", "build", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildstore/build.go#L286-L327
8,020
luci/luci-go
milo/buildsource/buildbot/buildstore/build.go
SaveBuild
func SaveBuild(c context.Context, b *buildbot.Build) (replaced bool, err error) { bs, err := summarizeBuild(c, b) if err != nil { err = errors.Annotate(err, "summarizing build").Err() return } err = datastore.RunInTransaction(c, func(c context.Context) error { existingBS := &model.BuildSummary{ BuildKey: bs.BuildKey, } existing := &buildEntity{ Master: b.Master, Buildername: b.Buildername, Number: b.Number, } if err := datastore.Get(c, existing, existingBS); err == nil { // they both exist replaced = true if bs.Version < existingBS.Version { return errors.Reason("Imported version older than existing (%d < %d)", bs.Version, existingBS.Version).Tag(ImportRejectedTag).Err() } else if bs.Version == existingBS.Version { return nil // idempotency } } else { me := err.(errors.MultiError) // one of the errors was NSE; bail. for _, ierr := range me { if ierr != nil && ierr != datastore.ErrNoSuchEntity { return errors.Annotate(ierr, "getting existing build summary").Err() } } // One or the other was NES; don't care, just record both entries to get // up to date. } if err := datastore.Put(c, (*buildEntity)(b), bs); err != nil { return err } return model.UpdateBuilderForBuild(c, bs) }, &datastore.TransactionOptions{XG: true}) return }
go
func SaveBuild(c context.Context, b *buildbot.Build) (replaced bool, err error) { bs, err := summarizeBuild(c, b) if err != nil { err = errors.Annotate(err, "summarizing build").Err() return } err = datastore.RunInTransaction(c, func(c context.Context) error { existingBS := &model.BuildSummary{ BuildKey: bs.BuildKey, } existing := &buildEntity{ Master: b.Master, Buildername: b.Buildername, Number: b.Number, } if err := datastore.Get(c, existing, existingBS); err == nil { // they both exist replaced = true if bs.Version < existingBS.Version { return errors.Reason("Imported version older than existing (%d < %d)", bs.Version, existingBS.Version).Tag(ImportRejectedTag).Err() } else if bs.Version == existingBS.Version { return nil // idempotency } } else { me := err.(errors.MultiError) // one of the errors was NSE; bail. for _, ierr := range me { if ierr != nil && ierr != datastore.ErrNoSuchEntity { return errors.Annotate(ierr, "getting existing build summary").Err() } } // One or the other was NES; don't care, just record both entries to get // up to date. } if err := datastore.Put(c, (*buildEntity)(b), bs); err != nil { return err } return model.UpdateBuilderForBuild(c, bs) }, &datastore.TransactionOptions{XG: true}) return }
[ "func", "SaveBuild", "(", "c", "context", ".", "Context", ",", "b", "*", "buildbot", ".", "Build", ")", "(", "replaced", "bool", ",", "err", "error", ")", "{", "bs", ",", "err", ":=", "summarizeBuild", "(", "c", ",", "b", ")", "\n", "if", "err", "!=", "nil", "{", "err", "=", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "return", "\n", "}", "\n\n", "err", "=", "datastore", ".", "RunInTransaction", "(", "c", ",", "func", "(", "c", "context", ".", "Context", ")", "error", "{", "existingBS", ":=", "&", "model", ".", "BuildSummary", "{", "BuildKey", ":", "bs", ".", "BuildKey", ",", "}", "\n", "existing", ":=", "&", "buildEntity", "{", "Master", ":", "b", ".", "Master", ",", "Buildername", ":", "b", ".", "Buildername", ",", "Number", ":", "b", ".", "Number", ",", "}", "\n\n", "if", "err", ":=", "datastore", ".", "Get", "(", "c", ",", "existing", ",", "existingBS", ")", ";", "err", "==", "nil", "{", "// they both exist", "replaced", "=", "true", "\n\n", "if", "bs", ".", "Version", "<", "existingBS", ".", "Version", "{", "return", "errors", ".", "Reason", "(", "\"", "\"", ",", "bs", ".", "Version", ",", "existingBS", ".", "Version", ")", ".", "Tag", "(", "ImportRejectedTag", ")", ".", "Err", "(", ")", "\n", "}", "else", "if", "bs", ".", "Version", "==", "existingBS", ".", "Version", "{", "return", "nil", "// idempotency", "\n", "}", "\n", "}", "else", "{", "me", ":=", "err", ".", "(", "errors", ".", "MultiError", ")", "\n", "// one of the errors was NSE; bail.", "for", "_", ",", "ierr", ":=", "range", "me", "{", "if", "ierr", "!=", "nil", "&&", "ierr", "!=", "datastore", ".", "ErrNoSuchEntity", "{", "return", "errors", ".", "Annotate", "(", "ierr", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "}", "\n\n", "// One or the other was NES; don't care, just record both entries to get", "// up to date.", "}", "\n\n", "if", "err", ":=", "datastore", ".", "Put", "(", "c", ",", "(", "*", "buildEntity", ")", "(", "b", ")", ",", "bs", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "model", ".", "UpdateBuilderForBuild", "(", "c", ",", "bs", ")", "\n", "}", ",", "&", "datastore", ".", "TransactionOptions", "{", "XG", ":", "true", "}", ")", "\n", "return", "\n", "}" ]
// SaveBuild persists the build in the storage. // // This will also update the model.BuildSummary and model.BuilderSummary.
[ "SaveBuild", "persists", "the", "build", "in", "the", "storage", ".", "This", "will", "also", "update", "the", "model", ".", "BuildSummary", "and", "model", ".", "BuilderSummary", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildstore/build.go#L332-L378
8,021
luci/luci-go
milo/buildsource/buildbot/buildstore/build.go
getID
func (b *buildEntity) getID() string { s := []string{b.Master, b.Buildername, strconv.Itoa(b.Number)} id, err := json.Marshal(s) if err != nil { panic(err) // This can't fail. } return string(id) }
go
func (b *buildEntity) getID() string { s := []string{b.Master, b.Buildername, strconv.Itoa(b.Number)} id, err := json.Marshal(s) if err != nil { panic(err) // This can't fail. } return string(id) }
[ "func", "(", "b", "*", "buildEntity", ")", "getID", "(", ")", "string", "{", "s", ":=", "[", "]", "string", "{", "b", ".", "Master", ",", "b", ".", "Buildername", ",", "strconv", ".", "Itoa", "(", "b", ".", "Number", ")", "}", "\n", "id", ",", "err", ":=", "json", ".", "Marshal", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "// This can't fail.", "\n", "}", "\n", "return", "string", "(", "id", ")", "\n", "}" ]
// getID is a helper function that returns b's datastore key.
[ "getID", "is", "a", "helper", "function", "that", "returns", "b", "s", "datastore", "key", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildstore/build.go#L391-L398
8,022
luci/luci-go
milo/buildsource/buildbot/buildstore/build.go
Save
func (b *buildEntity) Save(withMeta bool) (datastore.PropertyMap, error) { var ps datastore.PropertyMap if withMeta { ps = b.GetAllMeta() } else { ps = datastore.PropertyMap{} } build := (*buildbot.Build)(b) data, err := encode(b) if err != nil { return nil, err } if len(data) > maxDataSize { return nil, errors.Reason("build data is %d bytes, which is more than %d limit", len(data), maxDataSize). Tag(TooBigTag). Err() } ps["data"] = datastore.MkPropertyNI(data) ps["master"] = datastore.MkProperty(b.Master) ps["builder"] = datastore.MkProperty(b.Buildername) ps["number"] = datastore.MkProperty(b.Number) ps["finished"] = datastore.MkProperty(b.Finished) ps["is_experimental"] = datastore.MkProperty(build.Experimental()) return ps, nil }
go
func (b *buildEntity) Save(withMeta bool) (datastore.PropertyMap, error) { var ps datastore.PropertyMap if withMeta { ps = b.GetAllMeta() } else { ps = datastore.PropertyMap{} } build := (*buildbot.Build)(b) data, err := encode(b) if err != nil { return nil, err } if len(data) > maxDataSize { return nil, errors.Reason("build data is %d bytes, which is more than %d limit", len(data), maxDataSize). Tag(TooBigTag). Err() } ps["data"] = datastore.MkPropertyNI(data) ps["master"] = datastore.MkProperty(b.Master) ps["builder"] = datastore.MkProperty(b.Buildername) ps["number"] = datastore.MkProperty(b.Number) ps["finished"] = datastore.MkProperty(b.Finished) ps["is_experimental"] = datastore.MkProperty(build.Experimental()) return ps, nil }
[ "func", "(", "b", "*", "buildEntity", ")", "Save", "(", "withMeta", "bool", ")", "(", "datastore", ".", "PropertyMap", ",", "error", ")", "{", "var", "ps", "datastore", ".", "PropertyMap", "\n", "if", "withMeta", "{", "ps", "=", "b", ".", "GetAllMeta", "(", ")", "\n", "}", "else", "{", "ps", "=", "datastore", ".", "PropertyMap", "{", "}", "\n", "}", "\n\n", "build", ":=", "(", "*", "buildbot", ".", "Build", ")", "(", "b", ")", "\n\n", "data", ",", "err", ":=", "encode", "(", "b", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "data", ")", ">", "maxDataSize", "{", "return", "nil", ",", "errors", ".", "Reason", "(", "\"", "\"", ",", "len", "(", "data", ")", ",", "maxDataSize", ")", ".", "Tag", "(", "TooBigTag", ")", ".", "Err", "(", ")", "\n", "}", "\n", "ps", "[", "\"", "\"", "]", "=", "datastore", ".", "MkPropertyNI", "(", "data", ")", "\n", "ps", "[", "\"", "\"", "]", "=", "datastore", ".", "MkProperty", "(", "b", ".", "Master", ")", "\n", "ps", "[", "\"", "\"", "]", "=", "datastore", ".", "MkProperty", "(", "b", ".", "Buildername", ")", "\n", "ps", "[", "\"", "\"", "]", "=", "datastore", ".", "MkProperty", "(", "b", ".", "Number", ")", "\n", "ps", "[", "\"", "\"", "]", "=", "datastore", ".", "MkProperty", "(", "b", ".", "Finished", ")", "\n", "ps", "[", "\"", "\"", "]", "=", "datastore", ".", "MkProperty", "(", "build", ".", "Experimental", "(", ")", ")", "\n", "return", "ps", ",", "nil", "\n", "}" ]
// Save converts b to a property map. // The encoded build goes into "data" property. // In addition, Save returns "master", "builder", "number" and "finished" // properties for queries.
[ "Save", "converts", "b", "to", "a", "property", "map", ".", "The", "encoded", "build", "goes", "into", "data", "property", ".", "In", "addition", "Save", "returns", "master", "builder", "number", "and", "finished", "properties", "for", "queries", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildstore/build.go#L452-L478
8,023
luci/luci-go
milo/buildsource/buildbot/buildstore/build.go
Load
func (b *buildEntity) Load(pm datastore.PropertyMap) error { if p, ok := pm["id"]; ok { b.SetMeta("id", p.Slice()[0].Value()) } if p, ok := pm["data"]; ok { data, err := p.Slice()[0].Project(datastore.PTBytes) if err != nil { return err } build := (*buildbot.Build)(b) if err := decode(build, data.([]byte)); err != nil { return err } promoteLogdogAliases(build) } return nil }
go
func (b *buildEntity) Load(pm datastore.PropertyMap) error { if p, ok := pm["id"]; ok { b.SetMeta("id", p.Slice()[0].Value()) } if p, ok := pm["data"]; ok { data, err := p.Slice()[0].Project(datastore.PTBytes) if err != nil { return err } build := (*buildbot.Build)(b) if err := decode(build, data.([]byte)); err != nil { return err } promoteLogdogAliases(build) } return nil }
[ "func", "(", "b", "*", "buildEntity", ")", "Load", "(", "pm", "datastore", ".", "PropertyMap", ")", "error", "{", "if", "p", ",", "ok", ":=", "pm", "[", "\"", "\"", "]", ";", "ok", "{", "b", ".", "SetMeta", "(", "\"", "\"", ",", "p", ".", "Slice", "(", ")", "[", "0", "]", ".", "Value", "(", ")", ")", "\n", "}", "\n\n", "if", "p", ",", "ok", ":=", "pm", "[", "\"", "\"", "]", ";", "ok", "{", "data", ",", "err", ":=", "p", ".", "Slice", "(", ")", "[", "0", "]", ".", "Project", "(", "datastore", ".", "PTBytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "build", ":=", "(", "*", "buildbot", ".", "Build", ")", "(", "b", ")", "\n", "if", "err", ":=", "decode", "(", "build", ",", "data", ".", "(", "[", "]", "byte", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "promoteLogdogAliases", "(", "build", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Load loads b from the datastore property map. // Also promotes LogDog links.
[ "Load", "loads", "b", "from", "the", "datastore", "property", "map", ".", "Also", "promotes", "LogDog", "links", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildstore/build.go#L482-L500
8,024
luci/luci-go
milo/buildsource/buildbot/buildstore/build.go
addViewPath
func (b *buildEntity) addViewPath() { if b == nil { // Could be nil e.g. as part of a query result. return } b.ViewPath = (&model.BuildSummary{ BuildID: fmt.Sprintf("buildbot/%s/%s/%d", b.Master, b.Buildername, b.Number), }).SelfLink() }
go
func (b *buildEntity) addViewPath() { if b == nil { // Could be nil e.g. as part of a query result. return } b.ViewPath = (&model.BuildSummary{ BuildID: fmt.Sprintf("buildbot/%s/%s/%d", b.Master, b.Buildername, b.Number), }).SelfLink() }
[ "func", "(", "b", "*", "buildEntity", ")", "addViewPath", "(", ")", "{", "if", "b", "==", "nil", "{", "// Could be nil e.g. as part of a query result.", "return", "\n", "}", "\n", "b", ".", "ViewPath", "=", "(", "&", "model", ".", "BuildSummary", "{", "BuildID", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "b", ".", "Master", ",", "b", ".", "Buildername", ",", "b", ".", "Number", ")", ",", "}", ")", ".", "SelfLink", "(", ")", "\n", "}" ]
// addViewPath populates the 'ViewPath' field of the underlying buildbot.Build // struct.
[ "addViewPath", "populates", "the", "ViewPath", "field", "of", "the", "underlying", "buildbot", ".", "Build", "struct", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildstore/build.go#L504-L512
8,025
luci/luci-go
milo/buildsource/buildbot/buildstore/build.go
promoteLogdogAliases
func promoteLogdogAliases(b *buildbot.Build) { // If this is a LogDog-only build, we want to promote the LogDog links. if loc, ok := b.PropertyValue("log_location").(string); ok && strings.HasPrefix(loc, "logdog://") { linkMap := map[string]string{} for i := range b.Steps { promoteLogDogLinks(&b.Steps[i], i == 0, linkMap) } // Update "b.Logs". This field is part of BuildBot, and is the amalgamation // of all logs in the build's steps. Since each log is out of context of its // original step, we can't apply the promotion logic; instead, we will use // the link map to map any old URLs that were matched in "promoteLogDogLinks" // to their new URLs. for i := range b.Logs { l := &b.Logs[i] if newURL, ok := linkMap[l.URL]; ok { l.URL = newURL } } } }
go
func promoteLogdogAliases(b *buildbot.Build) { // If this is a LogDog-only build, we want to promote the LogDog links. if loc, ok := b.PropertyValue("log_location").(string); ok && strings.HasPrefix(loc, "logdog://") { linkMap := map[string]string{} for i := range b.Steps { promoteLogDogLinks(&b.Steps[i], i == 0, linkMap) } // Update "b.Logs". This field is part of BuildBot, and is the amalgamation // of all logs in the build's steps. Since each log is out of context of its // original step, we can't apply the promotion logic; instead, we will use // the link map to map any old URLs that were matched in "promoteLogDogLinks" // to their new URLs. for i := range b.Logs { l := &b.Logs[i] if newURL, ok := linkMap[l.URL]; ok { l.URL = newURL } } } }
[ "func", "promoteLogdogAliases", "(", "b", "*", "buildbot", ".", "Build", ")", "{", "// If this is a LogDog-only build, we want to promote the LogDog links.", "if", "loc", ",", "ok", ":=", "b", ".", "PropertyValue", "(", "\"", "\"", ")", ".", "(", "string", ")", ";", "ok", "&&", "strings", ".", "HasPrefix", "(", "loc", ",", "\"", "\"", ")", "{", "linkMap", ":=", "map", "[", "string", "]", "string", "{", "}", "\n", "for", "i", ":=", "range", "b", ".", "Steps", "{", "promoteLogDogLinks", "(", "&", "b", ".", "Steps", "[", "i", "]", ",", "i", "==", "0", ",", "linkMap", ")", "\n", "}", "\n\n", "// Update \"b.Logs\". This field is part of BuildBot, and is the amalgamation", "// of all logs in the build's steps. Since each log is out of context of its", "// original step, we can't apply the promotion logic; instead, we will use", "// the link map to map any old URLs that were matched in \"promoteLogDogLinks\"", "// to their new URLs.", "for", "i", ":=", "range", "b", ".", "Logs", "{", "l", ":=", "&", "b", ".", "Logs", "[", "i", "]", "\n", "if", "newURL", ",", "ok", ":=", "linkMap", "[", "l", ".", "URL", "]", ";", "ok", "{", "l", ".", "URL", "=", "newURL", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// promoteLogdogAliases promotes LogDog links to first-class links.
[ "promoteLogdogAliases", "promotes", "LogDog", "links", "to", "first", "-", "class", "links", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/buildsource/buildbot/buildstore/build.go#L515-L535
8,026
luci/luci-go
config/validation/rules.go
ConfigPatterns
func (r *RuleSet) ConfigPatterns(c context.Context) ([]*ConfigPattern, error) { r.l.RLock() defer r.l.RUnlock() out := make([]*ConfigPattern, len(r.r)) for i, rule := range r.r { var err error if out[i], err = r.renderedConfigPattern(c, rule); err != nil { return nil, err } } return out, nil }
go
func (r *RuleSet) ConfigPatterns(c context.Context) ([]*ConfigPattern, error) { r.l.RLock() defer r.l.RUnlock() out := make([]*ConfigPattern, len(r.r)) for i, rule := range r.r { var err error if out[i], err = r.renderedConfigPattern(c, rule); err != nil { return nil, err } } return out, nil }
[ "func", "(", "r", "*", "RuleSet", ")", "ConfigPatterns", "(", "c", "context", ".", "Context", ")", "(", "[", "]", "*", "ConfigPattern", ",", "error", ")", "{", "r", ".", "l", ".", "RLock", "(", ")", "\n", "defer", "r", ".", "l", ".", "RUnlock", "(", ")", "\n\n", "out", ":=", "make", "(", "[", "]", "*", "ConfigPattern", ",", "len", "(", "r", ".", "r", ")", ")", "\n", "for", "i", ",", "rule", ":=", "range", "r", ".", "r", "{", "var", "err", "error", "\n", "if", "out", "[", "i", "]", ",", "err", "=", "r", ".", "renderedConfigPattern", "(", "c", ",", "rule", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "return", "out", ",", "nil", "\n", "}" ]
// ConfigPatterns renders all registered config patterns and returns them. // // Used by the metadata handler to notify the config service about config files // we understand.
[ "ConfigPatterns", "renders", "all", "registered", "config", "patterns", "and", "returns", "them", ".", "Used", "by", "the", "metadata", "handler", "to", "notify", "the", "config", "service", "about", "config", "files", "we", "understand", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/validation/rules.go#L142-L155
8,027
luci/luci-go
config/validation/rules.go
renderedConfigPattern
func (r *RuleSet) renderedConfigPattern(c context.Context, rule *rule) (*ConfigPattern, error) { sub := func(name string) (string, error) { if cb := r.v[name]; cb != nil { return cb(c) } return "", fmt.Errorf("no placeholder named %q is registered", name) } configSet, err := renderPatternString(rule.configSet, sub) if err != nil { return nil, errors.Annotate(err, "failed to compile config set pattern %q", rule.configSet).Err() } path, err := renderPatternString(rule.path, sub) if err != nil { return nil, errors.Annotate(err, "failed to compile path pattern %q", rule.path).Err() } return &ConfigPattern{ ConfigSet: configSet, Path: path, }, nil }
go
func (r *RuleSet) renderedConfigPattern(c context.Context, rule *rule) (*ConfigPattern, error) { sub := func(name string) (string, error) { if cb := r.v[name]; cb != nil { return cb(c) } return "", fmt.Errorf("no placeholder named %q is registered", name) } configSet, err := renderPatternString(rule.configSet, sub) if err != nil { return nil, errors.Annotate(err, "failed to compile config set pattern %q", rule.configSet).Err() } path, err := renderPatternString(rule.path, sub) if err != nil { return nil, errors.Annotate(err, "failed to compile path pattern %q", rule.path).Err() } return &ConfigPattern{ ConfigSet: configSet, Path: path, }, nil }
[ "func", "(", "r", "*", "RuleSet", ")", "renderedConfigPattern", "(", "c", "context", ".", "Context", ",", "rule", "*", "rule", ")", "(", "*", "ConfigPattern", ",", "error", ")", "{", "sub", ":=", "func", "(", "name", "string", ")", "(", "string", ",", "error", ")", "{", "if", "cb", ":=", "r", ".", "v", "[", "name", "]", ";", "cb", "!=", "nil", "{", "return", "cb", "(", "c", ")", "\n", "}", "\n", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n\n", "configSet", ",", "err", ":=", "renderPatternString", "(", "rule", ".", "configSet", ",", "sub", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "rule", ".", "configSet", ")", ".", "Err", "(", ")", "\n", "}", "\n", "path", ",", "err", ":=", "renderPatternString", "(", "rule", ".", "path", ",", "sub", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "rule", ".", "path", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "return", "&", "ConfigPattern", "{", "ConfigSet", ":", "configSet", ",", "Path", ":", "path", ",", "}", ",", "nil", "\n", "}" ]
// renderedConfigPattern expands variables in the config patterns. // // Must be called with r.l read lock held.
[ "renderedConfigPattern", "expands", "variables", "in", "the", "config", "patterns", ".", "Must", "be", "called", "with", "r", ".", "l", "read", "lock", "held", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/validation/rules.go#L202-L223
8,028
luci/luci-go
common/data/rand/mathrand/impl.go
Int63
func (l *Locking) Int63() (v int64) { l.Lock() v = l.R.Int63() l.Unlock() return }
go
func (l *Locking) Int63() (v int64) { l.Lock() v = l.R.Int63() l.Unlock() return }
[ "func", "(", "l", "*", "Locking", ")", "Int63", "(", ")", "(", "v", "int64", ")", "{", "l", ".", "Lock", "(", ")", "\n", "v", "=", "l", ".", "R", ".", "Int63", "(", ")", "\n", "l", ".", "Unlock", "(", ")", "\n", "return", "\n", "}" ]
// Int63 returns a non-negative pseudo-random 63-bit integer as an int64 // from the source in the context or the shared global source.
[ "Int63", "returns", "a", "non", "-", "negative", "pseudo", "-", "random", "63", "-", "bit", "integer", "as", "an", "int64", "from", "the", "source", "in", "the", "context", "or", "the", "shared", "global", "source", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/rand/mathrand/impl.go#L142-L147
8,029
luci/luci-go
common/data/rand/mathrand/impl.go
Uint32
func (l *Locking) Uint32() (v uint32) { l.Lock() v = l.R.Uint32() l.Unlock() return }
go
func (l *Locking) Uint32() (v uint32) { l.Lock() v = l.R.Uint32() l.Unlock() return }
[ "func", "(", "l", "*", "Locking", ")", "Uint32", "(", ")", "(", "v", "uint32", ")", "{", "l", ".", "Lock", "(", ")", "\n", "v", "=", "l", ".", "R", ".", "Uint32", "(", ")", "\n", "l", ".", "Unlock", "(", ")", "\n", "return", "\n", "}" ]
// Uint32 returns a pseudo-random 32-bit value as a uint32 from the source in // the context or the shared global source.
[ "Uint32", "returns", "a", "pseudo", "-", "random", "32", "-", "bit", "value", "as", "a", "uint32", "from", "the", "source", "in", "the", "context", "or", "the", "shared", "global", "source", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/rand/mathrand/impl.go#L151-L156
8,030
luci/luci-go
common/data/rand/mathrand/impl.go
Int31
func (l *Locking) Int31() (v int32) { l.Lock() v = l.R.Int31() l.Unlock() return }
go
func (l *Locking) Int31() (v int32) { l.Lock() v = l.R.Int31() l.Unlock() return }
[ "func", "(", "l", "*", "Locking", ")", "Int31", "(", ")", "(", "v", "int32", ")", "{", "l", ".", "Lock", "(", ")", "\n", "v", "=", "l", ".", "R", ".", "Int31", "(", ")", "\n", "l", ".", "Unlock", "(", ")", "\n", "return", "\n", "}" ]
// Int31 returns a non-negative pseudo-random 31-bit integer as an int32 from // the source in the context or the shared global source.
[ "Int31", "returns", "a", "non", "-", "negative", "pseudo", "-", "random", "31", "-", "bit", "integer", "as", "an", "int32", "from", "the", "source", "in", "the", "context", "or", "the", "shared", "global", "source", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/rand/mathrand/impl.go#L160-L165
8,031
luci/luci-go
common/data/rand/mathrand/impl.go
Int
func (l *Locking) Int() (v int) { l.Lock() v = l.R.Int() l.Unlock() return }
go
func (l *Locking) Int() (v int) { l.Lock() v = l.R.Int() l.Unlock() return }
[ "func", "(", "l", "*", "Locking", ")", "Int", "(", ")", "(", "v", "int", ")", "{", "l", ".", "Lock", "(", ")", "\n", "v", "=", "l", ".", "R", ".", "Int", "(", ")", "\n", "l", ".", "Unlock", "(", ")", "\n", "return", "\n", "}" ]
// Int returns a non-negative pseudo-random int from the source in the context // or the shared global source.
[ "Int", "returns", "a", "non", "-", "negative", "pseudo", "-", "random", "int", "from", "the", "source", "in", "the", "context", "or", "the", "shared", "global", "source", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/rand/mathrand/impl.go#L169-L174
8,032
luci/luci-go
common/data/rand/mathrand/impl.go
Int63n
func (l *Locking) Int63n(n int64) (v int64) { l.Lock() v = l.R.Int63n(n) l.Unlock() return }
go
func (l *Locking) Int63n(n int64) (v int64) { l.Lock() v = l.R.Int63n(n) l.Unlock() return }
[ "func", "(", "l", "*", "Locking", ")", "Int63n", "(", "n", "int64", ")", "(", "v", "int64", ")", "{", "l", ".", "Lock", "(", ")", "\n", "v", "=", "l", ".", "R", ".", "Int63n", "(", "n", ")", "\n", "l", ".", "Unlock", "(", ")", "\n", "return", "\n", "}" ]
// Int63n returns, as an int64, a non-negative pseudo-random number in [0,n) // from the source in the context or the shared global source. // // It panics if n <= 0.
[ "Int63n", "returns", "as", "an", "int64", "a", "non", "-", "negative", "pseudo", "-", "random", "number", "in", "[", "0", "n", ")", "from", "the", "source", "in", "the", "context", "or", "the", "shared", "global", "source", ".", "It", "panics", "if", "n", "<", "=", "0", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/rand/mathrand/impl.go#L180-L185
8,033
luci/luci-go
common/data/rand/mathrand/impl.go
Int31n
func (l *Locking) Int31n(n int32) (v int32) { l.Lock() v = l.R.Int31n(n) l.Unlock() return }
go
func (l *Locking) Int31n(n int32) (v int32) { l.Lock() v = l.R.Int31n(n) l.Unlock() return }
[ "func", "(", "l", "*", "Locking", ")", "Int31n", "(", "n", "int32", ")", "(", "v", "int32", ")", "{", "l", ".", "Lock", "(", ")", "\n", "v", "=", "l", ".", "R", ".", "Int31n", "(", "n", ")", "\n", "l", ".", "Unlock", "(", ")", "\n", "return", "\n", "}" ]
// Int31n returns, as an int32, a non-negative pseudo-random number in [0,n) // from the source in the context or the shared global source. // // It panics if n <= 0.
[ "Int31n", "returns", "as", "an", "int32", "a", "non", "-", "negative", "pseudo", "-", "random", "number", "in", "[", "0", "n", ")", "from", "the", "source", "in", "the", "context", "or", "the", "shared", "global", "source", ".", "It", "panics", "if", "n", "<", "=", "0", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/rand/mathrand/impl.go#L191-L196
8,034
luci/luci-go
common/data/rand/mathrand/impl.go
Float64
func (l *Locking) Float64() (v float64) { l.Lock() v = l.R.Float64() l.Unlock() return }
go
func (l *Locking) Float64() (v float64) { l.Lock() v = l.R.Float64() l.Unlock() return }
[ "func", "(", "l", "*", "Locking", ")", "Float64", "(", ")", "(", "v", "float64", ")", "{", "l", ".", "Lock", "(", ")", "\n", "v", "=", "l", ".", "R", ".", "Float64", "(", ")", "\n", "l", ".", "Unlock", "(", ")", "\n", "return", "\n", "}" ]
// Float64 returns, as a float64, a pseudo-random number in [0.0,1.0) from // the source in the context or the shared global source.
[ "Float64", "returns", "as", "a", "float64", "a", "pseudo", "-", "random", "number", "in", "[", "0", ".", "0", "1", ".", "0", ")", "from", "the", "source", "in", "the", "context", "or", "the", "shared", "global", "source", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/rand/mathrand/impl.go#L211-L216
8,035
luci/luci-go
common/data/rand/mathrand/impl.go
Float32
func (l *Locking) Float32() (v float32) { l.Lock() v = l.R.Float32() l.Unlock() return }
go
func (l *Locking) Float32() (v float32) { l.Lock() v = l.R.Float32() l.Unlock() return }
[ "func", "(", "l", "*", "Locking", ")", "Float32", "(", ")", "(", "v", "float32", ")", "{", "l", ".", "Lock", "(", ")", "\n", "v", "=", "l", ".", "R", ".", "Float32", "(", ")", "\n", "l", ".", "Unlock", "(", ")", "\n", "return", "\n", "}" ]
// Float32 returns, as a float32, a pseudo-random number in [0.0,1.0) from // the source in the context or the shared global source.
[ "Float32", "returns", "as", "a", "float32", "a", "pseudo", "-", "random", "number", "in", "[", "0", ".", "0", "1", ".", "0", ")", "from", "the", "source", "in", "the", "context", "or", "the", "shared", "global", "source", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/rand/mathrand/impl.go#L220-L225
8,036
luci/luci-go
common/data/rand/mathrand/impl.go
Perm
func (l *Locking) Perm(n int) (v []int) { l.Lock() v = l.R.Perm(n) l.Unlock() return }
go
func (l *Locking) Perm(n int) (v []int) { l.Lock() v = l.R.Perm(n) l.Unlock() return }
[ "func", "(", "l", "*", "Locking", ")", "Perm", "(", "n", "int", ")", "(", "v", "[", "]", "int", ")", "{", "l", ".", "Lock", "(", ")", "\n", "v", "=", "l", ".", "R", ".", "Perm", "(", "n", ")", "\n", "l", ".", "Unlock", "(", ")", "\n", "return", "\n", "}" ]
// Perm returns, as a slice of n ints, a pseudo-random permutation of the // integers [0,n) from the source in the context or the shared global source.
[ "Perm", "returns", "as", "a", "slice", "of", "n", "ints", "a", "pseudo", "-", "random", "permutation", "of", "the", "integers", "[", "0", "n", ")", "from", "the", "source", "in", "the", "context", "or", "the", "shared", "global", "source", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/rand/mathrand/impl.go#L229-L234
8,037
luci/luci-go
mp/cmd/snapshot/main.go
getService
func getService(c context.Context) *compute.Service { return c.Value(&key).(*compute.Service) }
go
func getService(c context.Context) *compute.Service { return c.Value(&key).(*compute.Service) }
[ "func", "getService", "(", "c", "context", ".", "Context", ")", "*", "compute", ".", "Service", "{", "return", "c", ".", "Value", "(", "&", "key", ")", ".", "(", "*", "compute", ".", "Service", ")", "\n", "}" ]
// getService retrieves the GCE API service embedded in the given context.
[ "getService", "retrieves", "the", "GCE", "API", "service", "embedded", "in", "the", "given", "context", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mp/cmd/snapshot/main.go#L38-L40
8,038
luci/luci-go
mp/cmd/snapshot/main.go
Initialize
func (b *cmdRunBase) Initialize() { opts := chromeinfra.DefaultAuthOptions() opts.Scopes = []string{"https://www.googleapis.com/auth/compute"} b.authFlags.Register(b.GetFlags(), opts) }
go
func (b *cmdRunBase) Initialize() { opts := chromeinfra.DefaultAuthOptions() opts.Scopes = []string{"https://www.googleapis.com/auth/compute"} b.authFlags.Register(b.GetFlags(), opts) }
[ "func", "(", "b", "*", "cmdRunBase", ")", "Initialize", "(", ")", "{", "opts", ":=", "chromeinfra", ".", "DefaultAuthOptions", "(", ")", "\n", "opts", ".", "Scopes", "=", "[", "]", "string", "{", "\"", "\"", "}", "\n", "b", ".", "authFlags", ".", "Register", "(", "b", ".", "GetFlags", "(", ")", ",", "opts", ")", "\n", "}" ]
// Initialize registers common flags.
[ "Initialize", "registers", "common", "flags", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mp/cmd/snapshot/main.go#L50-L54
8,039
luci/luci-go
mp/cmd/snapshot/main.go
ModifyContext
func (b *cmdRunBase) ModifyContext(c context.Context) context.Context { c = logging.SetLevel(gologger.StdConfig.Use(c), logging.Debug) opts, err := b.authFlags.Options() if err != nil { logging.Errorf(c, "%s", err.Error()) panic("failed to get auth options") } http, err := auth.NewAuthenticator(c, auth.OptionalLogin, opts).Client() if err != nil { logging.Errorf(c, "%s", err.Error()) panic("failed to get authenticator") } srv, err := compute.New(http) if err != nil { logging.Errorf(c, "%s", err.Error()) panic("failed to get GCE API service") } return context.WithValue(c, &key, srv) }
go
func (b *cmdRunBase) ModifyContext(c context.Context) context.Context { c = logging.SetLevel(gologger.StdConfig.Use(c), logging.Debug) opts, err := b.authFlags.Options() if err != nil { logging.Errorf(c, "%s", err.Error()) panic("failed to get auth options") } http, err := auth.NewAuthenticator(c, auth.OptionalLogin, opts).Client() if err != nil { logging.Errorf(c, "%s", err.Error()) panic("failed to get authenticator") } srv, err := compute.New(http) if err != nil { logging.Errorf(c, "%s", err.Error()) panic("failed to get GCE API service") } return context.WithValue(c, &key, srv) }
[ "func", "(", "b", "*", "cmdRunBase", ")", "ModifyContext", "(", "c", "context", ".", "Context", ")", "context", ".", "Context", "{", "c", "=", "logging", ".", "SetLevel", "(", "gologger", ".", "StdConfig", ".", "Use", "(", "c", ")", ",", "logging", ".", "Debug", ")", "\n", "opts", ",", "err", ":=", "b", ".", "authFlags", ".", "Options", "(", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "Errorf", "(", "c", ",", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "http", ",", "err", ":=", "auth", ".", "NewAuthenticator", "(", "c", ",", "auth", ".", "OptionalLogin", ",", "opts", ")", ".", "Client", "(", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "Errorf", "(", "c", ",", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "srv", ",", "err", ":=", "compute", ".", "New", "(", "http", ")", "\n", "if", "err", "!=", "nil", "{", "logging", ".", "Errorf", "(", "c", ",", "\"", "\"", ",", "err", ".", "Error", "(", ")", ")", "\n", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "context", ".", "WithValue", "(", "c", ",", "&", "key", ",", "srv", ")", "\n", "}" ]
// ModifyContext returns a new context. // Configures logging and embeds the GCE API service. // Implements cli.ContextModificator.
[ "ModifyContext", "returns", "a", "new", "context", ".", "Configures", "logging", "and", "embeds", "the", "GCE", "API", "service", ".", "Implements", "cli", ".", "ContextModificator", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mp/cmd/snapshot/main.go#L59-L77
8,040
luci/luci-go
mp/cmd/snapshot/main.go
createService
func createService(c context.Context, opts auth.Options) (*compute.Service, error) { http, err := auth.NewAuthenticator(c, auth.OptionalLogin, opts).Client() if err != nil { return nil, err } service, err := compute.New(http) if err != nil { return nil, err } return service, nil }
go
func createService(c context.Context, opts auth.Options) (*compute.Service, error) { http, err := auth.NewAuthenticator(c, auth.OptionalLogin, opts).Client() if err != nil { return nil, err } service, err := compute.New(http) if err != nil { return nil, err } return service, nil }
[ "func", "createService", "(", "c", "context", ".", "Context", ",", "opts", "auth", ".", "Options", ")", "(", "*", "compute", ".", "Service", ",", "error", ")", "{", "http", ",", "err", ":=", "auth", ".", "NewAuthenticator", "(", "c", ",", "auth", ".", "OptionalLogin", ",", "opts", ")", ".", "Client", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "service", ",", "err", ":=", "compute", ".", "New", "(", "http", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "service", ",", "nil", "\n", "}" ]
// createService returns a new Compute Engine API service.
[ "createService", "returns", "a", "new", "Compute", "Engine", "API", "service", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mp/cmd/snapshot/main.go#L80-L90
8,041
luci/luci-go
mp/cmd/snapshot/main.go
New
func New() *cli.Application { return &cli.Application{ Name: "snapshot", Title: "Machine Provider disk snapshot tool", Commands: []*subcommands.Command{ subcommands.CmdHelp, getCreateSnapshotCmd(), }, } }
go
func New() *cli.Application { return &cli.Application{ Name: "snapshot", Title: "Machine Provider disk snapshot tool", Commands: []*subcommands.Command{ subcommands.CmdHelp, getCreateSnapshotCmd(), }, } }
[ "func", "New", "(", ")", "*", "cli", ".", "Application", "{", "return", "&", "cli", ".", "Application", "{", "Name", ":", "\"", "\"", ",", "Title", ":", "\"", "\"", ",", "Commands", ":", "[", "]", "*", "subcommands", ".", "Command", "{", "subcommands", ".", "CmdHelp", ",", "getCreateSnapshotCmd", "(", ")", ",", "}", ",", "}", "\n", "}" ]
// New returns a new snapshot application.
[ "New", "returns", "a", "new", "snapshot", "application", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/mp/cmd/snapshot/main.go#L93-L102
8,042
luci/luci-go
milo/common/pubsub.go
withClientFactory
func withClientFactory(c context.Context, fac pubsubClientFactory) context.Context { return context.WithValue(c, &pubsubClientFactoryKey, fac) }
go
func withClientFactory(c context.Context, fac pubsubClientFactory) context.Context { return context.WithValue(c, &pubsubClientFactoryKey, fac) }
[ "func", "withClientFactory", "(", "c", "context", ".", "Context", ",", "fac", "pubsubClientFactory", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "c", ",", "&", "pubsubClientFactoryKey", ",", "fac", ")", "\n", "}" ]
// withClientFactory returns a context with a given pubsub client factory.
[ "withClientFactory", "returns", "a", "context", "with", "a", "given", "pubsub", "client", "factory", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/pubsub.go#L101-L103
8,043
luci/luci-go
milo/common/pubsub.go
ensureBuildbucketSubscribed
func ensureBuildbucketSubscribed(c context.Context, projectID string) error { topicID := "builds" // Check the buildbucket project to see if the topic exists first. bbClient, err := newPubSubClient(c, projectID) if err != nil { return err } topic, err := bbClient.getTopic(c, topicID) switch err { case errNotExist: return errors.Annotate(err, "%s does not exist", topicID).Err() case nil: // continue default: if strings.Contains(err.Error(), "PermissionDenied") { URL := "https://console.cloud.google.com/iam-admin/iam/project?project=" + projectID acct, serr := info.ServiceAccount(c) if serr != nil { acct = fmt.Sprintf("Unknown: %s", serr.Error()) } // The documentation is incorrect. We need Editor permission because // the Subscriber permission does NOT permit attaching subscriptions to // topics or to view topics. logging.WithError(err).Errorf( c, "please go to %s and add %s as a Pub/Sub Editor", URL, acct) } else { logging.WithError(err).Errorf(c, "could not check topic %#v", topic) } return err } // Now check to see if the subscription already exists. miloClient, err := newPubSubClient(c, info.AppID(c)) if err != nil { return err } sub, err := miloClient.getSubscription(c, "buildbucket") switch err { case errNotExist: // continue case nil: logging.Infof(c, "subscription %#v exists, no need to update", sub) return nil default: logging.WithError(err).Errorf(c, "could not check subscription %#v", sub) return err } // Get the pubsub module of our app. We do not want to use info.ModuleHostname() // because it returns a version pinned hostname instead of the default route. pubsubModuleHost := "pubsub." + info.DefaultVersionHostname(c) // No subscription exists, attach a new subscription to the existing topic. endpointURL := url.URL{ Scheme: "https", Host: pubsubModuleHost, Path: "/_ah/push-handlers/buildbucket", } subConfig := pubsub.SubscriptionConfig{ Topic: topic, PushConfig: pubsub.PushConfig{Endpoint: endpointURL.String()}, AckDeadline: time.Minute * 10, } newSub, err := miloClient.createSubscription(c, "buildbucket", subConfig) if err != nil { return errors.Annotate(err, "could not create subscription %#v", sub).Err() } // Success! logging.Infof(c, "successfully created subscription %#v", newSub) return nil }
go
func ensureBuildbucketSubscribed(c context.Context, projectID string) error { topicID := "builds" // Check the buildbucket project to see if the topic exists first. bbClient, err := newPubSubClient(c, projectID) if err != nil { return err } topic, err := bbClient.getTopic(c, topicID) switch err { case errNotExist: return errors.Annotate(err, "%s does not exist", topicID).Err() case nil: // continue default: if strings.Contains(err.Error(), "PermissionDenied") { URL := "https://console.cloud.google.com/iam-admin/iam/project?project=" + projectID acct, serr := info.ServiceAccount(c) if serr != nil { acct = fmt.Sprintf("Unknown: %s", serr.Error()) } // The documentation is incorrect. We need Editor permission because // the Subscriber permission does NOT permit attaching subscriptions to // topics or to view topics. logging.WithError(err).Errorf( c, "please go to %s and add %s as a Pub/Sub Editor", URL, acct) } else { logging.WithError(err).Errorf(c, "could not check topic %#v", topic) } return err } // Now check to see if the subscription already exists. miloClient, err := newPubSubClient(c, info.AppID(c)) if err != nil { return err } sub, err := miloClient.getSubscription(c, "buildbucket") switch err { case errNotExist: // continue case nil: logging.Infof(c, "subscription %#v exists, no need to update", sub) return nil default: logging.WithError(err).Errorf(c, "could not check subscription %#v", sub) return err } // Get the pubsub module of our app. We do not want to use info.ModuleHostname() // because it returns a version pinned hostname instead of the default route. pubsubModuleHost := "pubsub." + info.DefaultVersionHostname(c) // No subscription exists, attach a new subscription to the existing topic. endpointURL := url.URL{ Scheme: "https", Host: pubsubModuleHost, Path: "/_ah/push-handlers/buildbucket", } subConfig := pubsub.SubscriptionConfig{ Topic: topic, PushConfig: pubsub.PushConfig{Endpoint: endpointURL.String()}, AckDeadline: time.Minute * 10, } newSub, err := miloClient.createSubscription(c, "buildbucket", subConfig) if err != nil { return errors.Annotate(err, "could not create subscription %#v", sub).Err() } // Success! logging.Infof(c, "successfully created subscription %#v", newSub) return nil }
[ "func", "ensureBuildbucketSubscribed", "(", "c", "context", ".", "Context", ",", "projectID", "string", ")", "error", "{", "topicID", ":=", "\"", "\"", "\n", "// Check the buildbucket project to see if the topic exists first.", "bbClient", ",", "err", ":=", "newPubSubClient", "(", "c", ",", "projectID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "topic", ",", "err", ":=", "bbClient", ".", "getTopic", "(", "c", ",", "topicID", ")", "\n", "switch", "err", "{", "case", "errNotExist", ":", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "topicID", ")", ".", "Err", "(", ")", "\n", "case", "nil", ":", "// continue", "default", ":", "if", "strings", ".", "Contains", "(", "err", ".", "Error", "(", ")", ",", "\"", "\"", ")", "{", "URL", ":=", "\"", "\"", "+", "projectID", "\n", "acct", ",", "serr", ":=", "info", ".", "ServiceAccount", "(", "c", ")", "\n", "if", "serr", "!=", "nil", "{", "acct", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "serr", ".", "Error", "(", ")", ")", "\n", "}", "\n", "// The documentation is incorrect. We need Editor permission because", "// the Subscriber permission does NOT permit attaching subscriptions to", "// topics or to view topics.", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ",", "URL", ",", "acct", ")", "\n", "}", "else", "{", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ",", "topic", ")", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "// Now check to see if the subscription already exists.", "miloClient", ",", "err", ":=", "newPubSubClient", "(", "c", ",", "info", ".", "AppID", "(", "c", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "sub", ",", "err", ":=", "miloClient", ".", "getSubscription", "(", "c", ",", "\"", "\"", ")", "\n", "switch", "err", "{", "case", "errNotExist", ":", "// continue", "case", "nil", ":", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "sub", ")", "\n", "return", "nil", "\n", "default", ":", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ",", "sub", ")", "\n", "return", "err", "\n", "}", "\n", "// Get the pubsub module of our app. We do not want to use info.ModuleHostname()", "// because it returns a version pinned hostname instead of the default route.", "pubsubModuleHost", ":=", "\"", "\"", "+", "info", ".", "DefaultVersionHostname", "(", "c", ")", "\n\n", "// No subscription exists, attach a new subscription to the existing topic.", "endpointURL", ":=", "url", ".", "URL", "{", "Scheme", ":", "\"", "\"", ",", "Host", ":", "pubsubModuleHost", ",", "Path", ":", "\"", "\"", ",", "}", "\n", "subConfig", ":=", "pubsub", ".", "SubscriptionConfig", "{", "Topic", ":", "topic", ",", "PushConfig", ":", "pubsub", ".", "PushConfig", "{", "Endpoint", ":", "endpointURL", ".", "String", "(", ")", "}", ",", "AckDeadline", ":", "time", ".", "Minute", "*", "10", ",", "}", "\n", "newSub", ",", "err", ":=", "miloClient", ".", "createSubscription", "(", "c", ",", "\"", "\"", ",", "subConfig", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "sub", ")", ".", "Err", "(", ")", "\n", "}", "\n", "// Success!", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "newSub", ")", "\n", "return", "nil", "\n", "}" ]
// ensureBuildbucketSubscribedis called by a cron job and ensures that the Milo // instance is properly subscribed to the buildbucket subscription endpoint.
[ "ensureBuildbucketSubscribedis", "called", "by", "a", "cron", "job", "and", "ensures", "that", "the", "Milo", "instance", "is", "properly", "subscribed", "to", "the", "buildbucket", "subscription", "endpoint", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/common/pubsub.go#L126-L194
8,044
luci/luci-go
cipd/appengine/impl/admin/acl.go
checkAdminPrelude
func checkAdminPrelude(c context.Context, method string, req proto.Message) (context.Context, error) { switch yep, err := auth.IsMember(c, AdminGroup); { case err != nil: logging.WithError(err).Errorf(c, "IsMember(%q) failed", AdminGroup) return nil, status.Errorf(codes.Internal, "failed to check ACL") case !yep: logging.Warningf(c, "Denying access to %q for %q, not in %q group", method, auth.CurrentIdentity(c), AdminGroup) return nil, status.Errorf(codes.PermissionDenied, "not allowed") } logging.Infof(c, "Admin %q is calling %q", auth.CurrentIdentity(c), method) return c, nil }
go
func checkAdminPrelude(c context.Context, method string, req proto.Message) (context.Context, error) { switch yep, err := auth.IsMember(c, AdminGroup); { case err != nil: logging.WithError(err).Errorf(c, "IsMember(%q) failed", AdminGroup) return nil, status.Errorf(codes.Internal, "failed to check ACL") case !yep: logging.Warningf(c, "Denying access to %q for %q, not in %q group", method, auth.CurrentIdentity(c), AdminGroup) return nil, status.Errorf(codes.PermissionDenied, "not allowed") } logging.Infof(c, "Admin %q is calling %q", auth.CurrentIdentity(c), method) return c, nil }
[ "func", "checkAdminPrelude", "(", "c", "context", ".", "Context", ",", "method", "string", ",", "req", "proto", ".", "Message", ")", "(", "context", ".", "Context", ",", "error", ")", "{", "switch", "yep", ",", "err", ":=", "auth", ".", "IsMember", "(", "c", ",", "AdminGroup", ")", ";", "{", "case", "err", "!=", "nil", ":", "logging", ".", "WithError", "(", "err", ")", ".", "Errorf", "(", "c", ",", "\"", "\"", ",", "AdminGroup", ")", "\n", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "Internal", ",", "\"", "\"", ")", "\n", "case", "!", "yep", ":", "logging", ".", "Warningf", "(", "c", ",", "\"", "\"", ",", "method", ",", "auth", ".", "CurrentIdentity", "(", "c", ")", ",", "AdminGroup", ")", "\n", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "PermissionDenied", ",", "\"", "\"", ")", "\n", "}", "\n", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "auth", ".", "CurrentIdentity", "(", "c", ")", ",", "method", ")", "\n", "return", "c", ",", "nil", "\n", "}" ]
// checkAdminPrelude is called before each RPC to check the caller is in // "administrators" group.
[ "checkAdminPrelude", "is", "called", "before", "each", "RPC", "to", "check", "the", "caller", "is", "in", "administrators", "group", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/admin/acl.go#L47-L58
8,045
luci/luci-go
gce/api/projects/v1/config.go
Validate
func (cfg *Config) Validate(c *validation.Context) { if cfg.GetProject() == "" { c.Errorf("project is required") } if cfg.GetRevision() != "" { c.Errorf("revision must not be specified") } }
go
func (cfg *Config) Validate(c *validation.Context) { if cfg.GetProject() == "" { c.Errorf("project is required") } if cfg.GetRevision() != "" { c.Errorf("revision must not be specified") } }
[ "func", "(", "cfg", "*", "Config", ")", "Validate", "(", "c", "*", "validation", ".", "Context", ")", "{", "if", "cfg", ".", "GetProject", "(", ")", "==", "\"", "\"", "{", "c", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "cfg", ".", "GetRevision", "(", ")", "!=", "\"", "\"", "{", "c", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// Validate validates this config.
[ "Validate", "validates", "this", "config", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/api/projects/v1/config.go#L41-L48
8,046
luci/luci-go
cipd/appengine/impl/admin/marked_tags.go
queryMarkedTags
func queryMarkedTags(job mapper.JobID) *datastore.Query { return datastore.NewQuery("mapper.MarkedTag").Eq("Job", job) }
go
func queryMarkedTags(job mapper.JobID) *datastore.Query { return datastore.NewQuery("mapper.MarkedTag").Eq("Job", job) }
[ "func", "queryMarkedTags", "(", "job", "mapper", ".", "JobID", ")", "*", "datastore", ".", "Query", "{", "return", "datastore", ".", "NewQuery", "(", "\"", "\"", ")", ".", "Eq", "(", "\"", "\"", ",", "job", ")", "\n", "}" ]
// queryMarkedTags returns a query for markedTags entities produced by a job.
[ "queryMarkedTags", "returns", "a", "query", "for", "markedTags", "entities", "produced", "by", "a", "job", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/admin/marked_tags.go#L67-L69
8,047
luci/luci-go
cipd/appengine/impl/admin/marked_tags.go
visitAndMarkTags
func visitAndMarkTags(c context.Context, job mapper.JobID, keys []*datastore.Key, cb func(*model.Tag) string) error { var marked []*markedTag err := multiGetTags(c, keys, func(key *datastore.Key, tag *model.Tag) error { if why := cb(tag); why != "" { mt := &markedTag{ Job: job, Key: key, Tag: tag.Tag, Why: why, } mt.genID() marked = append(marked, mt) } return nil }) if err != nil { return err } if err := datastore.Put(c, marked); err != nil { return errors.Annotate(err, "failed to store %d markedTag(s)", len(marked)).Tag(transient.Tag).Err() } return nil }
go
func visitAndMarkTags(c context.Context, job mapper.JobID, keys []*datastore.Key, cb func(*model.Tag) string) error { var marked []*markedTag err := multiGetTags(c, keys, func(key *datastore.Key, tag *model.Tag) error { if why := cb(tag); why != "" { mt := &markedTag{ Job: job, Key: key, Tag: tag.Tag, Why: why, } mt.genID() marked = append(marked, mt) } return nil }) if err != nil { return err } if err := datastore.Put(c, marked); err != nil { return errors.Annotate(err, "failed to store %d markedTag(s)", len(marked)).Tag(transient.Tag).Err() } return nil }
[ "func", "visitAndMarkTags", "(", "c", "context", ".", "Context", ",", "job", "mapper", ".", "JobID", ",", "keys", "[", "]", "*", "datastore", ".", "Key", ",", "cb", "func", "(", "*", "model", ".", "Tag", ")", "string", ")", "error", "{", "var", "marked", "[", "]", "*", "markedTag", "\n", "err", ":=", "multiGetTags", "(", "c", ",", "keys", ",", "func", "(", "key", "*", "datastore", ".", "Key", ",", "tag", "*", "model", ".", "Tag", ")", "error", "{", "if", "why", ":=", "cb", "(", "tag", ")", ";", "why", "!=", "\"", "\"", "{", "mt", ":=", "&", "markedTag", "{", "Job", ":", "job", ",", "Key", ":", "key", ",", "Tag", ":", "tag", ".", "Tag", ",", "Why", ":", "why", ",", "}", "\n", "mt", ".", "genID", "(", ")", "\n", "marked", "=", "append", "(", "marked", ",", "mt", ")", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "datastore", ".", "Put", "(", "c", ",", "marked", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "len", "(", "marked", ")", ")", ".", "Tag", "(", "transient", ".", "Tag", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// visitAndMarkTags fetches Tag entities given their keys and passes them to // the callback, which may choose to mark a tag by returning non-empty string // with the human-readable reason why the tag was marked. // // Such marked tags are then stored in the datastore and later can be queried.
[ "visitAndMarkTags", "fetches", "Tag", "entities", "given", "their", "keys", "and", "passes", "them", "to", "the", "callback", "which", "may", "choose", "to", "mark", "a", "tag", "by", "returning", "non", "-", "empty", "string", "with", "the", "human", "-", "readable", "reason", "why", "the", "tag", "was", "marked", ".", "Such", "marked", "tags", "are", "then", "stored", "in", "the", "datastore", "and", "later", "can", "be", "queried", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/admin/marked_tags.go#L118-L141
8,048
luci/luci-go
buildbucket/deprecated/annotations.go
convertSubsteps
func (p *stepConverter) convertSubsteps(c context.Context, bbSteps *[]*pb.Step, annSubsteps []*annotpb.Step_Substep, stepPrefix string) ([]*pb.Step, error) { bbSubsteps := make([]*pb.Step, 0, len(annSubsteps)) for _, annSubstep := range annSubsteps { annStep := annSubstep.GetStep() if annStep == nil { return nil, errors.Reason("unexpected non-Step substep %v", annSubstep).Err() } bbSubstep, err := p.convertSteps(c, bbSteps, annStep, stepPrefix) if err != nil { return nil, err } bbSubsteps = append(bbSubsteps, bbSubstep) } return bbSubsteps, nil }
go
func (p *stepConverter) convertSubsteps(c context.Context, bbSteps *[]*pb.Step, annSubsteps []*annotpb.Step_Substep, stepPrefix string) ([]*pb.Step, error) { bbSubsteps := make([]*pb.Step, 0, len(annSubsteps)) for _, annSubstep := range annSubsteps { annStep := annSubstep.GetStep() if annStep == nil { return nil, errors.Reason("unexpected non-Step substep %v", annSubstep).Err() } bbSubstep, err := p.convertSteps(c, bbSteps, annStep, stepPrefix) if err != nil { return nil, err } bbSubsteps = append(bbSubsteps, bbSubstep) } return bbSubsteps, nil }
[ "func", "(", "p", "*", "stepConverter", ")", "convertSubsteps", "(", "c", "context", ".", "Context", ",", "bbSteps", "*", "[", "]", "*", "pb", ".", "Step", ",", "annSubsteps", "[", "]", "*", "annotpb", ".", "Step_Substep", ",", "stepPrefix", "string", ")", "(", "[", "]", "*", "pb", ".", "Step", ",", "error", ")", "{", "bbSubsteps", ":=", "make", "(", "[", "]", "*", "pb", ".", "Step", ",", "0", ",", "len", "(", "annSubsteps", ")", ")", "\n", "for", "_", ",", "annSubstep", ":=", "range", "annSubsteps", "{", "annStep", ":=", "annSubstep", ".", "GetStep", "(", ")", "\n", "if", "annStep", "==", "nil", "{", "return", "nil", ",", "errors", ".", "Reason", "(", "\"", "\"", ",", "annSubstep", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "bbSubstep", ",", "err", ":=", "p", ".", "convertSteps", "(", "c", ",", "bbSteps", ",", "annStep", ",", "stepPrefix", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "bbSubsteps", "=", "append", "(", "bbSubsteps", ",", "bbSubstep", ")", "\n", "}", "\n\n", "return", "bbSubsteps", ",", "nil", "\n", "}" ]
// convertSubsteps converts substeps, which we expect to be Steps, not Logdog // annotation streams.
[ "convertSubsteps", "converts", "substeps", "which", "we", "expect", "to", "be", "Steps", "not", "Logdog", "annotation", "streams", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/deprecated/annotations.go#L87-L104
8,049
luci/luci-go
appengine/tq/tq.go
RegisterTask
func (d *Dispatcher) RegisterTask(prototype proto.Message, cb Handler, queue string, opts *taskqueue.RetryOptions) { if queue == "" { queue = "default" // default GAE task queue name, always exists } name := proto.MessageName(prototype) if name == "" { panic(fmt.Sprintf("unregistered proto message type %T", prototype)) } d.mu.Lock() defer d.mu.Unlock() if _, ok := d.handlers[name]; ok { panic(fmt.Sprintf("handler for %q has already been registered", name)) } if d.handlers == nil { d.handlers = make(map[string]handler) } d.handlers[name] = handler{ cb: cb, typeName: name, queue: queue, retryOpts: opts, } }
go
func (d *Dispatcher) RegisterTask(prototype proto.Message, cb Handler, queue string, opts *taskqueue.RetryOptions) { if queue == "" { queue = "default" // default GAE task queue name, always exists } name := proto.MessageName(prototype) if name == "" { panic(fmt.Sprintf("unregistered proto message type %T", prototype)) } d.mu.Lock() defer d.mu.Unlock() if _, ok := d.handlers[name]; ok { panic(fmt.Sprintf("handler for %q has already been registered", name)) } if d.handlers == nil { d.handlers = make(map[string]handler) } d.handlers[name] = handler{ cb: cb, typeName: name, queue: queue, retryOpts: opts, } }
[ "func", "(", "d", "*", "Dispatcher", ")", "RegisterTask", "(", "prototype", "proto", ".", "Message", ",", "cb", "Handler", ",", "queue", "string", ",", "opts", "*", "taskqueue", ".", "RetryOptions", ")", "{", "if", "queue", "==", "\"", "\"", "{", "queue", "=", "\"", "\"", "// default GAE task queue name, always exists", "\n", "}", "\n\n", "name", ":=", "proto", ".", "MessageName", "(", "prototype", ")", "\n", "if", "name", "==", "\"", "\"", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "prototype", ")", ")", "\n", "}", "\n\n", "d", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "d", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "if", "_", ",", "ok", ":=", "d", ".", "handlers", "[", "name", "]", ";", "ok", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "name", ")", ")", "\n", "}", "\n\n", "if", "d", ".", "handlers", "==", "nil", "{", "d", ".", "handlers", "=", "make", "(", "map", "[", "string", "]", "handler", ")", "\n", "}", "\n\n", "d", ".", "handlers", "[", "name", "]", "=", "handler", "{", "cb", ":", "cb", ",", "typeName", ":", "name", ",", "queue", ":", "queue", ",", "retryOpts", ":", "opts", ",", "}", "\n", "}" ]
// RegisterTask tells the dispatcher that tasks of given proto type should be // handled by the given handler and routed through the given task queue. // // 'prototype' should be a pointer to some concrete proto message. It will be // used only for its type signature. // // Intended to be called during process startup. Panics if such message has // already been registered.
[ "RegisterTask", "tells", "the", "dispatcher", "that", "tasks", "of", "given", "proto", "type", "should", "be", "handled", "by", "the", "given", "handler", "and", "routed", "through", "the", "given", "task", "queue", ".", "prototype", "should", "be", "a", "pointer", "to", "some", "concrete", "proto", "message", ".", "It", "will", "be", "used", "only", "for", "its", "type", "signature", ".", "Intended", "to", "be", "called", "during", "process", "startup", ".", "Panics", "if", "such", "message", "has", "already", "been", "registered", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/tq/tq.go#L194-L221
8,050
luci/luci-go
appengine/tq/tq.go
InstallRoutes
func (d *Dispatcher) InstallRoutes(r *router.Router, mw router.MiddlewareChain) { queues := stringset.New(0) d.mu.RLock() for _, h := range d.handlers { queues.Add(h.queue) } d.mu.RUnlock() for _, q := range queues.ToSlice() { r.POST( fmt.Sprintf("%s%s/*title", d.baseURL(), q), mw.Extend(gaemiddleware.RequireTaskQueue(q)), d.processHTTPRequest) } }
go
func (d *Dispatcher) InstallRoutes(r *router.Router, mw router.MiddlewareChain) { queues := stringset.New(0) d.mu.RLock() for _, h := range d.handlers { queues.Add(h.queue) } d.mu.RUnlock() for _, q := range queues.ToSlice() { r.POST( fmt.Sprintf("%s%s/*title", d.baseURL(), q), mw.Extend(gaemiddleware.RequireTaskQueue(q)), d.processHTTPRequest) } }
[ "func", "(", "d", "*", "Dispatcher", ")", "InstallRoutes", "(", "r", "*", "router", ".", "Router", ",", "mw", "router", ".", "MiddlewareChain", ")", "{", "queues", ":=", "stringset", ".", "New", "(", "0", ")", "\n\n", "d", ".", "mu", ".", "RLock", "(", ")", "\n", "for", "_", ",", "h", ":=", "range", "d", ".", "handlers", "{", "queues", ".", "Add", "(", "h", ".", "queue", ")", "\n", "}", "\n", "d", ".", "mu", ".", "RUnlock", "(", ")", "\n\n", "for", "_", ",", "q", ":=", "range", "queues", ".", "ToSlice", "(", ")", "{", "r", ".", "POST", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "d", ".", "baseURL", "(", ")", ",", "q", ")", ",", "mw", ".", "Extend", "(", "gaemiddleware", ".", "RequireTaskQueue", "(", "q", ")", ")", ",", "d", ".", "processHTTPRequest", ")", "\n", "}", "\n", "}" ]
// InstallRoutes installs appropriate HTTP routes in the router. // // Must be called only after all task handlers are registered!
[ "InstallRoutes", "installs", "appropriate", "HTTP", "routes", "in", "the", "router", ".", "Must", "be", "called", "only", "after", "all", "task", "handlers", "are", "registered!" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/tq/tq.go#L347-L362
8,051
luci/luci-go
appengine/tq/tq.go
RequestHeaders
func RequestHeaders(c context.Context) (*taskqueue.RequestHeaders, error) { if hdr, ok := c.Value(&requestHeadersKey).(*taskqueue.RequestHeaders); ok { return hdr, nil } return nil, errOutsideHandler }
go
func RequestHeaders(c context.Context) (*taskqueue.RequestHeaders, error) { if hdr, ok := c.Value(&requestHeadersKey).(*taskqueue.RequestHeaders); ok { return hdr, nil } return nil, errOutsideHandler }
[ "func", "RequestHeaders", "(", "c", "context", ".", "Context", ")", "(", "*", "taskqueue", ".", "RequestHeaders", ",", "error", ")", "{", "if", "hdr", ",", "ok", ":=", "c", ".", "Value", "(", "&", "requestHeadersKey", ")", ".", "(", "*", "taskqueue", ".", "RequestHeaders", ")", ";", "ok", "{", "return", "hdr", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "errOutsideHandler", "\n", "}" ]
// RequestHeaders returns the special task-queue HTTP request headers for // the current task handler. // // Returns an error if called from outside of a task handler.
[ "RequestHeaders", "returns", "the", "special", "task", "-", "queue", "HTTP", "request", "headers", "for", "the", "current", "task", "handler", ".", "Returns", "an", "error", "if", "called", "from", "outside", "of", "a", "task", "handler", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/tq/tq.go#L379-L384
8,052
luci/luci-go
appengine/tq/tq.go
tqTask
func (d *Dispatcher) tqTask(task *Task) (*taskqueue.Task, string, error) { handler, err := d.handler(task.Payload) if err != nil { return nil, "", err } blob, err := serializePayload(task.Payload) if err != nil { return nil, "", err } title := handler.typeName if task.Title != "" { title = task.Title } retryOpts := handler.retryOpts if task.RetryOptions != nil { retryOpts = task.RetryOptions } return &taskqueue.Task{ Path: fmt.Sprintf("%s%s/%s", d.baseURL(), handler.queue, title), Name: task.Name(), Method: "POST", Payload: blob, ETA: task.ETA, Delay: task.Delay, RetryOptions: retryOpts, }, handler.queue, nil }
go
func (d *Dispatcher) tqTask(task *Task) (*taskqueue.Task, string, error) { handler, err := d.handler(task.Payload) if err != nil { return nil, "", err } blob, err := serializePayload(task.Payload) if err != nil { return nil, "", err } title := handler.typeName if task.Title != "" { title = task.Title } retryOpts := handler.retryOpts if task.RetryOptions != nil { retryOpts = task.RetryOptions } return &taskqueue.Task{ Path: fmt.Sprintf("%s%s/%s", d.baseURL(), handler.queue, title), Name: task.Name(), Method: "POST", Payload: blob, ETA: task.ETA, Delay: task.Delay, RetryOptions: retryOpts, }, handler.queue, nil }
[ "func", "(", "d", "*", "Dispatcher", ")", "tqTask", "(", "task", "*", "Task", ")", "(", "*", "taskqueue", ".", "Task", ",", "string", ",", "error", ")", "{", "handler", ",", "err", ":=", "d", ".", "handler", "(", "task", ".", "Payload", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"", "\"", ",", "err", "\n", "}", "\n\n", "blob", ",", "err", ":=", "serializePayload", "(", "task", ".", "Payload", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "\"", "\"", ",", "err", "\n", "}", "\n\n", "title", ":=", "handler", ".", "typeName", "\n", "if", "task", ".", "Title", "!=", "\"", "\"", "{", "title", "=", "task", ".", "Title", "\n", "}", "\n\n", "retryOpts", ":=", "handler", ".", "retryOpts", "\n", "if", "task", ".", "RetryOptions", "!=", "nil", "{", "retryOpts", "=", "task", ".", "RetryOptions", "\n", "}", "\n\n", "return", "&", "taskqueue", ".", "Task", "{", "Path", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "d", ".", "baseURL", "(", ")", ",", "handler", ".", "queue", ",", "title", ")", ",", "Name", ":", "task", ".", "Name", "(", ")", ",", "Method", ":", "\"", "\"", ",", "Payload", ":", "blob", ",", "ETA", ":", "task", ".", "ETA", ",", "Delay", ":", "task", ".", "Delay", ",", "RetryOptions", ":", "retryOpts", ",", "}", ",", "handler", ".", "queue", ",", "nil", "\n", "}" ]
// tqTask constructs task queue task struct.
[ "tqTask", "constructs", "task", "queue", "task", "struct", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/tq/tq.go#L396-L426
8,053
luci/luci-go
appengine/tq/tq.go
handler
func (d *Dispatcher) handler(payload proto.Message) (handler, error) { name := proto.MessageName(payload) d.mu.RLock() defer d.mu.RUnlock() handler, registered := d.handlers[name] if !registered { return handler, fmt.Errorf("handler for %q is not registered", name) } return handler, nil }
go
func (d *Dispatcher) handler(payload proto.Message) (handler, error) { name := proto.MessageName(payload) d.mu.RLock() defer d.mu.RUnlock() handler, registered := d.handlers[name] if !registered { return handler, fmt.Errorf("handler for %q is not registered", name) } return handler, nil }
[ "func", "(", "d", "*", "Dispatcher", ")", "handler", "(", "payload", "proto", ".", "Message", ")", "(", "handler", ",", "error", ")", "{", "name", ":=", "proto", ".", "MessageName", "(", "payload", ")", "\n\n", "d", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "d", ".", "mu", ".", "RUnlock", "(", ")", "\n\n", "handler", ",", "registered", ":=", "d", ".", "handlers", "[", "name", "]", "\n", "if", "!", "registered", "{", "return", "handler", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "return", "handler", ",", "nil", "\n", "}" ]
// handler returns a handler struct registered with Register.
[ "handler", "returns", "a", "handler", "struct", "registered", "with", "Register", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/tq/tq.go#L443-L454
8,054
luci/luci-go
luci_notify/api/config/notify.go
ShouldNotify
func (n *Notification) ShouldNotify(oldStatus, newStatus buildbucketpb.Status) bool { switch { case newStatus == buildbucketpb.Status_STATUS_UNSPECIFIED: panic("new status must always be valid") case n.OnSuccess && newStatus == buildbucketpb.Status_SUCCESS: case n.OnFailure && newStatus == buildbucketpb.Status_FAILURE: case n.OnChange && oldStatus != buildbucketpb.Status_STATUS_UNSPECIFIED && newStatus != oldStatus: case n.OnNewFailure && newStatus == buildbucketpb.Status_FAILURE && oldStatus != buildbucketpb.Status_FAILURE: default: return false } return true }
go
func (n *Notification) ShouldNotify(oldStatus, newStatus buildbucketpb.Status) bool { switch { case newStatus == buildbucketpb.Status_STATUS_UNSPECIFIED: panic("new status must always be valid") case n.OnSuccess && newStatus == buildbucketpb.Status_SUCCESS: case n.OnFailure && newStatus == buildbucketpb.Status_FAILURE: case n.OnChange && oldStatus != buildbucketpb.Status_STATUS_UNSPECIFIED && newStatus != oldStatus: case n.OnNewFailure && newStatus == buildbucketpb.Status_FAILURE && oldStatus != buildbucketpb.Status_FAILURE: default: return false } return true }
[ "func", "(", "n", "*", "Notification", ")", "ShouldNotify", "(", "oldStatus", ",", "newStatus", "buildbucketpb", ".", "Status", ")", "bool", "{", "switch", "{", "case", "newStatus", "==", "buildbucketpb", ".", "Status_STATUS_UNSPECIFIED", ":", "panic", "(", "\"", "\"", ")", "\n", "case", "n", ".", "OnSuccess", "&&", "newStatus", "==", "buildbucketpb", ".", "Status_SUCCESS", ":", "case", "n", ".", "OnFailure", "&&", "newStatus", "==", "buildbucketpb", ".", "Status_FAILURE", ":", "case", "n", ".", "OnChange", "&&", "oldStatus", "!=", "buildbucketpb", ".", "Status_STATUS_UNSPECIFIED", "&&", "newStatus", "!=", "oldStatus", ":", "case", "n", ".", "OnNewFailure", "&&", "newStatus", "==", "buildbucketpb", ".", "Status_FAILURE", "&&", "oldStatus", "!=", "buildbucketpb", ".", "Status_FAILURE", ":", "default", ":", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// ShouldNotify is the predicate function for whether a trigger's conditions have been met.
[ "ShouldNotify", "is", "the", "predicate", "function", "for", "whether", "a", "trigger", "s", "conditions", "have", "been", "met", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/api/config/notify.go#L22-L35
8,055
luci/luci-go
luci_notify/api/config/notify.go
Filter
func (n *Notifications) Filter(oldStatus, newStatus buildbucketpb.Status) Notifications { notifications := n.GetNotifications() filtered := make([]*Notification, 0, len(notifications)) for _, notification := range notifications { if notification.ShouldNotify(oldStatus, newStatus) { filtered = append(filtered, notification) } } return Notifications{Notifications: filtered} }
go
func (n *Notifications) Filter(oldStatus, newStatus buildbucketpb.Status) Notifications { notifications := n.GetNotifications() filtered := make([]*Notification, 0, len(notifications)) for _, notification := range notifications { if notification.ShouldNotify(oldStatus, newStatus) { filtered = append(filtered, notification) } } return Notifications{Notifications: filtered} }
[ "func", "(", "n", "*", "Notifications", ")", "Filter", "(", "oldStatus", ",", "newStatus", "buildbucketpb", ".", "Status", ")", "Notifications", "{", "notifications", ":=", "n", ".", "GetNotifications", "(", ")", "\n", "filtered", ":=", "make", "(", "[", "]", "*", "Notification", ",", "0", ",", "len", "(", "notifications", ")", ")", "\n", "for", "_", ",", "notification", ":=", "range", "notifications", "{", "if", "notification", ".", "ShouldNotify", "(", "oldStatus", ",", "newStatus", ")", "{", "filtered", "=", "append", "(", "filtered", ",", "notification", ")", "\n", "}", "\n", "}", "\n", "return", "Notifications", "{", "Notifications", ":", "filtered", "}", "\n", "}" ]
// Filter filters out Notification objects from Notifications by checking if we ShouldNotify // based on two build statuses.
[ "Filter", "filters", "out", "Notification", "objects", "from", "Notifications", "by", "checking", "if", "we", "ShouldNotify", "based", "on", "two", "build", "statuses", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/api/config/notify.go#L39-L48
8,056
luci/luci-go
config/server/cfgclient/backend/client/client.go
GetConfigInterface
func (be *Backend) GetConfigInterface(c context.Context, a backend.Authority) config.Interface { return be.Provider.GetConfigClient(c, a) }
go
func (be *Backend) GetConfigInterface(c context.Context, a backend.Authority) config.Interface { return be.Provider.GetConfigClient(c, a) }
[ "func", "(", "be", "*", "Backend", ")", "GetConfigInterface", "(", "c", "context", ".", "Context", ",", "a", "backend", ".", "Authority", ")", "config", ".", "Interface", "{", "return", "be", ".", "Provider", ".", "GetConfigClient", "(", "c", ",", "a", ")", "\n", "}" ]
// GetConfigInterface implements backend.B.
[ "GetConfigInterface", "implements", "backend", ".", "B", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/backend/client/client.go#L93-L95
8,057
luci/luci-go
config/server/cfgclient/backend/client/client.go
GetServiceURL
func (p *RemoteProvider) GetServiceURL() url.URL { u := url.URL{ Scheme: "https", Host: p.Host, Path: "/_ah/api/config/v1/", } if p.Insecure { u.Scheme = "http" } return u }
go
func (p *RemoteProvider) GetServiceURL() url.URL { u := url.URL{ Scheme: "https", Host: p.Host, Path: "/_ah/api/config/v1/", } if p.Insecure { u.Scheme = "http" } return u }
[ "func", "(", "p", "*", "RemoteProvider", ")", "GetServiceURL", "(", ")", "url", ".", "URL", "{", "u", ":=", "url", ".", "URL", "{", "Scheme", ":", "\"", "\"", ",", "Host", ":", "p", ".", "Host", ",", "Path", ":", "\"", "\"", ",", "}", "\n", "if", "p", ".", "Insecure", "{", "u", ".", "Scheme", "=", "\"", "\"", "\n", "}", "\n", "return", "u", "\n", "}" ]
// GetServiceURL implements Provider.
[ "GetServiceURL", "implements", "Provider", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/backend/client/client.go#L117-L127
8,058
luci/luci-go
config/server/cfgclient/backend/client/client.go
GetConfigClient
func (p *RemoteProvider) GetConfigClient(c context.Context, a backend.Authority) config.Interface { p.cacheLock.RLock() impl, ok := p.cache[a] p.cacheLock.RUnlock() if ok { return impl } p.cacheLock.Lock() defer p.cacheLock.Unlock() if impl, ok := p.cache[a]; ok { return impl } // Create our remote implementation. impl = remote.New(p.Host, p.Insecure, func(c context.Context) (*http.Client, error) { var opts []auth.RPCOption if a == backend.AsUser && p.testUserDelegationToken != "" { opts = append(opts, auth.WithDelegationToken(p.testUserDelegationToken)) } t, err := auth.GetRPCTransport(c, rpcAuthorityKind(a), opts...) if err != nil { return nil, err } return &http.Client{Transport: t}, nil }) if p.cache == nil { p.cache = make(map[backend.Authority]config.Interface, 3) } p.cache[a] = impl return impl }
go
func (p *RemoteProvider) GetConfigClient(c context.Context, a backend.Authority) config.Interface { p.cacheLock.RLock() impl, ok := p.cache[a] p.cacheLock.RUnlock() if ok { return impl } p.cacheLock.Lock() defer p.cacheLock.Unlock() if impl, ok := p.cache[a]; ok { return impl } // Create our remote implementation. impl = remote.New(p.Host, p.Insecure, func(c context.Context) (*http.Client, error) { var opts []auth.RPCOption if a == backend.AsUser && p.testUserDelegationToken != "" { opts = append(opts, auth.WithDelegationToken(p.testUserDelegationToken)) } t, err := auth.GetRPCTransport(c, rpcAuthorityKind(a), opts...) if err != nil { return nil, err } return &http.Client{Transport: t}, nil }) if p.cache == nil { p.cache = make(map[backend.Authority]config.Interface, 3) } p.cache[a] = impl return impl }
[ "func", "(", "p", "*", "RemoteProvider", ")", "GetConfigClient", "(", "c", "context", ".", "Context", ",", "a", "backend", ".", "Authority", ")", "config", ".", "Interface", "{", "p", ".", "cacheLock", ".", "RLock", "(", ")", "\n", "impl", ",", "ok", ":=", "p", ".", "cache", "[", "a", "]", "\n", "p", ".", "cacheLock", ".", "RUnlock", "(", ")", "\n", "if", "ok", "{", "return", "impl", "\n", "}", "\n\n", "p", ".", "cacheLock", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "cacheLock", ".", "Unlock", "(", ")", "\n\n", "if", "impl", ",", "ok", ":=", "p", ".", "cache", "[", "a", "]", ";", "ok", "{", "return", "impl", "\n", "}", "\n\n", "// Create our remote implementation.", "impl", "=", "remote", ".", "New", "(", "p", ".", "Host", ",", "p", ".", "Insecure", ",", "func", "(", "c", "context", ".", "Context", ")", "(", "*", "http", ".", "Client", ",", "error", ")", "{", "var", "opts", "[", "]", "auth", ".", "RPCOption", "\n", "if", "a", "==", "backend", ".", "AsUser", "&&", "p", ".", "testUserDelegationToken", "!=", "\"", "\"", "{", "opts", "=", "append", "(", "opts", ",", "auth", ".", "WithDelegationToken", "(", "p", ".", "testUserDelegationToken", ")", ")", "\n", "}", "\n", "t", ",", "err", ":=", "auth", ".", "GetRPCTransport", "(", "c", ",", "rpcAuthorityKind", "(", "a", ")", ",", "opts", "...", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "http", ".", "Client", "{", "Transport", ":", "t", "}", ",", "nil", "\n", "}", ")", "\n", "if", "p", ".", "cache", "==", "nil", "{", "p", ".", "cache", "=", "make", "(", "map", "[", "backend", ".", "Authority", "]", "config", ".", "Interface", ",", "3", ")", "\n", "}", "\n", "p", ".", "cache", "[", "a", "]", "=", "impl", "\n\n", "return", "impl", "\n", "}" ]
// GetConfigClient implements Provider.
[ "GetConfigClient", "implements", "Provider", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/backend/client/client.go#L130-L163
8,059
luci/luci-go
config/server/cfgclient/backend/client/client.go
rpcAuthorityKind
func rpcAuthorityKind(a backend.Authority) auth.RPCAuthorityKind { switch a { case backend.AsAnonymous: return auth.NoAuth case backend.AsService: return auth.AsSelf case backend.AsUser: return auth.AsUser default: panic(fmt.Errorf("unknown config Authority (%d)", a)) } }
go
func rpcAuthorityKind(a backend.Authority) auth.RPCAuthorityKind { switch a { case backend.AsAnonymous: return auth.NoAuth case backend.AsService: return auth.AsSelf case backend.AsUser: return auth.AsUser default: panic(fmt.Errorf("unknown config Authority (%d)", a)) } }
[ "func", "rpcAuthorityKind", "(", "a", "backend", ".", "Authority", ")", "auth", ".", "RPCAuthorityKind", "{", "switch", "a", "{", "case", "backend", ".", "AsAnonymous", ":", "return", "auth", ".", "NoAuth", "\n", "case", "backend", ".", "AsService", ":", "return", "auth", ".", "AsSelf", "\n", "case", "backend", ".", "AsUser", ":", "return", "auth", ".", "AsUser", "\n", "default", ":", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "a", ")", ")", "\n", "}", "\n", "}" ]
// rpcAuthorityKind returns the RPC authority associated with this authority // level.
[ "rpcAuthorityKind", "returns", "the", "RPC", "authority", "associated", "with", "this", "authority", "level", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/backend/client/client.go#L189-L200
8,060
luci/luci-go
grpc/grpcmon/client.go
reportClientRPCMetrics
func reportClientRPCMetrics(ctx context.Context, method string, err error, dur time.Duration) { code := 0 if err != nil { code = int(grpc.Code(err)) } grpcClientCount.Add(ctx, 1, method, code) grpcClientDuration.Add(ctx, float64(dur.Nanoseconds()/1e6), method, code) }
go
func reportClientRPCMetrics(ctx context.Context, method string, err error, dur time.Duration) { code := 0 if err != nil { code = int(grpc.Code(err)) } grpcClientCount.Add(ctx, 1, method, code) grpcClientDuration.Add(ctx, float64(dur.Nanoseconds()/1e6), method, code) }
[ "func", "reportClientRPCMetrics", "(", "ctx", "context", ".", "Context", ",", "method", "string", ",", "err", "error", ",", "dur", "time", ".", "Duration", ")", "{", "code", ":=", "0", "\n", "if", "err", "!=", "nil", "{", "code", "=", "int", "(", "grpc", ".", "Code", "(", "err", ")", ")", "\n", "}", "\n", "grpcClientCount", ".", "Add", "(", "ctx", ",", "1", ",", "method", ",", "code", ")", "\n", "grpcClientDuration", ".", "Add", "(", "ctx", ",", "float64", "(", "dur", ".", "Nanoseconds", "(", ")", "/", "1e6", ")", ",", "method", ",", "code", ")", "\n", "}" ]
// reportClientRPCMetrics sends metrics after RPC call has finished.
[ "reportClientRPCMetrics", "sends", "metrics", "after", "RPC", "call", "has", "finished", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/grpcmon/client.go#L73-L80
8,061
luci/luci-go
gce/appengine/rpc/config.go
Delete
func (*Config) Delete(c context.Context, req *config.DeleteRequest) (*empty.Empty, error) { if req.GetId() == "" { return nil, status.Errorf(codes.InvalidArgument, "ID is required") } if err := datastore.Delete(c, &model.Config{ID: req.Id}); err != nil { return nil, errors.Annotate(err, "failed to delete config").Err() } return &empty.Empty{}, nil }
go
func (*Config) Delete(c context.Context, req *config.DeleteRequest) (*empty.Empty, error) { if req.GetId() == "" { return nil, status.Errorf(codes.InvalidArgument, "ID is required") } if err := datastore.Delete(c, &model.Config{ID: req.Id}); err != nil { return nil, errors.Annotate(err, "failed to delete config").Err() } return &empty.Empty{}, nil }
[ "func", "(", "*", "Config", ")", "Delete", "(", "c", "context", ".", "Context", ",", "req", "*", "config", ".", "DeleteRequest", ")", "(", "*", "empty", ".", "Empty", ",", "error", ")", "{", "if", "req", ".", "GetId", "(", ")", "==", "\"", "\"", "{", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "err", ":=", "datastore", ".", "Delete", "(", "c", ",", "&", "model", ".", "Config", "{", "ID", ":", "req", ".", "Id", "}", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "&", "empty", ".", "Empty", "{", "}", ",", "nil", "\n", "}" ]
// Delete handles a request to delete a config. // For app-internal use only.
[ "Delete", "handles", "a", "request", "to", "delete", "a", "config", ".", "For", "app", "-", "internal", "use", "only", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/rpc/config.go#L41-L49
8,062
luci/luci-go
gce/appengine/rpc/config.go
Ensure
func (*Config) Ensure(c context.Context, req *config.EnsureRequest) (*config.Config, error) { if req.GetId() == "" { return nil, status.Errorf(codes.InvalidArgument, "ID is required") } cfg := &model.Config{ ID: req.Id, Config: *req.Config, } if err := datastore.Put(c, cfg); err != nil { return nil, errors.Annotate(err, "failed to store config").Err() } return &cfg.Config, nil }
go
func (*Config) Ensure(c context.Context, req *config.EnsureRequest) (*config.Config, error) { if req.GetId() == "" { return nil, status.Errorf(codes.InvalidArgument, "ID is required") } cfg := &model.Config{ ID: req.Id, Config: *req.Config, } if err := datastore.Put(c, cfg); err != nil { return nil, errors.Annotate(err, "failed to store config").Err() } return &cfg.Config, nil }
[ "func", "(", "*", "Config", ")", "Ensure", "(", "c", "context", ".", "Context", ",", "req", "*", "config", ".", "EnsureRequest", ")", "(", "*", "config", ".", "Config", ",", "error", ")", "{", "if", "req", ".", "GetId", "(", ")", "==", "\"", "\"", "{", "return", "nil", ",", "status", ".", "Errorf", "(", "codes", ".", "InvalidArgument", ",", "\"", "\"", ")", "\n", "}", "\n", "cfg", ":=", "&", "model", ".", "Config", "{", "ID", ":", "req", ".", "Id", ",", "Config", ":", "*", "req", ".", "Config", ",", "}", "\n", "if", "err", ":=", "datastore", ".", "Put", "(", "c", ",", "cfg", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "&", "cfg", ".", "Config", ",", "nil", "\n", "}" ]
// Ensure handles a request to create or update a config. // For app-internal use only.
[ "Ensure", "handles", "a", "request", "to", "create", "or", "update", "a", "config", ".", "For", "app", "-", "internal", "use", "only", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/rpc/config.go#L53-L65
8,063
luci/luci-go
gce/appengine/rpc/config.go
NewConfigurationServer
func NewConfigurationServer() config.ConfigurationServer { return &config.DecoratedConfiguration{ Prelude: readOnlyAuthPrelude, Service: &Config{}, Postlude: gRPCifyAndLogErr, } }
go
func NewConfigurationServer() config.ConfigurationServer { return &config.DecoratedConfiguration{ Prelude: readOnlyAuthPrelude, Service: &Config{}, Postlude: gRPCifyAndLogErr, } }
[ "func", "NewConfigurationServer", "(", ")", "config", ".", "ConfigurationServer", "{", "return", "&", "config", ".", "DecoratedConfiguration", "{", "Prelude", ":", "readOnlyAuthPrelude", ",", "Service", ":", "&", "Config", "{", "}", ",", "Postlude", ":", "gRPCifyAndLogErr", ",", "}", "\n", "}" ]
// NewConfigurationServer returns a new configuration server.
[ "NewConfigurationServer", "returns", "a", "new", "configuration", "server", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/appengine/rpc/config.go#L103-L109
8,064
luci/luci-go
config/appengine/gaeconfig/settings.go
SetIfChanged
func (s *Settings) SetIfChanged(c context.Context, who, why string) error { return settings.SetIfChanged(c, settingsKey, s, who, why) }
go
func (s *Settings) SetIfChanged(c context.Context, who, why string) error { return settings.SetIfChanged(c, settingsKey, s, who, why) }
[ "func", "(", "s", "*", "Settings", ")", "SetIfChanged", "(", "c", "context", ".", "Context", ",", "who", ",", "why", "string", ")", "error", "{", "return", "settings", ".", "SetIfChanged", "(", "c", ",", "settingsKey", ",", "s", ",", "who", ",", "why", ")", "\n", "}" ]
// SetIfChanged sets "s" to be the new Settings if it differs from the current // settings value.
[ "SetIfChanged", "sets", "s", "to", "be", "the", "new", "Settings", "if", "it", "differs", "from", "the", "current", "settings", "value", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/appengine/gaeconfig/settings.go#L79-L81
8,065
luci/luci-go
config/appengine/gaeconfig/settings.go
CacheExpiration
func (s *Settings) CacheExpiration() time.Duration { if s.CacheExpirationSec > 0 { return time.Second * time.Duration(s.CacheExpirationSec) } return 0 }
go
func (s *Settings) CacheExpiration() time.Duration { if s.CacheExpirationSec > 0 { return time.Second * time.Duration(s.CacheExpirationSec) } return 0 }
[ "func", "(", "s", "*", "Settings", ")", "CacheExpiration", "(", ")", "time", ".", "Duration", "{", "if", "s", ".", "CacheExpirationSec", ">", "0", "{", "return", "time", ".", "Second", "*", "time", ".", "Duration", "(", "s", ".", "CacheExpirationSec", ")", "\n", "}", "\n", "return", "0", "\n", "}" ]
// CacheExpiration returns a Duration representing the configured cache // expiration. If the cache expiration is not configured, CacheExpiration // will return 0.
[ "CacheExpiration", "returns", "a", "Duration", "representing", "the", "configured", "cache", "expiration", ".", "If", "the", "cache", "expiration", "is", "not", "configured", "CacheExpiration", "will", "return", "0", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/appengine/gaeconfig/settings.go#L86-L91
8,066
luci/luci-go
config/appengine/gaeconfig/settings.go
DefaultSettings
func DefaultSettings(c context.Context) Settings { // Disable local cache on devserver by default to allows changes to local // configs to propagate instantly. This is usually preferred when developing // locally. exp := 0 if !info.IsDevAppServer(c) { exp = int(DefaultExpire.Seconds()) } return Settings{ CacheExpirationSec: exp, DatastoreCacheMode: DSCacheDisabled, AdministratorsGroup: configServiceAdmins, } }
go
func DefaultSettings(c context.Context) Settings { // Disable local cache on devserver by default to allows changes to local // configs to propagate instantly. This is usually preferred when developing // locally. exp := 0 if !info.IsDevAppServer(c) { exp = int(DefaultExpire.Seconds()) } return Settings{ CacheExpirationSec: exp, DatastoreCacheMode: DSCacheDisabled, AdministratorsGroup: configServiceAdmins, } }
[ "func", "DefaultSettings", "(", "c", "context", ".", "Context", ")", "Settings", "{", "// Disable local cache on devserver by default to allows changes to local", "// configs to propagate instantly. This is usually preferred when developing", "// locally.", "exp", ":=", "0", "\n", "if", "!", "info", ".", "IsDevAppServer", "(", "c", ")", "{", "exp", "=", "int", "(", "DefaultExpire", ".", "Seconds", "(", ")", ")", "\n", "}", "\n", "return", "Settings", "{", "CacheExpirationSec", ":", "exp", ",", "DatastoreCacheMode", ":", "DSCacheDisabled", ",", "AdministratorsGroup", ":", "configServiceAdmins", ",", "}", "\n", "}" ]
// DefaultSettings returns Settings to use if setting store is empty.
[ "DefaultSettings", "returns", "Settings", "to", "use", "if", "setting", "store", "is", "empty", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/appengine/gaeconfig/settings.go#L125-L138
8,067
luci/luci-go
logdog/appengine/coordinator/logPrefix.go
IsRetry
func (p *LogPrefix) IsRetry(c context.Context, nonce []byte) bool { if len(nonce) != types.OpNonceLength { logging.Infof(c, "user provided invalid nonce length (%d)", len(nonce)) return false } if len(p.OpNonce) == 0 { logging.Infof(c, "prefix %q has no associated nonce", p.Prefix) return false } if clock.Now(c).After(p.Created.Add(RegistrationNonceTimeout)) { logging.Infof(c, "prefix %q has expired nonce", p.Prefix) return false } return subtle.ConstantTimeCompare(p.OpNonce, nonce) == 1 }
go
func (p *LogPrefix) IsRetry(c context.Context, nonce []byte) bool { if len(nonce) != types.OpNonceLength { logging.Infof(c, "user provided invalid nonce length (%d)", len(nonce)) return false } if len(p.OpNonce) == 0 { logging.Infof(c, "prefix %q has no associated nonce", p.Prefix) return false } if clock.Now(c).After(p.Created.Add(RegistrationNonceTimeout)) { logging.Infof(c, "prefix %q has expired nonce", p.Prefix) return false } return subtle.ConstantTimeCompare(p.OpNonce, nonce) == 1 }
[ "func", "(", "p", "*", "LogPrefix", ")", "IsRetry", "(", "c", "context", ".", "Context", ",", "nonce", "[", "]", "byte", ")", "bool", "{", "if", "len", "(", "nonce", ")", "!=", "types", ".", "OpNonceLength", "{", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "len", "(", "nonce", ")", ")", "\n", "return", "false", "\n", "}", "\n", "if", "len", "(", "p", ".", "OpNonce", ")", "==", "0", "{", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "p", ".", "Prefix", ")", "\n", "return", "false", "\n", "}", "\n", "if", "clock", ".", "Now", "(", "c", ")", ".", "After", "(", "p", ".", "Created", ".", "Add", "(", "RegistrationNonceTimeout", ")", ")", "{", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "p", ".", "Prefix", ")", "\n", "return", "false", "\n", "}", "\n", "return", "subtle", ".", "ConstantTimeCompare", "(", "p", ".", "OpNonce", ",", "nonce", ")", "==", "1", "\n", "}" ]
// IsRetry checks to see if this LogPrefix is still in the OpNonce // window, and if nonce matches the one in this LogPrefix.
[ "IsRetry", "checks", "to", "see", "if", "this", "LogPrefix", "is", "still", "in", "the", "OpNonce", "window", "and", "if", "nonce", "matches", "the", "one", "in", "this", "LogPrefix", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/logPrefix.go#L124-L138
8,068
luci/luci-go
scheduler/appengine/engine/cron.go
pokeCron
func pokeCron(c context.Context, job *Job, disp *tq.Dispatcher, cb func(m *cron.Machine) error) error { assertInTransaction(c) sched, err := job.ParseSchedule() if err != nil { return errors.Annotate(err, "bad schedule %q", job.EffectiveSchedule()).Err() } now := clock.Now(c).UTC() rnd := mathrand.Get(c) machine := &cron.Machine{ Now: now, Schedule: sched, Nonce: func() int64 { return rnd.Int63() + 1 }, State: job.Cron, } if err := cb(machine); err != nil { return errors.Annotate(err, "callback error").Err() } tasks := []*tq.Task{} for _, action := range machine.Actions { switch a := action.(type) { case cron.TickLaterAction: logging.Infof(c, "Scheduling tick %d after %s", a.TickNonce, a.When.Sub(now)) tasks = append(tasks, &tq.Task{ Payload: &internal.CronTickTask{ JobId: job.JobID, TickNonce: a.TickNonce, }, ETA: a.When, }) case cron.StartInvocationAction: trigger := cronTrigger(a, now) logging.Infof(c, "Emitting cron trigger %s", trigger.Id) tasks = append(tasks, &tq.Task{ Payload: &internal.EnqueueTriggersTask{ JobId: job.JobID, Triggers: []*internal.Trigger{trigger}, }, }) default: return errors.Reason("unknown action %T emitted by the cron machine", action).Err() } } if err := disp.AddTask(c, tasks...); err != nil { return errors.Annotate(err, "failed to enqueue emitted actions").Err() } job.Cron = machine.State return nil }
go
func pokeCron(c context.Context, job *Job, disp *tq.Dispatcher, cb func(m *cron.Machine) error) error { assertInTransaction(c) sched, err := job.ParseSchedule() if err != nil { return errors.Annotate(err, "bad schedule %q", job.EffectiveSchedule()).Err() } now := clock.Now(c).UTC() rnd := mathrand.Get(c) machine := &cron.Machine{ Now: now, Schedule: sched, Nonce: func() int64 { return rnd.Int63() + 1 }, State: job.Cron, } if err := cb(machine); err != nil { return errors.Annotate(err, "callback error").Err() } tasks := []*tq.Task{} for _, action := range machine.Actions { switch a := action.(type) { case cron.TickLaterAction: logging.Infof(c, "Scheduling tick %d after %s", a.TickNonce, a.When.Sub(now)) tasks = append(tasks, &tq.Task{ Payload: &internal.CronTickTask{ JobId: job.JobID, TickNonce: a.TickNonce, }, ETA: a.When, }) case cron.StartInvocationAction: trigger := cronTrigger(a, now) logging.Infof(c, "Emitting cron trigger %s", trigger.Id) tasks = append(tasks, &tq.Task{ Payload: &internal.EnqueueTriggersTask{ JobId: job.JobID, Triggers: []*internal.Trigger{trigger}, }, }) default: return errors.Reason("unknown action %T emitted by the cron machine", action).Err() } } if err := disp.AddTask(c, tasks...); err != nil { return errors.Annotate(err, "failed to enqueue emitted actions").Err() } job.Cron = machine.State return nil }
[ "func", "pokeCron", "(", "c", "context", ".", "Context", ",", "job", "*", "Job", ",", "disp", "*", "tq", ".", "Dispatcher", ",", "cb", "func", "(", "m", "*", "cron", ".", "Machine", ")", "error", ")", "error", "{", "assertInTransaction", "(", "c", ")", "\n\n", "sched", ",", "err", ":=", "job", ".", "ParseSchedule", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "job", ".", "EffectiveSchedule", "(", ")", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "now", ":=", "clock", ".", "Now", "(", "c", ")", ".", "UTC", "(", ")", "\n", "rnd", ":=", "mathrand", ".", "Get", "(", "c", ")", "\n\n", "machine", ":=", "&", "cron", ".", "Machine", "{", "Now", ":", "now", ",", "Schedule", ":", "sched", ",", "Nonce", ":", "func", "(", ")", "int64", "{", "return", "rnd", ".", "Int63", "(", ")", "+", "1", "}", ",", "State", ":", "job", ".", "Cron", ",", "}", "\n", "if", "err", ":=", "cb", "(", "machine", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "tasks", ":=", "[", "]", "*", "tq", ".", "Task", "{", "}", "\n", "for", "_", ",", "action", ":=", "range", "machine", ".", "Actions", "{", "switch", "a", ":=", "action", ".", "(", "type", ")", "{", "case", "cron", ".", "TickLaterAction", ":", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "a", ".", "TickNonce", ",", "a", ".", "When", ".", "Sub", "(", "now", ")", ")", "\n", "tasks", "=", "append", "(", "tasks", ",", "&", "tq", ".", "Task", "{", "Payload", ":", "&", "internal", ".", "CronTickTask", "{", "JobId", ":", "job", ".", "JobID", ",", "TickNonce", ":", "a", ".", "TickNonce", ",", "}", ",", "ETA", ":", "a", ".", "When", ",", "}", ")", "\n", "case", "cron", ".", "StartInvocationAction", ":", "trigger", ":=", "cronTrigger", "(", "a", ",", "now", ")", "\n", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "trigger", ".", "Id", ")", "\n", "tasks", "=", "append", "(", "tasks", ",", "&", "tq", ".", "Task", "{", "Payload", ":", "&", "internal", ".", "EnqueueTriggersTask", "{", "JobId", ":", "job", ".", "JobID", ",", "Triggers", ":", "[", "]", "*", "internal", ".", "Trigger", "{", "trigger", "}", ",", "}", ",", "}", ")", "\n", "default", ":", "return", "errors", ".", "Reason", "(", "\"", "\"", ",", "action", ")", ".", "Err", "(", ")", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "disp", ".", "AddTask", "(", "c", ",", "tasks", "...", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "job", ".", "Cron", "=", "machine", ".", "State", "\n", "return", "nil", "\n", "}" ]
// pokeCron instantiates a cron state machine and calls the callback to advance // its state. // // Should be part of a Job transaction. If the callback succeeds, job.State // is updated with the new state and all emitted actions are dispatched to the // task queue. The job entity should eventually be saved as part of this // transaction. // // Returns fatal errors if something is not right with the job definition or // state. Returns transient errors on task queue failures.
[ "pokeCron", "instantiates", "a", "cron", "state", "machine", "and", "calls", "the", "callback", "to", "advance", "its", "state", ".", "Should", "be", "part", "of", "a", "Job", "transaction", ".", "If", "the", "callback", "succeeds", "job", ".", "State", "is", "updated", "with", "the", "new", "state", "and", "all", "emitted", "actions", "are", "dispatched", "to", "the", "task", "queue", ".", "The", "job", "entity", "should", "eventually", "be", "saved", "as", "part", "of", "this", "transaction", ".", "Returns", "fatal", "errors", "if", "something", "is", "not", "right", "with", "the", "job", "definition", "or", "state", ".", "Returns", "transient", "errors", "on", "task", "queue", "failures", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/cron.go#L44-L96
8,069
luci/luci-go
scheduler/appengine/engine/cron.go
cronTrigger
func cronTrigger(a cron.StartInvocationAction, now time.Time) *internal.Trigger { return &internal.Trigger{ Id: fmt.Sprintf("cron:v1:%d", a.Generation), Created: google.NewTimestamp(now), Payload: &internal.Trigger_Cron{ Cron: &api.CronTrigger{ Generation: a.Generation, }, }, } }
go
func cronTrigger(a cron.StartInvocationAction, now time.Time) *internal.Trigger { return &internal.Trigger{ Id: fmt.Sprintf("cron:v1:%d", a.Generation), Created: google.NewTimestamp(now), Payload: &internal.Trigger_Cron{ Cron: &api.CronTrigger{ Generation: a.Generation, }, }, } }
[ "func", "cronTrigger", "(", "a", "cron", ".", "StartInvocationAction", ",", "now", "time", ".", "Time", ")", "*", "internal", ".", "Trigger", "{", "return", "&", "internal", ".", "Trigger", "{", "Id", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "a", ".", "Generation", ")", ",", "Created", ":", "google", ".", "NewTimestamp", "(", "now", ")", ",", "Payload", ":", "&", "internal", ".", "Trigger_Cron", "{", "Cron", ":", "&", "api", ".", "CronTrigger", "{", "Generation", ":", "a", ".", "Generation", ",", "}", ",", "}", ",", "}", "\n", "}" ]
// cronTrigger generates a trigger struct from an invocation request generated // by the cron state machine.
[ "cronTrigger", "generates", "a", "trigger", "struct", "from", "an", "invocation", "request", "generated", "by", "the", "cron", "state", "machine", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/cron.go#L100-L110
8,070
luci/luci-go
vpython/python/command_line.go
String
func (f *CommandLineFlag) String() string { return fmt.Sprintf("-%s%s", f.Flag, f.Arg) }
go
func (f *CommandLineFlag) String() string { return fmt.Sprintf("-%s%s", f.Flag, f.Arg) }
[ "func", "(", "f", "*", "CommandLineFlag", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "f", ".", "Flag", ",", "f", ".", "Arg", ")", "\n", "}" ]
// String returns a string representation of this flag, which is a command-line // suitable representation of its value.
[ "String", "returns", "a", "string", "representation", "of", "this", "flag", "which", "is", "a", "command", "-", "line", "suitable", "representation", "of", "its", "value", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/python/command_line.go#L34-L36
8,071
luci/luci-go
vpython/python/command_line.go
BuildArgs
func (cl *CommandLine) BuildArgs() []string { targetArgs := cl.Target.buildArgsForTarget() args := make([]string, 0, len(cl.Flags)+1+len(targetArgs)+len(cl.Args)) for _, flag := range cl.Flags { args = append(args, flag.String()) } var flagSeparator []string if cl.FlagSeparator { flagSeparator = []string{"--"} } // If our target is specified as a flag, we need to emit it before the flag // separator. If our target is specified as a positional argument (e.g., // CommandTarget), we can emit it on either side. if !cl.Target.followsFlagSeparator() { args = append(args, targetArgs...) args = append(args, flagSeparator...) } else { args = append(args, flagSeparator...) args = append(args, targetArgs...) } args = append(args, cl.Args...) return args }
go
func (cl *CommandLine) BuildArgs() []string { targetArgs := cl.Target.buildArgsForTarget() args := make([]string, 0, len(cl.Flags)+1+len(targetArgs)+len(cl.Args)) for _, flag := range cl.Flags { args = append(args, flag.String()) } var flagSeparator []string if cl.FlagSeparator { flagSeparator = []string{"--"} } // If our target is specified as a flag, we need to emit it before the flag // separator. If our target is specified as a positional argument (e.g., // CommandTarget), we can emit it on either side. if !cl.Target.followsFlagSeparator() { args = append(args, targetArgs...) args = append(args, flagSeparator...) } else { args = append(args, flagSeparator...) args = append(args, targetArgs...) } args = append(args, cl.Args...) return args }
[ "func", "(", "cl", "*", "CommandLine", ")", "BuildArgs", "(", ")", "[", "]", "string", "{", "targetArgs", ":=", "cl", ".", "Target", ".", "buildArgsForTarget", "(", ")", "\n", "args", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "cl", ".", "Flags", ")", "+", "1", "+", "len", "(", "targetArgs", ")", "+", "len", "(", "cl", ".", "Args", ")", ")", "\n", "for", "_", ",", "flag", ":=", "range", "cl", ".", "Flags", "{", "args", "=", "append", "(", "args", ",", "flag", ".", "String", "(", ")", ")", "\n", "}", "\n\n", "var", "flagSeparator", "[", "]", "string", "\n", "if", "cl", ".", "FlagSeparator", "{", "flagSeparator", "=", "[", "]", "string", "{", "\"", "\"", "}", "\n", "}", "\n\n", "// If our target is specified as a flag, we need to emit it before the flag", "// separator. If our target is specified as a positional argument (e.g.,", "// CommandTarget), we can emit it on either side.", "if", "!", "cl", ".", "Target", ".", "followsFlagSeparator", "(", ")", "{", "args", "=", "append", "(", "args", ",", "targetArgs", "...", ")", "\n", "args", "=", "append", "(", "args", ",", "flagSeparator", "...", ")", "\n", "}", "else", "{", "args", "=", "append", "(", "args", ",", "flagSeparator", "...", ")", "\n", "args", "=", "append", "(", "args", ",", "targetArgs", "...", ")", "\n", "}", "\n\n", "args", "=", "append", "(", "args", ",", "cl", ".", "Args", "...", ")", "\n", "return", "args", "\n", "}" ]
// BuildArgs returns an array of Python interpreter arguments for cl.
[ "BuildArgs", "returns", "an", "array", "of", "Python", "interpreter", "arguments", "for", "cl", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/python/command_line.go#L134-L159
8,072
luci/luci-go
vpython/python/command_line.go
AddFlag
func (cl *CommandLine) AddFlag(flag CommandLineFlag) { if strings.HasPrefix(flag.Flag, "-") { panic("flag must not begin with '-'") } for _, f := range cl.Flags { if f == flag { return } } cl.Flags = append(cl.Flags, flag) }
go
func (cl *CommandLine) AddFlag(flag CommandLineFlag) { if strings.HasPrefix(flag.Flag, "-") { panic("flag must not begin with '-'") } for _, f := range cl.Flags { if f == flag { return } } cl.Flags = append(cl.Flags, flag) }
[ "func", "(", "cl", "*", "CommandLine", ")", "AddFlag", "(", "flag", "CommandLineFlag", ")", "{", "if", "strings", ".", "HasPrefix", "(", "flag", ".", "Flag", ",", "\"", "\"", ")", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "for", "_", ",", "f", ":=", "range", "cl", ".", "Flags", "{", "if", "f", "==", "flag", "{", "return", "\n", "}", "\n", "}", "\n", "cl", ".", "Flags", "=", "append", "(", "cl", ".", "Flags", ",", "flag", ")", "\n", "}" ]
// AddFlag adds an interpreter flag to cl if it's not already present.
[ "AddFlag", "adds", "an", "interpreter", "flag", "to", "cl", "if", "it", "s", "not", "already", "present", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/python/command_line.go#L176-L186
8,073
luci/luci-go
vpython/python/command_line.go
AddSingleFlag
func (cl *CommandLine) AddSingleFlag(flag string) { cl.AddFlag(CommandLineFlag{Flag: flag}) }
go
func (cl *CommandLine) AddSingleFlag(flag string) { cl.AddFlag(CommandLineFlag{Flag: flag}) }
[ "func", "(", "cl", "*", "CommandLine", ")", "AddSingleFlag", "(", "flag", "string", ")", "{", "cl", ".", "AddFlag", "(", "CommandLineFlag", "{", "Flag", ":", "flag", "}", ")", "\n", "}" ]
// AddSingleFlag adds a single no-argument interpreter flag to cl // if it's not already specified.
[ "AddSingleFlag", "adds", "a", "single", "no", "-", "argument", "interpreter", "flag", "to", "cl", "if", "it", "s", "not", "already", "specified", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/python/command_line.go#L190-L192
8,074
luci/luci-go
vpython/python/command_line.go
RemoveFlagMatch
func (cl *CommandLine) RemoveFlagMatch(matchFn func(CommandLineFlag) bool) (found bool) { newFlags := cl.Flags[:0] for _, f := range cl.Flags { if !matchFn(f) { newFlags = append(newFlags, f) } else { found = true } } cl.Flags = newFlags return }
go
func (cl *CommandLine) RemoveFlagMatch(matchFn func(CommandLineFlag) bool) (found bool) { newFlags := cl.Flags[:0] for _, f := range cl.Flags { if !matchFn(f) { newFlags = append(newFlags, f) } else { found = true } } cl.Flags = newFlags return }
[ "func", "(", "cl", "*", "CommandLine", ")", "RemoveFlagMatch", "(", "matchFn", "func", "(", "CommandLineFlag", ")", "bool", ")", "(", "found", "bool", ")", "{", "newFlags", ":=", "cl", ".", "Flags", "[", ":", "0", "]", "\n", "for", "_", ",", "f", ":=", "range", "cl", ".", "Flags", "{", "if", "!", "matchFn", "(", "f", ")", "{", "newFlags", "=", "append", "(", "newFlags", ",", "f", ")", "\n", "}", "else", "{", "found", "=", "true", "\n", "}", "\n", "}", "\n", "cl", ".", "Flags", "=", "newFlags", "\n", "return", "\n", "}" ]
// RemoveFlagMatch removes all instances of flags that match the selection // function. // // matchFn is a function that accepts a candidate flag and returns true if it // should be removed, false if it should not.
[ "RemoveFlagMatch", "removes", "all", "instances", "of", "flags", "that", "match", "the", "selection", "function", ".", "matchFn", "is", "a", "function", "that", "accepts", "a", "candidate", "flag", "and", "returns", "true", "if", "it", "should", "be", "removed", "false", "if", "it", "should", "not", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/python/command_line.go#L199-L210
8,075
luci/luci-go
vpython/python/command_line.go
RemoveFlag
func (cl *CommandLine) RemoveFlag(flag CommandLineFlag) (found bool) { return cl.RemoveFlagMatch(func(f CommandLineFlag) bool { return f == flag }) }
go
func (cl *CommandLine) RemoveFlag(flag CommandLineFlag) (found bool) { return cl.RemoveFlagMatch(func(f CommandLineFlag) bool { return f == flag }) }
[ "func", "(", "cl", "*", "CommandLine", ")", "RemoveFlag", "(", "flag", "CommandLineFlag", ")", "(", "found", "bool", ")", "{", "return", "cl", ".", "RemoveFlagMatch", "(", "func", "(", "f", "CommandLineFlag", ")", "bool", "{", "return", "f", "==", "flag", "}", ")", "\n", "}" ]
// RemoveFlag removes all instances of the specified flag from the interpreter // command line.
[ "RemoveFlag", "removes", "all", "instances", "of", "the", "specified", "flag", "from", "the", "interpreter", "command", "line", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/python/command_line.go#L214-L216
8,076
luci/luci-go
vpython/python/command_line.go
RemoveAllFlag
func (cl *CommandLine) RemoveAllFlag(flag string) (found bool) { return cl.RemoveFlagMatch(func(f CommandLineFlag) bool { return f.Flag == flag }) }
go
func (cl *CommandLine) RemoveAllFlag(flag string) (found bool) { return cl.RemoveFlagMatch(func(f CommandLineFlag) bool { return f.Flag == flag }) }
[ "func", "(", "cl", "*", "CommandLine", ")", "RemoveAllFlag", "(", "flag", "string", ")", "(", "found", "bool", ")", "{", "return", "cl", ".", "RemoveFlagMatch", "(", "func", "(", "f", "CommandLineFlag", ")", "bool", "{", "return", "f", ".", "Flag", "==", "flag", "}", ")", "\n", "}" ]
// RemoveAllFlag removes all instances of the specified flag from the interpreter // command line.
[ "RemoveAllFlag", "removes", "all", "instances", "of", "the", "specified", "flag", "from", "the", "interpreter", "command", "line", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/python/command_line.go#L220-L222
8,077
luci/luci-go
vpython/python/command_line.go
Clone
func (cl *CommandLine) Clone() *CommandLine { return &CommandLine{ Target: cl.Target, Flags: append([]CommandLineFlag(nil), cl.Flags...), Args: append([]string(nil), cl.Args...), } }
go
func (cl *CommandLine) Clone() *CommandLine { return &CommandLine{ Target: cl.Target, Flags: append([]CommandLineFlag(nil), cl.Flags...), Args: append([]string(nil), cl.Args...), } }
[ "func", "(", "cl", "*", "CommandLine", ")", "Clone", "(", ")", "*", "CommandLine", "{", "return", "&", "CommandLine", "{", "Target", ":", "cl", ".", "Target", ",", "Flags", ":", "append", "(", "[", "]", "CommandLineFlag", "(", "nil", ")", ",", "cl", ".", "Flags", "...", ")", ",", "Args", ":", "append", "(", "[", "]", "string", "(", "nil", ")", ",", "cl", ".", "Args", "...", ")", ",", "}", "\n", "}" ]
// Clone returns an independent deep copy of cl.
[ "Clone", "returns", "an", "independent", "deep", "copy", "of", "cl", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/python/command_line.go#L225-L231
8,078
luci/luci-go
vpython/python/command_line.go
parseSingleFlag
func (cl *CommandLine) parseSingleFlag(fs *parsedFlagState) error { // Consume the first character from flag into "r". "flag" is the remainder. r, l := utf8.DecodeRuneInString(fs.flag) if r == utf8.RuneError { return errors.Reason("invalid rune in flag").Err() } fs.flag = fs.flag[l:] // Retrieve the value for a non-binary flag. This mutates the flag state to // consume that value. getFlagValue := func() (val string, err error) { switch { case len(fs.flag) > 0: // Combined flag/value (e.g., -c'paoskdpo') val, fs.flag = fs.flag, "" case len(fs.args) == 0: err = errors.New("two-value flag missing second value") default: // Flag value is in subsequent argument (e.g., "-c 'paoskdpo'"). // Consume the argument. val, fs.args = fs.args[0], fs.args[1:] } return } // Some cases will set this to true if `r` is determined to just be a no-value // single-character flag isSingleCharFlag := false switch r { case 'c': // Inline command target. val, err := getFlagValue() if err != nil { return err } cl.Target = CommandTarget{val} case 'm': // Python module target. val, err := getFlagValue() if err != nil { return err } cl.Target = ModuleTarget{val} case 'Q', 'W', 'X': // Two-argument Python flags. val, err := getFlagValue() if err != nil { return err } cl.Flags = append(cl.Flags, CommandLineFlag{string(r), val}) case 'O': // Handle the case of the odd flag "-OO", which parses as a single flag. var has bool if fs.flag, has = trimPrefix(fs.flag, "O"); has { cl.Flags = append(cl.Flags, CommandLineFlag{"OO", ""}) break } // Single "O", do normal single-flag parsing. isSingleCharFlag = true case '-': // handle the case of "--version", which is an atypical many-character flag. if fs.flag == "version" { fs.flag = "" cl.Flags = append(cl.Flags, CommandLineFlag{"-version", ""}) break } // Not sure what this could be, but fall through none the less. isSingleCharFlag = true default: isSingleCharFlag = true } if isSingleCharFlag { // One-argument Python flags. If there are more characters in "flag", // don't consume the entire flag; instead, replace it with the remainder // for subsequent parses. This handles cases like "-vvc <script>". cl.Flags = append(cl.Flags, CommandLineFlag{string(r), ""}) } return nil }
go
func (cl *CommandLine) parseSingleFlag(fs *parsedFlagState) error { // Consume the first character from flag into "r". "flag" is the remainder. r, l := utf8.DecodeRuneInString(fs.flag) if r == utf8.RuneError { return errors.Reason("invalid rune in flag").Err() } fs.flag = fs.flag[l:] // Retrieve the value for a non-binary flag. This mutates the flag state to // consume that value. getFlagValue := func() (val string, err error) { switch { case len(fs.flag) > 0: // Combined flag/value (e.g., -c'paoskdpo') val, fs.flag = fs.flag, "" case len(fs.args) == 0: err = errors.New("two-value flag missing second value") default: // Flag value is in subsequent argument (e.g., "-c 'paoskdpo'"). // Consume the argument. val, fs.args = fs.args[0], fs.args[1:] } return } // Some cases will set this to true if `r` is determined to just be a no-value // single-character flag isSingleCharFlag := false switch r { case 'c': // Inline command target. val, err := getFlagValue() if err != nil { return err } cl.Target = CommandTarget{val} case 'm': // Python module target. val, err := getFlagValue() if err != nil { return err } cl.Target = ModuleTarget{val} case 'Q', 'W', 'X': // Two-argument Python flags. val, err := getFlagValue() if err != nil { return err } cl.Flags = append(cl.Flags, CommandLineFlag{string(r), val}) case 'O': // Handle the case of the odd flag "-OO", which parses as a single flag. var has bool if fs.flag, has = trimPrefix(fs.flag, "O"); has { cl.Flags = append(cl.Flags, CommandLineFlag{"OO", ""}) break } // Single "O", do normal single-flag parsing. isSingleCharFlag = true case '-': // handle the case of "--version", which is an atypical many-character flag. if fs.flag == "version" { fs.flag = "" cl.Flags = append(cl.Flags, CommandLineFlag{"-version", ""}) break } // Not sure what this could be, but fall through none the less. isSingleCharFlag = true default: isSingleCharFlag = true } if isSingleCharFlag { // One-argument Python flags. If there are more characters in "flag", // don't consume the entire flag; instead, replace it with the remainder // for subsequent parses. This handles cases like "-vvc <script>". cl.Flags = append(cl.Flags, CommandLineFlag{string(r), ""}) } return nil }
[ "func", "(", "cl", "*", "CommandLine", ")", "parseSingleFlag", "(", "fs", "*", "parsedFlagState", ")", "error", "{", "// Consume the first character from flag into \"r\". \"flag\" is the remainder.", "r", ",", "l", ":=", "utf8", ".", "DecodeRuneInString", "(", "fs", ".", "flag", ")", "\n", "if", "r", "==", "utf8", ".", "RuneError", "{", "return", "errors", ".", "Reason", "(", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "fs", ".", "flag", "=", "fs", ".", "flag", "[", "l", ":", "]", "\n\n", "// Retrieve the value for a non-binary flag. This mutates the flag state to", "// consume that value.", "getFlagValue", ":=", "func", "(", ")", "(", "val", "string", ",", "err", "error", ")", "{", "switch", "{", "case", "len", "(", "fs", ".", "flag", ")", ">", "0", ":", "// Combined flag/value (e.g., -c'paoskdpo')", "val", ",", "fs", ".", "flag", "=", "fs", ".", "flag", ",", "\"", "\"", "\n", "case", "len", "(", "fs", ".", "args", ")", "==", "0", ":", "err", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "default", ":", "// Flag value is in subsequent argument (e.g., \"-c 'paoskdpo'\").", "// Consume the argument.", "val", ",", "fs", ".", "args", "=", "fs", ".", "args", "[", "0", "]", ",", "fs", ".", "args", "[", "1", ":", "]", "\n", "}", "\n", "return", "\n", "}", "\n\n", "// Some cases will set this to true if `r` is determined to just be a no-value", "// single-character flag", "isSingleCharFlag", ":=", "false", "\n\n", "switch", "r", "{", "case", "'c'", ":", "// Inline command target.", "val", ",", "err", ":=", "getFlagValue", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cl", ".", "Target", "=", "CommandTarget", "{", "val", "}", "\n\n", "case", "'m'", ":", "// Python module target.", "val", ",", "err", ":=", "getFlagValue", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cl", ".", "Target", "=", "ModuleTarget", "{", "val", "}", "\n\n", "case", "'Q'", ",", "'W'", ",", "'X'", ":", "// Two-argument Python flags.", "val", ",", "err", ":=", "getFlagValue", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cl", ".", "Flags", "=", "append", "(", "cl", ".", "Flags", ",", "CommandLineFlag", "{", "string", "(", "r", ")", ",", "val", "}", ")", "\n\n", "case", "'O'", ":", "// Handle the case of the odd flag \"-OO\", which parses as a single flag.", "var", "has", "bool", "\n", "if", "fs", ".", "flag", ",", "has", "=", "trimPrefix", "(", "fs", ".", "flag", ",", "\"", "\"", ")", ";", "has", "{", "cl", ".", "Flags", "=", "append", "(", "cl", ".", "Flags", ",", "CommandLineFlag", "{", "\"", "\"", ",", "\"", "\"", "}", ")", "\n", "break", "\n", "}", "\n\n", "// Single \"O\", do normal single-flag parsing.", "isSingleCharFlag", "=", "true", "\n\n", "case", "'-'", ":", "// handle the case of \"--version\", which is an atypical many-character flag.", "if", "fs", ".", "flag", "==", "\"", "\"", "{", "fs", ".", "flag", "=", "\"", "\"", "\n", "cl", ".", "Flags", "=", "append", "(", "cl", ".", "Flags", ",", "CommandLineFlag", "{", "\"", "\"", ",", "\"", "\"", "}", ")", "\n", "break", "\n", "}", "\n\n", "// Not sure what this could be, but fall through none the less.", "isSingleCharFlag", "=", "true", "\n\n", "default", ":", "isSingleCharFlag", "=", "true", "\n", "}", "\n\n", "if", "isSingleCharFlag", "{", "// One-argument Python flags. If there are more characters in \"flag\",", "// don't consume the entire flag; instead, replace it with the remainder", "// for subsequent parses. This handles cases like \"-vvc <script>\".", "cl", ".", "Flags", "=", "append", "(", "cl", ".", "Flags", ",", "CommandLineFlag", "{", "string", "(", "r", ")", ",", "\"", "\"", "}", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// parseSingleFlag parses a single flag from a state.
[ "parseSingleFlag", "parses", "a", "single", "flag", "from", "a", "state", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/python/command_line.go#L234-L322
8,079
luci/luci-go
vpython/python/command_line.go
ParseCommandLine
func ParseCommandLine(args []string) (*CommandLine, error) { noTarget := NoTarget{} cl := CommandLine{ Target: noTarget, } i := 0 for len(args) > 0 { // Stop parsing after we have a target, as Python does. if cl.Target != noTarget { break } // Consume the next argument. arg := args[0] args = args[1:] i++ if arg == "-" { // "-" instructs Python to load the script from STDIN. cl.Target = ScriptTarget{ Path: "-", } continue } isFlag := false if !cl.FlagSeparator { arg, isFlag = trimPrefix(arg, "-") } if !isFlag { // The first positional argument is the path to the script, and all // subsequent arguments are script arguments. cl.Target = ScriptTarget{ Path: arg, FollowsSeparator: cl.FlagSeparator, } continue } // Note that at this point we've trimmed the preceding "-" from arg, so // this is really "--". If we encounter "--" that marks the end of // interpreter flag parsing; everything hereafter is considered positional // to the interpreter. if arg == "-" { cl.FlagSeparator = true continue } // Parse this flag and any remainder. fs := parsedFlagState{ flag: arg, args: args, } for len(fs.flag) > 0 { if err := cl.parseSingleFlag(&fs); err != nil { return nil, errors.Annotate(err, "failed to parse Python flag #%d", i). InternalReason("arg(%q)", arg).Err() } } args = fs.args } // The remainder of arguments are for the script. cl.Args = append([]string(nil), args...) return &cl, nil }
go
func ParseCommandLine(args []string) (*CommandLine, error) { noTarget := NoTarget{} cl := CommandLine{ Target: noTarget, } i := 0 for len(args) > 0 { // Stop parsing after we have a target, as Python does. if cl.Target != noTarget { break } // Consume the next argument. arg := args[0] args = args[1:] i++ if arg == "-" { // "-" instructs Python to load the script from STDIN. cl.Target = ScriptTarget{ Path: "-", } continue } isFlag := false if !cl.FlagSeparator { arg, isFlag = trimPrefix(arg, "-") } if !isFlag { // The first positional argument is the path to the script, and all // subsequent arguments are script arguments. cl.Target = ScriptTarget{ Path: arg, FollowsSeparator: cl.FlagSeparator, } continue } // Note that at this point we've trimmed the preceding "-" from arg, so // this is really "--". If we encounter "--" that marks the end of // interpreter flag parsing; everything hereafter is considered positional // to the interpreter. if arg == "-" { cl.FlagSeparator = true continue } // Parse this flag and any remainder. fs := parsedFlagState{ flag: arg, args: args, } for len(fs.flag) > 0 { if err := cl.parseSingleFlag(&fs); err != nil { return nil, errors.Annotate(err, "failed to parse Python flag #%d", i). InternalReason("arg(%q)", arg).Err() } } args = fs.args } // The remainder of arguments are for the script. cl.Args = append([]string(nil), args...) return &cl, nil }
[ "func", "ParseCommandLine", "(", "args", "[", "]", "string", ")", "(", "*", "CommandLine", ",", "error", ")", "{", "noTarget", ":=", "NoTarget", "{", "}", "\n\n", "cl", ":=", "CommandLine", "{", "Target", ":", "noTarget", ",", "}", "\n", "i", ":=", "0", "\n", "for", "len", "(", "args", ")", ">", "0", "{", "// Stop parsing after we have a target, as Python does.", "if", "cl", ".", "Target", "!=", "noTarget", "{", "break", "\n", "}", "\n\n", "// Consume the next argument.", "arg", ":=", "args", "[", "0", "]", "\n", "args", "=", "args", "[", "1", ":", "]", "\n", "i", "++", "\n\n", "if", "arg", "==", "\"", "\"", "{", "// \"-\" instructs Python to load the script from STDIN.", "cl", ".", "Target", "=", "ScriptTarget", "{", "Path", ":", "\"", "\"", ",", "}", "\n", "continue", "\n", "}", "\n\n", "isFlag", ":=", "false", "\n", "if", "!", "cl", ".", "FlagSeparator", "{", "arg", ",", "isFlag", "=", "trimPrefix", "(", "arg", ",", "\"", "\"", ")", "\n", "}", "\n\n", "if", "!", "isFlag", "{", "// The first positional argument is the path to the script, and all", "// subsequent arguments are script arguments.", "cl", ".", "Target", "=", "ScriptTarget", "{", "Path", ":", "arg", ",", "FollowsSeparator", ":", "cl", ".", "FlagSeparator", ",", "}", "\n", "continue", "\n", "}", "\n\n", "// Note that at this point we've trimmed the preceding \"-\" from arg, so", "// this is really \"--\". If we encounter \"--\" that marks the end of", "// interpreter flag parsing; everything hereafter is considered positional", "// to the interpreter.", "if", "arg", "==", "\"", "\"", "{", "cl", ".", "FlagSeparator", "=", "true", "\n", "continue", "\n", "}", "\n\n", "// Parse this flag and any remainder.", "fs", ":=", "parsedFlagState", "{", "flag", ":", "arg", ",", "args", ":", "args", ",", "}", "\n", "for", "len", "(", "fs", ".", "flag", ")", ">", "0", "{", "if", "err", ":=", "cl", ".", "parseSingleFlag", "(", "&", "fs", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "i", ")", ".", "InternalReason", "(", "\"", "\"", ",", "arg", ")", ".", "Err", "(", ")", "\n", "}", "\n", "}", "\n", "args", "=", "fs", ".", "args", "\n", "}", "\n\n", "// The remainder of arguments are for the script.", "cl", ".", "Args", "=", "append", "(", "[", "]", "string", "(", "nil", ")", ",", "args", "...", ")", "\n", "return", "&", "cl", ",", "nil", "\n", "}" ]
// ParseCommandLine parses Python command-line arguments and returns a // structured representation.
[ "ParseCommandLine", "parses", "Python", "command", "-", "line", "arguments", "and", "returns", "a", "structured", "representation", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/python/command_line.go#L326-L393
8,080
luci/luci-go
logdog/api/endpoints/coordinator/logs/v1/fakelogs/stream.go
Close
func (s *Stream) Close() error { _, err := s.c.srvServ.TerminateStream(s.c.ctx, &services.TerminateStreamRequest{ Project: coordinatorTest.AllAccessProject, Id: s.streamID, Secret: s.secret, TerminalIndex: s.streamIndex - 1, }) return err }
go
func (s *Stream) Close() error { _, err := s.c.srvServ.TerminateStream(s.c.ctx, &services.TerminateStreamRequest{ Project: coordinatorTest.AllAccessProject, Id: s.streamID, Secret: s.secret, TerminalIndex: s.streamIndex - 1, }) return err }
[ "func", "(", "s", "*", "Stream", ")", "Close", "(", ")", "error", "{", "_", ",", "err", ":=", "s", ".", "c", ".", "srvServ", ".", "TerminateStream", "(", "s", ".", "c", ".", "ctx", ",", "&", "services", ".", "TerminateStreamRequest", "{", "Project", ":", "coordinatorTest", ".", "AllAccessProject", ",", "Id", ":", "s", ".", "streamID", ",", "Secret", ":", "s", ".", "secret", ",", "TerminalIndex", ":", "s", ".", "streamIndex", "-", "1", ",", "}", ")", "\n", "return", "err", "\n", "}" ]
// Close terminates this stream.
[ "Close", "terminates", "this", "stream", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/api/endpoints/coordinator/logs/v1/fakelogs/stream.go#L100-L108
8,081
luci/luci-go
machine-db/appengine/config/vlans.go
importVLANs
func importVLANs(c context.Context, configSet config.Set) error { vlan := &configPB.VLANs{} metadata := &config.Meta{} if err := cfgclient.Get(c, cfgclient.AsService, configSet, vlansFilename, textproto.Message(vlan), metadata); err != nil { return errors.Annotate(err, "failed to load %s", vlansFilename).Err() } logging.Infof(c, "Found %s revision %q", vlansFilename, metadata.Revision) ctx := &validation.Context{Context: c} ctx.SetFile(vlansFilename) validateVLANs(ctx, vlan) if err := ctx.Finalize(); err != nil { return errors.Annotate(err, "invalid config").Err() } if err := model.EnsureVLANs(c, vlan.Vlan); err != nil { return errors.Annotate(err, "failed to ensure VLANs").Err() } if err := model.EnsureIPs(c, vlan.Vlan); err != nil { return errors.Annotate(err, "failed to ensure IP addresses").Err() } return nil }
go
func importVLANs(c context.Context, configSet config.Set) error { vlan := &configPB.VLANs{} metadata := &config.Meta{} if err := cfgclient.Get(c, cfgclient.AsService, configSet, vlansFilename, textproto.Message(vlan), metadata); err != nil { return errors.Annotate(err, "failed to load %s", vlansFilename).Err() } logging.Infof(c, "Found %s revision %q", vlansFilename, metadata.Revision) ctx := &validation.Context{Context: c} ctx.SetFile(vlansFilename) validateVLANs(ctx, vlan) if err := ctx.Finalize(); err != nil { return errors.Annotate(err, "invalid config").Err() } if err := model.EnsureVLANs(c, vlan.Vlan); err != nil { return errors.Annotate(err, "failed to ensure VLANs").Err() } if err := model.EnsureIPs(c, vlan.Vlan); err != nil { return errors.Annotate(err, "failed to ensure IP addresses").Err() } return nil }
[ "func", "importVLANs", "(", "c", "context", ".", "Context", ",", "configSet", "config", ".", "Set", ")", "error", "{", "vlan", ":=", "&", "configPB", ".", "VLANs", "{", "}", "\n", "metadata", ":=", "&", "config", ".", "Meta", "{", "}", "\n", "if", "err", ":=", "cfgclient", ".", "Get", "(", "c", ",", "cfgclient", ".", "AsService", ",", "configSet", ",", "vlansFilename", ",", "textproto", ".", "Message", "(", "vlan", ")", ",", "metadata", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ",", "vlansFilename", ")", ".", "Err", "(", ")", "\n", "}", "\n", "logging", ".", "Infof", "(", "c", ",", "\"", "\"", ",", "vlansFilename", ",", "metadata", ".", "Revision", ")", "\n\n", "ctx", ":=", "&", "validation", ".", "Context", "{", "Context", ":", "c", "}", "\n", "ctx", ".", "SetFile", "(", "vlansFilename", ")", "\n", "validateVLANs", "(", "ctx", ",", "vlan", ")", "\n", "if", "err", ":=", "ctx", ".", "Finalize", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n\n", "if", "err", ":=", "model", ".", "EnsureVLANs", "(", "c", ",", "vlan", ".", "Vlan", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "if", "err", ":=", "model", ".", "EnsureIPs", "(", "c", ",", "vlan", ".", "Vlan", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Annotate", "(", "err", ",", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// importVLANs fetches, validates, and applies VLAN configs.
[ "importVLANs", "fetches", "validates", "and", "applies", "VLAN", "configs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/config/vlans.go#L43-L65
8,082
luci/luci-go
machine-db/appengine/config/vlans.go
validateVLANs
func validateVLANs(c *validation.Context, cfg *configPB.VLANs) { // VLAN IDs must be unique. // Keep records of ones we've already seen. vlans := make(map[int64]struct{}, len(cfg.Vlan)) for _, vlan := range cfg.Vlan { switch _, ok := vlans[vlan.Id]; { case vlan.Id < 1: c.Errorf("VLAN ID %d must be positive", vlan.Id) case vlan.Id > vlanMaxId: c.Errorf("VLAN ID %d must not exceed %d", vlan.Id, vlanMaxId) case ok: c.Errorf("duplicate VLAN %d", vlan.Id) } vlans[vlan.Id] = struct{}{} c.Enter("VLAN %d", vlan.Id) _, subnet, err := net.ParseCIDR(vlan.CidrBlock) if err != nil { c.Errorf("invalid CIDR block") } else { ones, _ := subnet.Mask.Size() if ones < vlanMinCIDRBlockSuffix { c.Errorf("CIDR block suffix must be at least %d", vlanMinCIDRBlockSuffix) } } c.Exit() // TODO(smut): Check that CIDR blocks are disjoint. } }
go
func validateVLANs(c *validation.Context, cfg *configPB.VLANs) { // VLAN IDs must be unique. // Keep records of ones we've already seen. vlans := make(map[int64]struct{}, len(cfg.Vlan)) for _, vlan := range cfg.Vlan { switch _, ok := vlans[vlan.Id]; { case vlan.Id < 1: c.Errorf("VLAN ID %d must be positive", vlan.Id) case vlan.Id > vlanMaxId: c.Errorf("VLAN ID %d must not exceed %d", vlan.Id, vlanMaxId) case ok: c.Errorf("duplicate VLAN %d", vlan.Id) } vlans[vlan.Id] = struct{}{} c.Enter("VLAN %d", vlan.Id) _, subnet, err := net.ParseCIDR(vlan.CidrBlock) if err != nil { c.Errorf("invalid CIDR block") } else { ones, _ := subnet.Mask.Size() if ones < vlanMinCIDRBlockSuffix { c.Errorf("CIDR block suffix must be at least %d", vlanMinCIDRBlockSuffix) } } c.Exit() // TODO(smut): Check that CIDR blocks are disjoint. } }
[ "func", "validateVLANs", "(", "c", "*", "validation", ".", "Context", ",", "cfg", "*", "configPB", ".", "VLANs", ")", "{", "// VLAN IDs must be unique.", "// Keep records of ones we've already seen.", "vlans", ":=", "make", "(", "map", "[", "int64", "]", "struct", "{", "}", ",", "len", "(", "cfg", ".", "Vlan", ")", ")", "\n", "for", "_", ",", "vlan", ":=", "range", "cfg", ".", "Vlan", "{", "switch", "_", ",", "ok", ":=", "vlans", "[", "vlan", ".", "Id", "]", ";", "{", "case", "vlan", ".", "Id", "<", "1", ":", "c", ".", "Errorf", "(", "\"", "\"", ",", "vlan", ".", "Id", ")", "\n", "case", "vlan", ".", "Id", ">", "vlanMaxId", ":", "c", ".", "Errorf", "(", "\"", "\"", ",", "vlan", ".", "Id", ",", "vlanMaxId", ")", "\n", "case", "ok", ":", "c", ".", "Errorf", "(", "\"", "\"", ",", "vlan", ".", "Id", ")", "\n", "}", "\n", "vlans", "[", "vlan", ".", "Id", "]", "=", "struct", "{", "}", "{", "}", "\n", "c", ".", "Enter", "(", "\"", "\"", ",", "vlan", ".", "Id", ")", "\n", "_", ",", "subnet", ",", "err", ":=", "net", ".", "ParseCIDR", "(", "vlan", ".", "CidrBlock", ")", "\n", "if", "err", "!=", "nil", "{", "c", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "else", "{", "ones", ",", "_", ":=", "subnet", ".", "Mask", ".", "Size", "(", ")", "\n", "if", "ones", "<", "vlanMinCIDRBlockSuffix", "{", "c", ".", "Errorf", "(", "\"", "\"", ",", "vlanMinCIDRBlockSuffix", ")", "\n", "}", "\n", "}", "\n", "c", ".", "Exit", "(", ")", "\n", "// TODO(smut): Check that CIDR blocks are disjoint.", "}", "\n", "}" ]
// validateVLANs validates vlans.cfg.
[ "validateVLANs", "validates", "vlans", ".", "cfg", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/config/vlans.go#L68-L95
8,083
luci/luci-go
common/sync/parallel/semaphore.go
TakeAll
func (s Semaphore) TakeAll() { for i := 0; i < cap(s); i++ { s.Lock() } }
go
func (s Semaphore) TakeAll() { for i := 0; i < cap(s); i++ { s.Lock() } }
[ "func", "(", "s", "Semaphore", ")", "TakeAll", "(", ")", "{", "for", "i", ":=", "0", ";", "i", "<", "cap", "(", "s", ")", ";", "i", "++", "{", "s", ".", "Lock", "(", ")", "\n", "}", "\n", "}" ]
// TakeAll blocks until it holds all available semaphore resources. When it // returns, the caller owns all of the resources in the semaphore.
[ "TakeAll", "blocks", "until", "it", "holds", "all", "available", "semaphore", "resources", ".", "When", "it", "returns", "the", "caller", "owns", "all", "of", "the", "resources", "in", "the", "semaphore", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/sync/parallel/semaphore.go#L47-L51
8,084
luci/luci-go
common/flag/nestedflagset/nestedflagset.go
Parse
func (fs *FlagSet) Parse(line string) error { var args []string for _, token := range lexer(line, ',').split() { name, value := token.split() args = append(args, fmt.Sprintf("-%s", name)) if value != "" { args = append(args, value) } } return fs.F.Parse(args) }
go
func (fs *FlagSet) Parse(line string) error { var args []string for _, token := range lexer(line, ',').split() { name, value := token.split() args = append(args, fmt.Sprintf("-%s", name)) if value != "" { args = append(args, value) } } return fs.F.Parse(args) }
[ "func", "(", "fs", "*", "FlagSet", ")", "Parse", "(", "line", "string", ")", "error", "{", "var", "args", "[", "]", "string", "\n", "for", "_", ",", "token", ":=", "range", "lexer", "(", "line", ",", "','", ")", ".", "split", "(", ")", "{", "name", ",", "value", ":=", "token", ".", "split", "(", ")", "\n", "args", "=", "append", "(", "args", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "name", ")", ")", "\n", "if", "value", "!=", "\"", "\"", "{", "args", "=", "append", "(", "args", ",", "value", ")", "\n", "}", "\n", "}", "\n\n", "return", "fs", ".", "F", ".", "Parse", "(", "args", ")", "\n", "}" ]
// Parse parses a one-line option string into the underlying flag set.
[ "Parse", "parses", "a", "one", "-", "line", "option", "string", "into", "the", "underlying", "flag", "set", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/flag/nestedflagset/nestedflagset.go#L34-L45
8,085
luci/luci-go
common/flag/nestedflagset/nestedflagset.go
Usage
func (fs *FlagSet) Usage() string { var flags []string // If there is no "help" flag defined, we will use it to display help/usage // (default FlagSet). if fs.F.Lookup("help") == nil { flags = append(flags, "help") } fs.F.VisitAll(func(f *flag.Flag) { comma := "" if len(flags) > 0 { comma = "," } flags = append(flags, fmt.Sprintf("[%s%s]", comma, f.Name)) }) return strings.Join(flags, "") }
go
func (fs *FlagSet) Usage() string { var flags []string // If there is no "help" flag defined, we will use it to display help/usage // (default FlagSet). if fs.F.Lookup("help") == nil { flags = append(flags, "help") } fs.F.VisitAll(func(f *flag.Flag) { comma := "" if len(flags) > 0 { comma = "," } flags = append(flags, fmt.Sprintf("[%s%s]", comma, f.Name)) }) return strings.Join(flags, "") }
[ "func", "(", "fs", "*", "FlagSet", ")", "Usage", "(", ")", "string", "{", "var", "flags", "[", "]", "string", "\n\n", "// If there is no \"help\" flag defined, we will use it to display help/usage", "// (default FlagSet).", "if", "fs", ".", "F", ".", "Lookup", "(", "\"", "\"", ")", "==", "nil", "{", "flags", "=", "append", "(", "flags", ",", "\"", "\"", ")", "\n", "}", "\n\n", "fs", ".", "F", ".", "VisitAll", "(", "func", "(", "f", "*", "flag", ".", "Flag", ")", "{", "comma", ":=", "\"", "\"", "\n", "if", "len", "(", "flags", ")", ">", "0", "{", "comma", "=", "\"", "\"", "\n", "}", "\n", "flags", "=", "append", "(", "flags", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "comma", ",", "f", ".", "Name", ")", ")", "\n", "}", ")", "\n", "return", "strings", ".", "Join", "(", "flags", ",", "\"", "\"", ")", "\n", "}" ]
// Usage constructs a one-line usage string for all of the options defined in // Flags.
[ "Usage", "constructs", "a", "one", "-", "line", "usage", "string", "for", "all", "of", "the", "options", "defined", "in", "Flags", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/flag/nestedflagset/nestedflagset.go#L49-L66
8,086
luci/luci-go
server/templates/middleware.go
WithTemplates
func WithTemplates(b *Bundle) router.Middleware { return func(c *router.Context, next router.Handler) { // Note: Use(...) calls EnsureLoaded and initializes b.err inside. c.Context = Use(c.Context, b, &Extra{ Request: c.Request, Params: c.Params, }) if b.err != nil { http.Error(c.Writer, fmt.Sprintf("Can't load HTML templates.\n%s", b.err), http.StatusInternalServerError) return } next(c) } }
go
func WithTemplates(b *Bundle) router.Middleware { return func(c *router.Context, next router.Handler) { // Note: Use(...) calls EnsureLoaded and initializes b.err inside. c.Context = Use(c.Context, b, &Extra{ Request: c.Request, Params: c.Params, }) if b.err != nil { http.Error(c.Writer, fmt.Sprintf("Can't load HTML templates.\n%s", b.err), http.StatusInternalServerError) return } next(c) } }
[ "func", "WithTemplates", "(", "b", "*", "Bundle", ")", "router", ".", "Middleware", "{", "return", "func", "(", "c", "*", "router", ".", "Context", ",", "next", "router", ".", "Handler", ")", "{", "// Note: Use(...) calls EnsureLoaded and initializes b.err inside.", "c", ".", "Context", "=", "Use", "(", "c", ".", "Context", ",", "b", ",", "&", "Extra", "{", "Request", ":", "c", ".", "Request", ",", "Params", ":", "c", ".", "Params", ",", "}", ")", "\n", "if", "b", ".", "err", "!=", "nil", "{", "http", ".", "Error", "(", "c", ".", "Writer", ",", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "b", ".", "err", ")", ",", "http", ".", "StatusInternalServerError", ")", "\n", "return", "\n", "}", "\n", "next", "(", "c", ")", "\n", "}", "\n", "}" ]
// WithTemplates is middleware that lazily loads template bundle and injects it // into the context. // // Wrapper reply with HTTP 500 if templates can not be loaded. Inner handler // receives context with all templates successfully loaded.
[ "WithTemplates", "is", "middleware", "that", "lazily", "loads", "template", "bundle", "and", "injects", "it", "into", "the", "context", ".", "Wrapper", "reply", "with", "HTTP", "500", "if", "templates", "can", "not", "be", "loaded", ".", "Inner", "handler", "receives", "context", "with", "all", "templates", "successfully", "loaded", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/templates/middleware.go#L29-L42
8,087
luci/luci-go
tokenserver/appengine/impl/utils/policy/bundle.go
serializeBundle
func serializeBundle(b ConfigBundle) ([]byte, error) { keys := make([]string, 0, len(b)) for k := range b { keys = append(keys, k) } sort.Strings(keys) items := make([]blobWithType, 0, len(b)) for _, k := range keys { v := b[k] blob, err := proto.Marshal(v) if err != nil { return nil, err } items = append(items, blobWithType{ Path: k, Kind: proto.MessageName(v), Blob: blob, }) } out := bytes.Buffer{} if err := gob.NewEncoder(&out).Encode(items); err != nil { return nil, err } return out.Bytes(), nil }
go
func serializeBundle(b ConfigBundle) ([]byte, error) { keys := make([]string, 0, len(b)) for k := range b { keys = append(keys, k) } sort.Strings(keys) items := make([]blobWithType, 0, len(b)) for _, k := range keys { v := b[k] blob, err := proto.Marshal(v) if err != nil { return nil, err } items = append(items, blobWithType{ Path: k, Kind: proto.MessageName(v), Blob: blob, }) } out := bytes.Buffer{} if err := gob.NewEncoder(&out).Encode(items); err != nil { return nil, err } return out.Bytes(), nil }
[ "func", "serializeBundle", "(", "b", "ConfigBundle", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "keys", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "b", ")", ")", "\n", "for", "k", ":=", "range", "b", "{", "keys", "=", "append", "(", "keys", ",", "k", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "keys", ")", "\n\n", "items", ":=", "make", "(", "[", "]", "blobWithType", ",", "0", ",", "len", "(", "b", ")", ")", "\n", "for", "_", ",", "k", ":=", "range", "keys", "{", "v", ":=", "b", "[", "k", "]", "\n", "blob", ",", "err", ":=", "proto", ".", "Marshal", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "items", "=", "append", "(", "items", ",", "blobWithType", "{", "Path", ":", "k", ",", "Kind", ":", "proto", ".", "MessageName", "(", "v", ")", ",", "Blob", ":", "blob", ",", "}", ")", "\n", "}", "\n\n", "out", ":=", "bytes", ".", "Buffer", "{", "}", "\n", "if", "err", ":=", "gob", ".", "NewEncoder", "(", "&", "out", ")", ".", "Encode", "(", "items", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "out", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// serializeBundle deterministically converts ConfigBundle into a byte blob. // // The byte blob references proto message names to know how to deserialize them // later.
[ "serializeBundle", "deterministically", "converts", "ConfigBundle", "into", "a", "byte", "blob", ".", "The", "byte", "blob", "references", "proto", "message", "names", "to", "know", "how", "to", "deserialize", "them", "later", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/policy/bundle.go#L46-L72
8,088
luci/luci-go
tokenserver/appengine/impl/utils/policy/bundle.go
deserializeBundle
func deserializeBundle(blob []byte) (b ConfigBundle, unknown []blobWithType, err error) { items := []blobWithType{} if err := gob.NewDecoder(bytes.NewReader(blob)).Decode(&items); err != nil { return nil, nil, err } b = make(ConfigBundle, len(items)) for _, item := range items { t := proto.MessageType(item.Kind) // this is *SomeProto type if t == nil { unknown = append(unknown, item) continue } msg := reflect.New(t.Elem()).Interface().(proto.Message) if err := proto.Unmarshal(item.Blob, msg); err != nil { return nil, nil, err } b[item.Path] = msg } return b, unknown, nil }
go
func deserializeBundle(blob []byte) (b ConfigBundle, unknown []blobWithType, err error) { items := []blobWithType{} if err := gob.NewDecoder(bytes.NewReader(blob)).Decode(&items); err != nil { return nil, nil, err } b = make(ConfigBundle, len(items)) for _, item := range items { t := proto.MessageType(item.Kind) // this is *SomeProto type if t == nil { unknown = append(unknown, item) continue } msg := reflect.New(t.Elem()).Interface().(proto.Message) if err := proto.Unmarshal(item.Blob, msg); err != nil { return nil, nil, err } b[item.Path] = msg } return b, unknown, nil }
[ "func", "deserializeBundle", "(", "blob", "[", "]", "byte", ")", "(", "b", "ConfigBundle", ",", "unknown", "[", "]", "blobWithType", ",", "err", "error", ")", "{", "items", ":=", "[", "]", "blobWithType", "{", "}", "\n", "if", "err", ":=", "gob", ".", "NewDecoder", "(", "bytes", ".", "NewReader", "(", "blob", ")", ")", ".", "Decode", "(", "&", "items", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n\n", "b", "=", "make", "(", "ConfigBundle", ",", "len", "(", "items", ")", ")", "\n", "for", "_", ",", "item", ":=", "range", "items", "{", "t", ":=", "proto", ".", "MessageType", "(", "item", ".", "Kind", ")", "// this is *SomeProto type", "\n", "if", "t", "==", "nil", "{", "unknown", "=", "append", "(", "unknown", ",", "item", ")", "\n", "continue", "\n", "}", "\n", "msg", ":=", "reflect", ".", "New", "(", "t", ".", "Elem", "(", ")", ")", ".", "Interface", "(", ")", ".", "(", "proto", ".", "Message", ")", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "item", ".", "Blob", ",", "msg", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "b", "[", "item", ".", "Path", "]", "=", "msg", "\n", "}", "\n\n", "return", "b", ",", "unknown", ",", "nil", "\n", "}" ]
// deserialize parses the serialized ConfigBundle. // // It skips configs with proto types no longer registered in the proto lib // registry. It returns them unparsed in 'unknown' slice. // // Returns an error if some known proto message can't be deserialized.
[ "deserialize", "parses", "the", "serialized", "ConfigBundle", ".", "It", "skips", "configs", "with", "proto", "types", "no", "longer", "registered", "in", "the", "proto", "lib", "registry", ".", "It", "returns", "them", "unparsed", "in", "unknown", "slice", ".", "Returns", "an", "error", "if", "some", "known", "proto", "message", "can", "t", "be", "deserialized", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/policy/bundle.go#L80-L101
8,089
luci/luci-go
logdog/common/storage/bigtable/storage.go
DefaultClientOptions
func DefaultClientOptions() []option.ClientOption { return []option.ClientOption{ option.WithGRPCDialOption(grpc.WithDefaultCallOptions( grpc.MaxCallRecvMsgSize(1024*1024*16), grpc.MaxCallSendMsgSize(1024*1024*16), )), } }
go
func DefaultClientOptions() []option.ClientOption { return []option.ClientOption{ option.WithGRPCDialOption(grpc.WithDefaultCallOptions( grpc.MaxCallRecvMsgSize(1024*1024*16), grpc.MaxCallSendMsgSize(1024*1024*16), )), } }
[ "func", "DefaultClientOptions", "(", ")", "[", "]", "option", ".", "ClientOption", "{", "return", "[", "]", "option", ".", "ClientOption", "{", "option", ".", "WithGRPCDialOption", "(", "grpc", ".", "WithDefaultCallOptions", "(", "grpc", ".", "MaxCallRecvMsgSize", "(", "1024", "*", "1024", "*", "16", ")", ",", "grpc", ".", "MaxCallSendMsgSize", "(", "1024", "*", "1024", "*", "16", ")", ",", ")", ")", ",", "}", "\n", "}" ]
// DefaultCallOptions returns a function set of ClientOptions to apply to a // BigTable client.
[ "DefaultCallOptions", "returns", "a", "function", "set", "of", "ClientOptions", "to", "apply", "to", "a", "BigTable", "client", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/storage/bigtable/storage.go#L71-L78
8,090
luci/luci-go
common/errors/multierror.go
Summary
func (m MultiError) Summary() (n int, first error) { for _, e := range m { if e != nil { if n == 0 { first = e } n++ } } return }
go
func (m MultiError) Summary() (n int, first error) { for _, e := range m { if e != nil { if n == 0 { first = e } n++ } } return }
[ "func", "(", "m", "MultiError", ")", "Summary", "(", ")", "(", "n", "int", ",", "first", "error", ")", "{", "for", "_", ",", "e", ":=", "range", "m", "{", "if", "e", "!=", "nil", "{", "if", "n", "==", "0", "{", "first", "=", "e", "\n", "}", "\n", "n", "++", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// Summary gets the total count of non-nil errors and returns the first one.
[ "Summary", "gets", "the", "total", "count", "of", "non", "-", "nil", "errors", "and", "returns", "the", "first", "one", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/errors/multierror.go#L39-L49
8,091
luci/luci-go
common/errors/multierror.go
First
func (m MultiError) First() error { for _, e := range m { if e != nil { return e } } return nil }
go
func (m MultiError) First() error { for _, e := range m { if e != nil { return e } } return nil }
[ "func", "(", "m", "MultiError", ")", "First", "(", ")", "error", "{", "for", "_", ",", "e", ":=", "range", "m", "{", "if", "e", "!=", "nil", "{", "return", "e", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// First returns the first non-nil error.
[ "First", "returns", "the", "first", "non", "-", "nil", "error", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/errors/multierror.go#L52-L59
8,092
luci/luci-go
common/errors/multierror.go
SingleError
func SingleError(err error) error { if me, ok := err.(MultiError); ok { if len(me) == 0 { return nil } return me[0] } return err }
go
func SingleError(err error) error { if me, ok := err.(MultiError); ok { if len(me) == 0 { return nil } return me[0] } return err }
[ "func", "SingleError", "(", "err", "error", ")", "error", "{", "if", "me", ",", "ok", ":=", "err", ".", "(", "MultiError", ")", ";", "ok", "{", "if", "len", "(", "me", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "return", "me", "[", "0", "]", "\n", "}", "\n", "return", "err", "\n", "}" ]
// SingleError provides a simple way to uwrap a MultiError if you know that it // could only ever contain one element. // // If err is a MultiError, return its first element. Otherwise, return err.
[ "SingleError", "provides", "a", "simple", "way", "to", "uwrap", "a", "MultiError", "if", "you", "know", "that", "it", "could", "only", "ever", "contain", "one", "element", ".", "If", "err", "is", "a", "MultiError", "return", "its", "first", "element", ".", "Otherwise", "return", "err", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/errors/multierror.go#L82-L90
8,093
luci/luci-go
tokenserver/appengine/impl/utils/rpc_utils.go
ValidateProject
func ValidateProject(c context.Context, project string) error { if project == "" { return fmt.Errorf("luci_project is empty") } return nil }
go
func ValidateProject(c context.Context, project string) error { if project == "" { return fmt.Errorf("luci_project is empty") } return nil }
[ "func", "ValidateProject", "(", "c", "context", ".", "Context", ",", "project", "string", ")", "error", "{", "if", "project", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ValidateProject validates a LUCI project string.
[ "ValidateProject", "validates", "a", "LUCI", "project", "string", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/rpc_utils.go#L45-L50
8,094
luci/luci-go
tokenserver/appengine/impl/utils/rpc_utils.go
ValidateAndNormalizeRequest
func ValidateAndNormalizeRequest(c context.Context, oauthScope []string, durationSecs *int64, auditTags []string) error { minDur := time.Duration(*durationSecs) * time.Second // Test error cases switch { case len(oauthScope) <= 0: return fmt.Errorf("oauth_scope is required") case minDur < 0: return fmt.Errorf("min_validity_duration must be positive") case minDur > maxAllowedMinValidityDuration: return fmt.Errorf("min_validity_duration must not exceed %d", maxAllowedMinValidityDuration/time.Second) } if err := ValidateTags(auditTags); err != nil { return fmt.Errorf("bad audit_tags - %s", err) } // Perform normalization if minDur == 0 { *durationSecs = int64(DefaultMinValidityDuration.Seconds()) } return nil }
go
func ValidateAndNormalizeRequest(c context.Context, oauthScope []string, durationSecs *int64, auditTags []string) error { minDur := time.Duration(*durationSecs) * time.Second // Test error cases switch { case len(oauthScope) <= 0: return fmt.Errorf("oauth_scope is required") case minDur < 0: return fmt.Errorf("min_validity_duration must be positive") case minDur > maxAllowedMinValidityDuration: return fmt.Errorf("min_validity_duration must not exceed %d", maxAllowedMinValidityDuration/time.Second) } if err := ValidateTags(auditTags); err != nil { return fmt.Errorf("bad audit_tags - %s", err) } // Perform normalization if minDur == 0 { *durationSecs = int64(DefaultMinValidityDuration.Seconds()) } return nil }
[ "func", "ValidateAndNormalizeRequest", "(", "c", "context", ".", "Context", ",", "oauthScope", "[", "]", "string", ",", "durationSecs", "*", "int64", ",", "auditTags", "[", "]", "string", ")", "error", "{", "minDur", ":=", "time", ".", "Duration", "(", "*", "durationSecs", ")", "*", "time", ".", "Second", "\n", "// Test error cases", "switch", "{", "case", "len", "(", "oauthScope", ")", "<=", "0", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "case", "minDur", "<", "0", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "case", "minDur", ">", "maxAllowedMinValidityDuration", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "maxAllowedMinValidityDuration", "/", "time", ".", "Second", ")", "\n", "}", "\n", "if", "err", ":=", "ValidateTags", "(", "auditTags", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Perform normalization", "if", "minDur", "==", "0", "{", "*", "durationSecs", "=", "int64", "(", "DefaultMinValidityDuration", ".", "Seconds", "(", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// ValidateAndNormalizeRequest validates and normalizes RPC requests.
[ "ValidateAndNormalizeRequest", "validates", "and", "normalizes", "RPC", "requests", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/rpc_utils.go#L53-L73
8,095
luci/luci-go
tokenserver/appengine/impl/utils/rpc_utils.go
LogRequest
func LogRequest(c context.Context, rpc RPC, req proto.Message, caller identity.Identity) { if !logging.IsLogging(c, logging.Debug) { return } m := jsonpb.Marshaler{Indent: " "} dump, err := m.MarshalToString(req) if err != nil { panic(err) } logging.Debugf(c, "Identity: %s, %s:\n%s", caller, rpc.Name(), dump) }
go
func LogRequest(c context.Context, rpc RPC, req proto.Message, caller identity.Identity) { if !logging.IsLogging(c, logging.Debug) { return } m := jsonpb.Marshaler{Indent: " "} dump, err := m.MarshalToString(req) if err != nil { panic(err) } logging.Debugf(c, "Identity: %s, %s:\n%s", caller, rpc.Name(), dump) }
[ "func", "LogRequest", "(", "c", "context", ".", "Context", ",", "rpc", "RPC", ",", "req", "proto", ".", "Message", ",", "caller", "identity", ".", "Identity", ")", "{", "if", "!", "logging", ".", "IsLogging", "(", "c", ",", "logging", ".", "Debug", ")", "{", "return", "\n", "}", "\n", "m", ":=", "jsonpb", ".", "Marshaler", "{", "Indent", ":", "\"", "\"", "}", "\n", "dump", ",", "err", ":=", "m", ".", "MarshalToString", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "logging", ".", "Debugf", "(", "c", ",", "\"", "\\n", "\"", ",", "caller", ",", "rpc", ".", "Name", "(", ")", ",", "dump", ")", "\n", "}" ]
// LogRequest logs the RPC request.
[ "LogRequest", "logs", "the", "RPC", "request", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/rpc_utils.go#L76-L86
8,096
luci/luci-go
gce/api/config/v1/schedule.go
isSameDay
func isSameDay(wkd time.Weekday, dow dayofweek.DayOfWeek) bool { switch dow { case dayofweek.DayOfWeek_DAY_OF_WEEK_UNSPECIFIED: return false case dayofweek.DayOfWeek_SUNDAY: // time.Weekday has Sunday == 0, dayofweek.DayOfWeek has Sunday == 7. return wkd == time.Sunday default: // For all other values, time.Weekday == dayofweek.DayOfWeek. return int(wkd) == int(dow) } }
go
func isSameDay(wkd time.Weekday, dow dayofweek.DayOfWeek) bool { switch dow { case dayofweek.DayOfWeek_DAY_OF_WEEK_UNSPECIFIED: return false case dayofweek.DayOfWeek_SUNDAY: // time.Weekday has Sunday == 0, dayofweek.DayOfWeek has Sunday == 7. return wkd == time.Sunday default: // For all other values, time.Weekday == dayofweek.DayOfWeek. return int(wkd) == int(dow) } }
[ "func", "isSameDay", "(", "wkd", "time", ".", "Weekday", ",", "dow", "dayofweek", ".", "DayOfWeek", ")", "bool", "{", "switch", "dow", "{", "case", "dayofweek", ".", "DayOfWeek_DAY_OF_WEEK_UNSPECIFIED", ":", "return", "false", "\n", "case", "dayofweek", ".", "DayOfWeek_SUNDAY", ":", "// time.Weekday has Sunday == 0, dayofweek.DayOfWeek has Sunday == 7.", "return", "wkd", "==", "time", ".", "Sunday", "\n", "default", ":", "// For all other values, time.Weekday == dayofweek.DayOfWeek.", "return", "int", "(", "wkd", ")", "==", "int", "(", "dow", ")", "\n", "}", "\n", "}" ]
// isSameDay returns whether the given time.Weekday and dayofweek.DayOfWeek // represent the same day of the week.
[ "isSameDay", "returns", "whether", "the", "given", "time", ".", "Weekday", "and", "dayofweek", ".", "DayOfWeek", "represent", "the", "same", "day", "of", "the", "week", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/api/config/v1/schedule.go#L28-L39
8,097
luci/luci-go
gce/api/config/v1/schedule.go
mostRecentStart
func (s *Schedule) mostRecentStart(now time.Time) (time.Time, error) { t, err := s.GetStart().toTime() if err != nil { return time.Time{}, err } now = now.In(t.Location()) // toTime returns a time relative to the current date. Change it to be relative to the given date. t = time.Date(now.Year(), now.Month(), now.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), t.Location()) if s.GetStart().Day == dayofweek.DayOfWeek_DAY_OF_WEEK_UNSPECIFIED { return time.Time{}, errors.Reason("day must be specified").Err() } for !isSameDay(t.Weekday(), s.GetStart().Day) { t = t.Add(time.Hour * -24) } if t.After(now) { t = t.Add(time.Hour * -24 * 7) } return t, nil }
go
func (s *Schedule) mostRecentStart(now time.Time) (time.Time, error) { t, err := s.GetStart().toTime() if err != nil { return time.Time{}, err } now = now.In(t.Location()) // toTime returns a time relative to the current date. Change it to be relative to the given date. t = time.Date(now.Year(), now.Month(), now.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), t.Location()) if s.GetStart().Day == dayofweek.DayOfWeek_DAY_OF_WEEK_UNSPECIFIED { return time.Time{}, errors.Reason("day must be specified").Err() } for !isSameDay(t.Weekday(), s.GetStart().Day) { t = t.Add(time.Hour * -24) } if t.After(now) { t = t.Add(time.Hour * -24 * 7) } return t, nil }
[ "func", "(", "s", "*", "Schedule", ")", "mostRecentStart", "(", "now", "time", ".", "Time", ")", "(", "time", ".", "Time", ",", "error", ")", "{", "t", ",", "err", ":=", "s", ".", "GetStart", "(", ")", ".", "toTime", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "time", ".", "Time", "{", "}", ",", "err", "\n", "}", "\n", "now", "=", "now", ".", "In", "(", "t", ".", "Location", "(", ")", ")", "\n", "// toTime returns a time relative to the current date. Change it to be relative to the given date.", "t", "=", "time", ".", "Date", "(", "now", ".", "Year", "(", ")", ",", "now", ".", "Month", "(", ")", ",", "now", ".", "Day", "(", ")", ",", "t", ".", "Hour", "(", ")", ",", "t", ".", "Minute", "(", ")", ",", "t", ".", "Second", "(", ")", ",", "t", ".", "Nanosecond", "(", ")", ",", "t", ".", "Location", "(", ")", ")", "\n", "if", "s", ".", "GetStart", "(", ")", ".", "Day", "==", "dayofweek", ".", "DayOfWeek_DAY_OF_WEEK_UNSPECIFIED", "{", "return", "time", ".", "Time", "{", "}", ",", "errors", ".", "Reason", "(", "\"", "\"", ")", ".", "Err", "(", ")", "\n", "}", "\n", "for", "!", "isSameDay", "(", "t", ".", "Weekday", "(", ")", ",", "s", ".", "GetStart", "(", ")", ".", "Day", ")", "{", "t", "=", "t", ".", "Add", "(", "time", ".", "Hour", "*", "-", "24", ")", "\n", "}", "\n", "if", "t", ".", "After", "(", "now", ")", "{", "t", "=", "t", ".", "Add", "(", "time", ".", "Hour", "*", "-", "24", "*", "7", ")", "\n", "}", "\n", "return", "t", ",", "nil", "\n", "}" ]
// mostRecentStart returns the most recent start time for this schedule relative // to the given time. The date in the returned time.Time will be the most recent // date falling on the day of the week specified in this schedule which results // in the returned time being equal to or before the given time.
[ "mostRecentStart", "returns", "the", "most", "recent", "start", "time", "for", "this", "schedule", "relative", "to", "the", "given", "time", ".", "The", "date", "in", "the", "returned", "time", ".", "Time", "will", "be", "the", "most", "recent", "date", "falling", "on", "the", "day", "of", "the", "week", "specified", "in", "this", "schedule", "which", "results", "in", "the", "returned", "time", "being", "equal", "to", "or", "before", "the", "given", "time", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/api/config/v1/schedule.go#L45-L63
8,098
luci/luci-go
gce/api/config/v1/schedule.go
Validate
func (s *Schedule) Validate(c *validation.Context) { if s.GetAmount() < 0 { c.Errorf("amount must be non-negative") } c.Enter("length") s.GetLength().Validate(c) switch n, err := s.Length.ToSeconds(); { case err != nil: c.Errorf("%s", err) case n == 0: c.Errorf("duration or seconds is required") } c.Exit() c.Enter("start") s.GetStart().Validate(c) c.Exit() }
go
func (s *Schedule) Validate(c *validation.Context) { if s.GetAmount() < 0 { c.Errorf("amount must be non-negative") } c.Enter("length") s.GetLength().Validate(c) switch n, err := s.Length.ToSeconds(); { case err != nil: c.Errorf("%s", err) case n == 0: c.Errorf("duration or seconds is required") } c.Exit() c.Enter("start") s.GetStart().Validate(c) c.Exit() }
[ "func", "(", "s", "*", "Schedule", ")", "Validate", "(", "c", "*", "validation", ".", "Context", ")", "{", "if", "s", ".", "GetAmount", "(", ")", "<", "0", "{", "c", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "c", ".", "Enter", "(", "\"", "\"", ")", "\n", "s", ".", "GetLength", "(", ")", ".", "Validate", "(", "c", ")", "\n", "switch", "n", ",", "err", ":=", "s", ".", "Length", ".", "ToSeconds", "(", ")", ";", "{", "case", "err", "!=", "nil", ":", "c", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "case", "n", "==", "0", ":", "c", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "c", ".", "Exit", "(", ")", "\n", "c", ".", "Enter", "(", "\"", "\"", ")", "\n", "s", ".", "GetStart", "(", ")", ".", "Validate", "(", "c", ")", "\n", "c", ".", "Exit", "(", ")", "\n", "}" ]
// Validate validates this schedule.
[ "Validate", "validates", "this", "schedule", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/api/config/v1/schedule.go#L66-L82
8,099
luci/luci-go
cipd/client/cipd/reader/calc_pin.go
CalculatePin
func CalculatePin(ctx context.Context, body io.ReadSeeker, algo api.HashAlgo) (common.Pin, error) { inst, err := OpenInstance(ctx, noopCloserSrc{body}, OpenInstanceOpts{ VerificationMode: CalculateHash, HashAlgo: algo, }) if err != nil { return common.Pin{}, err } defer inst.Close(ctx, false) return inst.Pin(), nil }
go
func CalculatePin(ctx context.Context, body io.ReadSeeker, algo api.HashAlgo) (common.Pin, error) { inst, err := OpenInstance(ctx, noopCloserSrc{body}, OpenInstanceOpts{ VerificationMode: CalculateHash, HashAlgo: algo, }) if err != nil { return common.Pin{}, err } defer inst.Close(ctx, false) return inst.Pin(), nil }
[ "func", "CalculatePin", "(", "ctx", "context", ".", "Context", ",", "body", "io", ".", "ReadSeeker", ",", "algo", "api", ".", "HashAlgo", ")", "(", "common", ".", "Pin", ",", "error", ")", "{", "inst", ",", "err", ":=", "OpenInstance", "(", "ctx", ",", "noopCloserSrc", "{", "body", "}", ",", "OpenInstanceOpts", "{", "VerificationMode", ":", "CalculateHash", ",", "HashAlgo", ":", "algo", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "common", ".", "Pin", "{", "}", ",", "err", "\n", "}", "\n", "defer", "inst", ".", "Close", "(", "ctx", ",", "false", ")", "\n", "return", "inst", ".", "Pin", "(", ")", ",", "nil", "\n", "}" ]
// CalculatePin returns a pin that represents the package. // // It reads the package name from the manifest inside, and calculates package's // hash to get instance ID.
[ "CalculatePin", "returns", "a", "pin", "that", "represents", "the", "package", ".", "It", "reads", "the", "package", "name", "from", "the", "manifest", "inside", "and", "calculates", "package", "s", "hash", "to", "get", "instance", "ID", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/reader/calc_pin.go#L35-L45