id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
8,500
luci/luci-go
machine-db/client/cli/nics.go
addNICCmd
func addNICCmd(params *Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "add-nic -name <name> -machine <machine> -mac <mac address> -switch <switch> [-port <switch port>] [-host <hostname>] [-ip <ip address>]", ShortDesc: "adds a NIC", LongDesc: "Adds a network interface to the database.\n\nExample:\ncrimson add-nic -name eth0 -machine xx1-01-720 -mac 00:00:00:00:00:bc -switch switch1.lab -port 30", CommandRun: func() subcommands.CommandRun { cmd := &AddNICCmd{} cmd.Initialize(params) cmd.Flags.StringVar(&cmd.nic.Name, "name", "", "The name of the NIC. Required and must be unique per machine within the database.") cmd.Flags.StringVar(&cmd.nic.Machine, "machine", "", "The machine this NIC belongs to. Required and must be the name of a machine returned by get-machines.") cmd.Flags.StringVar(&cmd.nic.MacAddress, "mac", "", "The MAC address of this NIC. Required and must be a valid MAC-48 address.") cmd.Flags.StringVar(&cmd.nic.Switch, "switch", "", "The switch this NIC is connected to. Required and must be the name of a switch returned by get-switches.") cmd.Flags.Var(flag.Int32(&cmd.nic.Switchport), "port", "The switchport this NIC is connected to.") cmd.Flags.StringVar(&cmd.nic.Hostname, "host", "", "The name of this NIC on the network.") cmd.Flags.StringVar(&cmd.nic.Ipv4, "ip", "", "The IPv4 address assigned to this NIC. Must be a free IP address returned by get-ips.") return cmd }, } }
go
func addNICCmd(params *Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "add-nic -name <name> -machine <machine> -mac <mac address> -switch <switch> [-port <switch port>] [-host <hostname>] [-ip <ip address>]", ShortDesc: "adds a NIC", LongDesc: "Adds a network interface to the database.\n\nExample:\ncrimson add-nic -name eth0 -machine xx1-01-720 -mac 00:00:00:00:00:bc -switch switch1.lab -port 30", CommandRun: func() subcommands.CommandRun { cmd := &AddNICCmd{} cmd.Initialize(params) cmd.Flags.StringVar(&cmd.nic.Name, "name", "", "The name of the NIC. Required and must be unique per machine within the database.") cmd.Flags.StringVar(&cmd.nic.Machine, "machine", "", "The machine this NIC belongs to. Required and must be the name of a machine returned by get-machines.") cmd.Flags.StringVar(&cmd.nic.MacAddress, "mac", "", "The MAC address of this NIC. Required and must be a valid MAC-48 address.") cmd.Flags.StringVar(&cmd.nic.Switch, "switch", "", "The switch this NIC is connected to. Required and must be the name of a switch returned by get-switches.") cmd.Flags.Var(flag.Int32(&cmd.nic.Switchport), "port", "The switchport this NIC is connected to.") cmd.Flags.StringVar(&cmd.nic.Hostname, "host", "", "The name of this NIC on the network.") cmd.Flags.StringVar(&cmd.nic.Ipv4, "ip", "", "The IPv4 address assigned to this NIC. Must be a free IP address returned by get-ips.") return cmd }, } }
[ "func", "addNICCmd", "(", "params", "*", "Parameters", ")", "*", "subcommands", ".", "Command", "{", "return", "&", "subcommands", ".", "Command", "{", "UsageLine", ":", "\"", "\"", ",", "ShortDesc", ":", "\"", "\"", ",", "LongDesc", ":", "\"", "\\n", ...
// addNICCmd returns a command to add a network interface.
[ "addNICCmd", "returns", "a", "command", "to", "add", "a", "network", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/nics.go#L65-L83
8,501
luci/luci-go
machine-db/client/cli/nics.go
deleteNICCmd
func deleteNICCmd(params *Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "del-nic -name <name> -machine <machine>", ShortDesc: "deletes a NIC", LongDesc: "Deletes a network interface from the database.\n\nExample:\ncrimson del-nic -name eth1 -machine xx1-01-720", CommandRun: func() subcommands.CommandRun { cmd := &DeleteNICCmd{} cmd.Initialize(params) cmd.Flags.StringVar(&cmd.req.Name, "name", "", "The name of the NIC to delete.") cmd.Flags.StringVar(&cmd.req.Machine, "machine", "", "The machine the NIC belongs to.") return cmd }, } }
go
func deleteNICCmd(params *Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "del-nic -name <name> -machine <machine>", ShortDesc: "deletes a NIC", LongDesc: "Deletes a network interface from the database.\n\nExample:\ncrimson del-nic -name eth1 -machine xx1-01-720", CommandRun: func() subcommands.CommandRun { cmd := &DeleteNICCmd{} cmd.Initialize(params) cmd.Flags.StringVar(&cmd.req.Name, "name", "", "The name of the NIC to delete.") cmd.Flags.StringVar(&cmd.req.Machine, "machine", "", "The machine the NIC belongs to.") return cmd }, } }
[ "func", "deleteNICCmd", "(", "params", "*", "Parameters", ")", "*", "subcommands", ".", "Command", "{", "return", "&", "subcommands", ".", "Command", "{", "UsageLine", ":", "\"", "\"", ",", "ShortDesc", ":", "\"", "\"", ",", "LongDesc", ":", "\"", "\\n",...
// deleteNICCmd returns a command to delete a network interface.
[ "deleteNICCmd", "returns", "a", "command", "to", "delete", "a", "network", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/nics.go#L105-L118
8,502
luci/luci-go
machine-db/client/cli/nics.go
Run
func (c *EditNICCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int { ctx := cli.GetContext(app, c, env) // TODO(smut): Validate required fields client-side. req := &crimson.UpdateNICRequest{ Nic: &c.nic, UpdateMask: getUpdateMask(&c.Flags, map[string]string{ "mac": "mac_address", "switch": "switch", "port": "switchport", }), } client := getClient(ctx) resp, err := client.UpdateNIC(ctx, req) if err != nil { errors.Log(ctx, err) return 1 } printNICs(c.f.tsv, resp) return 0 }
go
func (c *EditNICCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int { ctx := cli.GetContext(app, c, env) // TODO(smut): Validate required fields client-side. req := &crimson.UpdateNICRequest{ Nic: &c.nic, UpdateMask: getUpdateMask(&c.Flags, map[string]string{ "mac": "mac_address", "switch": "switch", "port": "switchport", }), } client := getClient(ctx) resp, err := client.UpdateNIC(ctx, req) if err != nil { errors.Log(ctx, err) return 1 } printNICs(c.f.tsv, resp) return 0 }
[ "func", "(", "c", "*", "EditNICCmd", ")", "Run", "(", "app", "subcommands", ".", "Application", ",", "args", "[", "]", "string", ",", "env", "subcommands", ".", "Env", ")", "int", "{", "ctx", ":=", "cli", ".", "GetContext", "(", "app", ",", "c", ",...
// Run runs the command to edit a network interface.
[ "Run", "runs", "the", "command", "to", "edit", "a", "network", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/nics.go#L127-L146
8,503
luci/luci-go
machine-db/client/cli/nics.go
editNICCmd
func editNICCmd(params *Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "edit-nic -name <name> -machine <machine> [-mac <mac address>] [-switch <switch>] [-port <switch port>]", ShortDesc: "edit a NIC", LongDesc: "Edits a network interface in the database.\n\nExample to edit a NIC's MAC address:\ncrimson edit-nic -name eth0 -machine xx1-01-720 -mac 00:00:00:00:00:bc", CommandRun: func() subcommands.CommandRun { cmd := &EditNICCmd{} cmd.Initialize(params) cmd.Flags.StringVar(&cmd.nic.Name, "name", "", "The name of the NIC. Required and must be the name of a NIC returned by get-nics.") cmd.Flags.StringVar(&cmd.nic.Machine, "machine", "", "The machine this NIC belongs to. Required and must be the name of a machine returned by get-machines.") cmd.Flags.StringVar(&cmd.nic.MacAddress, "mac", "", "The MAC address of this NIC. Must be a valid MAC-48 address.") cmd.Flags.StringVar(&cmd.nic.Switch, "switch", "", "The switch this NIC is connected to. Must be the name of a switch returned by get-switches.") cmd.Flags.Var(flag.Int32(&cmd.nic.Switchport), "port", "The switchport this NIC is connected to.") return cmd }, } }
go
func editNICCmd(params *Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "edit-nic -name <name> -machine <machine> [-mac <mac address>] [-switch <switch>] [-port <switch port>]", ShortDesc: "edit a NIC", LongDesc: "Edits a network interface in the database.\n\nExample to edit a NIC's MAC address:\ncrimson edit-nic -name eth0 -machine xx1-01-720 -mac 00:00:00:00:00:bc", CommandRun: func() subcommands.CommandRun { cmd := &EditNICCmd{} cmd.Initialize(params) cmd.Flags.StringVar(&cmd.nic.Name, "name", "", "The name of the NIC. Required and must be the name of a NIC returned by get-nics.") cmd.Flags.StringVar(&cmd.nic.Machine, "machine", "", "The machine this NIC belongs to. Required and must be the name of a machine returned by get-machines.") cmd.Flags.StringVar(&cmd.nic.MacAddress, "mac", "", "The MAC address of this NIC. Must be a valid MAC-48 address.") cmd.Flags.StringVar(&cmd.nic.Switch, "switch", "", "The switch this NIC is connected to. Must be the name of a switch returned by get-switches.") cmd.Flags.Var(flag.Int32(&cmd.nic.Switchport), "port", "The switchport this NIC is connected to.") return cmd }, } }
[ "func", "editNICCmd", "(", "params", "*", "Parameters", ")", "*", "subcommands", ".", "Command", "{", "return", "&", "subcommands", ".", "Command", "{", "UsageLine", ":", "\"", "\"", ",", "ShortDesc", ":", "\"", "\"", ",", "LongDesc", ":", "\"", "\\n", ...
// editNICCmd returns a command to edit a network interface.
[ "editNICCmd", "returns", "a", "command", "to", "edit", "a", "network", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/nics.go#L149-L165
8,504
luci/luci-go
machine-db/client/cli/nics.go
Run
func (c *GetNICsCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int { ctx := cli.GetContext(app, c, env) client := getClient(ctx) resp, err := client.ListNICs(ctx, &c.req) if err != nil { errors.Log(ctx, err) return 1 } printNICs(c.f.tsv, resp.Nics...) return 0 }
go
func (c *GetNICsCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int { ctx := cli.GetContext(app, c, env) client := getClient(ctx) resp, err := client.ListNICs(ctx, &c.req) if err != nil { errors.Log(ctx, err) return 1 } printNICs(c.f.tsv, resp.Nics...) return 0 }
[ "func", "(", "c", "*", "GetNICsCmd", ")", "Run", "(", "app", "subcommands", ".", "Application", ",", "args", "[", "]", "string", ",", "env", "subcommands", ".", "Env", ")", "int", "{", "ctx", ":=", "cli", ".", "GetContext", "(", "app", ",", "c", ",...
// Run runs the command to get network interfaces.
[ "Run", "runs", "the", "command", "to", "get", "network", "interfaces", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/nics.go#L174-L184
8,505
luci/luci-go
machine-db/client/cli/nics.go
getNICsCmd
func getNICsCmd(params *Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "get-nics [-name <name>]... [-machine <machine>]...", ShortDesc: "retrieves NICs", LongDesc: "Retrieves network interfaces matching the given names and machines, or all network interfaces if names and machines are omitted.\n\nExample to get all NICs:\ncrimson get-nics\nExample to get the NIC with a certain MAC address:\ncrimson get-nics -mac 00:00:00:00:00:bc", CommandRun: func() subcommands.CommandRun { cmd := &GetNICsCmd{} cmd.Initialize(params) cmd.Flags.Var(flag.StringSlice(&cmd.req.Names), "name", "Name of a NIC to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Machines), "machine", "Name of a machine to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.MacAddresses), "mac", "MAC address to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Switches), "switch", "Name of a switch to filter by. Can be specified multiple times.") return cmd }, } }
go
func getNICsCmd(params *Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "get-nics [-name <name>]... [-machine <machine>]...", ShortDesc: "retrieves NICs", LongDesc: "Retrieves network interfaces matching the given names and machines, or all network interfaces if names and machines are omitted.\n\nExample to get all NICs:\ncrimson get-nics\nExample to get the NIC with a certain MAC address:\ncrimson get-nics -mac 00:00:00:00:00:bc", CommandRun: func() subcommands.CommandRun { cmd := &GetNICsCmd{} cmd.Initialize(params) cmd.Flags.Var(flag.StringSlice(&cmd.req.Names), "name", "Name of a NIC to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Machines), "machine", "Name of a machine to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.MacAddresses), "mac", "MAC address to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Switches), "switch", "Name of a switch to filter by. Can be specified multiple times.") return cmd }, } }
[ "func", "getNICsCmd", "(", "params", "*", "Parameters", ")", "*", "subcommands", ".", "Command", "{", "return", "&", "subcommands", ".", "Command", "{", "UsageLine", ":", "\"", "\"", ",", "ShortDesc", ":", "\"", "\"", ",", "LongDesc", ":", "\"", "\\n", ...
// getNICCmd returns a command to get network interfaces.
[ "getNICCmd", "returns", "a", "command", "to", "get", "network", "interfaces", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/nics.go#L187-L202
8,506
luci/luci-go
common/sync/parallel/runner.go
init
func (r *Runner) init() { r.initOnce.Do(func() { r.workC = make(chan WorkItem) r.dispatchFinishedC = make(chan struct{}) go r.dispatchLoop(r.Sustained, r.Maximum) }) }
go
func (r *Runner) init() { r.initOnce.Do(func() { r.workC = make(chan WorkItem) r.dispatchFinishedC = make(chan struct{}) go r.dispatchLoop(r.Sustained, r.Maximum) }) }
[ "func", "(", "r", "*", "Runner", ")", "init", "(", ")", "{", "r", ".", "initOnce", ".", "Do", "(", "func", "(", ")", "{", "r", ".", "workC", "=", "make", "(", "chan", "WorkItem", ")", "\n", "r", ".", "dispatchFinishedC", "=", "make", "(", "chan...
// init initializes the starting state of the Runner. It must be called at the // beginning of all exported methods.
[ "init", "initializes", "the", "starting", "state", "of", "the", "Runner", ".", "It", "must", "be", "called", "at", "the", "beginning", "of", "all", "exported", "methods", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/sync/parallel/runner.go#L97-L104
8,507
luci/luci-go
common/sync/parallel/runner.go
dispatchLoop
func (r *Runner) dispatchLoop(sustained int, maximum int) { defer close(r.dispatchFinishedC) // If a Maximum is set, use Semaphore to enforce it. if maximum > 0 { spawnC := make(Semaphore, maximum) r.dispatchLoopBody(sustained, spawnC.Lock, spawnC.Unlock) spawnC.TakeAll() } else { // Unbounded number of goroutines. Use a WaitGroup to track them, and block // until all of the task goroutines have completed. var wg sync.WaitGroup r.dispatchLoopBody(sustained, func() { wg.Add(1) }, wg.Done) wg.Wait() } }
go
func (r *Runner) dispatchLoop(sustained int, maximum int) { defer close(r.dispatchFinishedC) // If a Maximum is set, use Semaphore to enforce it. if maximum > 0 { spawnC := make(Semaphore, maximum) r.dispatchLoopBody(sustained, spawnC.Lock, spawnC.Unlock) spawnC.TakeAll() } else { // Unbounded number of goroutines. Use a WaitGroup to track them, and block // until all of the task goroutines have completed. var wg sync.WaitGroup r.dispatchLoopBody(sustained, func() { wg.Add(1) }, wg.Done) wg.Wait() } }
[ "func", "(", "r", "*", "Runner", ")", "dispatchLoop", "(", "sustained", "int", ",", "maximum", "int", ")", "{", "defer", "close", "(", "r", ".", "dispatchFinishedC", ")", "\n\n", "// If a Maximum is set, use Semaphore to enforce it.", "if", "maximum", ">", "0", ...
// disaptchLoop is run in a goroutine. It reads tasks from workC and executes // them.
[ "disaptchLoop", "is", "run", "in", "a", "goroutine", ".", "It", "reads", "tasks", "from", "workC", "and", "executes", "them", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/sync/parallel/runner.go#L108-L123
8,508
luci/luci-go
common/sync/parallel/runner.go
Close
func (r *Runner) Close() { r.init() close(r.workC) <-r.dispatchFinishedC }
go
func (r *Runner) Close() { r.init() close(r.workC) <-r.dispatchFinishedC }
[ "func", "(", "r", "*", "Runner", ")", "Close", "(", ")", "{", "r", ".", "init", "(", ")", "\n\n", "close", "(", "r", ".", "workC", ")", "\n", "<-", "r", ".", "dispatchFinishedC", "\n", "}" ]
// Close will instruct the Runner to not accept any more jobs and block until // all current work is finished. // // Close may only be called once; additional calls will panic. // // The Runner's dispatch methods will panic if new work is dispatched after // Close has been called.
[ "Close", "will", "instruct", "the", "Runner", "to", "not", "accept", "any", "more", "jobs", "and", "block", "until", "all", "current", "work", "is", "finished", ".", "Close", "may", "only", "be", "called", "once", ";", "additional", "calls", "will", "panic...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/sync/parallel/runner.go#L164-L169
8,509
luci/luci-go
common/sync/parallel/runner.go
runThen
func (r *Runner) runThen(gen func(chan<- func() error), then func()) <-chan error { r.init() return runImpl(gen, r.workC, then) }
go
func (r *Runner) runThen(gen func(chan<- func() error), then func()) <-chan error { r.init() return runImpl(gen, r.workC, then) }
[ "func", "(", "r", "*", "Runner", ")", "runThen", "(", "gen", "func", "(", "chan", "<-", "func", "(", ")", "error", ")", ",", "then", "func", "(", ")", ")", "<-", "chan", "error", "{", "r", ".", "init", "(", ")", "\n\n", "return", "runImpl", "("...
// runThen is a thin wrapper around Run that enables an after call function to // be invoked when the generator has finished.
[ "runThen", "is", "a", "thin", "wrapper", "around", "Run", "that", "enables", "an", "after", "call", "function", "to", "be", "invoked", "when", "the", "generator", "has", "finished", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/sync/parallel/runner.go#L193-L197
8,510
luci/luci-go
common/sync/parallel/runner.go
runImpl
func runImpl(gen func(chan<- func() error), workC chan<- WorkItem, then func()) <-chan error { errC := make(chan error) taskC := make(chan func() error) // Execute our generator method. go func() { defer close(taskC) gen(taskC) }() // Read tasks from taskC and dispatch actual work. go func() { if then != nil { defer then() } // Use a counter to track the number of active jobs. // // Add one implicit job for the outer task loop. This will ensure that if // we will never hit 0 until all of our tasks have dispatched. count := int32(1) finish := func() { if atomic.AddInt32(&count, -1) == 0 { close(errC) } } defer finish() // Dispatch the tasks in the task channel. for task := range taskC { atomic.AddInt32(&count, 1) workC <- WorkItem{ F: task, ErrC: errC, After: finish, } } }() return errC }
go
func runImpl(gen func(chan<- func() error), workC chan<- WorkItem, then func()) <-chan error { errC := make(chan error) taskC := make(chan func() error) // Execute our generator method. go func() { defer close(taskC) gen(taskC) }() // Read tasks from taskC and dispatch actual work. go func() { if then != nil { defer then() } // Use a counter to track the number of active jobs. // // Add one implicit job for the outer task loop. This will ensure that if // we will never hit 0 until all of our tasks have dispatched. count := int32(1) finish := func() { if atomic.AddInt32(&count, -1) == 0 { close(errC) } } defer finish() // Dispatch the tasks in the task channel. for task := range taskC { atomic.AddInt32(&count, 1) workC <- WorkItem{ F: task, ErrC: errC, After: finish, } } }() return errC }
[ "func", "runImpl", "(", "gen", "func", "(", "chan", "<-", "func", "(", ")", "error", ")", ",", "workC", "chan", "<-", "WorkItem", ",", "then", "func", "(", ")", ")", "<-", "chan", "error", "{", "errC", ":=", "make", "(", "chan", "error", ")", "\n...
// runImpl sets up a localized system where a generator generates tasks and // dispatches them to the supplied work channel. // // After all tasks have been written to the work channel, then is called.
[ "runImpl", "sets", "up", "a", "localized", "system", "where", "a", "generator", "generates", "tasks", "and", "dispatches", "them", "to", "the", "supplied", "work", "channel", ".", "After", "all", "tasks", "have", "been", "written", "to", "the", "work", "chan...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/sync/parallel/runner.go#L232-L272
8,511
luci/luci-go
luci_notify/config/config.go
updateProject
func updateProject(c context.Context, cs *parsedProjectConfigSet) error { return datastore.RunInTransaction(c, func(c context.Context) error { project := &Project{ Name: cs.ProjectID, Revision: cs.Revision, URL: cs.ViewURL, } parentKey := datastore.KeyForObj(c, project) toSave := make([]interface{}, 0, 1+len(cs.ProjectConfig.Notifiers)+len(cs.EmailTemplates)) toSave = append(toSave, project) // Collect the list of builders we want to update or create. liveBuilders := stringset.New(len(cs.ProjectConfig.Notifiers)) builders := make([]*Builder, 0, len(cs.ProjectConfig.Notifiers)) for _, cfgNotifier := range cs.ProjectConfig.Notifiers { for _, cfgBuilder := range cfgNotifier.Builders { id := fmt.Sprintf("%s/%s", cfgBuilder.Bucket, cfgBuilder.Name) builders = append(builders, &Builder{ ProjectKey: parentKey, ID: id, }) liveBuilders.Add(id) } } // Lookup the builders in the datastore, if they're not found that's OK since // there could be new builders being initialized. datastore.Get(c, builders) i := 0 for _, cfgNotifier := range cs.ProjectConfig.Notifiers { for _, cfgBuilder := range cfgNotifier.Builders { builders[i].Repository = cfgBuilder.Repository builders[i].Notifications = notifypb.Notifications{ Notifications: cfgNotifier.Notifications, } toSave = append(toSave, builders[i]) i++ } } for _, et := range cs.EmailTemplates { et.ProjectKey = parentKey toSave = append(toSave, et) } return parallel.FanOutIn(func(work chan<- func() error) { work <- func() error { return datastore.Put(c, toSave) } work <- func() error { return removeDescendants(c, "Builder", parentKey, liveBuilders.Has) } work <- func() error { return removeDescendants(c, "EmailTemplate", parentKey, func(name string) bool { _, ok := cs.EmailTemplates[name] return ok }) } }) }, nil) }
go
func updateProject(c context.Context, cs *parsedProjectConfigSet) error { return datastore.RunInTransaction(c, func(c context.Context) error { project := &Project{ Name: cs.ProjectID, Revision: cs.Revision, URL: cs.ViewURL, } parentKey := datastore.KeyForObj(c, project) toSave := make([]interface{}, 0, 1+len(cs.ProjectConfig.Notifiers)+len(cs.EmailTemplates)) toSave = append(toSave, project) // Collect the list of builders we want to update or create. liveBuilders := stringset.New(len(cs.ProjectConfig.Notifiers)) builders := make([]*Builder, 0, len(cs.ProjectConfig.Notifiers)) for _, cfgNotifier := range cs.ProjectConfig.Notifiers { for _, cfgBuilder := range cfgNotifier.Builders { id := fmt.Sprintf("%s/%s", cfgBuilder.Bucket, cfgBuilder.Name) builders = append(builders, &Builder{ ProjectKey: parentKey, ID: id, }) liveBuilders.Add(id) } } // Lookup the builders in the datastore, if they're not found that's OK since // there could be new builders being initialized. datastore.Get(c, builders) i := 0 for _, cfgNotifier := range cs.ProjectConfig.Notifiers { for _, cfgBuilder := range cfgNotifier.Builders { builders[i].Repository = cfgBuilder.Repository builders[i].Notifications = notifypb.Notifications{ Notifications: cfgNotifier.Notifications, } toSave = append(toSave, builders[i]) i++ } } for _, et := range cs.EmailTemplates { et.ProjectKey = parentKey toSave = append(toSave, et) } return parallel.FanOutIn(func(work chan<- func() error) { work <- func() error { return datastore.Put(c, toSave) } work <- func() error { return removeDescendants(c, "Builder", parentKey, liveBuilders.Has) } work <- func() error { return removeDescendants(c, "EmailTemplate", parentKey, func(name string) bool { _, ok := cs.EmailTemplates[name] return ok }) } }) }, nil) }
[ "func", "updateProject", "(", "c", "context", ".", "Context", ",", "cs", "*", "parsedProjectConfigSet", ")", "error", "{", "return", "datastore", ".", "RunInTransaction", "(", "c", ",", "func", "(", "c", "context", ".", "Context", ")", "error", "{", "proje...
// updateProject updates all relevant entities corresponding to a particular project in // a single datastore transaction. // // Returns the set of notifiers that were updated.
[ "updateProject", "updates", "all", "relevant", "entities", "corresponding", "to", "a", "particular", "project", "in", "a", "single", "datastore", "transaction", ".", "Returns", "the", "set", "of", "notifiers", "that", "were", "updated", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/config/config.go#L50-L112
8,512
luci/luci-go
luci_notify/config/config.go
clearDeadProjects
func clearDeadProjects(c context.Context, liveProjects stringset.Set) error { var allProjects []*Project projectQ := datastore.NewQuery("Project").KeysOnly(true) if err := datastore.GetAll(c, projectQ, &allProjects); err != nil { return err } return parallel.WorkPool(10, func(work chan<- func() error) { for _, p := range allProjects { p := p if !liveProjects.Has(p.Name) { work <- func() error { logging.Warningf(c, "deleting project %s", p.Name) return deleteProject(c, p.Name) } } } }) }
go
func clearDeadProjects(c context.Context, liveProjects stringset.Set) error { var allProjects []*Project projectQ := datastore.NewQuery("Project").KeysOnly(true) if err := datastore.GetAll(c, projectQ, &allProjects); err != nil { return err } return parallel.WorkPool(10, func(work chan<- func() error) { for _, p := range allProjects { p := p if !liveProjects.Has(p.Name) { work <- func() error { logging.Warningf(c, "deleting project %s", p.Name) return deleteProject(c, p.Name) } } } }) }
[ "func", "clearDeadProjects", "(", "c", "context", ".", "Context", ",", "liveProjects", "stringset", ".", "Set", ")", "error", "{", "var", "allProjects", "[", "]", "*", "Project", "\n", "projectQ", ":=", "datastore", ".", "NewQuery", "(", "\"", "\"", ")", ...
// clearDeadProjects calls deleteProject for all projects in the datastore // that are not in liveProjects.
[ "clearDeadProjects", "calls", "deleteProject", "for", "all", "projects", "in", "the", "datastore", "that", "are", "not", "in", "liveProjects", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/config/config.go#L116-L133
8,513
luci/luci-go
luci_notify/config/config.go
deleteProject
func deleteProject(c context.Context, projectId string) error { return datastore.RunInTransaction(c, func(c context.Context) error { project := &Project{Name: projectId} ancestorKey := datastore.KeyForObj(c, project) return parallel.FanOutIn(func(work chan<- func() error) { work <- func() error { return removeDescendants(c, "Builder", ancestorKey, nil) } work <- func() error { return removeDescendants(c, "EmailTemplate", ancestorKey, nil) } work <- func() error { return datastore.Delete(c, project) } }) }, nil) }
go
func deleteProject(c context.Context, projectId string) error { return datastore.RunInTransaction(c, func(c context.Context) error { project := &Project{Name: projectId} ancestorKey := datastore.KeyForObj(c, project) return parallel.FanOutIn(func(work chan<- func() error) { work <- func() error { return removeDescendants(c, "Builder", ancestorKey, nil) } work <- func() error { return removeDescendants(c, "EmailTemplate", ancestorKey, nil) } work <- func() error { return datastore.Delete(c, project) } }) }, nil) }
[ "func", "deleteProject", "(", "c", "context", ".", "Context", ",", "projectId", "string", ")", "error", "{", "return", "datastore", ".", "RunInTransaction", "(", "c", ",", "func", "(", "c", "context", ".", "Context", ")", "error", "{", "project", ":=", "...
// deleteProject deletes a Project entity and all of its descendants.
[ "deleteProject", "deletes", "a", "Project", "entity", "and", "all", "of", "its", "descendants", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/config/config.go#L136-L152
8,514
luci/luci-go
luci_notify/config/config.go
updateProjects
func updateProjects(c context.Context) error { cfgName := info.AppID(c) + ".cfg" logging.Debugf(c, "fetching configs for %s", cfgName) lucicfg := GetConfigService(c) configs, err := lucicfg.GetProjectConfigs(c, cfgName, false) if err != nil { return errors.Annotate(err, "while fetching project configs").Err() } logging.Infof(c, "got %d project configs", len(configs)) // Load revisions of the existing projects from Datastore. projectRevisions := map[string]string{} // project id -> revision err = datastore.Run(c, datastore.NewQuery("Project"), func(p *Project) error { projectRevisions[p.Name] = p.Revision return nil }) if err != nil { return err } // Update each project concurrently. err = parallel.WorkPool(10, func(work chan<- func() error) { for _, cfg := range configs { cfg := cfg curRev, ok := projectRevisions[cfg.ConfigSet.Project()] if ok && curRev == cfg.Revision { // Same revision. continue } logging.Infof( c, "upgrading config of project %q: %q => %q", cfg.ConfigSet.Project(), curRev, cfg.Revision) work <- func() error { projectId := cfg.ConfigSet.Project() project := &notifypb.ProjectConfig{} if err := proto.UnmarshalText(cfg.Content, project); err != nil { return errors.Annotate(err, "unmarshalling project config").Err() } ctx := &validation.Context{Context: c} ctx.SetFile(cfgName) validateProjectConfig(ctx, project) if err := ctx.Finalize(); err != nil { return errors.Annotate(err, "validating project config").Err() } emailTemplates, err := fetchAllEmailTemplates(c, lucicfg, projectId) if err != nil { return errors.Annotate(err, "failed to fetch email templates").Err() } parsedConfigSet := &parsedProjectConfigSet{ ProjectID: projectId, ProjectConfig: project, EmailTemplates: emailTemplates, Revision: cfg.Revision, ViewURL: cfg.ViewURL, } if err := updateProject(c, parsedConfigSet); err != nil { return errors.Annotate(err, "importing project %q", projectId).Err() } return nil } } }) if err != nil { return err } // Live projects includes both valid and invalid configurations, as long as // they are found via luci-config. Otherwise, a minor mistake in a // configuration can cause projects to be deleted. liveProjects := stringset.New(0) for _, cfg := range configs { liveProjects.Add(cfg.ConfigSet.Project()) } return clearDeadProjects(c, liveProjects) }
go
func updateProjects(c context.Context) error { cfgName := info.AppID(c) + ".cfg" logging.Debugf(c, "fetching configs for %s", cfgName) lucicfg := GetConfigService(c) configs, err := lucicfg.GetProjectConfigs(c, cfgName, false) if err != nil { return errors.Annotate(err, "while fetching project configs").Err() } logging.Infof(c, "got %d project configs", len(configs)) // Load revisions of the existing projects from Datastore. projectRevisions := map[string]string{} // project id -> revision err = datastore.Run(c, datastore.NewQuery("Project"), func(p *Project) error { projectRevisions[p.Name] = p.Revision return nil }) if err != nil { return err } // Update each project concurrently. err = parallel.WorkPool(10, func(work chan<- func() error) { for _, cfg := range configs { cfg := cfg curRev, ok := projectRevisions[cfg.ConfigSet.Project()] if ok && curRev == cfg.Revision { // Same revision. continue } logging.Infof( c, "upgrading config of project %q: %q => %q", cfg.ConfigSet.Project(), curRev, cfg.Revision) work <- func() error { projectId := cfg.ConfigSet.Project() project := &notifypb.ProjectConfig{} if err := proto.UnmarshalText(cfg.Content, project); err != nil { return errors.Annotate(err, "unmarshalling project config").Err() } ctx := &validation.Context{Context: c} ctx.SetFile(cfgName) validateProjectConfig(ctx, project) if err := ctx.Finalize(); err != nil { return errors.Annotate(err, "validating project config").Err() } emailTemplates, err := fetchAllEmailTemplates(c, lucicfg, projectId) if err != nil { return errors.Annotate(err, "failed to fetch email templates").Err() } parsedConfigSet := &parsedProjectConfigSet{ ProjectID: projectId, ProjectConfig: project, EmailTemplates: emailTemplates, Revision: cfg.Revision, ViewURL: cfg.ViewURL, } if err := updateProject(c, parsedConfigSet); err != nil { return errors.Annotate(err, "importing project %q", projectId).Err() } return nil } } }) if err != nil { return err } // Live projects includes both valid and invalid configurations, as long as // they are found via luci-config. Otherwise, a minor mistake in a // configuration can cause projects to be deleted. liveProjects := stringset.New(0) for _, cfg := range configs { liveProjects.Add(cfg.ConfigSet.Project()) } return clearDeadProjects(c, liveProjects) }
[ "func", "updateProjects", "(", "c", "context", ".", "Context", ")", "error", "{", "cfgName", ":=", "info", ".", "AppID", "(", "c", ")", "+", "\"", "\"", "\n", "logging", ".", "Debugf", "(", "c", ",", "\"", "\"", ",", "cfgName", ")", "\n", "lucicfg"...
// updateProjects updates all Projects and their Notifiers in the datastore.
[ "updateProjects", "updates", "all", "Projects", "and", "their", "Notifiers", "in", "the", "datastore", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/config/config.go#L155-L235
8,515
luci/luci-go
luci_notify/config/config.go
WithConfigService
func WithConfigService(c context.Context, cInterface configInterface.Interface) context.Context { return context.WithValue(c, &configInterfaceKey, cInterface) }
go
func WithConfigService(c context.Context, cInterface configInterface.Interface) context.Context { return context.WithValue(c, &configInterfaceKey, cInterface) }
[ "func", "WithConfigService", "(", "c", "context", ".", "Context", ",", "cInterface", "configInterface", ".", "Interface", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "c", ",", "&", "configInterfaceKey", ",", "cInterface", "...
// WithConfigService sets a luci_notify config interface to be used for all config interaction.
[ "WithConfigService", "sets", "a", "luci_notify", "config", "interface", "to", "be", "used", "for", "all", "config", "interaction", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/config/config.go#L240-L242
8,516
luci/luci-go
luci_notify/config/config.go
GetConfigService
func GetConfigService(c context.Context) configInterface.Interface { if iface, ok := c.Value(&configInterfaceKey).(configInterface.Interface); ok { return iface } return nil }
go
func GetConfigService(c context.Context) configInterface.Interface { if iface, ok := c.Value(&configInterfaceKey).(configInterface.Interface); ok { return iface } return nil }
[ "func", "GetConfigService", "(", "c", "context", ".", "Context", ")", "configInterface", ".", "Interface", "{", "if", "iface", ",", "ok", ":=", "c", ".", "Value", "(", "&", "configInterfaceKey", ")", ".", "(", "configInterface", ".", "Interface", ")", ";",...
// GetConfigService returns an Inteface based on the provided context values
[ "GetConfigService", "returns", "an", "Inteface", "based", "on", "the", "provided", "context", "values" ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/config/config.go#L245-L250
8,517
luci/luci-go
luci_notify/config/config.go
UpdateHandler
func UpdateHandler(ctx *router.Context) { c, h := ctx.Context, ctx.Writer c, _ = context.WithTimeout(c, time.Minute) if err := updateProjects(c); err != nil { logging.WithError(err).Errorf(c, "error while updating project configs") h.WriteHeader(http.StatusInternalServerError) return } if err := updateSettings(c); err != nil { logging.WithError(err).Errorf(c, "error while updating settings") h.WriteHeader(http.StatusInternalServerError) return } h.WriteHeader(http.StatusOK) }
go
func UpdateHandler(ctx *router.Context) { c, h := ctx.Context, ctx.Writer c, _ = context.WithTimeout(c, time.Minute) if err := updateProjects(c); err != nil { logging.WithError(err).Errorf(c, "error while updating project configs") h.WriteHeader(http.StatusInternalServerError) return } if err := updateSettings(c); err != nil { logging.WithError(err).Errorf(c, "error while updating settings") h.WriteHeader(http.StatusInternalServerError) return } h.WriteHeader(http.StatusOK) }
[ "func", "UpdateHandler", "(", "ctx", "*", "router", ".", "Context", ")", "{", "c", ",", "h", ":=", "ctx", ".", "Context", ",", "ctx", ".", "Writer", "\n", "c", ",", "_", "=", "context", ".", "WithTimeout", "(", "c", ",", "time", ".", "Minute", ")...
// UpdateHandler is the HTTP router handler for handling cron-triggered // configuration update requests.
[ "UpdateHandler", "is", "the", "HTTP", "router", "handler", "for", "handling", "cron", "-", "triggered", "configuration", "update", "requests", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/config/config.go#L254-L268
8,518
luci/luci-go
luci_notify/config/config.go
removeDescendants
func removeDescendants(c context.Context, kind string, ancestor *datastore.Key, preserve func(string) bool) error { var toDelete []*datastore.Key q := datastore.NewQuery(kind).Ancestor(ancestor).KeysOnly(true) err := datastore.Run(c, q, func(key *datastore.Key) error { id := key.StringID() if preserve != nil && preserve(id) { return nil } logging.Infof(c, "deleting entity %s", key.String()) toDelete = append(toDelete, key) return nil }) if err != nil { return err } return datastore.Delete(c, toDelete) }
go
func removeDescendants(c context.Context, kind string, ancestor *datastore.Key, preserve func(string) bool) error { var toDelete []*datastore.Key q := datastore.NewQuery(kind).Ancestor(ancestor).KeysOnly(true) err := datastore.Run(c, q, func(key *datastore.Key) error { id := key.StringID() if preserve != nil && preserve(id) { return nil } logging.Infof(c, "deleting entity %s", key.String()) toDelete = append(toDelete, key) return nil }) if err != nil { return err } return datastore.Delete(c, toDelete) }
[ "func", "removeDescendants", "(", "c", "context", ".", "Context", ",", "kind", "string", ",", "ancestor", "*", "datastore", ".", "Key", ",", "preserve", "func", "(", "string", ")", "bool", ")", "error", "{", "var", "toDelete", "[", "]", "*", "datastore",...
// removeDescedants deletes all entities of a given kind under the ancestor. // If preserve is not nil and it returns true for a string id, the entity // is not deleted.
[ "removeDescedants", "deletes", "all", "entities", "of", "a", "given", "kind", "under", "the", "ancestor", ".", "If", "preserve", "is", "not", "nil", "and", "it", "returns", "true", "for", "a", "string", "id", "the", "entity", "is", "not", "deleted", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/luci_notify/config/config.go#L273-L289
8,519
luci/luci-go
client/archiver/uploader.go
NewUploader
func NewUploader(ctx context.Context, client *isolatedclient.Client, maxConcurrent int) *ConcurrentUploader { return newUploader(ctx, client, maxConcurrent) }
go
func NewUploader(ctx context.Context, client *isolatedclient.Client, maxConcurrent int) *ConcurrentUploader { return newUploader(ctx, client, maxConcurrent) }
[ "func", "NewUploader", "(", "ctx", "context", ".", "Context", ",", "client", "*", "isolatedclient", ".", "Client", ",", "maxConcurrent", "int", ")", "*", "ConcurrentUploader", "{", "return", "newUploader", "(", "ctx", ",", "client", ",", "maxConcurrent", ")", ...
// NewUploader creates a new ConcurrentUploader with the given isolated client. // maxConcurrent controls maximum number of uploads to be in-flight at once. // The provided context is used to make all requests to the isolate server.
[ "NewUploader", "creates", "a", "new", "ConcurrentUploader", "with", "the", "given", "isolated", "client", ".", "maxConcurrent", "controls", "maximum", "number", "of", "uploads", "to", "be", "in", "-", "flight", "at", "once", ".", "The", "provided", "context", ...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/archiver/uploader.go#L53-L55
8,520
luci/luci-go
scheduler/appengine/ui/common.go
config
func config(c context.Context) *Config { cfg, _ := c.Value(configContextKey(0)).(*Config) if cfg == nil { panic("impossible, configContextKey is not set") } return cfg }
go
func config(c context.Context) *Config { cfg, _ := c.Value(configContextKey(0)).(*Config) if cfg == nil { panic("impossible, configContextKey is not set") } return cfg }
[ "func", "config", "(", "c", "context", ".", "Context", ")", "*", "Config", "{", "cfg", ",", "_", ":=", "c", ".", "Value", "(", "configContextKey", "(", "0", ")", ")", ".", "(", "*", "Config", ")", "\n", "if", "cfg", "==", "nil", "{", "panic", "...
// config returns Config passed to InstallHandlers.
[ "config", "returns", "Config", "passed", "to", "InstallHandlers", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/ui/common.go#L75-L81
8,521
luci/luci-go
scheduler/appengine/ui/common.go
startTime
func startTime(c context.Context) time.Time { ts, ok := c.Value(startTimeContextKey(0)).(time.Time) if !ok { panic("impossible, startTimeContextKey is not set") } return ts }
go
func startTime(c context.Context) time.Time { ts, ok := c.Value(startTimeContextKey(0)).(time.Time) if !ok { panic("impossible, startTimeContextKey is not set") } return ts }
[ "func", "startTime", "(", "c", "context", ".", "Context", ")", "time", ".", "Time", "{", "ts", ",", "ok", ":=", "c", ".", "Value", "(", "startTimeContextKey", "(", "0", ")", ")", ".", "(", "time", ".", "Time", ")", "\n", "if", "!", "ok", "{", "...
// startTime returns timestamp when we started handling the request.
[ "startTime", "returns", "timestamp", "when", "we", "started", "handling", "the", "request", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/ui/common.go#L86-L92
8,522
luci/luci-go
buildbucket/luciexe/logdog.go
ExportIntoEnv
func (l *logdogServer) ExportIntoEnv(env environ.Env) error { if l.serv == nil { return fmt.Errorf("not started") } (&bootstrap.Environment{ CoordinatorHost: l.CoordinatorHost, Project: l.Project, Prefix: l.Prefix, StreamServerURI: l.serv.Address(), }).Augment(env) return nil }
go
func (l *logdogServer) ExportIntoEnv(env environ.Env) error { if l.serv == nil { return fmt.Errorf("not started") } (&bootstrap.Environment{ CoordinatorHost: l.CoordinatorHost, Project: l.Project, Prefix: l.Prefix, StreamServerURI: l.serv.Address(), }).Augment(env) return nil }
[ "func", "(", "l", "*", "logdogServer", ")", "ExportIntoEnv", "(", "env", "environ", ".", "Env", ")", "error", "{", "if", "l", ".", "serv", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "(", "&", "boots...
// ExportIntoEnv modifies env to export location of this local LogDog server // into the environment, so a subprocesses can stream logs.
[ "ExportIntoEnv", "modifies", "env", "to", "export", "location", "of", "this", "local", "LogDog", "server", "into", "the", "environment", "so", "a", "subprocesses", "can", "stream", "logs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/luciexe/logdog.go#L142-L154
8,523
luci/luci-go
buildbucket/luciexe/logdog.go
AddStream
func (l *logdogServer) AddStream(rc io.ReadCloser, props *streamproto.Properties) error { return l.butler.AddStream(rc, props) }
go
func (l *logdogServer) AddStream(rc io.ReadCloser, props *streamproto.Properties) error { return l.butler.AddStream(rc, props) }
[ "func", "(", "l", "*", "logdogServer", ")", "AddStream", "(", "rc", "io", ".", "ReadCloser", ",", "props", "*", "streamproto", ".", "Properties", ")", "error", "{", "return", "l", ".", "butler", ".", "AddStream", "(", "rc", ",", "props", ")", "\n", "...
// AddStream adds a new stream. // If no error is returned, the logdogServ assumes ownership of the supplied // stream. The stream will be closed when processing is finished.
[ "AddStream", "adds", "a", "new", "stream", ".", "If", "no", "error", "is", "returned", "the", "logdogServ", "assumes", "ownership", "of", "the", "supplied", "stream", ".", "The", "stream", "will", "be", "closed", "when", "processing", "is", "finished", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/luciexe/logdog.go#L159-L161
8,524
luci/luci-go
buildbucket/luciexe/logdog.go
Stop
func (l *logdogServer) Stop() error { if l.serv == nil { return fmt.Errorf("not started") } l.butler.Activate() if err := l.butler.Wait(); err != nil { return err } l.output.Close() l.serv = nil l.output = nil l.butler = nil return nil }
go
func (l *logdogServer) Stop() error { if l.serv == nil { return fmt.Errorf("not started") } l.butler.Activate() if err := l.butler.Wait(); err != nil { return err } l.output.Close() l.serv = nil l.output = nil l.butler = nil return nil }
[ "func", "(", "l", "*", "logdogServer", ")", "Stop", "(", ")", "error", "{", "if", "l", ".", "serv", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "l", ".", "butler", ".", "Activate", "(", ")", "\n", ...
// Stop stops the server.
[ "Stop", "stops", "the", "server", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/luciexe/logdog.go#L164-L180
8,525
luci/luci-go
buildbucket/luciexe/logdog.go
disableGRPCLogging
func disableGRPCLogging(ctx context.Context) { level := logging.Debug if !logging.IsLogging(ctx, logging.Debug) { level = grpcLogging.Suppress } grpcLogging.Install(logging.Get(ctx), level) }
go
func disableGRPCLogging(ctx context.Context) { level := logging.Debug if !logging.IsLogging(ctx, logging.Debug) { level = grpcLogging.Suppress } grpcLogging.Install(logging.Get(ctx), level) }
[ "func", "disableGRPCLogging", "(", "ctx", "context", ".", "Context", ")", "{", "level", ":=", "logging", ".", "Debug", "\n", "if", "!", "logging", ".", "IsLogging", "(", "ctx", ",", "logging", ".", "Debug", ")", "{", "level", "=", "grpcLogging", ".", "...
// disableGRPCLogging routes gRPC log messages that are emitted through our // logger. We only log gRPC prints if our logger is configured to log // debug-level or lower, which it isn't by default.
[ "disableGRPCLogging", "routes", "gRPC", "log", "messages", "that", "are", "emitted", "through", "our", "logger", ".", "We", "only", "log", "gRPC", "prints", "if", "our", "logger", "is", "configured", "to", "log", "debug", "-", "level", "or", "lower", "which"...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/luciexe/logdog.go#L185-L191
8,526
luci/luci-go
common/gcloud/pubsub/subscription.go
SplitErr
func (s Subscription) SplitErr() (p, n string, err error) { p, n, err = resourceProjectName(string(s)) return }
go
func (s Subscription) SplitErr() (p, n string, err error) { p, n, err = resourceProjectName(string(s)) return }
[ "func", "(", "s", "Subscription", ")", "SplitErr", "(", ")", "(", "p", ",", "n", "string", ",", "err", "error", ")", "{", "p", ",", "n", ",", "err", "=", "resourceProjectName", "(", "string", "(", "s", ")", ")", "\n", "return", "\n", "}" ]
// SplitErr returns the Subscription's project and name components.
[ "SplitErr", "returns", "the", "Subscription", "s", "project", "and", "name", "components", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/gcloud/pubsub/subscription.go#L59-L62
8,527
luci/luci-go
server/settings/context.go
Use
func Use(c context.Context, s *Settings) context.Context { return context.WithValue(c, contextKey(0), s) }
go
func Use(c context.Context, s *Settings) context.Context { return context.WithValue(c, contextKey(0), s) }
[ "func", "Use", "(", "c", "context", ".", "Context", ",", "s", "*", "Settings", ")", "context", ".", "Context", "{", "return", "context", ".", "WithValue", "(", "c", ",", "contextKey", "(", "0", ")", ",", "s", ")", "\n", "}" ]
// Use injects Settings into the context to be used by Get and Set.
[ "Use", "injects", "Settings", "into", "the", "context", "to", "be", "used", "by", "Get", "and", "Set", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/settings/context.go#L22-L24
8,528
luci/luci-go
server/settings/context.go
GetSettings
func GetSettings(c context.Context) *Settings { if s, ok := c.Value(contextKey(0)).(*Settings); ok && s != nil { return s } return nil }
go
func GetSettings(c context.Context) *Settings { if s, ok := c.Value(contextKey(0)).(*Settings); ok && s != nil { return s } return nil }
[ "func", "GetSettings", "(", "c", "context", ".", "Context", ")", "*", "Settings", "{", "if", "s", ",", "ok", ":=", "c", ".", "Value", "(", "contextKey", "(", "0", ")", ")", ".", "(", "*", "Settings", ")", ";", "ok", "&&", "s", "!=", "nil", "{",...
// GetSettings grabs Settings from the context if it's there.
[ "GetSettings", "grabs", "Settings", "from", "the", "context", "if", "it", "s", "there", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/settings/context.go#L27-L32
8,529
luci/luci-go
machine-db/client/cli/switches.go
printSwitches
func printSwitches(tsv bool, switches ...*crimson.Switch) { if len(switches) > 0 { p := newStdoutPrinter(tsv) defer p.Flush() if !tsv { p.Row("Name", "Ports", "Rack", "Datacenter", "Description", "State") } for _, s := range switches { p.Row(s.Name, s.Ports, s.Rack, s.Datacenter, s.Description, s.State) } } }
go
func printSwitches(tsv bool, switches ...*crimson.Switch) { if len(switches) > 0 { p := newStdoutPrinter(tsv) defer p.Flush() if !tsv { p.Row("Name", "Ports", "Rack", "Datacenter", "Description", "State") } for _, s := range switches { p.Row(s.Name, s.Ports, s.Rack, s.Datacenter, s.Description, s.State) } } }
[ "func", "printSwitches", "(", "tsv", "bool", ",", "switches", "...", "*", "crimson", ".", "Switch", ")", "{", "if", "len", "(", "switches", ")", ">", "0", "{", "p", ":=", "newStdoutPrinter", "(", "tsv", ")", "\n", "defer", "p", ".", "Flush", "(", "...
// printSwitches prints switch data to stdout in tab-separated columns.
[ "printSwitches", "prints", "switch", "data", "to", "stdout", "in", "tab", "-", "separated", "columns", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/switches.go#L28-L39
8,530
luci/luci-go
machine-db/client/cli/switches.go
Run
func (c *GetSwitchesCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int { ctx := cli.GetContext(app, c, env) client := getClient(ctx) resp, err := client.ListSwitches(ctx, &c.req) if err != nil { errors.Log(ctx, err) return 1 } printSwitches(c.f.tsv, resp.Switches...) return 0 }
go
func (c *GetSwitchesCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int { ctx := cli.GetContext(app, c, env) client := getClient(ctx) resp, err := client.ListSwitches(ctx, &c.req) if err != nil { errors.Log(ctx, err) return 1 } printSwitches(c.f.tsv, resp.Switches...) return 0 }
[ "func", "(", "c", "*", "GetSwitchesCmd", ")", "Run", "(", "app", "subcommands", ".", "Application", ",", "args", "[", "]", "string", ",", "env", "subcommands", ".", "Env", ")", "int", "{", "ctx", ":=", "cli", ".", "GetContext", "(", "app", ",", "c", ...
// Run runs the command to get switches.
[ "Run", "runs", "the", "command", "to", "get", "switches", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/switches.go#L48-L58
8,531
luci/luci-go
machine-db/client/cli/switches.go
getSwitchesCmd
func getSwitchesCmd(params *Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "get-switches [-name <name>]... [-rack <rack>]... [-dc <datacenter>]...", ShortDesc: "retrieves switches", LongDesc: "Retrieves switches matching the given names, racks and dcs, or all switches if names, racks, and dcs are omitted.\n\nExample to get all switches:\ncrimson get-switches\nExample to get the switch of rack xx1:\ncrimson get-switches -rack xx1", CommandRun: func() subcommands.CommandRun { cmd := &GetSwitchesCmd{} cmd.Initialize(params) cmd.Flags.Var(flag.StringSlice(&cmd.req.Names), "name", "Name of a switch to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Racks), "rack", "Name of a rack to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Datacenters), "dc", "Name of a datacenter to filter by. Can be specified multiple times.") return cmd }, } }
go
func getSwitchesCmd(params *Parameters) *subcommands.Command { return &subcommands.Command{ UsageLine: "get-switches [-name <name>]... [-rack <rack>]... [-dc <datacenter>]...", ShortDesc: "retrieves switches", LongDesc: "Retrieves switches matching the given names, racks and dcs, or all switches if names, racks, and dcs are omitted.\n\nExample to get all switches:\ncrimson get-switches\nExample to get the switch of rack xx1:\ncrimson get-switches -rack xx1", CommandRun: func() subcommands.CommandRun { cmd := &GetSwitchesCmd{} cmd.Initialize(params) cmd.Flags.Var(flag.StringSlice(&cmd.req.Names), "name", "Name of a switch to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Racks), "rack", "Name of a rack to filter by. Can be specified multiple times.") cmd.Flags.Var(flag.StringSlice(&cmd.req.Datacenters), "dc", "Name of a datacenter to filter by. Can be specified multiple times.") return cmd }, } }
[ "func", "getSwitchesCmd", "(", "params", "*", "Parameters", ")", "*", "subcommands", ".", "Command", "{", "return", "&", "subcommands", ".", "Command", "{", "UsageLine", ":", "\"", "\"", ",", "ShortDesc", ":", "\"", "\"", ",", "LongDesc", ":", "\"", "\\n...
// getSwitchesCmd returns a command to get switches.
[ "getSwitchesCmd", "returns", "a", "command", "to", "get", "switches", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/switches.go#L61-L75
8,532
luci/luci-go
logdog/client/butler/streamserver/namedPipe_windows.go
NewNamedPipeServer
func NewNamedPipeServer(ctx context.Context, name string) (StreamServer, error) { switch l := len(name); { case l == 0: return nil, errors.New("cannot have empty name") case l > maxWindowsNamedPipeLength: return nil, errors.Reason("name exceeds maximum length %d", maxWindowsNamedPipeLength). InternalReason("name(%s)", name).Err() } ctx = log.SetField(ctx, "name", name) return &listenerStreamServer{ Context: ctx, gen: func() (net.Listener, string, error) { address := "net.pipe:" + name pipePath := streamclient.LocalNamedPipePath(name) log.Fields{ "addr": address, "pipePath": pipePath, }.Debugf(ctx, "Creating Windows server socket Listener.") l, err := winio.ListenPipe(pipePath, nil) if err != nil { return nil, "", errors.Annotate(err, "failed to listen on named pipe").Err() } return l, address, nil }, }, nil }
go
func NewNamedPipeServer(ctx context.Context, name string) (StreamServer, error) { switch l := len(name); { case l == 0: return nil, errors.New("cannot have empty name") case l > maxWindowsNamedPipeLength: return nil, errors.Reason("name exceeds maximum length %d", maxWindowsNamedPipeLength). InternalReason("name(%s)", name).Err() } ctx = log.SetField(ctx, "name", name) return &listenerStreamServer{ Context: ctx, gen: func() (net.Listener, string, error) { address := "net.pipe:" + name pipePath := streamclient.LocalNamedPipePath(name) log.Fields{ "addr": address, "pipePath": pipePath, }.Debugf(ctx, "Creating Windows server socket Listener.") l, err := winio.ListenPipe(pipePath, nil) if err != nil { return nil, "", errors.Annotate(err, "failed to listen on named pipe").Err() } return l, address, nil }, }, nil }
[ "func", "NewNamedPipeServer", "(", "ctx", "context", ".", "Context", ",", "name", "string", ")", "(", "StreamServer", ",", "error", ")", "{", "switch", "l", ":=", "len", "(", "name", ")", ";", "{", "case", "l", "==", "0", ":", "return", "nil", ",", ...
// NewNamedPipeServer instantiates a new Windows named pipe server instance.
[ "NewNamedPipeServer", "instantiates", "a", "new", "Windows", "named", "pipe", "server", "instance", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/streamserver/namedPipe_windows.go#L32-L59
8,533
luci/luci-go
logdog/appengine/coordinator/auth.go
IsAdminUser
func IsAdminUser(c context.Context) error { cfg, err := GetConfigProvider(c).Config(c) if err != nil { return err } return checkMember(c, cfg.Coordinator.AdminAuthGroup) }
go
func IsAdminUser(c context.Context) error { cfg, err := GetConfigProvider(c).Config(c) if err != nil { return err } return checkMember(c, cfg.Coordinator.AdminAuthGroup) }
[ "func", "IsAdminUser", "(", "c", "context", ".", "Context", ")", "error", "{", "cfg", ",", "err", ":=", "GetConfigProvider", "(", "c", ")", ".", "Config", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return...
// IsAdminUser tests whether the current user belongs to the administrative // users group. // // If the user is not, a MembershipError will be returned.
[ "IsAdminUser", "tests", "whether", "the", "current", "user", "belongs", "to", "the", "administrative", "users", "group", ".", "If", "the", "user", "is", "not", "a", "MembershipError", "will", "be", "returned", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/auth.go#L33-L39
8,534
luci/luci-go
logdog/appengine/coordinator/auth.go
IsServiceUser
func IsServiceUser(c context.Context) error { cfg, err := GetConfigProvider(c).Config(c) if err != nil { return err } return checkMember(c, cfg.Coordinator.ServiceAuthGroup) }
go
func IsServiceUser(c context.Context) error { cfg, err := GetConfigProvider(c).Config(c) if err != nil { return err } return checkMember(c, cfg.Coordinator.ServiceAuthGroup) }
[ "func", "IsServiceUser", "(", "c", "context", ".", "Context", ")", "error", "{", "cfg", ",", "err", ":=", "GetConfigProvider", "(", "c", ")", ".", "Config", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "retu...
// IsServiceUser tests whether the current user belongs to the backend services // users group. // // If the user is not, a MembershipError will be returned.
[ "IsServiceUser", "tests", "whether", "the", "current", "user", "belongs", "to", "the", "backend", "services", "users", "group", ".", "If", "the", "user", "is", "not", "a", "MembershipError", "will", "be", "returned", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/auth.go#L45-L51
8,535
luci/luci-go
logdog/appengine/coordinator/auth.go
IsProjectReader
func IsProjectReader(c context.Context, pcfg *svcconfig.ProjectConfig) error { return checkMember(c, pcfg.ReaderAuthGroups...) }
go
func IsProjectReader(c context.Context, pcfg *svcconfig.ProjectConfig) error { return checkMember(c, pcfg.ReaderAuthGroups...) }
[ "func", "IsProjectReader", "(", "c", "context", ".", "Context", ",", "pcfg", "*", "svcconfig", ".", "ProjectConfig", ")", "error", "{", "return", "checkMember", "(", "c", ",", "pcfg", ".", "ReaderAuthGroups", "...", ")", "\n", "}" ]
// IsProjectReader tests whether the current user belongs to one of the // project's declared reader groups. // // If the user is not, a MembershipError will be returned.
[ "IsProjectReader", "tests", "whether", "the", "current", "user", "belongs", "to", "one", "of", "the", "project", "s", "declared", "reader", "groups", ".", "If", "the", "user", "is", "not", "a", "MembershipError", "will", "be", "returned", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/auth.go#L57-L59
8,536
luci/luci-go
logdog/appengine/coordinator/auth.go
IsProjectWriter
func IsProjectWriter(c context.Context, pcfg *svcconfig.ProjectConfig) error { return checkMember(c, pcfg.WriterAuthGroups...) }
go
func IsProjectWriter(c context.Context, pcfg *svcconfig.ProjectConfig) error { return checkMember(c, pcfg.WriterAuthGroups...) }
[ "func", "IsProjectWriter", "(", "c", "context", ".", "Context", ",", "pcfg", "*", "svcconfig", ".", "ProjectConfig", ")", "error", "{", "return", "checkMember", "(", "c", ",", "pcfg", ".", "WriterAuthGroups", "...", ")", "\n", "}" ]
// IsProjectWriter tests whether the current user belongs to one of the // project's declared writer groups. // // If the user is not a member of any of the groups, a MembershipError will be // returned.
[ "IsProjectWriter", "tests", "whether", "the", "current", "user", "belongs", "to", "one", "of", "the", "project", "s", "declared", "writer", "groups", ".", "If", "the", "user", "is", "not", "a", "member", "of", "any", "of", "the", "groups", "a", "Membership...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/auth.go#L66-L68
8,537
luci/luci-go
common/gcloud/gs/limited.go
NewReader
func (lc *LimitedClient) NewReader(p Path, offset, length int64) (io.ReadCloser, error) { if lc.MaxReadBytes <= 0 || (length > 0 && length <= lc.MaxReadBytes) { return lc.Client.NewReader(p, offset, length) } lr := limitedReader{ lc: lc, path: p, maxReadBytes: lc.MaxReadBytes, nextOffset: offset, nextLength: length, } if err := lr.nextReader(); err != nil { return nil, err } return &lr, nil }
go
func (lc *LimitedClient) NewReader(p Path, offset, length int64) (io.ReadCloser, error) { if lc.MaxReadBytes <= 0 || (length > 0 && length <= lc.MaxReadBytes) { return lc.Client.NewReader(p, offset, length) } lr := limitedReader{ lc: lc, path: p, maxReadBytes: lc.MaxReadBytes, nextOffset: offset, nextLength: length, } if err := lr.nextReader(); err != nil { return nil, err } return &lr, nil }
[ "func", "(", "lc", "*", "LimitedClient", ")", "NewReader", "(", "p", "Path", ",", "offset", ",", "length", "int64", ")", "(", "io", ".", "ReadCloser", ",", "error", ")", "{", "if", "lc", ".", "MaxReadBytes", "<=", "0", "||", "(", "length", ">", "0"...
// NewReader implements Client.
[ "NewReader", "implements", "Client", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/gcloud/gs/limited.go#L33-L49
8,538
luci/luci-go
common/tsmon/target/flags.go
NewFlags
func NewFlags() Flags { return Flags{ TargetType: DeviceType, DeviceHostname: "", DeviceRegion: "", DeviceRole: "default", DeviceNetwork: "", TaskServiceName: "", TaskJobName: "", TaskRegion: "", TaskHostname: "", TaskNumber: 0, AutoGenHostname: false, } }
go
func NewFlags() Flags { return Flags{ TargetType: DeviceType, DeviceHostname: "", DeviceRegion: "", DeviceRole: "default", DeviceNetwork: "", TaskServiceName: "", TaskJobName: "", TaskRegion: "", TaskHostname: "", TaskNumber: 0, AutoGenHostname: false, } }
[ "func", "NewFlags", "(", ")", "Flags", "{", "return", "Flags", "{", "TargetType", ":", "DeviceType", ",", "DeviceHostname", ":", "\"", "\"", ",", "DeviceRegion", ":", "\"", "\"", ",", "DeviceRole", ":", "\"", "\"", ",", "DeviceNetwork", ":", "\"", "\"", ...
// NewFlags returns a Flags struct with sensible default values. Hostname, // region and network flags are expensive to compute, so get assigned default // values later in SetDefaultsFromHostname.
[ "NewFlags", "returns", "a", "Flags", "struct", "with", "sensible", "default", "values", ".", "Hostname", "region", "and", "network", "flags", "are", "expensive", "to", "compute", "so", "get", "assigned", "default", "values", "later", "in", "SetDefaultsFromHostname...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/target/flags.go#L53-L67
8,539
luci/luci-go
common/tsmon/target/flags.go
SetDefaultsFromHostname
func (fl *Flags) SetDefaultsFromHostname() { if fl.SysInfo == nil { hostname, region := getFQDN() fl.SysInfo = &SysInfo{Hostname: hostname, Region: region} } network := getNetwork(fl.SysInfo.Hostname) hostname := fl.SysInfo.Hostname if fl.DeviceHostname == "" { fl.DeviceHostname = hostname } if fl.DeviceRegion == "" { fl.DeviceRegion = fl.SysInfo.Region } if fl.DeviceNetwork == "" { fl.DeviceNetwork = network } if fl.TaskRegion == "" { fl.TaskRegion = fl.SysInfo.Region } if fl.TaskHostname == "" { fl.TaskHostname = hostname } if fl.AutoGenHostname { fl.DeviceHostname = "autogen:" + fl.DeviceHostname fl.TaskHostname = "autogen:" + fl.TaskHostname } }
go
func (fl *Flags) SetDefaultsFromHostname() { if fl.SysInfo == nil { hostname, region := getFQDN() fl.SysInfo = &SysInfo{Hostname: hostname, Region: region} } network := getNetwork(fl.SysInfo.Hostname) hostname := fl.SysInfo.Hostname if fl.DeviceHostname == "" { fl.DeviceHostname = hostname } if fl.DeviceRegion == "" { fl.DeviceRegion = fl.SysInfo.Region } if fl.DeviceNetwork == "" { fl.DeviceNetwork = network } if fl.TaskRegion == "" { fl.TaskRegion = fl.SysInfo.Region } if fl.TaskHostname == "" { fl.TaskHostname = hostname } if fl.AutoGenHostname { fl.DeviceHostname = "autogen:" + fl.DeviceHostname fl.TaskHostname = "autogen:" + fl.TaskHostname } }
[ "func", "(", "fl", "*", "Flags", ")", "SetDefaultsFromHostname", "(", ")", "{", "if", "fl", ".", "SysInfo", "==", "nil", "{", "hostname", ",", "region", ":=", "getFQDN", "(", ")", "\n", "fl", ".", "SysInfo", "=", "&", "SysInfo", "{", "Hostname", ":",...
// SetDefaultsFromHostname computes the expensive default values for hostname, // region and network fields.
[ "SetDefaultsFromHostname", "computes", "the", "expensive", "default", "values", "for", "hostname", "region", "and", "network", "fields", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/target/flags.go#L71-L98
8,540
luci/luci-go
common/tsmon/target/flags.go
Register
func (fl *Flags) Register(f *flag.FlagSet) { f.Var(&fl.TargetType, "ts-mon-target-type", "the type of target that is being monitored ("+targetTypeEnum.Choices()+")") f.StringVar(&fl.DeviceHostname, "ts-mon-device-hostname", fl.DeviceHostname, "name of this device") f.StringVar(&fl.DeviceRegion, "ts-mon-device-region", fl.DeviceRegion, "name of the region this devices lives in") f.StringVar(&fl.DeviceRole, "ts-mon-device-role", fl.DeviceRole, "role of the device") f.StringVar(&fl.DeviceNetwork, "ts-mon-device-network", fl.DeviceNetwork, "name of the network this device is connected to") f.StringVar(&fl.TaskServiceName, "ts-mon-task-service-name", fl.TaskServiceName, "name of the service being monitored") f.StringVar(&fl.TaskJobName, "ts-mon-task-job-name", fl.TaskJobName, "name of this job instance of the task") f.StringVar(&fl.TaskRegion, "ts-mon-task-region", fl.TaskRegion, "name of the region in which this task is running") f.StringVar(&fl.TaskHostname, "ts-mon-task-hostname", fl.TaskHostname, "name of the host on which this task is running") f.IntVar(&fl.TaskNumber, "ts-mon-task-number", fl.TaskNumber, "number (e.g. for replication) of this instance of this task") f.BoolVar(&fl.AutoGenHostname, "ts-mon-autogen-hostname", fl.AutoGenHostname, "Indicate that the hostname is autogenerated. "+ "This option must be set on autoscaled GCE VMs, Kubernetes pods, "+ "or any other hosts with dynamically generated names.") }
go
func (fl *Flags) Register(f *flag.FlagSet) { f.Var(&fl.TargetType, "ts-mon-target-type", "the type of target that is being monitored ("+targetTypeEnum.Choices()+")") f.StringVar(&fl.DeviceHostname, "ts-mon-device-hostname", fl.DeviceHostname, "name of this device") f.StringVar(&fl.DeviceRegion, "ts-mon-device-region", fl.DeviceRegion, "name of the region this devices lives in") f.StringVar(&fl.DeviceRole, "ts-mon-device-role", fl.DeviceRole, "role of the device") f.StringVar(&fl.DeviceNetwork, "ts-mon-device-network", fl.DeviceNetwork, "name of the network this device is connected to") f.StringVar(&fl.TaskServiceName, "ts-mon-task-service-name", fl.TaskServiceName, "name of the service being monitored") f.StringVar(&fl.TaskJobName, "ts-mon-task-job-name", fl.TaskJobName, "name of this job instance of the task") f.StringVar(&fl.TaskRegion, "ts-mon-task-region", fl.TaskRegion, "name of the region in which this task is running") f.StringVar(&fl.TaskHostname, "ts-mon-task-hostname", fl.TaskHostname, "name of the host on which this task is running") f.IntVar(&fl.TaskNumber, "ts-mon-task-number", fl.TaskNumber, "number (e.g. for replication) of this instance of this task") f.BoolVar(&fl.AutoGenHostname, "ts-mon-autogen-hostname", fl.AutoGenHostname, "Indicate that the hostname is autogenerated. "+ "This option must be set on autoscaled GCE VMs, Kubernetes pods, "+ "or any other hosts with dynamically generated names.") }
[ "func", "(", "fl", "*", "Flags", ")", "Register", "(", "f", "*", "flag", ".", "FlagSet", ")", "{", "f", ".", "Var", "(", "&", "fl", ".", "TargetType", ",", "\"", "\"", ",", "\"", "\"", "+", "targetTypeEnum", ".", "Choices", "(", ")", "+", "\"",...
// Register adds tsmon target related flags to a FlagSet.
[ "Register", "adds", "tsmon", "target", "related", "flags", "to", "a", "FlagSet", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/tsmon/target/flags.go#L101-L126
8,541
luci/luci-go
dm/appengine/distributor/config.go
EnqueueTask
func (cfg *Config) EnqueueTask(c context.Context, tsk *tq.Task) error { tsk.Path = handlerPath(cfg.Name) return tq.Add(c, "", tsk) }
go
func (cfg *Config) EnqueueTask(c context.Context, tsk *tq.Task) error { tsk.Path = handlerPath(cfg.Name) return tq.Add(c, "", tsk) }
[ "func", "(", "cfg", "*", "Config", ")", "EnqueueTask", "(", "c", "context", ".", "Context", ",", "tsk", "*", "tq", ".", "Task", ")", "error", "{", "tsk", ".", "Path", "=", "handlerPath", "(", "cfg", ".", "Name", ")", "\n", "return", "tq", ".", "A...
// EnqueueTask allows a Distributor to enqueue a TaskQueue task that will be // handled by the Distributor's HandleTaskQueueTask method.
[ "EnqueueTask", "allows", "a", "Distributor", "to", "enqueue", "a", "TaskQueue", "task", "that", "will", "be", "handled", "by", "the", "Distributor", "s", "HandleTaskQueueTask", "method", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/distributor/config.go#L49-L52
8,542
luci/luci-go
dm/appengine/distributor/config.go
PrepareTopic
func (cfg *Config) PrepareTopic(c context.Context, eid *dm.Execution_ID) (topic pubsub.Topic, token string, err error) { topic = pubsub.NewTopic(info.TrimmedAppID(c), notifyTopicSuffix) if err := topic.Validate(); err != nil { panic(fmt.Errorf("failed to validate Topic %q: %s", topic, err)) } token, err = encodeAuthToken(c, eid, cfg.Name) return }
go
func (cfg *Config) PrepareTopic(c context.Context, eid *dm.Execution_ID) (topic pubsub.Topic, token string, err error) { topic = pubsub.NewTopic(info.TrimmedAppID(c), notifyTopicSuffix) if err := topic.Validate(); err != nil { panic(fmt.Errorf("failed to validate Topic %q: %s", topic, err)) } token, err = encodeAuthToken(c, eid, cfg.Name) return }
[ "func", "(", "cfg", "*", "Config", ")", "PrepareTopic", "(", "c", "context", ".", "Context", ",", "eid", "*", "dm", ".", "Execution_ID", ")", "(", "topic", "pubsub", ".", "Topic", ",", "token", "string", ",", "err", "error", ")", "{", "topic", "=", ...
// PrepareTopic returns a pubsub topic that notifications should be sent to, and // is meant to be called from the D.Run method. // // It returns the full name of the topic and a token that will be used to route // PubSub messages back to the Distributor. The publisher to the topic must be // instructed to put the token into the 'auth_token' attribute of PubSub // messages. DM will know how to route such messages to D.HandleNotification.
[ "PrepareTopic", "returns", "a", "pubsub", "topic", "that", "notifications", "should", "be", "sent", "to", "and", "is", "meant", "to", "be", "called", "from", "the", "D", ".", "Run", "method", ".", "It", "returns", "the", "full", "name", "of", "the", "top...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/distributor/config.go#L61-L68
8,543
luci/luci-go
starlark/builtins/stacktrace.go
CaptureStacktrace
func CaptureStacktrace(th *starlark.Thread, skip int) (*CapturedStacktrace, error) { f := th.Caller() skipped := 0 for skipped < skip && f != nil { f = f.Parent() skipped++ } if f == nil { return nil, fmt.Errorf("stacktrace: the stack is not deep enough to skip %d levels, has only %d frames", skip, skipped) } buf := strings.Builder{} f.WriteBacktrace(&buf) return &CapturedStacktrace{buf.String()}, nil }
go
func CaptureStacktrace(th *starlark.Thread, skip int) (*CapturedStacktrace, error) { f := th.Caller() skipped := 0 for skipped < skip && f != nil { f = f.Parent() skipped++ } if f == nil { return nil, fmt.Errorf("stacktrace: the stack is not deep enough to skip %d levels, has only %d frames", skip, skipped) } buf := strings.Builder{} f.WriteBacktrace(&buf) return &CapturedStacktrace{buf.String()}, nil }
[ "func", "CaptureStacktrace", "(", "th", "*", "starlark", ".", "Thread", ",", "skip", "int", ")", "(", "*", "CapturedStacktrace", ",", "error", ")", "{", "f", ":=", "th", ".", "Caller", "(", ")", "\n", "skipped", ":=", "0", "\n", "for", "skipped", "<"...
// CaptureStacktrace captures thread's stack trace, skipping some number of // innermost frames. // // Returns an error if the stack is not deep enough to skip the requested number // of frames.
[ "CaptureStacktrace", "captures", "thread", "s", "stack", "trace", "skipping", "some", "number", "of", "innermost", "frames", ".", "Returns", "an", "error", "if", "the", "stack", "is", "not", "deep", "enough", "to", "skip", "the", "requested", "number", "of", ...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/starlark/builtins/stacktrace.go#L42-L55
8,544
luci/luci-go
client/internal/common/types.go
Set
func (c *Strings) Set(value string) error { *c = append(*c, value) return nil }
go
func (c *Strings) Set(value string) error { *c = append(*c, value) return nil }
[ "func", "(", "c", "*", "Strings", ")", "Set", "(", "value", "string", ")", "error", "{", "*", "c", "=", "append", "(", "*", "c", ",", "value", ")", "\n", "return", "nil", "\n", "}" ]
// Set is needed to implements flag.Var interface.
[ "Set", "is", "needed", "to", "implements", "flag", ".", "Var", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/internal/common/types.go#L31-L34
8,545
luci/luci-go
auth/authctx/context.go
Launch
func (ac *Context) Launch(ctx context.Context, tempDir string) (nc context.Context, err error) { defer func() { if err != nil { ac.Close() } nc = ac.ctx // nil if err != nil }() ac.ctx = ctx if tempDir == "" { ac.tmpDir, err = ioutil.TempDir("", "luci") if err != nil { return nil, errors.Annotate(err, "failed to create a temp directory").Err() } tempDir = ac.tmpDir } // Expand AuthSelectMethod into the actual method. We'll be checking it later. // We do this expansion now to consistently use new 'opts' through out. opts := ac.Options if opts.Method == auth.AutoSelectMethod { opts.Method = auth.SelectBestMethod(ac.ctx, opts) } // Construct the authenticator to be used directly by the helpers hosted in // the current process (devshell, gsutil, firebase) and by the new // localauth.Server (if we are going to launch it). Out-of-process helpers // (git, docker) will use LUCI_CONTEXT protocol. ac.authenticator = auth.NewAuthenticator(ac.ctx, auth.SilentLogin, opts) // Figure out what email is associated with this account (if any). ac.email, err = ac.authenticator.GetEmail() switch { case err == auth.ErrLoginRequired: // This context is not associated with any account. This happens when // running Swarming tasks without service account specified or running // locally without doing 'luci-auth login' first. ac.anonymous = true case err != nil: return nil, errors.Annotate(err, "failed to get email of %q account", ac.ID).Err() } // Check whether we are allowed to inherit the existing LUCI_CONTEXT. We do it // if 'opts' indicate to use LUCI_CONTEXT and do NOT use impersonation. When // impersonating, we must launch a new auth server to actually perform it // there. // // If we can't reuse the existing LUCI_CONTEXT, launch a new one (deriving // a new context.Context with it). // // If there's no auth credentials at all, do not launch any LUCI_CONTEXT (it // is impossible without credentials). Subprocesses will discover lack of // ambient credentials on their own and fail (or proceed) appropriately. canInherit := opts.Method == auth.LUCIContextMethod && opts.ActAsServiceAccount == "" if !canInherit && !ac.anonymous { var la *lucictx.LocalAuth if ac.luciSrv, la, err = launchSrv(ac.ctx, opts, ac.authenticator, ac.ID); err != nil { return nil, errors.Annotate(err, "failed to launch local auth server for %q account", ac.ID).Err() } ac.ctx = lucictx.SetLocalAuth(ac.ctx, la) // switch to new LUCI_CONTEXT } // Drop the new LUCI_CONTEXT file to the disk. This is noop when reusing // an existing one. if ac.exported, err = lucictx.ExportInto(ac.ctx, tempDir); err != nil { return nil, errors.Annotate(err, "failed to export LUCI_CONTEXT for %q account", ac.ID).Err() } // Now setup various credential helpers (they all mutate 'ac' and return // annotated errors). if ac.EnableGitAuth { if err := ac.setupGitAuth(tempDir); err != nil { return nil, err } } if ac.EnableDockerAuth { if err := ac.setupDockerAuth(tempDir); err != nil { return nil, err } } if ac.EnableDevShell && !ac.anonymous { if err := ac.setupDevShellAuth(tempDir); err != nil { return nil, err } } if ac.EnableFirebaseAuth && !ac.anonymous { if err := ac.setupFirebaseAuth(); err != nil { return nil, err } } return }
go
func (ac *Context) Launch(ctx context.Context, tempDir string) (nc context.Context, err error) { defer func() { if err != nil { ac.Close() } nc = ac.ctx // nil if err != nil }() ac.ctx = ctx if tempDir == "" { ac.tmpDir, err = ioutil.TempDir("", "luci") if err != nil { return nil, errors.Annotate(err, "failed to create a temp directory").Err() } tempDir = ac.tmpDir } // Expand AuthSelectMethod into the actual method. We'll be checking it later. // We do this expansion now to consistently use new 'opts' through out. opts := ac.Options if opts.Method == auth.AutoSelectMethod { opts.Method = auth.SelectBestMethod(ac.ctx, opts) } // Construct the authenticator to be used directly by the helpers hosted in // the current process (devshell, gsutil, firebase) and by the new // localauth.Server (if we are going to launch it). Out-of-process helpers // (git, docker) will use LUCI_CONTEXT protocol. ac.authenticator = auth.NewAuthenticator(ac.ctx, auth.SilentLogin, opts) // Figure out what email is associated with this account (if any). ac.email, err = ac.authenticator.GetEmail() switch { case err == auth.ErrLoginRequired: // This context is not associated with any account. This happens when // running Swarming tasks without service account specified or running // locally without doing 'luci-auth login' first. ac.anonymous = true case err != nil: return nil, errors.Annotate(err, "failed to get email of %q account", ac.ID).Err() } // Check whether we are allowed to inherit the existing LUCI_CONTEXT. We do it // if 'opts' indicate to use LUCI_CONTEXT and do NOT use impersonation. When // impersonating, we must launch a new auth server to actually perform it // there. // // If we can't reuse the existing LUCI_CONTEXT, launch a new one (deriving // a new context.Context with it). // // If there's no auth credentials at all, do not launch any LUCI_CONTEXT (it // is impossible without credentials). Subprocesses will discover lack of // ambient credentials on their own and fail (or proceed) appropriately. canInherit := opts.Method == auth.LUCIContextMethod && opts.ActAsServiceAccount == "" if !canInherit && !ac.anonymous { var la *lucictx.LocalAuth if ac.luciSrv, la, err = launchSrv(ac.ctx, opts, ac.authenticator, ac.ID); err != nil { return nil, errors.Annotate(err, "failed to launch local auth server for %q account", ac.ID).Err() } ac.ctx = lucictx.SetLocalAuth(ac.ctx, la) // switch to new LUCI_CONTEXT } // Drop the new LUCI_CONTEXT file to the disk. This is noop when reusing // an existing one. if ac.exported, err = lucictx.ExportInto(ac.ctx, tempDir); err != nil { return nil, errors.Annotate(err, "failed to export LUCI_CONTEXT for %q account", ac.ID).Err() } // Now setup various credential helpers (they all mutate 'ac' and return // annotated errors). if ac.EnableGitAuth { if err := ac.setupGitAuth(tempDir); err != nil { return nil, err } } if ac.EnableDockerAuth { if err := ac.setupDockerAuth(tempDir); err != nil { return nil, err } } if ac.EnableDevShell && !ac.anonymous { if err := ac.setupDevShellAuth(tempDir); err != nil { return nil, err } } if ac.EnableFirebaseAuth && !ac.anonymous { if err := ac.setupFirebaseAuth(); err != nil { return nil, err } } return }
[ "func", "(", "ac", "*", "Context", ")", "Launch", "(", "ctx", "context", ".", "Context", ",", "tempDir", "string", ")", "(", "nc", "context", ".", "Context", ",", "err", "error", ")", "{", "defer", "func", "(", ")", "{", "if", "err", "!=", "nil", ...
// Launch launches this auth context. It must be called before any other method. // // It launches various local server and prepares various configs, by putting // them into tempDir which may be "" to use some new ioutil.TempDir. // // On success returns a new context.Context with updated LUCI_CONTEXT value. // // To run a subprocess within this new context use 'ExportIntoEnv' to modify an // environ for a new process.
[ "Launch", "launches", "this", "auth", "context", ".", "It", "must", "be", "called", "before", "any", "other", "method", ".", "It", "launches", "various", "local", "server", "and", "prepares", "various", "configs", "by", "putting", "them", "into", "tempDir", ...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/authctx/context.go#L153-L246
8,546
luci/luci-go
auth/authctx/context.go
ExportIntoEnv
func (ac *Context) ExportIntoEnv(env environ.Env) environ.Env { env = env.Clone() ac.exported.SetInEnviron(env) if ac.EnableGitAuth { env.Set("GIT_TERMINAL_PROMPT", "0") // no interactive prompts env.Set("GIT_CONFIG_NOSYSTEM", "1") // no $(prefix)/etc/gitconfig env.Set("INFRA_GIT_WRAPPER_HOME", ac.gitHome) // tell gitwrapper about the new HOME } if ac.EnableDockerAuth { env.Set("DOCKER_CONFIG", ac.dockerConfig) env.Set("DOCKER_TMPDIR", ac.dockerTmpDir) } if ac.EnableDevShell { env.Remove("BOTO_PATH") // avoid picking up bot-local configs, if any if ac.anonymous { // Make sure gsutil is not picking up any stale .boto configs randomly // laying around on the bot. Setting BOTO_CONFIG to empty dir disables // default ~/.boto. env.Set("BOTO_CONFIG", "") } else { // Point gsutil to use our auth shim server and export devshell port. env.Set("BOTO_CONFIG", ac.gsutilBoto) if ac.devShellAddr != nil { env.Set(devshell.EnvKey, fmt.Sprintf("%d", ac.devShellAddr.Port)) } else { // See https://crbug.com/788058#c14. logging.Warningf(ac.ctx, "Disabling devshell auth for account %q", ac.ID) } } } if ac.EnableFirebaseAuth && !ac.anonymous { // Point firebase to the generated token. env.Set("FIREBASE_TOKEN_URL", ac.firebaseTokenURL) } return env }
go
func (ac *Context) ExportIntoEnv(env environ.Env) environ.Env { env = env.Clone() ac.exported.SetInEnviron(env) if ac.EnableGitAuth { env.Set("GIT_TERMINAL_PROMPT", "0") // no interactive prompts env.Set("GIT_CONFIG_NOSYSTEM", "1") // no $(prefix)/etc/gitconfig env.Set("INFRA_GIT_WRAPPER_HOME", ac.gitHome) // tell gitwrapper about the new HOME } if ac.EnableDockerAuth { env.Set("DOCKER_CONFIG", ac.dockerConfig) env.Set("DOCKER_TMPDIR", ac.dockerTmpDir) } if ac.EnableDevShell { env.Remove("BOTO_PATH") // avoid picking up bot-local configs, if any if ac.anonymous { // Make sure gsutil is not picking up any stale .boto configs randomly // laying around on the bot. Setting BOTO_CONFIG to empty dir disables // default ~/.boto. env.Set("BOTO_CONFIG", "") } else { // Point gsutil to use our auth shim server and export devshell port. env.Set("BOTO_CONFIG", ac.gsutilBoto) if ac.devShellAddr != nil { env.Set(devshell.EnvKey, fmt.Sprintf("%d", ac.devShellAddr.Port)) } else { // See https://crbug.com/788058#c14. logging.Warningf(ac.ctx, "Disabling devshell auth for account %q", ac.ID) } } } if ac.EnableFirebaseAuth && !ac.anonymous { // Point firebase to the generated token. env.Set("FIREBASE_TOKEN_URL", ac.firebaseTokenURL) } return env }
[ "func", "(", "ac", "*", "Context", ")", "ExportIntoEnv", "(", "env", "environ", ".", "Env", ")", "environ", ".", "Env", "{", "env", "=", "env", ".", "Clone", "(", ")", "\n", "ac", ".", "exported", ".", "SetInEnviron", "(", "env", ")", "\n\n", "if",...
// ExportIntoEnv exports details of this context into the environment, so it can // be inherited by subprocesses that supports it. // // Returns a modified copy of 'env'.
[ "ExportIntoEnv", "exports", "details", "of", "this", "context", "into", "the", "environment", "so", "it", "can", "be", "inherited", "by", "subprocesses", "that", "supports", "it", ".", "Returns", "a", "modified", "copy", "of", "env", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/authctx/context.go#L332-L372
8,547
luci/luci-go
auth/authctx/context.go
Report
func (ac *Context) Report() { account := ac.email if ac.anonymous { account = "anonymous" } logging.Infof(ac.ctx, "%q account is %s (git_auth: %v, devshell: %v, docker:%v, firebase: %v)", ac.ID, account, ac.EnableGitAuth, ac.EnableDevShell, ac.EnableDockerAuth, ac.EnableFirebaseAuth) }
go
func (ac *Context) Report() { account := ac.email if ac.anonymous { account = "anonymous" } logging.Infof(ac.ctx, "%q account is %s (git_auth: %v, devshell: %v, docker:%v, firebase: %v)", ac.ID, account, ac.EnableGitAuth, ac.EnableDevShell, ac.EnableDockerAuth, ac.EnableFirebaseAuth) }
[ "func", "(", "ac", "*", "Context", ")", "Report", "(", ")", "{", "account", ":=", "ac", ".", "email", "\n", "if", "ac", ".", "anonymous", "{", "account", "=", "\"", "\"", "\n", "}", "\n", "logging", ".", "Infof", "(", "ac", ".", "ctx", ",", "\"...
// Report logs the service account email used by this auth context.
[ "Report", "logs", "the", "service", "account", "email", "used", "by", "this", "auth", "context", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/authctx/context.go#L375-L383
8,548
luci/luci-go
client/archiver/tarring_archiver.go
NewTarringArchiver
func NewTarringArchiver(checker Checker, uploader Uploader) *TarringArchiver { return &TarringArchiver{checker: checker, uploader: uploader} }
go
func NewTarringArchiver(checker Checker, uploader Uploader) *TarringArchiver { return &TarringArchiver{checker: checker, uploader: uploader} }
[ "func", "NewTarringArchiver", "(", "checker", "Checker", ",", "uploader", "Uploader", ")", "*", "TarringArchiver", "{", "return", "&", "TarringArchiver", "{", "checker", ":", "checker", ",", "uploader", ":", "uploader", "}", "\n", "}" ]
// NewTarringArchiver constructs a TarringArchiver. //
[ "NewTarringArchiver", "constructs", "a", "TarringArchiver", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/archiver/tarring_archiver.go#L38-L41
8,549
luci/luci-go
client/archiver/tarring_archiver.go
Archive
func (ta *TarringArchiver) Archive(deps []string, rootDir string, isol *isolated.Isolated, blacklist []string, isolated string) (IsolatedSummary, error) { parts, err := partitionDeps(deps, rootDir, blacklist) if err != nil { return IsolatedSummary{}, fmt.Errorf("partitioning deps: %v", err) } log.Printf("Expanded to the following items to be isolated:\n%s", parts) tracker := newUploadTracker(ta.checker, ta.uploader, isol) if err := tracker.UploadDeps(parts); err != nil { return IsolatedSummary{}, err } return tracker.Finalize(isolated) }
go
func (ta *TarringArchiver) Archive(deps []string, rootDir string, isol *isolated.Isolated, blacklist []string, isolated string) (IsolatedSummary, error) { parts, err := partitionDeps(deps, rootDir, blacklist) if err != nil { return IsolatedSummary{}, fmt.Errorf("partitioning deps: %v", err) } log.Printf("Expanded to the following items to be isolated:\n%s", parts) tracker := newUploadTracker(ta.checker, ta.uploader, isol) if err := tracker.UploadDeps(parts); err != nil { return IsolatedSummary{}, err } return tracker.Finalize(isolated) }
[ "func", "(", "ta", "*", "TarringArchiver", ")", "Archive", "(", "deps", "[", "]", "string", ",", "rootDir", "string", ",", "isol", "*", "isolated", ".", "Isolated", ",", "blacklist", "[", "]", "string", ",", "isolated", "string", ")", "(", "IsolatedSumma...
// Archive uploads a single isolate.
[ "Archive", "uploads", "a", "single", "isolate", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/archiver/tarring_archiver.go#L44-L56
8,550
luci/luci-go
client/archiver/tarring_archiver.go
walkFn
func (pw *partitioningWalker) walkFn(path string, info os.FileInfo, err error) error { if err != nil { return err } relPath, err := pw.fsView.RelativePath(path) if err != nil { return err } if !pw.seen.Add(relPath) || relPath == "" { // Either the file or directory was already walked, or empty string // indicates skip. return common.WalkFuncSkipFile(info) } if info.IsDir() { return nil } item := &Item{ Path: path, RelPath: relPath, Mode: info.Mode(), Size: info.Size(), } switch { case item.Mode&os.ModeSymlink == os.ModeSymlink: pw.parts.links.AddItem(item) case item.Size < archiveThreshold: pw.parts.filesToArchive.AddItem(item) default: pw.parts.indivFiles.AddItem(item) } return nil }
go
func (pw *partitioningWalker) walkFn(path string, info os.FileInfo, err error) error { if err != nil { return err } relPath, err := pw.fsView.RelativePath(path) if err != nil { return err } if !pw.seen.Add(relPath) || relPath == "" { // Either the file or directory was already walked, or empty string // indicates skip. return common.WalkFuncSkipFile(info) } if info.IsDir() { return nil } item := &Item{ Path: path, RelPath: relPath, Mode: info.Mode(), Size: info.Size(), } switch { case item.Mode&os.ModeSymlink == os.ModeSymlink: pw.parts.links.AddItem(item) case item.Size < archiveThreshold: pw.parts.filesToArchive.AddItem(item) default: pw.parts.indivFiles.AddItem(item) } return nil }
[ "func", "(", "pw", "*", "partitioningWalker", ")", "walkFn", "(", "path", "string", ",", "info", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "relPath", ",", "err", ...
// walkFn implements filepath.WalkFunc, for use traversing a directory hierarchy to be isolated. // It accumulates files in pw.parts, partitioned into symlinks and files categorized by size.
[ "walkFn", "implements", "filepath", ".", "WalkFunc", "for", "use", "traversing", "a", "directory", "hierarchy", "to", "be", "isolated", ".", "It", "accumulates", "files", "in", "pw", ".", "parts", "partitioned", "into", "symlinks", "and", "files", "categorized",...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/archiver/tarring_archiver.go#L113-L147
8,551
luci/luci-go
client/archiver/tarring_archiver.go
partitionDeps
func partitionDeps(deps []string, rootDir string, blacklist []string) (partitionedDeps, error) { fsView, err := common.NewFilesystemView(rootDir, blacklist) if err != nil { return partitionedDeps{}, err } walker := partitioningWalker{fsView: fsView, seen: stringset.New(1024)} for _, dep := range deps { // Try to walk dep. If dep is a file (or symlink), the inner function is called exactly once. if err := filepath.Walk(filepath.Clean(dep), walker.walkFn); err != nil { return partitionedDeps{}, err } } return walker.parts, nil }
go
func partitionDeps(deps []string, rootDir string, blacklist []string) (partitionedDeps, error) { fsView, err := common.NewFilesystemView(rootDir, blacklist) if err != nil { return partitionedDeps{}, err } walker := partitioningWalker{fsView: fsView, seen: stringset.New(1024)} for _, dep := range deps { // Try to walk dep. If dep is a file (or symlink), the inner function is called exactly once. if err := filepath.Walk(filepath.Clean(dep), walker.walkFn); err != nil { return partitionedDeps{}, err } } return walker.parts, nil }
[ "func", "partitionDeps", "(", "deps", "[", "]", "string", ",", "rootDir", "string", ",", "blacklist", "[", "]", "string", ")", "(", "partitionedDeps", ",", "error", ")", "{", "fsView", ",", "err", ":=", "common", ".", "NewFilesystemView", "(", "rootDir", ...
// partitionDeps walks each of the deps, partioning the results into symlinks and files categorized by size.
[ "partitionDeps", "walks", "each", "of", "the", "deps", "partioning", "the", "results", "into", "symlinks", "and", "files", "categorized", "by", "size", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/archiver/tarring_archiver.go#L150-L164
8,552
luci/luci-go
tokenserver/appengine/impl/services/minter/tokenminter/service.go
NewServer
func NewServer() minter.TokenMinterServer { return &serverImpl{ MintMachineTokenRPC: machinetoken.MintMachineTokenRPC{ Signer: gaesigner.Signer{}, CheckCertificate: certchecker.CheckCertificate, LogToken: machinetoken.LogToken, }, MintDelegationTokenRPC: delegation.MintDelegationTokenRPC{ Signer: gaesigner.Signer{}, Rules: delegation.GlobalRulesCache.Rules, LogToken: delegation.LogToken, }, MintOAuthTokenGrantRPC: serviceaccounts.MintOAuthTokenGrantRPC{ Signer: gaesigner.Signer{}, Rules: serviceaccounts.GlobalRulesCache.Rules, LogGrant: serviceaccounts.LogGrant, }, MintOAuthTokenViaGrantRPC: serviceaccounts.MintOAuthTokenViaGrantRPC{ Signer: gaesigner.Signer{}, Rules: serviceaccounts.GlobalRulesCache.Rules, MintAccessToken: auth.MintAccessTokenForServiceAccount, LogOAuthToken: serviceaccounts.LogOAuthToken, }, MintProjectTokenRPC: projectscope.MintProjectTokenRPC{ Signer: gaesigner.Signer{}, MintAccessToken: auth.MintAccessTokenForServiceAccount, ProjectIdentities: projectidentity.ProjectIdentities, LogToken: projectscope.LogToken, }, } }
go
func NewServer() minter.TokenMinterServer { return &serverImpl{ MintMachineTokenRPC: machinetoken.MintMachineTokenRPC{ Signer: gaesigner.Signer{}, CheckCertificate: certchecker.CheckCertificate, LogToken: machinetoken.LogToken, }, MintDelegationTokenRPC: delegation.MintDelegationTokenRPC{ Signer: gaesigner.Signer{}, Rules: delegation.GlobalRulesCache.Rules, LogToken: delegation.LogToken, }, MintOAuthTokenGrantRPC: serviceaccounts.MintOAuthTokenGrantRPC{ Signer: gaesigner.Signer{}, Rules: serviceaccounts.GlobalRulesCache.Rules, LogGrant: serviceaccounts.LogGrant, }, MintOAuthTokenViaGrantRPC: serviceaccounts.MintOAuthTokenViaGrantRPC{ Signer: gaesigner.Signer{}, Rules: serviceaccounts.GlobalRulesCache.Rules, MintAccessToken: auth.MintAccessTokenForServiceAccount, LogOAuthToken: serviceaccounts.LogOAuthToken, }, MintProjectTokenRPC: projectscope.MintProjectTokenRPC{ Signer: gaesigner.Signer{}, MintAccessToken: auth.MintAccessTokenForServiceAccount, ProjectIdentities: projectidentity.ProjectIdentities, LogToken: projectscope.LogToken, }, } }
[ "func", "NewServer", "(", ")", "minter", ".", "TokenMinterServer", "{", "return", "&", "serverImpl", "{", "MintMachineTokenRPC", ":", "machinetoken", ".", "MintMachineTokenRPC", "{", "Signer", ":", "gaesigner", ".", "Signer", "{", "}", ",", "CheckCertificate", "...
// NewServer returns prod TokenMinterServer implementation. // // It does all authorization checks inside.
[ "NewServer", "returns", "prod", "TokenMinterServer", "implementation", ".", "It", "does", "all", "authorization", "checks", "inside", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/services/minter/tokenminter/service.go#L48-L78
8,553
luci/luci-go
machine-db/appengine/rpc/datacenters.go
ListDatacenters
func (*Service) ListDatacenters(c context.Context, req *crimson.ListDatacentersRequest) (*crimson.ListDatacentersResponse, error) { datacenters, err := listDatacenters(c, stringset.NewFromSlice(req.Names...)) if err != nil { return nil, err } return &crimson.ListDatacentersResponse{ Datacenters: datacenters, }, nil }
go
func (*Service) ListDatacenters(c context.Context, req *crimson.ListDatacentersRequest) (*crimson.ListDatacentersResponse, error) { datacenters, err := listDatacenters(c, stringset.NewFromSlice(req.Names...)) if err != nil { return nil, err } return &crimson.ListDatacentersResponse{ Datacenters: datacenters, }, nil }
[ "func", "(", "*", "Service", ")", "ListDatacenters", "(", "c", "context", ".", "Context", ",", "req", "*", "crimson", ".", "ListDatacentersRequest", ")", "(", "*", "crimson", ".", "ListDatacentersResponse", ",", "error", ")", "{", "datacenters", ",", "err", ...
// ListDatacenters handles a request to retrieve datacenters.
[ "ListDatacenters", "handles", "a", "request", "to", "retrieve", "datacenters", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/datacenters.go#L28-L36
8,554
luci/luci-go
machine-db/appengine/rpc/datacenters.go
listDatacenters
func listDatacenters(c context.Context, names stringset.Set) ([]*crimson.Datacenter, error) { db := database.Get(c) rows, err := db.QueryContext(c, ` SELECT name, description, state FROM datacenters `) if err != nil { return nil, errors.Annotate(err, "failed to fetch datacenters").Err() } defer rows.Close() var datacenters []*crimson.Datacenter for rows.Next() { dc := &crimson.Datacenter{} if err = rows.Scan(&dc.Name, &dc.Description, &dc.State); err != nil { return nil, errors.Annotate(err, "failed to fetch datacenter").Err() } if matches(dc.Name, names) { datacenters = append(datacenters, dc) } } return datacenters, nil }
go
func listDatacenters(c context.Context, names stringset.Set) ([]*crimson.Datacenter, error) { db := database.Get(c) rows, err := db.QueryContext(c, ` SELECT name, description, state FROM datacenters `) if err != nil { return nil, errors.Annotate(err, "failed to fetch datacenters").Err() } defer rows.Close() var datacenters []*crimson.Datacenter for rows.Next() { dc := &crimson.Datacenter{} if err = rows.Scan(&dc.Name, &dc.Description, &dc.State); err != nil { return nil, errors.Annotate(err, "failed to fetch datacenter").Err() } if matches(dc.Name, names) { datacenters = append(datacenters, dc) } } return datacenters, nil }
[ "func", "listDatacenters", "(", "c", "context", ".", "Context", ",", "names", "stringset", ".", "Set", ")", "(", "[", "]", "*", "crimson", ".", "Datacenter", ",", "error", ")", "{", "db", ":=", "database", ".", "Get", "(", "c", ")", "\n", "rows", "...
// listDatacenters returns a slice of datacenters in the database.
[ "listDatacenters", "returns", "a", "slice", "of", "datacenters", "in", "the", "database", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/datacenters.go#L39-L61
8,555
luci/luci-go
lucicfg/rule.go
newRuleImpl
func newRuleImpl(impl starlark.Callable, defaults *starlark.Dict) (*ruleImpl, error) { pairs := defaults.Items() for _, pair := range pairs { k, v := pair[0], pair[1] if _, ok := k.(starlark.String); !ok { return nil, fmt.Errorf("lucicfg.rule: keys in \"defaults\" must be strings") } if !isNamedStruct(v, "lucicfg.var") { return nil, fmt.Errorf("lucicfg.rule: values in \"defaults\" must be lucicfg.var") } } return &ruleImpl{ Callable: impl, defaults: starlarkstruct.FromKeywords(starlark.String("lucicfg.rule.defaults"), pairs), }, nil }
go
func newRuleImpl(impl starlark.Callable, defaults *starlark.Dict) (*ruleImpl, error) { pairs := defaults.Items() for _, pair := range pairs { k, v := pair[0], pair[1] if _, ok := k.(starlark.String); !ok { return nil, fmt.Errorf("lucicfg.rule: keys in \"defaults\" must be strings") } if !isNamedStruct(v, "lucicfg.var") { return nil, fmt.Errorf("lucicfg.rule: values in \"defaults\" must be lucicfg.var") } } return &ruleImpl{ Callable: impl, defaults: starlarkstruct.FromKeywords(starlark.String("lucicfg.rule.defaults"), pairs), }, nil }
[ "func", "newRuleImpl", "(", "impl", "starlark", ".", "Callable", ",", "defaults", "*", "starlark", ".", "Dict", ")", "(", "*", "ruleImpl", ",", "error", ")", "{", "pairs", ":=", "defaults", ".", "Items", "(", ")", "\n", "for", "_", ",", "pair", ":=",...
// newRuleImpl construct a new rule if arguments pass the validation.
[ "newRuleImpl", "construct", "a", "new", "rule", "if", "arguments", "pass", "the", "validation", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/rule.go#L38-L53
8,556
luci/luci-go
lucicfg/rule.go
String
func (r *ruleImpl) String() string { name := r.Callable.Name() return fmt.Sprintf("<rule %s>", strings.TrimPrefix(name, "_")) }
go
func (r *ruleImpl) String() string { name := r.Callable.Name() return fmt.Sprintf("<rule %s>", strings.TrimPrefix(name, "_")) }
[ "func", "(", "r", "*", "ruleImpl", ")", "String", "(", ")", "string", "{", "name", ":=", "r", ".", "Callable", ".", "Name", "(", ")", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "strings", ".", "TrimPrefix", "(", "name", ",", "\"...
// String lets caller know this is a rule now.
[ "String", "lets", "caller", "know", "this", "is", "a", "rule", "now", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/rule.go#L56-L59
8,557
luci/luci-go
lucicfg/rule.go
Attr
func (r *ruleImpl) Attr(name string) (starlark.Value, error) { switch name { case "defaults": return r.defaults, nil default: return nil, nil } }
go
func (r *ruleImpl) Attr(name string) (starlark.Value, error) { switch name { case "defaults": return r.defaults, nil default: return nil, nil } }
[ "func", "(", "r", "*", "ruleImpl", ")", "Attr", "(", "name", "string", ")", "(", "starlark", ".", "Value", ",", "error", ")", "{", "switch", "name", "{", "case", "\"", "\"", ":", "return", "r", ".", "defaults", ",", "nil", "\n", "default", ":", "...
// Attr is part of starlark.HasAttrs interface.
[ "Attr", "is", "part", "of", "starlark", ".", "HasAttrs", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/rule.go#L91-L98
8,558
luci/luci-go
tokenserver/appengine/impl/utils/projectidentity/storage.go
lookup
func (s *persistentStorage) lookup(c context.Context, identity *ProjectIdentity) (*ProjectIdentity, error) { logging.Debugf(c, "lookup project scoped identity %v", identity) tmp := *identity if err := ds.Get(c, &tmp); err != nil { switch { case err == ds.ErrNoSuchEntity: return nil, ErrNotFound case err != nil: return nil, transient.Tag.Apply(err) } } return &tmp, nil }
go
func (s *persistentStorage) lookup(c context.Context, identity *ProjectIdentity) (*ProjectIdentity, error) { logging.Debugf(c, "lookup project scoped identity %v", identity) tmp := *identity if err := ds.Get(c, &tmp); err != nil { switch { case err == ds.ErrNoSuchEntity: return nil, ErrNotFound case err != nil: return nil, transient.Tag.Apply(err) } } return &tmp, nil }
[ "func", "(", "s", "*", "persistentStorage", ")", "lookup", "(", "c", "context", ".", "Context", ",", "identity", "*", "ProjectIdentity", ")", "(", "*", "ProjectIdentity", ",", "error", ")", "{", "logging", ".", "Debugf", "(", "c", ",", "\"", "\"", ",",...
// lookup reads an identity from the storage based on what fields are set in the identity struct.
[ "lookup", "reads", "an", "identity", "from", "the", "storage", "based", "on", "what", "fields", "are", "set", "in", "the", "identity", "struct", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/projectidentity/storage.go#L68-L80
8,559
luci/luci-go
tokenserver/appengine/impl/utils/projectidentity/storage.go
LookupByProject
func (s *persistentStorage) LookupByProject(c context.Context, project string) (*ProjectIdentity, error) { return s.lookup(c, &ProjectIdentity{Project: project}) }
go
func (s *persistentStorage) LookupByProject(c context.Context, project string) (*ProjectIdentity, error) { return s.lookup(c, &ProjectIdentity{Project: project}) }
[ "func", "(", "s", "*", "persistentStorage", ")", "LookupByProject", "(", "c", "context", ".", "Context", ",", "project", "string", ")", "(", "*", "ProjectIdentity", ",", "error", ")", "{", "return", "s", ".", "lookup", "(", "c", ",", "&", "ProjectIdentit...
// LookupByProject returns the project identity stored for a given project.
[ "LookupByProject", "returns", "the", "project", "identity", "stored", "for", "a", "given", "project", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/projectidentity/storage.go#L83-L85
8,560
luci/luci-go
tokenserver/appengine/impl/utils/projectidentity/storage.go
Delete
func (s *persistentStorage) Delete(c context.Context, identity *ProjectIdentity) error { logging.Debugf(c, "delete project scoped identity %v", identity) return ds.Delete(c, identity) }
go
func (s *persistentStorage) Delete(c context.Context, identity *ProjectIdentity) error { logging.Debugf(c, "delete project scoped identity %v", identity) return ds.Delete(c, identity) }
[ "func", "(", "s", "*", "persistentStorage", ")", "Delete", "(", "c", "context", ".", "Context", ",", "identity", "*", "ProjectIdentity", ")", "error", "{", "logging", ".", "Debugf", "(", "c", ",", "\"", "\"", ",", "identity", ")", "\n", "return", "ds",...
// Delete removes an identity from the storage.
[ "Delete", "removes", "an", "identity", "from", "the", "storage", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/projectidentity/storage.go#L88-L91
8,561
luci/luci-go
tokenserver/appengine/impl/utils/projectidentity/storage.go
Create
func (s *persistentStorage) Create(c context.Context, identity *ProjectIdentity) (*ProjectIdentity, error) { logging.Debugf(c, "create project scoped identity %v", identity) return s.Update(c, identity) }
go
func (s *persistentStorage) Create(c context.Context, identity *ProjectIdentity) (*ProjectIdentity, error) { logging.Debugf(c, "create project scoped identity %v", identity) return s.Update(c, identity) }
[ "func", "(", "s", "*", "persistentStorage", ")", "Create", "(", "c", "context", ".", "Context", ",", "identity", "*", "ProjectIdentity", ")", "(", "*", "ProjectIdentity", ",", "error", ")", "{", "logging", ".", "Debugf", "(", "c", ",", "\"", "\"", ",",...
// Create stores a new entry for a project identity.
[ "Create", "stores", "a", "new", "entry", "for", "a", "project", "identity", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/projectidentity/storage.go#L94-L97
8,562
luci/luci-go
logdog/client/butler/output/output.go
Merge
func (s *StatsBase) Merge(o Stats) { s.F.SentBytes += o.SentBytes() s.F.SentMessages += o.SentMessages() s.F.DiscardedMessages += o.DiscardedMessages() s.F.Errors += o.Errors() }
go
func (s *StatsBase) Merge(o Stats) { s.F.SentBytes += o.SentBytes() s.F.SentMessages += o.SentMessages() s.F.DiscardedMessages += o.DiscardedMessages() s.F.Errors += o.Errors() }
[ "func", "(", "s", "*", "StatsBase", ")", "Merge", "(", "o", "Stats", ")", "{", "s", ".", "F", ".", "SentBytes", "+=", "o", ".", "SentBytes", "(", ")", "\n", "s", ".", "F", ".", "SentMessages", "+=", "o", ".", "SentMessages", "(", ")", "\n", "s"...
// Merge merges the values from one Stats block into another.
[ "Merge", "merges", "the", "values", "from", "one", "Stats", "block", "into", "another", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/butler/output/output.go#L111-L116
8,563
luci/luci-go
common/flag/nestedflagset/token.go
split
func (t token) split() (name, value string) { split := strings.SplitN(string(t), "=", 2) name = split[0] if len(split) == 2 { value = split[1] } return }
go
func (t token) split() (name, value string) { split := strings.SplitN(string(t), "=", 2) name = split[0] if len(split) == 2 { value = split[1] } return }
[ "func", "(", "t", "token", ")", "split", "(", ")", "(", "name", ",", "value", "string", ")", "{", "split", ":=", "strings", ".", "SplitN", "(", "string", "(", "t", ")", ",", "\"", "\"", ",", "2", ")", "\n", "name", "=", "split", "[", "0", "]"...
// split breaks a token into its name and value components.
[ "split", "breaks", "a", "token", "into", "its", "name", "and", "value", "components", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/flag/nestedflagset/token.go#L25-L32
8,564
luci/luci-go
server/auth/openid/method.go
InstallHandlers
func (m *AuthMethod) InstallHandlers(r *router.Router, base router.MiddlewareChain) { r.GET(loginURL, base, m.loginHandler) r.GET(logoutURL, base, m.logoutHandler) r.GET(callbackURL, base, m.callbackHandler) }
go
func (m *AuthMethod) InstallHandlers(r *router.Router, base router.MiddlewareChain) { r.GET(loginURL, base, m.loginHandler) r.GET(logoutURL, base, m.logoutHandler) r.GET(callbackURL, base, m.callbackHandler) }
[ "func", "(", "m", "*", "AuthMethod", ")", "InstallHandlers", "(", "r", "*", "router", ".", "Router", ",", "base", "router", ".", "MiddlewareChain", ")", "{", "r", ".", "GET", "(", "loginURL", ",", "base", ",", "m", ".", "loginHandler", ")", "\n", "r"...
// InstallHandlers installs HTTP handlers used in OpenID protocol. Must be // installed in server HTTP router for OpenID authentication flow to work.
[ "InstallHandlers", "installs", "HTTP", "handlers", "used", "in", "OpenID", "protocol", ".", "Must", "be", "installed", "in", "server", "HTTP", "router", "for", "OpenID", "authentication", "flow", "to", "work", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/openid/method.go#L69-L73
8,565
luci/luci-go
server/auth/openid/method.go
Warmup
func (m *AuthMethod) Warmup(c context.Context) (err error) { cfg, err := fetchCachedSettings(c) if err != nil { return } if cfg.DiscoveryURL != "" { _, err = fetchDiscoveryDoc(c, cfg.DiscoveryURL) } else { logging.Infof(c, "Skipping OpenID warmup, not configured") } return }
go
func (m *AuthMethod) Warmup(c context.Context) (err error) { cfg, err := fetchCachedSettings(c) if err != nil { return } if cfg.DiscoveryURL != "" { _, err = fetchDiscoveryDoc(c, cfg.DiscoveryURL) } else { logging.Infof(c, "Skipping OpenID warmup, not configured") } return }
[ "func", "(", "m", "*", "AuthMethod", ")", "Warmup", "(", "c", "context", ".", "Context", ")", "(", "err", "error", ")", "{", "cfg", ",", "err", ":=", "fetchCachedSettings", "(", "c", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", ...
// Warmup prepares local caches. It's optional.
[ "Warmup", "prepares", "local", "caches", ".", "It", "s", "optional", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/openid/method.go#L76-L87
8,566
luci/luci-go
server/auth/openid/method.go
Authenticate
func (m *AuthMethod) Authenticate(c context.Context, r *http.Request) (*auth.User, error) { if m.SessionStore == nil { return nil, ErrNotConfigured } // Grab session ID from the cookie. sid, err := decodeSessionCookie(c, r) if err != nil { return nil, err } if sid == "" { return nil, nil } // Grab session (with user information) from the store. session, err := m.SessionStore.GetSession(c, sid) if err != nil { return nil, err } if session == nil { (logging.Fields{"sid": sid}).Warningf(c, "The session cookie references unknown session") return nil, nil } (logging.Fields{ "sid": sid, "email": session.User.Email, }).Debugf(c, "Fetched the session") return &session.User, nil }
go
func (m *AuthMethod) Authenticate(c context.Context, r *http.Request) (*auth.User, error) { if m.SessionStore == nil { return nil, ErrNotConfigured } // Grab session ID from the cookie. sid, err := decodeSessionCookie(c, r) if err != nil { return nil, err } if sid == "" { return nil, nil } // Grab session (with user information) from the store. session, err := m.SessionStore.GetSession(c, sid) if err != nil { return nil, err } if session == nil { (logging.Fields{"sid": sid}).Warningf(c, "The session cookie references unknown session") return nil, nil } (logging.Fields{ "sid": sid, "email": session.User.Email, }).Debugf(c, "Fetched the session") return &session.User, nil }
[ "func", "(", "m", "*", "AuthMethod", ")", "Authenticate", "(", "c", "context", ".", "Context", ",", "r", "*", "http", ".", "Request", ")", "(", "*", "auth", ".", "User", ",", "error", ")", "{", "if", "m", ".", "SessionStore", "==", "nil", "{", "r...
// Authenticate extracts peer's identity from the incoming request. It is part // of auth.Method interface.
[ "Authenticate", "extracts", "peer", "s", "identity", "from", "the", "incoming", "request", ".", "It", "is", "part", "of", "auth", ".", "Method", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/openid/method.go#L91-L119
8,567
luci/luci-go
server/auth/openid/method.go
LoginURL
func (m *AuthMethod) LoginURL(c context.Context, dest string) (string, error) { if m.SessionStore == nil { return "", ErrNotConfigured } return makeRedirectURL(loginURL, dest) }
go
func (m *AuthMethod) LoginURL(c context.Context, dest string) (string, error) { if m.SessionStore == nil { return "", ErrNotConfigured } return makeRedirectURL(loginURL, dest) }
[ "func", "(", "m", "*", "AuthMethod", ")", "LoginURL", "(", "c", "context", ".", "Context", ",", "dest", "string", ")", "(", "string", ",", "error", ")", "{", "if", "m", ".", "SessionStore", "==", "nil", "{", "return", "\"", "\"", ",", "ErrNotConfigur...
// LoginURL returns a URL that, when visited, prompts the user to sign in, // then redirects the user to the URL specified by dest. It is part of // auth.UsersAPI interface.
[ "LoginURL", "returns", "a", "URL", "that", "when", "visited", "prompts", "the", "user", "to", "sign", "in", "then", "redirects", "the", "user", "to", "the", "URL", "specified", "by", "dest", ".", "It", "is", "part", "of", "auth", ".", "UsersAPI", "interf...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/openid/method.go#L124-L129
8,568
luci/luci-go
server/auth/openid/method.go
LogoutURL
func (m *AuthMethod) LogoutURL(c context.Context, dest string) (string, error) { if m.SessionStore == nil { return "", ErrNotConfigured } return makeRedirectURL(logoutURL, dest) }
go
func (m *AuthMethod) LogoutURL(c context.Context, dest string) (string, error) { if m.SessionStore == nil { return "", ErrNotConfigured } return makeRedirectURL(logoutURL, dest) }
[ "func", "(", "m", "*", "AuthMethod", ")", "LogoutURL", "(", "c", "context", ".", "Context", ",", "dest", "string", ")", "(", "string", ",", "error", ")", "{", "if", "m", ".", "SessionStore", "==", "nil", "{", "return", "\"", "\"", ",", "ErrNotConfigu...
// LogoutURL returns a URL that, when visited, signs the user out, // then redirects the user to the URL specified by dest. It is part of // auth.UsersAPI interface.
[ "LogoutURL", "returns", "a", "URL", "that", "when", "visited", "signs", "the", "user", "out", "then", "redirects", "the", "user", "to", "the", "URL", "specified", "by", "dest", ".", "It", "is", "part", "of", "auth", ".", "UsersAPI", "interface", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/openid/method.go#L134-L139
8,569
luci/luci-go
server/auth/openid/method.go
logoutHandler
func (m *AuthMethod) logoutHandler(ctx *router.Context) { c, rw, r := ctx.Context, ctx.Writer, ctx.Request dest, err := normalizeURL(r.URL.Query().Get("r")) if err != nil { replyError(c, rw, err, "Bad redirect URI (%q) - %s", dest, err) return } // Close a session if there's one. sid, err := decodeSessionCookie(c, r) if err != nil { replyError(c, rw, err, "Error when decoding session cookie - %s", err) return } if sid != "" { (logging.Fields{"sid": sid}).Infof(c, "Closing the session") if err = m.SessionStore.CloseSession(c, sid); err != nil { replyError(c, rw, err, "Error when closing the session - %s", err) return } } // Nuke all session cookies to get to a completely clean state. removeCookie(rw, r, sessionCookieName) m.removeIncompatibleCookies(rw, r) // Redirect to the final destination. logging.Infof(c, "Redirecting to %s", dest) http.Redirect(rw, r, dest, http.StatusFound) }
go
func (m *AuthMethod) logoutHandler(ctx *router.Context) { c, rw, r := ctx.Context, ctx.Writer, ctx.Request dest, err := normalizeURL(r.URL.Query().Get("r")) if err != nil { replyError(c, rw, err, "Bad redirect URI (%q) - %s", dest, err) return } // Close a session if there's one. sid, err := decodeSessionCookie(c, r) if err != nil { replyError(c, rw, err, "Error when decoding session cookie - %s", err) return } if sid != "" { (logging.Fields{"sid": sid}).Infof(c, "Closing the session") if err = m.SessionStore.CloseSession(c, sid); err != nil { replyError(c, rw, err, "Error when closing the session - %s", err) return } } // Nuke all session cookies to get to a completely clean state. removeCookie(rw, r, sessionCookieName) m.removeIncompatibleCookies(rw, r) // Redirect to the final destination. logging.Infof(c, "Redirecting to %s", dest) http.Redirect(rw, r, dest, http.StatusFound) }
[ "func", "(", "m", "*", "AuthMethod", ")", "logoutHandler", "(", "ctx", "*", "router", ".", "Context", ")", "{", "c", ",", "rw", ",", "r", ":=", "ctx", ".", "Context", ",", "ctx", ".", "Writer", ",", "ctx", ".", "Request", "\n\n", "dest", ",", "er...
// logoutHandler nukes active session and redirect back to destination URL.
[ "logoutHandler", "nukes", "active", "session", "and", "redirect", "back", "to", "destination", "URL", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/openid/method.go#L174-L204
8,570
luci/luci-go
server/auth/openid/method.go
removeIncompatibleCookies
func (m *AuthMethod) removeIncompatibleCookies(rw http.ResponseWriter, r *http.Request) { for _, cookie := range m.IncompatibleCookies { removeCookie(rw, r, cookie) } }
go
func (m *AuthMethod) removeIncompatibleCookies(rw http.ResponseWriter, r *http.Request) { for _, cookie := range m.IncompatibleCookies { removeCookie(rw, r, cookie) } }
[ "func", "(", "m", "*", "AuthMethod", ")", "removeIncompatibleCookies", "(", "rw", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "for", "_", ",", "cookie", ":=", "range", "m", ".", "IncompatibleCookies", "{", "removeCookie"...
// removeIncompatibleCookies removes cookies specified by m.IncompatibleCookies.
[ "removeIncompatibleCookies", "removes", "cookies", "specified", "by", "m", ".", "IncompatibleCookies", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/openid/method.go#L318-L322
8,571
luci/luci-go
server/auth/openid/method.go
makeRedirectURL
func makeRedirectURL(base, dest string) (string, error) { dest, err := normalizeURL(dest) if err != nil { return "", err } v := url.Values{} v.Set("r", dest) return base + "?" + v.Encode(), nil }
go
func makeRedirectURL(base, dest string) (string, error) { dest, err := normalizeURL(dest) if err != nil { return "", err } v := url.Values{} v.Set("r", dest) return base + "?" + v.Encode(), nil }
[ "func", "makeRedirectURL", "(", "base", ",", "dest", "string", ")", "(", "string", ",", "error", ")", "{", "dest", ",", "err", ":=", "normalizeURL", "(", "dest", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}",...
// makeRedirectURL is used to generate login and logout URLs.
[ "makeRedirectURL", "is", "used", "to", "generate", "login", "and", "logout", "URLs", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/openid/method.go#L349-L357
8,572
luci/luci-go
server/auth/openid/method.go
removeCookie
func removeCookie(rw http.ResponseWriter, r *http.Request, cookie string) { if prev, err := r.Cookie(cookie); err == nil { cpy := *prev cpy.Value = "deleted" cpy.Path = "/" cpy.MaxAge = -1 cpy.Expires = time.Unix(1, 0) http.SetCookie(rw, &cpy) } }
go
func removeCookie(rw http.ResponseWriter, r *http.Request, cookie string) { if prev, err := r.Cookie(cookie); err == nil { cpy := *prev cpy.Value = "deleted" cpy.Path = "/" cpy.MaxAge = -1 cpy.Expires = time.Unix(1, 0) http.SetCookie(rw, &cpy) } }
[ "func", "removeCookie", "(", "rw", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "cookie", "string", ")", "{", "if", "prev", ",", "err", ":=", "r", ".", "Cookie", "(", "cookie", ")", ";", "err", "==", "nil", "{", "cpy",...
// removeCookie sets a cookie to past expiration date so that browser can remove // it. Also replaced value with junk, in case browser decides to ignore // expiration time.
[ "removeCookie", "sets", "a", "cookie", "to", "past", "expiration", "date", "so", "that", "browser", "can", "remove", "it", ".", "Also", "replaced", "value", "with", "junk", "in", "case", "browser", "decides", "to", "ignore", "expiration", "time", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/openid/method.go#L362-L371
8,573
luci/luci-go
server/auth/auth.go
GetMiddleware
func (a *Authenticator) GetMiddleware() router.Middleware { return func(c *router.Context, next router.Handler) { ctx, err := a.Authenticate(c.Context, c.Request) switch { case transient.Tag.In(err): replyError(c.Context, c.Writer, 500, "Transient error during authentication", err) case err != nil: replyError(c.Context, c.Writer, 401, "Authentication error", err) default: c.Context = ctx next(c) } } }
go
func (a *Authenticator) GetMiddleware() router.Middleware { return func(c *router.Context, next router.Handler) { ctx, err := a.Authenticate(c.Context, c.Request) switch { case transient.Tag.In(err): replyError(c.Context, c.Writer, 500, "Transient error during authentication", err) case err != nil: replyError(c.Context, c.Writer, 401, "Authentication error", err) default: c.Context = ctx next(c) } } }
[ "func", "(", "a", "*", "Authenticator", ")", "GetMiddleware", "(", ")", "router", ".", "Middleware", "{", "return", "func", "(", "c", "*", "router", ".", "Context", ",", "next", "router", ".", "Handler", ")", "{", "ctx", ",", "err", ":=", "a", ".", ...
// GetMiddleware returns a middleware that uses this Authenticator for // authentication. // // It uses a.Authenticate internally and handles errors appropriately.
[ "GetMiddleware", "returns", "a", "middleware", "that", "uses", "this", "Authenticator", "for", "authentication", ".", "It", "uses", "a", ".", "Authenticate", "internally", "and", "handles", "errors", "appropriately", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/auth.go#L146-L159
8,574
luci/luci-go
server/auth/auth.go
usersAPI
func (a *Authenticator) usersAPI() UsersAPI { for _, m := range a.Methods { if api, ok := m.(UsersAPI); ok { return api } } return nil }
go
func (a *Authenticator) usersAPI() UsersAPI { for _, m := range a.Methods { if api, ok := m.(UsersAPI); ok { return api } } return nil }
[ "func", "(", "a", "*", "Authenticator", ")", "usersAPI", "(", ")", "UsersAPI", "{", "for", "_", ",", "m", ":=", "range", "a", ".", "Methods", "{", "if", "api", ",", "ok", ":=", "m", ".", "(", "UsersAPI", ")", ";", "ok", "{", "return", "api", "\...
// usersAPI returns implementation of UsersAPI by examining Methods. // // Returns nil if none of Methods implement UsersAPI.
[ "usersAPI", "returns", "implementation", "of", "UsersAPI", "by", "examining", "Methods", ".", "Returns", "nil", "if", "none", "of", "Methods", "implement", "UsersAPI", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/auth.go#L318-L325
8,575
luci/luci-go
server/auth/auth.go
LoginURL
func (a *Authenticator) LoginURL(c context.Context, dest string) (string, error) { if api := a.usersAPI(); api != nil { return api.LoginURL(c, dest) } return "", ErrNoUsersAPI }
go
func (a *Authenticator) LoginURL(c context.Context, dest string) (string, error) { if api := a.usersAPI(); api != nil { return api.LoginURL(c, dest) } return "", ErrNoUsersAPI }
[ "func", "(", "a", "*", "Authenticator", ")", "LoginURL", "(", "c", "context", ".", "Context", ",", "dest", "string", ")", "(", "string", ",", "error", ")", "{", "if", "api", ":=", "a", ".", "usersAPI", "(", ")", ";", "api", "!=", "nil", "{", "ret...
// LoginURL returns a URL that, when visited, prompts the user to sign in, // then redirects the user to the URL specified by dest. // // Returns ErrNoUsersAPI if none of the authentication methods support login // URLs.
[ "LoginURL", "returns", "a", "URL", "that", "when", "visited", "prompts", "the", "user", "to", "sign", "in", "then", "redirects", "the", "user", "to", "the", "URL", "specified", "by", "dest", ".", "Returns", "ErrNoUsersAPI", "if", "none", "of", "the", "auth...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/auth.go#L332-L337
8,576
luci/luci-go
dm/api/service/v1/datastore_embed.go
DMEncoded
func (a *Attempt_ID) DMEncoded() string { return fmt.Sprintf("%s|%08x", a.Quest, flipMask^a.Id) }
go
func (a *Attempt_ID) DMEncoded() string { return fmt.Sprintf("%s|%08x", a.Quest, flipMask^a.Id) }
[ "func", "(", "a", "*", "Attempt_ID", ")", "DMEncoded", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "a", ".", "Quest", ",", "flipMask", "^", "a", ".", "Id", ")", "\n", "}" ]
// DMEncoded returns the encoded string id for this Attempt. Numeric values are // inverted if flip is true.
[ "DMEncoded", "returns", "the", "encoded", "string", "id", "for", "this", "Attempt", ".", "Numeric", "values", "are", "inverted", "if", "flip", "is", "true", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/datastore_embed.go#L69-L71
8,577
luci/luci-go
dm/api/service/v1/datastore_embed.go
SetDMEncoded
func (a *Attempt_ID) SetDMEncoded(val string) error { toks := strings.SplitN(val, "|", 2) if len(toks) != 2 { return fmt.Errorf("unable to parse Attempt id: %q", val) } an, err := strconv.ParseUint(toks[1], 16, 32) if err != nil { return err } a.Quest = toks[0] a.Id = flipMask ^ uint32(an) return nil }
go
func (a *Attempt_ID) SetDMEncoded(val string) error { toks := strings.SplitN(val, "|", 2) if len(toks) != 2 { return fmt.Errorf("unable to parse Attempt id: %q", val) } an, err := strconv.ParseUint(toks[1], 16, 32) if err != nil { return err } a.Quest = toks[0] a.Id = flipMask ^ uint32(an) return nil }
[ "func", "(", "a", "*", "Attempt_ID", ")", "SetDMEncoded", "(", "val", "string", ")", "error", "{", "toks", ":=", "strings", ".", "SplitN", "(", "val", ",", "\"", "\"", ",", "2", ")", "\n", "if", "len", "(", "toks", ")", "!=", "2", "{", "return", ...
// SetDMEncoded decodes val into this Attempt_ID, returning an error if // there's a problem. Numeric values are inverted if flip is true.
[ "SetDMEncoded", "decodes", "val", "into", "this", "Attempt_ID", "returning", "an", "error", "if", "there", "s", "a", "problem", ".", "Numeric", "values", "are", "inverted", "if", "flip", "is", "true", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/datastore_embed.go#L75-L88
8,578
luci/luci-go
dm/api/service/v1/datastore_embed.go
GetQuest
func (g *GraphData) GetQuest(qid string) (*Quest, bool) { cur, ok := g.Quests[qid] if !ok { cur = &Quest{ Id: NewQuestID(qid), Attempts: map[uint32]*Attempt{}, } if g.Quests == nil { g.Quests = map[string]*Quest{} } g.Quests[qid] = cur } return cur, ok }
go
func (g *GraphData) GetQuest(qid string) (*Quest, bool) { cur, ok := g.Quests[qid] if !ok { cur = &Quest{ Id: NewQuestID(qid), Attempts: map[uint32]*Attempt{}, } if g.Quests == nil { g.Quests = map[string]*Quest{} } g.Quests[qid] = cur } return cur, ok }
[ "func", "(", "g", "*", "GraphData", ")", "GetQuest", "(", "qid", "string", ")", "(", "*", "Quest", ",", "bool", ")", "{", "cur", ",", "ok", ":=", "g", ".", "Quests", "[", "qid", "]", "\n", "if", "!", "ok", "{", "cur", "=", "&", "Quest", "{", ...
// GetQuest gets the specified quest from GraphData, if it's already there. If // it's not, then a new Quest will be created, added, and returned. // // If the Quests map is uninitialized, this will initialize it.
[ "GetQuest", "gets", "the", "specified", "quest", "from", "GraphData", "if", "it", "s", "already", "there", ".", "If", "it", "s", "not", "then", "a", "new", "Quest", "will", "be", "created", "added", "and", "returned", ".", "If", "the", "Quests", "map", ...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/datastore_embed.go#L94-L107
8,579
luci/luci-go
dm/api/service/v1/datastore_embed.go
Equals
func (t *Quest_TemplateSpec) Equals(o *Quest_TemplateSpec) bool { return proto.Equal(t, o) }
go
func (t *Quest_TemplateSpec) Equals(o *Quest_TemplateSpec) bool { return proto.Equal(t, o) }
[ "func", "(", "t", "*", "Quest_TemplateSpec", ")", "Equals", "(", "o", "*", "Quest_TemplateSpec", ")", "bool", "{", "return", "proto", ".", "Equal", "(", "t", ",", "o", ")", "\n", "}" ]
// Equals returns true iff this Quest_TemplateSpec matches all of the fields of // the `o` Quest_TemplateSpec.
[ "Equals", "returns", "true", "iff", "this", "Quest_TemplateSpec", "matches", "all", "of", "the", "fields", "of", "the", "o", "Quest_TemplateSpec", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/datastore_embed.go#L131-L133
8,580
luci/luci-go
dm/appengine/model/execution.go
MakeExecution
func MakeExecution(c context.Context, e *dm.Execution_ID, cfgName, cfgVers string) *Execution { now := clock.Now(c).UTC() ret := &Execution{ ID: invertedHexUint32(e.Id), Attempt: AttemptKeyFromID(c, e.AttemptID()), Created: now, Modified: now, DistributorConfigName: cfgName, DistributorConfigVersion: cfgVers, Token: MakeRandomToken(c, dm.MinimumActivationTokenLength), } return ret }
go
func MakeExecution(c context.Context, e *dm.Execution_ID, cfgName, cfgVers string) *Execution { now := clock.Now(c).UTC() ret := &Execution{ ID: invertedHexUint32(e.Id), Attempt: AttemptKeyFromID(c, e.AttemptID()), Created: now, Modified: now, DistributorConfigName: cfgName, DistributorConfigVersion: cfgVers, Token: MakeRandomToken(c, dm.MinimumActivationTokenLength), } return ret }
[ "func", "MakeExecution", "(", "c", "context", ".", "Context", ",", "e", "*", "dm", ".", "Execution_ID", ",", "cfgName", ",", "cfgVers", "string", ")", "*", "Execution", "{", "now", ":=", "clock", ".", "Now", "(", "c", ")", ".", "UTC", "(", ")", "\n...
// MakeExecution makes a new Execution in the SCHEDULING state, with a new // random Token.
[ "MakeExecution", "makes", "a", "new", "Execution", "in", "the", "SCHEDULING", "state", "with", "a", "new", "random", "Token", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/model/execution.go#L122-L137
8,581
luci/luci-go
dm/appengine/model/execution.go
ModifyState
func (e *Execution) ModifyState(c context.Context, newState dm.Execution_State) error { if e.State == newState { return nil } if err := e.State.Evolve(newState); err != nil { return err } now := clock.Now(c).UTC() if now.After(e.Modified) { e.Modified = now } else { // Microsecond is the smallest granularity that datastore can store // timestamps, so use that to disambiguate: the goal here is that any // modification always increments the modified time, and never decrements // it. e.Modified = e.Modified.Add(time.Microsecond) } return nil }
go
func (e *Execution) ModifyState(c context.Context, newState dm.Execution_State) error { if e.State == newState { return nil } if err := e.State.Evolve(newState); err != nil { return err } now := clock.Now(c).UTC() if now.After(e.Modified) { e.Modified = now } else { // Microsecond is the smallest granularity that datastore can store // timestamps, so use that to disambiguate: the goal here is that any // modification always increments the modified time, and never decrements // it. e.Modified = e.Modified.Add(time.Microsecond) } return nil }
[ "func", "(", "e", "*", "Execution", ")", "ModifyState", "(", "c", "context", ".", "Context", ",", "newState", "dm", ".", "Execution_State", ")", "error", "{", "if", "e", ".", "State", "==", "newState", "{", "return", "nil", "\n", "}", "\n", "if", "er...
// ModifyState changes the current state of this Execution and updates its // Modified timestamp.
[ "ModifyState", "changes", "the", "current", "state", "of", "this", "Execution", "and", "updates", "its", "Modified", "timestamp", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/model/execution.go#L141-L159
8,582
luci/luci-go
dm/appengine/model/execution.go
MakeRandomToken
func MakeRandomToken(c context.Context, l uint32) []byte { rtok := make([]byte, l) if _, err := cryptorand.Read(c, rtok); err != nil { panic(err) } return rtok }
go
func MakeRandomToken(c context.Context, l uint32) []byte { rtok := make([]byte, l) if _, err := cryptorand.Read(c, rtok); err != nil { panic(err) } return rtok }
[ "func", "MakeRandomToken", "(", "c", "context", ".", "Context", ",", "l", "uint32", ")", "[", "]", "byte", "{", "rtok", ":=", "make", "(", "[", "]", "byte", ",", "l", ")", "\n", "if", "_", ",", "err", ":=", "cryptorand", ".", "Read", "(", "c", ...
// MakeRandomToken creates a cryptographically random byte slice of the // specified length. It panics if the specified length cannot be read in full.
[ "MakeRandomToken", "creates", "a", "cryptographically", "random", "byte", "slice", "of", "the", "specified", "length", ".", "It", "panics", "if", "the", "specified", "length", "cannot", "be", "read", "in", "full", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/model/execution.go#L163-L169
8,583
luci/luci-go
dm/appengine/model/execution.go
Revoke
func (e *Execution) Revoke(c context.Context) error { e.Token = nil if err := e.ModifyState(c, dm.Execution_STOPPING); err != nil { return err } return ds.Put(c, e) }
go
func (e *Execution) Revoke(c context.Context) error { e.Token = nil if err := e.ModifyState(c, dm.Execution_STOPPING); err != nil { return err } return ds.Put(c, e) }
[ "func", "(", "e", "*", "Execution", ")", "Revoke", "(", "c", "context", ".", "Context", ")", "error", "{", "e", ".", "Token", "=", "nil", "\n", "if", "err", ":=", "e", ".", "ModifyState", "(", "c", ",", "dm", ".", "Execution_STOPPING", ")", ";", ...
// Revoke will clear the Token and Put this Execution to the datastore. This // action requires the Execution to be in the RUNNING state, and causes it to // enter the STOPPING state.
[ "Revoke", "will", "clear", "the", "Token", "and", "Put", "this", "Execution", "to", "the", "datastore", ".", "This", "action", "requires", "the", "Execution", "to", "be", "in", "the", "RUNNING", "state", "and", "causes", "it", "to", "enter", "the", "STOPPI...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/model/execution.go#L174-L180
8,584
luci/luci-go
dm/appengine/model/execution.go
AuthenticateExecution
func AuthenticateExecution(c context.Context, auth *dm.Execution_Auth) (a *Attempt, e *Execution, err error) { a, e, err = verifyExecutionAndCheckExTok(c, auth) if err != nil { logging.Fields{ek: err, "eid": auth.Id}.Errorf(c, "failed to verify execution") err = makeError(err, "requires execution Auth") } return a, e, err }
go
func AuthenticateExecution(c context.Context, auth *dm.Execution_Auth) (a *Attempt, e *Execution, err error) { a, e, err = verifyExecutionAndCheckExTok(c, auth) if err != nil { logging.Fields{ek: err, "eid": auth.Id}.Errorf(c, "failed to verify execution") err = makeError(err, "requires execution Auth") } return a, e, err }
[ "func", "AuthenticateExecution", "(", "c", "context", ".", "Context", ",", "auth", "*", "dm", ".", "Execution_Auth", ")", "(", "a", "*", "Attempt", ",", "e", "*", "Execution", ",", "err", "error", ")", "{", "a", ",", "e", ",", "err", "=", "verifyExec...
// AuthenticateExecution verifies that the Attempt is executing, and that evkey // matches the execution key of the current Execution for this Attempt. // // As a bonus, it will return the loaded Attempt and Execution.
[ "AuthenticateExecution", "verifies", "that", "the", "Attempt", "is", "executing", "and", "that", "evkey", "matches", "the", "execution", "key", "of", "the", "current", "Execution", "for", "this", "Attempt", ".", "As", "a", "bonus", "it", "will", "return", "the...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/model/execution.go#L234-L241
8,585
luci/luci-go
dm/appengine/model/execution.go
InvalidateExecution
func InvalidateExecution(c context.Context, auth *dm.Execution_Auth) (a *Attempt, e *Execution, err error) { if a, e, err = verifyExecutionAndCheckExTok(c, auth); err != nil { logging.Fields{ek: err, "eid": auth.Id}.Errorf(c, "failed to verify execution") err = makeError(err, "requires execution Auth") return } err = e.Revoke(c) if err != nil { logging.Fields{ek: err, "eid": auth.Id}.Errorf(c, "failed to revoke execution") err = makeError(err, "unable to invalidate Auth") } return }
go
func InvalidateExecution(c context.Context, auth *dm.Execution_Auth) (a *Attempt, e *Execution, err error) { if a, e, err = verifyExecutionAndCheckExTok(c, auth); err != nil { logging.Fields{ek: err, "eid": auth.Id}.Errorf(c, "failed to verify execution") err = makeError(err, "requires execution Auth") return } err = e.Revoke(c) if err != nil { logging.Fields{ek: err, "eid": auth.Id}.Errorf(c, "failed to revoke execution") err = makeError(err, "unable to invalidate Auth") } return }
[ "func", "InvalidateExecution", "(", "c", "context", ".", "Context", ",", "auth", "*", "dm", ".", "Execution_Auth", ")", "(", "a", "*", "Attempt", ",", "e", "*", "Execution", ",", "err", "error", ")", "{", "if", "a", ",", "e", ",", "err", "=", "veri...
// InvalidateExecution verifies that the execution key is valid, and then // revokes the execution key. // // As a bonus, it will return the loaded Attempt and Execution.
[ "InvalidateExecution", "verifies", "that", "the", "execution", "key", "is", "valid", "and", "then", "revokes", "the", "execution", "key", ".", "As", "a", "bonus", "it", "will", "return", "the", "loaded", "Attempt", "and", "Execution", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/model/execution.go#L247-L260
8,586
luci/luci-go
dm/appengine/model/execution.go
ActivateExecution
func ActivateExecution(c context.Context, auth *dm.Execution_Auth, actToken []byte) (a *Attempt, e *Execution, err error) { a, e, err = verifyExecutionAndActivate(c, auth, actToken) if err != nil { logging.Fields{ek: err, "eid": auth.Id}.Errorf(c, "failed to activate execution") err = makeError(err, "failed to activate execution Auth") } return a, e, err }
go
func ActivateExecution(c context.Context, auth *dm.Execution_Auth, actToken []byte) (a *Attempt, e *Execution, err error) { a, e, err = verifyExecutionAndActivate(c, auth, actToken) if err != nil { logging.Fields{ek: err, "eid": auth.Id}.Errorf(c, "failed to activate execution") err = makeError(err, "failed to activate execution Auth") } return a, e, err }
[ "func", "ActivateExecution", "(", "c", "context", ".", "Context", ",", "auth", "*", "dm", ".", "Execution_Auth", ",", "actToken", "[", "]", "byte", ")", "(", "a", "*", "Attempt", ",", "e", "*", "Execution", ",", "err", "error", ")", "{", "a", ",", ...
// ActivateExecution validates that the execution is unactivated and that // the activation token matches and then sets the token to the new // value. // // It's OK to retry this. Subsequent invocations with the same Token // will recognize this case and not return an error.
[ "ActivateExecution", "validates", "that", "the", "execution", "is", "unactivated", "and", "that", "the", "activation", "token", "matches", "and", "then", "sets", "the", "token", "to", "the", "new", "value", ".", "It", "s", "OK", "to", "retry", "this", ".", ...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/model/execution.go#L307-L314
8,587
luci/luci-go
dm/appengine/model/execution.go
GetEID
func (e *Execution) GetEID() *dm.Execution_ID { aid := &dm.Attempt_ID{} if e.ID == 0 { panic("cannot create valid Execution_ID with 0-value ID field") } if err := aid.SetDMEncoded(e.Attempt.StringID()); err != nil { panic(err) } return dm.NewExecutionID(aid.Quest, aid.Id, uint32(e.ID)) }
go
func (e *Execution) GetEID() *dm.Execution_ID { aid := &dm.Attempt_ID{} if e.ID == 0 { panic("cannot create valid Execution_ID with 0-value ID field") } if err := aid.SetDMEncoded(e.Attempt.StringID()); err != nil { panic(err) } return dm.NewExecutionID(aid.Quest, aid.Id, uint32(e.ID)) }
[ "func", "(", "e", "*", "Execution", ")", "GetEID", "(", ")", "*", "dm", ".", "Execution_ID", "{", "aid", ":=", "&", "dm", ".", "Attempt_ID", "{", "}", "\n", "if", "e", ".", "ID", "==", "0", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n",...
// GetEID gets an Execution_ID for this Execution. It panics if the Execution // is in an invalid state.
[ "GetEID", "gets", "an", "Execution_ID", "for", "this", "Execution", ".", "It", "panics", "if", "the", "Execution", "is", "in", "an", "invalid", "state", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/model/execution.go#L318-L327
8,588
luci/luci-go
dm/appengine/model/execution.go
ToProto
func (e *Execution) ToProto(includeID bool) *dm.Execution { ret := &dm.Execution{Data: e.DataProto()} if includeID { ret.Id = e.GetEID() } return ret }
go
func (e *Execution) ToProto(includeID bool) *dm.Execution { ret := &dm.Execution{Data: e.DataProto()} if includeID { ret.Id = e.GetEID() } return ret }
[ "func", "(", "e", "*", "Execution", ")", "ToProto", "(", "includeID", "bool", ")", "*", "dm", ".", "Execution", "{", "ret", ":=", "&", "dm", ".", "Execution", "{", "Data", ":", "e", ".", "DataProto", "(", ")", "}", "\n", "if", "includeID", "{", "...
// ToProto returns a dm proto version of this Execution.
[ "ToProto", "returns", "a", "dm", "proto", "version", "of", "this", "Execution", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/model/execution.go#L330-L336
8,589
luci/luci-go
dm/appengine/model/execution.go
DataProto
func (e *Execution) DataProto() (ret *dm.Execution_Data) { switch e.State { case dm.Execution_SCHEDULING: ret = dm.NewExecutionScheduling().Data case dm.Execution_RUNNING: ret = dm.NewExecutionRunning().Data case dm.Execution_STOPPING: ret = dm.NewExecutionStopping().Data case dm.Execution_FINISHED: ret = dm.NewExecutionFinished(e.Result.Data).Data case dm.Execution_ABNORMAL_FINISHED: ret = dm.NewExecutionAbnormalFinish(e.Result.AbnormalFinish).Data default: panic(fmt.Errorf("unknown Execution_State: %s", e.State)) } ret.Created = google_pb.NewTimestamp(e.Created) ret.Modified = google_pb.NewTimestamp(e.Modified) ret.DistributorInfo = &dm.Execution_Data_DistributorInfo{ ConfigName: e.DistributorConfigName, ConfigVersion: e.DistributorConfigVersion, Token: e.DistributorToken, } return ret }
go
func (e *Execution) DataProto() (ret *dm.Execution_Data) { switch e.State { case dm.Execution_SCHEDULING: ret = dm.NewExecutionScheduling().Data case dm.Execution_RUNNING: ret = dm.NewExecutionRunning().Data case dm.Execution_STOPPING: ret = dm.NewExecutionStopping().Data case dm.Execution_FINISHED: ret = dm.NewExecutionFinished(e.Result.Data).Data case dm.Execution_ABNORMAL_FINISHED: ret = dm.NewExecutionAbnormalFinish(e.Result.AbnormalFinish).Data default: panic(fmt.Errorf("unknown Execution_State: %s", e.State)) } ret.Created = google_pb.NewTimestamp(e.Created) ret.Modified = google_pb.NewTimestamp(e.Modified) ret.DistributorInfo = &dm.Execution_Data_DistributorInfo{ ConfigName: e.DistributorConfigName, ConfigVersion: e.DistributorConfigVersion, Token: e.DistributorToken, } return ret }
[ "func", "(", "e", "*", "Execution", ")", "DataProto", "(", ")", "(", "ret", "*", "dm", ".", "Execution_Data", ")", "{", "switch", "e", ".", "State", "{", "case", "dm", ".", "Execution_SCHEDULING", ":", "ret", "=", "dm", ".", "NewExecutionScheduling", "...
// DataProto returns an Execution.Data message for this Execution. // // This omits the DistributorInfo.Url portion, which must be filled in elsewhere for // package cyclical import reasons.
[ "DataProto", "returns", "an", "Execution", ".", "Data", "message", "for", "this", "Execution", ".", "This", "omits", "the", "DistributorInfo", ".", "Url", "portion", "which", "must", "be", "filled", "in", "elsewhere", "for", "package", "cyclical", "import", "r...
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/model/execution.go#L342-L365
8,590
luci/luci-go
lucicfg/duration.go
String
func (x duration) String() string { ms, ok := x.Int64() if !ok { return "<invalid-duration>" // probably very-very large } return (time.Duration(ms) * time.Millisecond).String() }
go
func (x duration) String() string { ms, ok := x.Int64() if !ok { return "<invalid-duration>" // probably very-very large } return (time.Duration(ms) * time.Millisecond).String() }
[ "func", "(", "x", "duration", ")", "String", "(", ")", "string", "{", "ms", ",", "ok", ":=", "x", ".", "Int64", "(", ")", "\n", "if", "!", "ok", "{", "return", "\"", "\"", "// probably very-very large", "\n", "}", "\n", "return", "(", "time", ".", ...
// String formats the duration using Go's time.Duration rules.
[ "String", "formats", "the", "duration", "using", "Go", "s", "time", ".", "Duration", "rules", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/duration.go#L37-L43
8,591
luci/luci-go
lucicfg/duration.go
CompareSameType
func (x duration) CompareSameType(op syntax.Token, y starlark.Value, depth int) (bool, error) { return x.Int.CompareSameType(op, y.(duration).Int, depth) }
go
func (x duration) CompareSameType(op syntax.Token, y starlark.Value, depth int) (bool, error) { return x.Int.CompareSameType(op, y.(duration).Int, depth) }
[ "func", "(", "x", "duration", ")", "CompareSameType", "(", "op", "syntax", ".", "Token", ",", "y", "starlark", ".", "Value", ",", "depth", "int", ")", "(", "bool", ",", "error", ")", "{", "return", "x", ".", "Int", ".", "CompareSameType", "(", "op", ...
// CompareSameType makes durations comparable by comparing them as integers.
[ "CompareSameType", "makes", "durations", "comparable", "by", "comparing", "them", "as", "integers", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/duration.go#L46-L48
8,592
luci/luci-go
lucicfg/duration.go
Binary
func (x duration) Binary(op syntax.Token, y starlark.Value, side starlark.Side) (starlark.Value, error) { switch y := y.(type) { case starlark.Int: switch { case op == syntax.STAR: return duration{x.Int.Mul(y)}, nil case op == syntax.SLASH && side == starlark.Left: return duration{x.Int.Div(y)}, nil } case duration: switch { case op == syntax.PLUS: return duration{x.Int.Add(y.Int)}, nil case op == syntax.MINUS && side == starlark.Left: return duration{x.Int.Sub(y.Int)}, nil case op == syntax.MINUS && side == starlark.Right: return duration{y.Int.Sub(x.Int)}, nil case op == syntax.SLASH && side == starlark.Left: return x.Int.Div(y.Int), nil case op == syntax.SLASH && side == starlark.Right: return y.Int.Div(x.Int), nil } } // All other combinations aren't supported. return nil, nil }
go
func (x duration) Binary(op syntax.Token, y starlark.Value, side starlark.Side) (starlark.Value, error) { switch y := y.(type) { case starlark.Int: switch { case op == syntax.STAR: return duration{x.Int.Mul(y)}, nil case op == syntax.SLASH && side == starlark.Left: return duration{x.Int.Div(y)}, nil } case duration: switch { case op == syntax.PLUS: return duration{x.Int.Add(y.Int)}, nil case op == syntax.MINUS && side == starlark.Left: return duration{x.Int.Sub(y.Int)}, nil case op == syntax.MINUS && side == starlark.Right: return duration{y.Int.Sub(x.Int)}, nil case op == syntax.SLASH && side == starlark.Left: return x.Int.Div(y.Int), nil case op == syntax.SLASH && side == starlark.Right: return y.Int.Div(x.Int), nil } } // All other combinations aren't supported. return nil, nil }
[ "func", "(", "x", "duration", ")", "Binary", "(", "op", "syntax", ".", "Token", ",", "y", "starlark", ".", "Value", ",", "side", "starlark", ".", "Side", ")", "(", "starlark", ".", "Value", ",", "error", ")", "{", "switch", "y", ":=", "y", ".", "...
// Binary implements binary operations between durations and ints.
[ "Binary", "implements", "binary", "operations", "between", "durations", "and", "ints", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/duration.go#L51-L78
8,593
luci/luci-go
lucicfg/duration.go
Unary
func (x duration) Unary(op syntax.Token) (starlark.Value, error) { switch op { case syntax.PLUS: return x, nil case syntax.MINUS: return duration{zero.Sub(x.Int)}, nil } return nil, nil }
go
func (x duration) Unary(op syntax.Token) (starlark.Value, error) { switch op { case syntax.PLUS: return x, nil case syntax.MINUS: return duration{zero.Sub(x.Int)}, nil } return nil, nil }
[ "func", "(", "x", "duration", ")", "Unary", "(", "op", "syntax", ".", "Token", ")", "(", "starlark", ".", "Value", ",", "error", ")", "{", "switch", "op", "{", "case", "syntax", ".", "PLUS", ":", "return", "x", ",", "nil", "\n", "case", "syntax", ...
// Unary implements +-.
[ "Unary", "implements", "+", "-", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/duration.go#L81-L89
8,594
luci/luci-go
lucicfg/docgen/docstring/docstring.go
FieldsBlock
func (p *Parsed) FieldsBlock(title string) FieldsBlock { for _, b := range p.Fields { if b.Title == title { return b } } return FieldsBlock{} }
go
func (p *Parsed) FieldsBlock(title string) FieldsBlock { for _, b := range p.Fields { if b.Title == title { return b } } return FieldsBlock{} }
[ "func", "(", "p", "*", "Parsed", ")", "FieldsBlock", "(", "title", "string", ")", "FieldsBlock", "{", "for", "_", ",", "b", ":=", "range", "p", ".", "Fields", "{", "if", "b", ".", "Title", "==", "title", "{", "return", "b", "\n", "}", "\n", "}", ...
// FieldsBlock returns a fields block with the given title or an empty block if // not found.
[ "FieldsBlock", "returns", "a", "fields", "block", "with", "the", "given", "title", "or", "an", "empty", "block", "if", "not", "found", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/docgen/docstring/docstring.go#L59-L66
8,595
luci/luci-go
lucicfg/docgen/docstring/docstring.go
RemarkBlock
func (p *Parsed) RemarkBlock(title string) RemarkBlock { for _, b := range p.Remarks { if b.Title == title { return b } } return RemarkBlock{} }
go
func (p *Parsed) RemarkBlock(title string) RemarkBlock { for _, b := range p.Remarks { if b.Title == title { return b } } return RemarkBlock{} }
[ "func", "(", "p", "*", "Parsed", ")", "RemarkBlock", "(", "title", "string", ")", "RemarkBlock", "{", "for", "_", ",", "b", ":=", "range", "p", ".", "Remarks", "{", "if", "b", ".", "Title", "==", "title", "{", "return", "b", "\n", "}", "\n", "}",...
// RemarkBlock returns a remark block with the given title or an empty block if // not found.
[ "RemarkBlock", "returns", "a", "remark", "block", "with", "the", "given", "title", "or", "an", "empty", "block", "if", "not", "found", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/docgen/docstring/docstring.go#L70-L77
8,596
luci/luci-go
lucicfg/docgen/docstring/docstring.go
trimEmptyLines
func trimEmptyLines(lines []string) []string { for len(lines) > 0 && lines[0] == "" { lines = lines[1:] } for len(lines) > 0 && lines[len(lines)-1] == "" { lines = lines[:len(lines)-1] } return lines }
go
func trimEmptyLines(lines []string) []string { for len(lines) > 0 && lines[0] == "" { lines = lines[1:] } for len(lines) > 0 && lines[len(lines)-1] == "" { lines = lines[:len(lines)-1] } return lines }
[ "func", "trimEmptyLines", "(", "lines", "[", "]", "string", ")", "[", "]", "string", "{", "for", "len", "(", "lines", ")", ">", "0", "&&", "lines", "[", "0", "]", "==", "\"", "\"", "{", "lines", "=", "lines", "[", "1", ":", "]", "\n", "}", "\...
// trimEmptyLines removes leading and trailing empty lines from the slice.
[ "trimEmptyLines", "removes", "leading", "and", "trailing", "empty", "lines", "from", "the", "slice", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/docgen/docstring/docstring.go#L292-L300
8,597
luci/luci-go
lucicfg/docgen/docstring/docstring.go
countLeadingSpace
func countLeadingSpace(s string) (runes int) { for _, r := range s { if !unicode.IsSpace(r) { break } runes++ } return }
go
func countLeadingSpace(s string) (runes int) { for _, r := range s { if !unicode.IsSpace(r) { break } runes++ } return }
[ "func", "countLeadingSpace", "(", "s", "string", ")", "(", "runes", "int", ")", "{", "for", "_", ",", "r", ":=", "range", "s", "{", "if", "!", "unicode", ".", "IsSpace", "(", "r", ")", "{", "break", "\n", "}", "\n", "runes", "++", "\n", "}", "\...
// countLeadingSpace returns number of space runes at the prefix of a string.
[ "countLeadingSpace", "returns", "number", "of", "space", "runes", "at", "the", "prefix", "of", "a", "string", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/docgen/docstring/docstring.go#L352-L360
8,598
luci/luci-go
lucicfg/docgen/docstring/docstring.go
hasLeadingSpace
func hasLeadingSpace(s string) bool { for _, r := range s { return unicode.IsSpace(r) } return false }
go
func hasLeadingSpace(s string) bool { for _, r := range s { return unicode.IsSpace(r) } return false }
[ "func", "hasLeadingSpace", "(", "s", "string", ")", "bool", "{", "for", "_", ",", "r", ":=", "range", "s", "{", "return", "unicode", ".", "IsSpace", "(", "r", ")", "\n", "}", "\n", "return", "false", "\n", "}" ]
// hasLeadingSpace returns true if 's' starts with a space.
[ "hasLeadingSpace", "returns", "true", "if", "s", "starts", "with", "a", "space", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/docgen/docstring/docstring.go#L363-L368
8,599
luci/luci-go
config/server/cfgclient/backend/caching/config.go
ParamHash
func (k *Key) ParamHash() []byte { cstr := "" if k.Content { cstr = "y" } return HashParams(k.Schema, k.ServiceURL, string(k.Authority), string(k.Op), cstr, k.Formatter, k.FormatData, string(k.ConfigSet), k.Path, string(k.GetAllTarget)) }
go
func (k *Key) ParamHash() []byte { cstr := "" if k.Content { cstr = "y" } return HashParams(k.Schema, k.ServiceURL, string(k.Authority), string(k.Op), cstr, k.Formatter, k.FormatData, string(k.ConfigSet), k.Path, string(k.GetAllTarget)) }
[ "func", "(", "k", "*", "Key", ")", "ParamHash", "(", ")", "[", "]", "byte", "{", "cstr", ":=", "\"", "\"", "\n", "if", "k", ".", "Content", "{", "cstr", "=", "\"", "\"", "\n", "}", "\n", "return", "HashParams", "(", "k", ".", "Schema", ",", "...
// ParamHash returns a deterministic hash of all of the key parameters.
[ "ParamHash", "returns", "a", "deterministic", "hash", "of", "all", "of", "the", "key", "parameters", "." ]
f6cef429871eee3be7c6903af88d3ee884eaf683
https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/backend/caching/config.go#L78-L85