id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
9,100 | luci/luci-go | client/isolate/format.go | convertIsolateToJSON5 | func convertIsolateToJSON5(content []byte) io.Reader {
out := &bytes.Buffer{}
for _, l := range strings.Split(string(content), "\n") {
l = strings.TrimSpace(l)
if len(l) == 0 || l[0] == '#' {
continue
}
l = strings.Replace(l, "\"", "\\\"", -1)
l = strings.Replace(l, "'", "\"", -1)
_, _ = io.WriteString(out, l+"\n")
}
return out
} | go | func convertIsolateToJSON5(content []byte) io.Reader {
out := &bytes.Buffer{}
for _, l := range strings.Split(string(content), "\n") {
l = strings.TrimSpace(l)
if len(l) == 0 || l[0] == '#' {
continue
}
l = strings.Replace(l, "\"", "\\\"", -1)
l = strings.Replace(l, "'", "\"", -1)
_, _ = io.WriteString(out, l+"\n")
}
return out
} | [
"func",
"convertIsolateToJSON5",
"(",
"content",
"[",
"]",
"byte",
")",
"io",
".",
"Reader",
"{",
"out",
":=",
"&",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"for",
"_",
",",
"l",
":=",
"range",
"strings",
".",
"Split",
"(",
"string",
"(",
"content",
")",
",",
"\"",
"\\n",
"\"",
")",
"{",
"l",
"=",
"strings",
".",
"TrimSpace",
"(",
"l",
")",
"\n",
"if",
"len",
"(",
"l",
")",
"==",
"0",
"||",
"l",
"[",
"0",
"]",
"==",
"'#'",
"{",
"continue",
"\n",
"}",
"\n",
"l",
"=",
"strings",
".",
"Replace",
"(",
"l",
",",
"\"",
"\\\"",
"\"",
",",
"\"",
"\\\\",
"\\\"",
"\"",
",",
"-",
"1",
")",
"\n",
"l",
"=",
"strings",
".",
"Replace",
"(",
"l",
",",
"\"",
"\"",
",",
"\"",
"\\\"",
"\"",
",",
"-",
"1",
")",
"\n",
"_",
",",
"_",
"=",
"io",
".",
"WriteString",
"(",
"out",
",",
"l",
"+",
"\"",
"\\n",
"\"",
")",
"\n",
"}",
"\n",
"return",
"out",
"\n",
"}"
] | // convertIsolateToJSON5 cleans up isolate content to be json5. | [
"convertIsolateToJSON5",
"cleans",
"up",
"isolate",
"content",
"to",
"be",
"json5",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/isolate/format.go#L691-L703 |
9,101 | luci/luci-go | client/isolate/format.go | processIsolate | func processIsolate(content []byte) (*processedIsolate, error) {
isolate, err := parseIsolate(content)
if err != nil {
return nil, err
}
if err := isolate.Variables.verify(); err != nil {
return nil, err
}
out := &processedIsolate{
isolate.Includes,
make([]*processedCondition, len(isolate.Conditions)),
isolate.Variables,
variablesValuesSet{},
}
for i, cond := range isolate.Conditions {
out.conditions[i], err = processCondition(cond, out.varsValsSet)
if err != nil {
return nil, err
}
}
return out, nil
} | go | func processIsolate(content []byte) (*processedIsolate, error) {
isolate, err := parseIsolate(content)
if err != nil {
return nil, err
}
if err := isolate.Variables.verify(); err != nil {
return nil, err
}
out := &processedIsolate{
isolate.Includes,
make([]*processedCondition, len(isolate.Conditions)),
isolate.Variables,
variablesValuesSet{},
}
for i, cond := range isolate.Conditions {
out.conditions[i], err = processCondition(cond, out.varsValsSet)
if err != nil {
return nil, err
}
}
return out, nil
} | [
"func",
"processIsolate",
"(",
"content",
"[",
"]",
"byte",
")",
"(",
"*",
"processedIsolate",
",",
"error",
")",
"{",
"isolate",
",",
"err",
":=",
"parseIsolate",
"(",
"content",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"isolate",
".",
"Variables",
".",
"verify",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"out",
":=",
"&",
"processedIsolate",
"{",
"isolate",
".",
"Includes",
",",
"make",
"(",
"[",
"]",
"*",
"processedCondition",
",",
"len",
"(",
"isolate",
".",
"Conditions",
")",
")",
",",
"isolate",
".",
"Variables",
",",
"variablesValuesSet",
"{",
"}",
",",
"}",
"\n",
"for",
"i",
",",
"cond",
":=",
"range",
"isolate",
".",
"Conditions",
"{",
"out",
".",
"conditions",
"[",
"i",
"]",
",",
"err",
"=",
"processCondition",
"(",
"cond",
",",
"out",
".",
"varsValsSet",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"out",
",",
"nil",
"\n",
"}"
] | // processIsolate loads isolate, then verifies and returns it as
// a processedIsolate for faster further processing. | [
"processIsolate",
"loads",
"isolate",
"then",
"verifies",
"and",
"returns",
"it",
"as",
"a",
"processedIsolate",
"for",
"faster",
"further",
"processing",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/isolate/format.go#L723-L744 |
9,102 | luci/luci-go | client/isolate/format.go | processCondition | func processCondition(c condition, varsAndValues variablesValuesSet) (*processedCondition, error) {
goCond, err := pythonToGoCondition(c.Condition)
if err != nil {
return nil, err
}
out := &processedCondition{condition: c.Condition, variables: c.Variables}
if out.expr, err = parser.ParseExpr(goCond); err != nil {
return nil, err
}
if out.equalityValues, err = processConditionAst(out.expr, varsAndValues); err != nil {
return nil, err
}
return out, out.variables.verify()
} | go | func processCondition(c condition, varsAndValues variablesValuesSet) (*processedCondition, error) {
goCond, err := pythonToGoCondition(c.Condition)
if err != nil {
return nil, err
}
out := &processedCondition{condition: c.Condition, variables: c.Variables}
if out.expr, err = parser.ParseExpr(goCond); err != nil {
return nil, err
}
if out.equalityValues, err = processConditionAst(out.expr, varsAndValues); err != nil {
return nil, err
}
return out, out.variables.verify()
} | [
"func",
"processCondition",
"(",
"c",
"condition",
",",
"varsAndValues",
"variablesValuesSet",
")",
"(",
"*",
"processedCondition",
",",
"error",
")",
"{",
"goCond",
",",
"err",
":=",
"pythonToGoCondition",
"(",
"c",
".",
"Condition",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"out",
":=",
"&",
"processedCondition",
"{",
"condition",
":",
"c",
".",
"Condition",
",",
"variables",
":",
"c",
".",
"Variables",
"}",
"\n",
"if",
"out",
".",
"expr",
",",
"err",
"=",
"parser",
".",
"ParseExpr",
"(",
"goCond",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"out",
".",
"equalityValues",
",",
"err",
"=",
"processConditionAst",
"(",
"out",
".",
"expr",
",",
"varsAndValues",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"out",
",",
"out",
".",
"variables",
".",
"verify",
"(",
")",
"\n",
"}"
] | // processCondition ensures condition is in correct format, and converts it
// to processedCondition for further evaluation. | [
"processCondition",
"ensures",
"condition",
"is",
"in",
"correct",
"format",
"and",
"converts",
"it",
"to",
"processedCondition",
"for",
"further",
"evaluation",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/isolate/format.go#L771-L784 |
9,103 | luci/luci-go | client/isolate/format.go | pythonToGoCondition | func pythonToGoCondition(pyCond string) (string, error) {
// Isolate supported grammar is:
// expr ::= expr ( "or" | "and" ) expr
// | identifier "==" ( string | int )
// and parentheses.
// We convert this to equivalent Go expression by:
// * replacing all 'string' to "string"
// * replacing `and` and `or` to `&&` and `||` operators, respectively.
// We work with runes to be safe against unicode.
left := []rune(pyCond)
var err error
goChunk := ""
var out []string
for len(left) > 0 {
// Process non-string tokens till next string token.
goChunk, left = pythonToGoNonString(left)
out = append(out, goChunk)
if len(left) != 0 {
if goChunk, left, err = pythonToGoString(left); err != nil {
return "", err
}
out = append(out, goChunk)
}
}
return strings.Join(out, ""), nil
} | go | func pythonToGoCondition(pyCond string) (string, error) {
// Isolate supported grammar is:
// expr ::= expr ( "or" | "and" ) expr
// | identifier "==" ( string | int )
// and parentheses.
// We convert this to equivalent Go expression by:
// * replacing all 'string' to "string"
// * replacing `and` and `or` to `&&` and `||` operators, respectively.
// We work with runes to be safe against unicode.
left := []rune(pyCond)
var err error
goChunk := ""
var out []string
for len(left) > 0 {
// Process non-string tokens till next string token.
goChunk, left = pythonToGoNonString(left)
out = append(out, goChunk)
if len(left) != 0 {
if goChunk, left, err = pythonToGoString(left); err != nil {
return "", err
}
out = append(out, goChunk)
}
}
return strings.Join(out, ""), nil
} | [
"func",
"pythonToGoCondition",
"(",
"pyCond",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"// Isolate supported grammar is:",
"//\texpr ::= expr ( \"or\" | \"and\" ) expr",
"//\t\t\t| identifier \"==\" ( string | int )",
"// and parentheses.",
"// We convert this to equivalent Go expression by:",
"//\t* replacing all 'string' to \"string\"",
"// * replacing `and` and `or` to `&&` and `||` operators, respectively.",
"// We work with runes to be safe against unicode.",
"left",
":=",
"[",
"]",
"rune",
"(",
"pyCond",
")",
"\n",
"var",
"err",
"error",
"\n",
"goChunk",
":=",
"\"",
"\"",
"\n",
"var",
"out",
"[",
"]",
"string",
"\n",
"for",
"len",
"(",
"left",
")",
">",
"0",
"{",
"// Process non-string tokens till next string token.",
"goChunk",
",",
"left",
"=",
"pythonToGoNonString",
"(",
"left",
")",
"\n",
"out",
"=",
"append",
"(",
"out",
",",
"goChunk",
")",
"\n",
"if",
"len",
"(",
"left",
")",
"!=",
"0",
"{",
"if",
"goChunk",
",",
"left",
",",
"err",
"=",
"pythonToGoString",
"(",
"left",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"out",
"=",
"append",
"(",
"out",
",",
"goChunk",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"strings",
".",
"Join",
"(",
"out",
",",
"\"",
"\"",
")",
",",
"nil",
"\n",
"}"
] | // pythonToGoCondition converts Python code into valid Go code. | [
"pythonToGoCondition",
"converts",
"Python",
"code",
"into",
"valid",
"Go",
"code",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/isolate/format.go#L948-L973 |
9,104 | luci/luci-go | dm/api/service/v1/ensure_graph_data_normalize.go | Normalize | func (t *TemplateInstantiation) Normalize() error {
if t.Project == "" {
return errors.New("empty project")
}
return t.Specifier.Normalize()
} | go | func (t *TemplateInstantiation) Normalize() error {
if t.Project == "" {
return errors.New("empty project")
}
return t.Specifier.Normalize()
} | [
"func",
"(",
"t",
"*",
"TemplateInstantiation",
")",
"Normalize",
"(",
")",
"error",
"{",
"if",
"t",
".",
"Project",
"==",
"\"",
"\"",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"t",
".",
"Specifier",
".",
"Normalize",
"(",
")",
"\n",
"}"
] | // Normalize returns an error iff the TemplateInstantiation is invalid. | [
"Normalize",
"returns",
"an",
"error",
"iff",
"the",
"TemplateInstantiation",
"is",
"invalid",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/ensure_graph_data_normalize.go#L24-L29 |
9,105 | luci/luci-go | dm/api/service/v1/ensure_graph_data_normalize.go | Normalize | func (r *EnsureGraphDataReq) Normalize() error {
if r.ForExecution != nil {
if err := r.ForExecution.Normalize(); err != nil {
return err
}
}
if err := r.RawAttempts.Normalize(); err != nil {
return err
}
hasAttempts := false
if r.RawAttempts != nil {
for _, nums := range r.RawAttempts.To {
if len(nums.Nums) == 0 {
return errors.New("EnsureGraphDataReq.attempts must only include valid (non-0, non-empty) attempt numbers")
}
hasAttempts = true
}
}
if len(r.Quest) != len(r.QuestAttempt) {
return errors.New("mismatched quest_attempt v. quest lengths")
}
if len(r.TemplateQuest) != len(r.TemplateAttempt) {
return errors.New("mismatched template_attempt v. template_quest lengths")
}
if err := checkAttemptNums("template_attempts", r.TemplateAttempt); err != nil {
return err
}
for i, q := range r.TemplateQuest {
if err := q.Normalize(); err != nil {
return fmt.Errorf("template_quests[%d]: %s", i, err)
}
}
if err := checkAttemptNums("quest_attempt", r.QuestAttempt); err != nil {
return err
}
for i, desc := range r.Quest {
if err := desc.Normalize(); err != nil {
return fmt.Errorf("quest[%d]: %s", i, err)
}
}
if len(r.Quest) == 0 && len(r.TemplateQuest) == 0 && !hasAttempts {
return errors.New("EnsureGraphDataReq must have at least one of quests, template_quests and raw_attempts")
}
if r.Limit == nil {
r.Limit = &EnsureGraphDataReq_Limit{}
}
if r.Limit.MaxDataSize == 0 {
r.Limit.MaxDataSize = DefaultLimitMaxDataSize
}
if r.Limit.MaxDataSize > MaxLimitMaxDataSize {
r.Limit.MaxDataSize = MaxLimitMaxDataSize
}
if r.Include == nil {
r.Include = &EnsureGraphDataReq_Include{Attempt: &EnsureGraphDataReq_Include_Options{}}
} else if r.Include.Attempt == nil {
r.Include.Attempt = &EnsureGraphDataReq_Include_Options{}
}
return nil
} | go | func (r *EnsureGraphDataReq) Normalize() error {
if r.ForExecution != nil {
if err := r.ForExecution.Normalize(); err != nil {
return err
}
}
if err := r.RawAttempts.Normalize(); err != nil {
return err
}
hasAttempts := false
if r.RawAttempts != nil {
for _, nums := range r.RawAttempts.To {
if len(nums.Nums) == 0 {
return errors.New("EnsureGraphDataReq.attempts must only include valid (non-0, non-empty) attempt numbers")
}
hasAttempts = true
}
}
if len(r.Quest) != len(r.QuestAttempt) {
return errors.New("mismatched quest_attempt v. quest lengths")
}
if len(r.TemplateQuest) != len(r.TemplateAttempt) {
return errors.New("mismatched template_attempt v. template_quest lengths")
}
if err := checkAttemptNums("template_attempts", r.TemplateAttempt); err != nil {
return err
}
for i, q := range r.TemplateQuest {
if err := q.Normalize(); err != nil {
return fmt.Errorf("template_quests[%d]: %s", i, err)
}
}
if err := checkAttemptNums("quest_attempt", r.QuestAttempt); err != nil {
return err
}
for i, desc := range r.Quest {
if err := desc.Normalize(); err != nil {
return fmt.Errorf("quest[%d]: %s", i, err)
}
}
if len(r.Quest) == 0 && len(r.TemplateQuest) == 0 && !hasAttempts {
return errors.New("EnsureGraphDataReq must have at least one of quests, template_quests and raw_attempts")
}
if r.Limit == nil {
r.Limit = &EnsureGraphDataReq_Limit{}
}
if r.Limit.MaxDataSize == 0 {
r.Limit.MaxDataSize = DefaultLimitMaxDataSize
}
if r.Limit.MaxDataSize > MaxLimitMaxDataSize {
r.Limit.MaxDataSize = MaxLimitMaxDataSize
}
if r.Include == nil {
r.Include = &EnsureGraphDataReq_Include{Attempt: &EnsureGraphDataReq_Include_Options{}}
} else if r.Include.Attempt == nil {
r.Include.Attempt = &EnsureGraphDataReq_Include_Options{}
}
return nil
} | [
"func",
"(",
"r",
"*",
"EnsureGraphDataReq",
")",
"Normalize",
"(",
")",
"error",
"{",
"if",
"r",
".",
"ForExecution",
"!=",
"nil",
"{",
"if",
"err",
":=",
"r",
".",
"ForExecution",
".",
"Normalize",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"r",
".",
"RawAttempts",
".",
"Normalize",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"hasAttempts",
":=",
"false",
"\n",
"if",
"r",
".",
"RawAttempts",
"!=",
"nil",
"{",
"for",
"_",
",",
"nums",
":=",
"range",
"r",
".",
"RawAttempts",
".",
"To",
"{",
"if",
"len",
"(",
"nums",
".",
"Nums",
")",
"==",
"0",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"hasAttempts",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"r",
".",
"Quest",
")",
"!=",
"len",
"(",
"r",
".",
"QuestAttempt",
")",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"r",
".",
"TemplateQuest",
")",
"!=",
"len",
"(",
"r",
".",
"TemplateAttempt",
")",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"checkAttemptNums",
"(",
"\"",
"\"",
",",
"r",
".",
"TemplateAttempt",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"for",
"i",
",",
"q",
":=",
"range",
"r",
".",
"TemplateQuest",
"{",
"if",
"err",
":=",
"q",
".",
"Normalize",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"i",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"checkAttemptNums",
"(",
"\"",
"\"",
",",
"r",
".",
"QuestAttempt",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"for",
"i",
",",
"desc",
":=",
"range",
"r",
".",
"Quest",
"{",
"if",
"err",
":=",
"desc",
".",
"Normalize",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"i",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"len",
"(",
"r",
".",
"Quest",
")",
"==",
"0",
"&&",
"len",
"(",
"r",
".",
"TemplateQuest",
")",
"==",
"0",
"&&",
"!",
"hasAttempts",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"if",
"r",
".",
"Limit",
"==",
"nil",
"{",
"r",
".",
"Limit",
"=",
"&",
"EnsureGraphDataReq_Limit",
"{",
"}",
"\n",
"}",
"\n",
"if",
"r",
".",
"Limit",
".",
"MaxDataSize",
"==",
"0",
"{",
"r",
".",
"Limit",
".",
"MaxDataSize",
"=",
"DefaultLimitMaxDataSize",
"\n",
"}",
"\n",
"if",
"r",
".",
"Limit",
".",
"MaxDataSize",
">",
"MaxLimitMaxDataSize",
"{",
"r",
".",
"Limit",
".",
"MaxDataSize",
"=",
"MaxLimitMaxDataSize",
"\n",
"}",
"\n\n",
"if",
"r",
".",
"Include",
"==",
"nil",
"{",
"r",
".",
"Include",
"=",
"&",
"EnsureGraphDataReq_Include",
"{",
"Attempt",
":",
"&",
"EnsureGraphDataReq_Include_Options",
"{",
"}",
"}",
"\n",
"}",
"else",
"if",
"r",
".",
"Include",
".",
"Attempt",
"==",
"nil",
"{",
"r",
".",
"Include",
".",
"Attempt",
"=",
"&",
"EnsureGraphDataReq_Include_Options",
"{",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Normalize returns an error iff the request is invalid. | [
"Normalize",
"returns",
"an",
"error",
"iff",
"the",
"request",
"is",
"invalid",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/service/v1/ensure_graph_data_normalize.go#L44-L113 |
9,106 | luci/luci-go | client/internal/common/flags.go | StartTracing | func (d *Flags) StartTracing() (io.Closer, error) {
if d.TracePath == "" {
return &tracingState{}, nil
}
f, err := os.Create(d.TracePath)
if err != nil {
return &tracingState{}, err
}
if err = tracer.Start(f, 0); err != nil {
_ = f.Close()
return &tracingState{}, err
}
return &tracingState{f}, nil
} | go | func (d *Flags) StartTracing() (io.Closer, error) {
if d.TracePath == "" {
return &tracingState{}, nil
}
f, err := os.Create(d.TracePath)
if err != nil {
return &tracingState{}, err
}
if err = tracer.Start(f, 0); err != nil {
_ = f.Close()
return &tracingState{}, err
}
return &tracingState{f}, nil
} | [
"func",
"(",
"d",
"*",
"Flags",
")",
"StartTracing",
"(",
")",
"(",
"io",
".",
"Closer",
",",
"error",
")",
"{",
"if",
"d",
".",
"TracePath",
"==",
"\"",
"\"",
"{",
"return",
"&",
"tracingState",
"{",
"}",
",",
"nil",
"\n",
"}",
"\n",
"f",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"d",
".",
"TracePath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"&",
"tracingState",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
"=",
"tracer",
".",
"Start",
"(",
"f",
",",
"0",
")",
";",
"err",
"!=",
"nil",
"{",
"_",
"=",
"f",
".",
"Close",
"(",
")",
"\n",
"return",
"&",
"tracingState",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"tracingState",
"{",
"f",
"}",
",",
"nil",
"\n",
"}"
] | // StartTracing enables tracing and returns a closer that must be called on
// process termination. | [
"StartTracing",
"enables",
"tracing",
"and",
"returns",
"a",
"closer",
"that",
"must",
"be",
"called",
"on",
"process",
"termination",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/client/internal/common/flags.go#L67-L80 |
9,107 | luci/luci-go | server/templates/bundle.go | MergeArgs | func MergeArgs(args ...Args) Args {
total := 0
for _, a := range args {
total += len(a)
}
if total == 0 {
return nil
}
res := make(Args, total)
for _, a := range args {
for k, v := range a {
res[k] = v
}
}
return res
} | go | func MergeArgs(args ...Args) Args {
total := 0
for _, a := range args {
total += len(a)
}
if total == 0 {
return nil
}
res := make(Args, total)
for _, a := range args {
for k, v := range a {
res[k] = v
}
}
return res
} | [
"func",
"MergeArgs",
"(",
"args",
"...",
"Args",
")",
"Args",
"{",
"total",
":=",
"0",
"\n",
"for",
"_",
",",
"a",
":=",
"range",
"args",
"{",
"total",
"+=",
"len",
"(",
"a",
")",
"\n",
"}",
"\n",
"if",
"total",
"==",
"0",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"res",
":=",
"make",
"(",
"Args",
",",
"total",
")",
"\n",
"for",
"_",
",",
"a",
":=",
"range",
"args",
"{",
"for",
"k",
",",
"v",
":=",
"range",
"a",
"{",
"res",
"[",
"k",
"]",
"=",
"v",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"res",
"\n",
"}"
] | // MergeArgs combines multiple Args instances into one. Returns nil if all
// passed args are empty. | [
"MergeArgs",
"combines",
"multiple",
"Args",
"instances",
"into",
"one",
".",
"Returns",
"nil",
"if",
"all",
"passed",
"args",
"are",
"empty",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/templates/bundle.go#L37-L52 |
9,108 | luci/luci-go | server/templates/bundle.go | EnsureLoaded | func (b *Bundle) EnsureLoaded(c context.Context) error {
// Always reload in debug mode. Load only once in non-debug mode.
if dm := b.DebugMode; dm != nil && dm(c) {
b.templates, b.err = b.Loader(c, b.FuncMap)
} else {
b.once.Do(func() {
b.templates, b.err = b.Loader(c, b.FuncMap)
})
}
return b.err
} | go | func (b *Bundle) EnsureLoaded(c context.Context) error {
// Always reload in debug mode. Load only once in non-debug mode.
if dm := b.DebugMode; dm != nil && dm(c) {
b.templates, b.err = b.Loader(c, b.FuncMap)
} else {
b.once.Do(func() {
b.templates, b.err = b.Loader(c, b.FuncMap)
})
}
return b.err
} | [
"func",
"(",
"b",
"*",
"Bundle",
")",
"EnsureLoaded",
"(",
"c",
"context",
".",
"Context",
")",
"error",
"{",
"// Always reload in debug mode. Load only once in non-debug mode.",
"if",
"dm",
":=",
"b",
".",
"DebugMode",
";",
"dm",
"!=",
"nil",
"&&",
"dm",
"(",
"c",
")",
"{",
"b",
".",
"templates",
",",
"b",
".",
"err",
"=",
"b",
".",
"Loader",
"(",
"c",
",",
"b",
".",
"FuncMap",
")",
"\n",
"}",
"else",
"{",
"b",
".",
"once",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"b",
".",
"templates",
",",
"b",
".",
"err",
"=",
"b",
".",
"Loader",
"(",
"c",
",",
"b",
".",
"FuncMap",
")",
"\n",
"}",
")",
"\n",
"}",
"\n",
"return",
"b",
".",
"err",
"\n",
"}"
] | // EnsureLoaded loads all the templates if they haven't been loaded yet. | [
"EnsureLoaded",
"loads",
"all",
"the",
"templates",
"if",
"they",
"haven",
"t",
"been",
"loaded",
"yet",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/templates/bundle.go#L112-L122 |
9,109 | luci/luci-go | server/auth/signing/certs.go | FetchCertificatesForServiceAccount | func FetchCertificatesForServiceAccount(c context.Context, email string) (*PublicCertificates, error) {
// Do only basic validation and offload full validation to the google backend.
if !strings.HasSuffix(email, ".gserviceaccount.com") {
return nil, fmt.Errorf("signature: not a google service account %q", email)
}
certs, err := certsCache.LRU(c).GetOrCreate(c, "email:"+email, func() (interface{}, time.Duration, error) {
certs, err := fetchCertsJSON(c, robotCertsURL+url.QueryEscape(email))
if err != nil {
return nil, 0, err
}
certs.ServiceAccountName = email
return certs, CertsCacheExpiration, nil
})
if err != nil {
return nil, err
}
return certs.(*PublicCertificates), nil
} | go | func FetchCertificatesForServiceAccount(c context.Context, email string) (*PublicCertificates, error) {
// Do only basic validation and offload full validation to the google backend.
if !strings.HasSuffix(email, ".gserviceaccount.com") {
return nil, fmt.Errorf("signature: not a google service account %q", email)
}
certs, err := certsCache.LRU(c).GetOrCreate(c, "email:"+email, func() (interface{}, time.Duration, error) {
certs, err := fetchCertsJSON(c, robotCertsURL+url.QueryEscape(email))
if err != nil {
return nil, 0, err
}
certs.ServiceAccountName = email
return certs, CertsCacheExpiration, nil
})
if err != nil {
return nil, err
}
return certs.(*PublicCertificates), nil
} | [
"func",
"FetchCertificatesForServiceAccount",
"(",
"c",
"context",
".",
"Context",
",",
"email",
"string",
")",
"(",
"*",
"PublicCertificates",
",",
"error",
")",
"{",
"// Do only basic validation and offload full validation to the google backend.",
"if",
"!",
"strings",
".",
"HasSuffix",
"(",
"email",
",",
"\"",
"\"",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"email",
")",
"\n",
"}",
"\n",
"certs",
",",
"err",
":=",
"certsCache",
".",
"LRU",
"(",
"c",
")",
".",
"GetOrCreate",
"(",
"c",
",",
"\"",
"\"",
"+",
"email",
",",
"func",
"(",
")",
"(",
"interface",
"{",
"}",
",",
"time",
".",
"Duration",
",",
"error",
")",
"{",
"certs",
",",
"err",
":=",
"fetchCertsJSON",
"(",
"c",
",",
"robotCertsURL",
"+",
"url",
".",
"QueryEscape",
"(",
"email",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"0",
",",
"err",
"\n",
"}",
"\n",
"certs",
".",
"ServiceAccountName",
"=",
"email",
"\n",
"return",
"certs",
",",
"CertsCacheExpiration",
",",
"nil",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"certs",
".",
"(",
"*",
"PublicCertificates",
")",
",",
"nil",
"\n",
"}"
] | // FetchCertificatesForServiceAccount fetches certificates of some Google
// service account.
//
// Works only with Google service accounts (@*.gserviceaccount.com). Uses the
// process cache to cache them for CertsCacheExpiration minutes.
//
// Usage (roughly):
//
// certs, err := signing.FetchCertificatesForServiceAccount(ctx, <email>)
// if certs.CheckSignature(<key id>, <blob>, <signature>) == nil {
// <signature is valid!>
// } | [
"FetchCertificatesForServiceAccount",
"fetches",
"certificates",
"of",
"some",
"Google",
"service",
"account",
".",
"Works",
"only",
"with",
"Google",
"service",
"accounts",
"("
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/signing/certs.go#L140-L157 |
9,110 | luci/luci-go | server/auth/signing/certs.go | fetchCertsJSON | func fetchCertsJSON(c context.Context, url string) (*PublicCertificates, error) {
keysAndCerts := map[string]string{}
req := internal.Request{
Method: "GET",
URL: url,
Out: &keysAndCerts,
}
if err := req.Do(c); err != nil {
return nil, err
}
// Sort by key for reproducibility of return values.
keys := make([]string, 0, len(keysAndCerts))
for key := range keysAndCerts {
keys = append(keys, key)
}
sort.Strings(keys)
// Convert to PublicCertificates struct.
certs := &PublicCertificates{}
for _, key := range keys {
certs.Certificates = append(certs.Certificates, Certificate{
KeyName: key,
X509CertificatePEM: keysAndCerts[key],
})
}
return certs, nil
} | go | func fetchCertsJSON(c context.Context, url string) (*PublicCertificates, error) {
keysAndCerts := map[string]string{}
req := internal.Request{
Method: "GET",
URL: url,
Out: &keysAndCerts,
}
if err := req.Do(c); err != nil {
return nil, err
}
// Sort by key for reproducibility of return values.
keys := make([]string, 0, len(keysAndCerts))
for key := range keysAndCerts {
keys = append(keys, key)
}
sort.Strings(keys)
// Convert to PublicCertificates struct.
certs := &PublicCertificates{}
for _, key := range keys {
certs.Certificates = append(certs.Certificates, Certificate{
KeyName: key,
X509CertificatePEM: keysAndCerts[key],
})
}
return certs, nil
} | [
"func",
"fetchCertsJSON",
"(",
"c",
"context",
".",
"Context",
",",
"url",
"string",
")",
"(",
"*",
"PublicCertificates",
",",
"error",
")",
"{",
"keysAndCerts",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"req",
":=",
"internal",
".",
"Request",
"{",
"Method",
":",
"\"",
"\"",
",",
"URL",
":",
"url",
",",
"Out",
":",
"&",
"keysAndCerts",
",",
"}",
"\n",
"if",
"err",
":=",
"req",
".",
"Do",
"(",
"c",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Sort by key for reproducibility of return values.",
"keys",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"keysAndCerts",
")",
")",
"\n",
"for",
"key",
":=",
"range",
"keysAndCerts",
"{",
"keys",
"=",
"append",
"(",
"keys",
",",
"key",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"keys",
")",
"\n\n",
"// Convert to PublicCertificates struct.",
"certs",
":=",
"&",
"PublicCertificates",
"{",
"}",
"\n",
"for",
"_",
",",
"key",
":=",
"range",
"keys",
"{",
"certs",
".",
"Certificates",
"=",
"append",
"(",
"certs",
".",
"Certificates",
",",
"Certificate",
"{",
"KeyName",
":",
"key",
",",
"X509CertificatePEM",
":",
"keysAndCerts",
"[",
"key",
"]",
",",
"}",
")",
"\n",
"}",
"\n",
"return",
"certs",
",",
"nil",
"\n",
"}"
] | // fetchCertsJSON loads certificates from a JSON dict "key id => x509 PEM cert".
//
// This is the format served by Google certificate endpoints. | [
"fetchCertsJSON",
"loads",
"certificates",
"from",
"a",
"JSON",
"dict",
"key",
"id",
"=",
">",
"x509",
"PEM",
"cert",
".",
"This",
"is",
"the",
"format",
"served",
"by",
"Google",
"certificate",
"endpoints",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/signing/certs.go#L183-L210 |
9,111 | luci/luci-go | server/auth/signing/certs.go | CertificateForKey | func (pc *PublicCertificates) CertificateForKey(key string) (*x509.Certificate, error) {
// Use fast reader lock first.
pc.lock.RLock()
cert, ok := pc.cache[key]
pc.lock.RUnlock()
if ok {
return cert, nil
}
// Grab the write lock and recheck the cache.
pc.lock.Lock()
defer pc.lock.Unlock()
if cert, ok := pc.cache[key]; ok {
return cert, nil
}
for _, cert := range pc.Certificates {
if cert.KeyName == key {
block, _ := pem.Decode([]byte(cert.X509CertificatePEM))
if block == nil {
return nil, fmt.Errorf("signature: the certificate %q is not PEM encoded", key)
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, err
}
if pc.cache == nil {
pc.cache = make(map[string]*x509.Certificate)
}
pc.cache[key] = cert
return cert, nil
}
}
return nil, fmt.Errorf("signature: no such certificate %q", key)
} | go | func (pc *PublicCertificates) CertificateForKey(key string) (*x509.Certificate, error) {
// Use fast reader lock first.
pc.lock.RLock()
cert, ok := pc.cache[key]
pc.lock.RUnlock()
if ok {
return cert, nil
}
// Grab the write lock and recheck the cache.
pc.lock.Lock()
defer pc.lock.Unlock()
if cert, ok := pc.cache[key]; ok {
return cert, nil
}
for _, cert := range pc.Certificates {
if cert.KeyName == key {
block, _ := pem.Decode([]byte(cert.X509CertificatePEM))
if block == nil {
return nil, fmt.Errorf("signature: the certificate %q is not PEM encoded", key)
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, err
}
if pc.cache == nil {
pc.cache = make(map[string]*x509.Certificate)
}
pc.cache[key] = cert
return cert, nil
}
}
return nil, fmt.Errorf("signature: no such certificate %q", key)
} | [
"func",
"(",
"pc",
"*",
"PublicCertificates",
")",
"CertificateForKey",
"(",
"key",
"string",
")",
"(",
"*",
"x509",
".",
"Certificate",
",",
"error",
")",
"{",
"// Use fast reader lock first.",
"pc",
".",
"lock",
".",
"RLock",
"(",
")",
"\n",
"cert",
",",
"ok",
":=",
"pc",
".",
"cache",
"[",
"key",
"]",
"\n",
"pc",
".",
"lock",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"ok",
"{",
"return",
"cert",
",",
"nil",
"\n",
"}",
"\n\n",
"// Grab the write lock and recheck the cache.",
"pc",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"pc",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"if",
"cert",
",",
"ok",
":=",
"pc",
".",
"cache",
"[",
"key",
"]",
";",
"ok",
"{",
"return",
"cert",
",",
"nil",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"cert",
":=",
"range",
"pc",
".",
"Certificates",
"{",
"if",
"cert",
".",
"KeyName",
"==",
"key",
"{",
"block",
",",
"_",
":=",
"pem",
".",
"Decode",
"(",
"[",
"]",
"byte",
"(",
"cert",
".",
"X509CertificatePEM",
")",
")",
"\n",
"if",
"block",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"key",
")",
"\n",
"}",
"\n",
"cert",
",",
"err",
":=",
"x509",
".",
"ParseCertificate",
"(",
"block",
".",
"Bytes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"pc",
".",
"cache",
"==",
"nil",
"{",
"pc",
".",
"cache",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"x509",
".",
"Certificate",
")",
"\n",
"}",
"\n",
"pc",
".",
"cache",
"[",
"key",
"]",
"=",
"cert",
"\n",
"return",
"cert",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"key",
")",
"\n",
"}"
] | // CertificateForKey finds the certificate for given key and deserializes it. | [
"CertificateForKey",
"finds",
"the",
"certificate",
"for",
"given",
"key",
"and",
"deserializes",
"it",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/signing/certs.go#L213-L248 |
9,112 | luci/luci-go | server/auth/signing/certs.go | CheckSignature | func (pc *PublicCertificates) CheckSignature(key string, signed, signature []byte) error {
cert, err := pc.CertificateForKey(key)
if err != nil {
return err
}
return cert.CheckSignature(x509.SHA256WithRSA, signed, signature)
} | go | func (pc *PublicCertificates) CheckSignature(key string, signed, signature []byte) error {
cert, err := pc.CertificateForKey(key)
if err != nil {
return err
}
return cert.CheckSignature(x509.SHA256WithRSA, signed, signature)
} | [
"func",
"(",
"pc",
"*",
"PublicCertificates",
")",
"CheckSignature",
"(",
"key",
"string",
",",
"signed",
",",
"signature",
"[",
"]",
"byte",
")",
"error",
"{",
"cert",
",",
"err",
":=",
"pc",
".",
"CertificateForKey",
"(",
"key",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"cert",
".",
"CheckSignature",
"(",
"x509",
".",
"SHA256WithRSA",
",",
"signed",
",",
"signature",
")",
"\n",
"}"
] | // CheckSignature returns nil if `signed` was indeed signed by given key. | [
"CheckSignature",
"returns",
"nil",
"if",
"signed",
"was",
"indeed",
"signed",
"by",
"given",
"key",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/signing/certs.go#L251-L257 |
9,113 | luci/luci-go | appengine/gaeauth/server/internal/authdbimpl/handlers.go | InstallHandlers | func InstallHandlers(r *router.Router, base router.MiddlewareChain) {
if appengine.IsDevAppServer() {
r.GET(pubSubPullURLPath, base, pubSubPull)
}
r.POST(pubSubPushURLPath, base, pubSubPush)
} | go | func InstallHandlers(r *router.Router, base router.MiddlewareChain) {
if appengine.IsDevAppServer() {
r.GET(pubSubPullURLPath, base, pubSubPull)
}
r.POST(pubSubPushURLPath, base, pubSubPush)
} | [
"func",
"InstallHandlers",
"(",
"r",
"*",
"router",
".",
"Router",
",",
"base",
"router",
".",
"MiddlewareChain",
")",
"{",
"if",
"appengine",
".",
"IsDevAppServer",
"(",
")",
"{",
"r",
".",
"GET",
"(",
"pubSubPullURLPath",
",",
"base",
",",
"pubSubPull",
")",
"\n",
"}",
"\n",
"r",
".",
"POST",
"(",
"pubSubPushURLPath",
",",
"base",
",",
"pubSubPush",
")",
"\n",
"}"
] | // InstallHandlers installs PubSub related HTTP handlers. | [
"InstallHandlers",
"installs",
"PubSub",
"related",
"HTTP",
"handlers",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaeauth/server/internal/authdbimpl/handlers.go#L41-L46 |
9,114 | luci/luci-go | appengine/gaeauth/server/internal/authdbimpl/handlers.go | setupPubSub | func setupPubSub(c context.Context, baseURL, authServiceURL string) error {
pushURL := ""
if !info.IsDevAppServer(c) {
pushURL = baseURL + pubSubPushURLPath // push in prod, pull on dev server
}
service := getAuthService(c, authServiceURL)
return service.EnsureSubscription(c, subscriptionName(c, authServiceURL), pushURL)
} | go | func setupPubSub(c context.Context, baseURL, authServiceURL string) error {
pushURL := ""
if !info.IsDevAppServer(c) {
pushURL = baseURL + pubSubPushURLPath // push in prod, pull on dev server
}
service := getAuthService(c, authServiceURL)
return service.EnsureSubscription(c, subscriptionName(c, authServiceURL), pushURL)
} | [
"func",
"setupPubSub",
"(",
"c",
"context",
".",
"Context",
",",
"baseURL",
",",
"authServiceURL",
"string",
")",
"error",
"{",
"pushURL",
":=",
"\"",
"\"",
"\n",
"if",
"!",
"info",
".",
"IsDevAppServer",
"(",
"c",
")",
"{",
"pushURL",
"=",
"baseURL",
"+",
"pubSubPushURLPath",
"// push in prod, pull on dev server",
"\n",
"}",
"\n",
"service",
":=",
"getAuthService",
"(",
"c",
",",
"authServiceURL",
")",
"\n",
"return",
"service",
".",
"EnsureSubscription",
"(",
"c",
",",
"subscriptionName",
"(",
"c",
",",
"authServiceURL",
")",
",",
"pushURL",
")",
"\n",
"}"
] | // setupPubSub creates a subscription to AuthDB service notification stream. | [
"setupPubSub",
"creates",
"a",
"subscription",
"to",
"AuthDB",
"service",
"notification",
"stream",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaeauth/server/internal/authdbimpl/handlers.go#L49-L56 |
9,115 | luci/luci-go | appengine/gaeauth/server/internal/authdbimpl/handlers.go | killPubSub | func killPubSub(c context.Context, authServiceURL string) error {
service := getAuthService(c, authServiceURL)
return service.DeleteSubscription(c, subscriptionName(c, authServiceURL))
} | go | func killPubSub(c context.Context, authServiceURL string) error {
service := getAuthService(c, authServiceURL)
return service.DeleteSubscription(c, subscriptionName(c, authServiceURL))
} | [
"func",
"killPubSub",
"(",
"c",
"context",
".",
"Context",
",",
"authServiceURL",
"string",
")",
"error",
"{",
"service",
":=",
"getAuthService",
"(",
"c",
",",
"authServiceURL",
")",
"\n",
"return",
"service",
".",
"DeleteSubscription",
"(",
"c",
",",
"subscriptionName",
"(",
"c",
",",
"authServiceURL",
")",
")",
"\n",
"}"
] | // killPubSub removes PubSub subscription created with setupPubSub. | [
"killPubSub",
"removes",
"PubSub",
"subscription",
"created",
"with",
"setupPubSub",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaeauth/server/internal/authdbimpl/handlers.go#L59-L62 |
9,116 | luci/luci-go | appengine/gaeauth/server/internal/authdbimpl/handlers.go | subscriptionName | func subscriptionName(c context.Context, authServiceURL string) string {
subIDPrefix := "gae-v1"
if info.IsDevAppServer(c) {
subIDPrefix = "dev-app-server-v1"
}
serviceURL, err := url.Parse(authServiceURL)
if err != nil {
panic(err)
}
return fmt.Sprintf("projects/%s/subscriptions/%s+%s", info.AppID(c), subIDPrefix, serviceURL.Host)
} | go | func subscriptionName(c context.Context, authServiceURL string) string {
subIDPrefix := "gae-v1"
if info.IsDevAppServer(c) {
subIDPrefix = "dev-app-server-v1"
}
serviceURL, err := url.Parse(authServiceURL)
if err != nil {
panic(err)
}
return fmt.Sprintf("projects/%s/subscriptions/%s+%s", info.AppID(c), subIDPrefix, serviceURL.Host)
} | [
"func",
"subscriptionName",
"(",
"c",
"context",
".",
"Context",
",",
"authServiceURL",
"string",
")",
"string",
"{",
"subIDPrefix",
":=",
"\"",
"\"",
"\n",
"if",
"info",
".",
"IsDevAppServer",
"(",
"c",
")",
"{",
"subIDPrefix",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"serviceURL",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"authServiceURL",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"info",
".",
"AppID",
"(",
"c",
")",
",",
"subIDPrefix",
",",
"serviceURL",
".",
"Host",
")",
"\n",
"}"
] | // subscriptionName returns full PubSub subscription name for AuthDB
// change notifications stream from given auth service. | [
"subscriptionName",
"returns",
"full",
"PubSub",
"subscription",
"name",
"for",
"AuthDB",
"change",
"notifications",
"stream",
"from",
"given",
"auth",
"service",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaeauth/server/internal/authdbimpl/handlers.go#L66-L76 |
9,117 | luci/luci-go | appengine/gaeauth/server/internal/authdbimpl/handlers.go | pubSubPull | func pubSubPull(c *router.Context) {
if !appengine.IsDevAppServer() {
replyError(c.Context, c.Writer, errors.New("not a dev server"))
return
}
processPubSubRequest(c.Context, c.Writer, c.Request, func(c context.Context, srv authService, serviceURL string) (*service.Notification, error) {
return srv.PullPubSub(c, subscriptionName(c, serviceURL))
})
} | go | func pubSubPull(c *router.Context) {
if !appengine.IsDevAppServer() {
replyError(c.Context, c.Writer, errors.New("not a dev server"))
return
}
processPubSubRequest(c.Context, c.Writer, c.Request, func(c context.Context, srv authService, serviceURL string) (*service.Notification, error) {
return srv.PullPubSub(c, subscriptionName(c, serviceURL))
})
} | [
"func",
"pubSubPull",
"(",
"c",
"*",
"router",
".",
"Context",
")",
"{",
"if",
"!",
"appengine",
".",
"IsDevAppServer",
"(",
")",
"{",
"replyError",
"(",
"c",
".",
"Context",
",",
"c",
".",
"Writer",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"processPubSubRequest",
"(",
"c",
".",
"Context",
",",
"c",
".",
"Writer",
",",
"c",
".",
"Request",
",",
"func",
"(",
"c",
"context",
".",
"Context",
",",
"srv",
"authService",
",",
"serviceURL",
"string",
")",
"(",
"*",
"service",
".",
"Notification",
",",
"error",
")",
"{",
"return",
"srv",
".",
"PullPubSub",
"(",
"c",
",",
"subscriptionName",
"(",
"c",
",",
"serviceURL",
")",
")",
"\n",
"}",
")",
"\n",
"}"
] | // pubSubPull is HTTP handler that pulls PubSub messages from AuthDB change
// notification topic.
//
// Used only on dev server for manual testing. Prod services use push-based
// delivery. | [
"pubSubPull",
"is",
"HTTP",
"handler",
"that",
"pulls",
"PubSub",
"messages",
"from",
"AuthDB",
"change",
"notification",
"topic",
".",
"Used",
"only",
"on",
"dev",
"server",
"for",
"manual",
"testing",
".",
"Prod",
"services",
"use",
"push",
"-",
"based",
"delivery",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaeauth/server/internal/authdbimpl/handlers.go#L83-L91 |
9,118 | luci/luci-go | appengine/gaeauth/server/internal/authdbimpl/handlers.go | pubSubPush | func pubSubPush(c *router.Context) {
processPubSubRequest(c.Context, c.Writer, c.Request, func(ctx context.Context, srv authService, serviceURL string) (*service.Notification, error) {
body, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
return nil, err
}
return srv.ProcessPubSubPush(ctx, body)
})
} | go | func pubSubPush(c *router.Context) {
processPubSubRequest(c.Context, c.Writer, c.Request, func(ctx context.Context, srv authService, serviceURL string) (*service.Notification, error) {
body, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
return nil, err
}
return srv.ProcessPubSubPush(ctx, body)
})
} | [
"func",
"pubSubPush",
"(",
"c",
"*",
"router",
".",
"Context",
")",
"{",
"processPubSubRequest",
"(",
"c",
".",
"Context",
",",
"c",
".",
"Writer",
",",
"c",
".",
"Request",
",",
"func",
"(",
"ctx",
"context",
".",
"Context",
",",
"srv",
"authService",
",",
"serviceURL",
"string",
")",
"(",
"*",
"service",
".",
"Notification",
",",
"error",
")",
"{",
"body",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"c",
".",
"Request",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"srv",
".",
"ProcessPubSubPush",
"(",
"ctx",
",",
"body",
")",
"\n",
"}",
")",
"\n",
"}"
] | // pubSubPush is HTTP handler that processes incoming PubSub push notifications.
//
// It uses the signature inside PubSub message body for authentication. Skips
// messages not signed by currently configured auth service. | [
"pubSubPush",
"is",
"HTTP",
"handler",
"that",
"processes",
"incoming",
"PubSub",
"push",
"notifications",
".",
"It",
"uses",
"the",
"signature",
"inside",
"PubSub",
"message",
"body",
"for",
"authentication",
".",
"Skips",
"messages",
"not",
"signed",
"by",
"currently",
"configured",
"auth",
"service",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaeauth/server/internal/authdbimpl/handlers.go#L97-L105 |
9,119 | luci/luci-go | appengine/gaeauth/server/internal/authdbimpl/handlers.go | processPubSubRequest | func processPubSubRequest(c context.Context, rw http.ResponseWriter, r *http.Request, callback notifcationGetter) {
c = defaultNS(c)
info, err := GetLatestSnapshotInfo(c)
if err != nil {
replyError(c, rw, err)
return
}
if info == nil {
// Return HTTP 200 to avoid a redelivery.
replyOK(c, rw, "Auth Service URL is not configured, skipping the message")
return
}
srv := getAuthService(c, info.AuthServiceURL)
notify, err := callback(c, srv, info.AuthServiceURL)
if err != nil {
replyError(c, rw, err)
return
}
// notify may be nil if PubSub messages didn't pass authentication.
if notify == nil {
replyOK(c, rw, "No new valid AuthDB change notifications")
return
}
// Don't bother processing late messages (ack them though).
latest := info
if notify.Revision > info.Rev {
var err error
if latest, err = syncAuthDB(c); err != nil {
replyError(c, rw, err)
return
}
}
if err := notify.Acknowledge(c); err != nil {
replyError(c, rw, err)
return
}
replyOK(
c, rw, "Processed PubSub notification for rev %d: %d -> %d",
notify.Revision, info.Rev, latest.Rev)
} | go | func processPubSubRequest(c context.Context, rw http.ResponseWriter, r *http.Request, callback notifcationGetter) {
c = defaultNS(c)
info, err := GetLatestSnapshotInfo(c)
if err != nil {
replyError(c, rw, err)
return
}
if info == nil {
// Return HTTP 200 to avoid a redelivery.
replyOK(c, rw, "Auth Service URL is not configured, skipping the message")
return
}
srv := getAuthService(c, info.AuthServiceURL)
notify, err := callback(c, srv, info.AuthServiceURL)
if err != nil {
replyError(c, rw, err)
return
}
// notify may be nil if PubSub messages didn't pass authentication.
if notify == nil {
replyOK(c, rw, "No new valid AuthDB change notifications")
return
}
// Don't bother processing late messages (ack them though).
latest := info
if notify.Revision > info.Rev {
var err error
if latest, err = syncAuthDB(c); err != nil {
replyError(c, rw, err)
return
}
}
if err := notify.Acknowledge(c); err != nil {
replyError(c, rw, err)
return
}
replyOK(
c, rw, "Processed PubSub notification for rev %d: %d -> %d",
notify.Revision, info.Rev, latest.Rev)
} | [
"func",
"processPubSubRequest",
"(",
"c",
"context",
".",
"Context",
",",
"rw",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
",",
"callback",
"notifcationGetter",
")",
"{",
"c",
"=",
"defaultNS",
"(",
"c",
")",
"\n",
"info",
",",
"err",
":=",
"GetLatestSnapshotInfo",
"(",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"replyError",
"(",
"c",
",",
"rw",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"info",
"==",
"nil",
"{",
"// Return HTTP 200 to avoid a redelivery.",
"replyOK",
"(",
"c",
",",
"rw",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"srv",
":=",
"getAuthService",
"(",
"c",
",",
"info",
".",
"AuthServiceURL",
")",
"\n\n",
"notify",
",",
"err",
":=",
"callback",
"(",
"c",
",",
"srv",
",",
"info",
".",
"AuthServiceURL",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"replyError",
"(",
"c",
",",
"rw",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// notify may be nil if PubSub messages didn't pass authentication.",
"if",
"notify",
"==",
"nil",
"{",
"replyOK",
"(",
"c",
",",
"rw",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Don't bother processing late messages (ack them though).",
"latest",
":=",
"info",
"\n",
"if",
"notify",
".",
"Revision",
">",
"info",
".",
"Rev",
"{",
"var",
"err",
"error",
"\n",
"if",
"latest",
",",
"err",
"=",
"syncAuthDB",
"(",
"c",
")",
";",
"err",
"!=",
"nil",
"{",
"replyError",
"(",
"c",
",",
"rw",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"notify",
".",
"Acknowledge",
"(",
"c",
")",
";",
"err",
"!=",
"nil",
"{",
"replyError",
"(",
"c",
",",
"rw",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"replyOK",
"(",
"c",
",",
"rw",
",",
"\"",
"\"",
",",
"notify",
".",
"Revision",
",",
"info",
".",
"Rev",
",",
"latest",
".",
"Rev",
")",
"\n",
"}"
] | // processPubSubRequest is common wrapper for pubSubPull and pubSubPush.
//
// It implements most logic of notification handling. Calls supplied callback
// to actually get service.Notification, since this part is different from Pull
// and Push subscriptions. | [
"processPubSubRequest",
"is",
"common",
"wrapper",
"for",
"pubSubPull",
"and",
"pubSubPush",
".",
"It",
"implements",
"most",
"logic",
"of",
"notification",
"handling",
".",
"Calls",
"supplied",
"callback",
"to",
"actually",
"get",
"service",
".",
"Notification",
"since",
"this",
"part",
"is",
"different",
"from",
"Pull",
"and",
"Push",
"subscriptions",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaeauth/server/internal/authdbimpl/handlers.go#L114-L158 |
9,120 | luci/luci-go | appengine/gaeauth/server/internal/authdbimpl/handlers.go | replyError | func replyError(c context.Context, rw http.ResponseWriter, err error) {
logging.Errorf(c, "Error while processing PubSub notification - %s", err)
if transient.Tag.In(err) {
http.Error(rw, err.Error(), http.StatusInternalServerError)
} else {
http.Error(rw, err.Error(), http.StatusBadRequest)
}
} | go | func replyError(c context.Context, rw http.ResponseWriter, err error) {
logging.Errorf(c, "Error while processing PubSub notification - %s", err)
if transient.Tag.In(err) {
http.Error(rw, err.Error(), http.StatusInternalServerError)
} else {
http.Error(rw, err.Error(), http.StatusBadRequest)
}
} | [
"func",
"replyError",
"(",
"c",
"context",
".",
"Context",
",",
"rw",
"http",
".",
"ResponseWriter",
",",
"err",
"error",
")",
"{",
"logging",
".",
"Errorf",
"(",
"c",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"if",
"transient",
".",
"Tag",
".",
"In",
"(",
"err",
")",
"{",
"http",
".",
"Error",
"(",
"rw",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"}",
"else",
"{",
"http",
".",
"Error",
"(",
"rw",
",",
"err",
".",
"Error",
"(",
")",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"}",
"\n",
"}"
] | // replyError sends HTTP 500 on transient errors, HTTP 400 on fatal ones. | [
"replyError",
"sends",
"HTTP",
"500",
"on",
"transient",
"errors",
"HTTP",
"400",
"on",
"fatal",
"ones",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaeauth/server/internal/authdbimpl/handlers.go#L161-L168 |
9,121 | luci/luci-go | appengine/gaeauth/server/internal/authdbimpl/handlers.go | replyOK | func replyOK(c context.Context, rw http.ResponseWriter, msg string, args ...interface{}) {
logging.Infof(c, msg, args...)
rw.Write([]byte(fmt.Sprintf(msg, args...)))
} | go | func replyOK(c context.Context, rw http.ResponseWriter, msg string, args ...interface{}) {
logging.Infof(c, msg, args...)
rw.Write([]byte(fmt.Sprintf(msg, args...)))
} | [
"func",
"replyOK",
"(",
"c",
"context",
".",
"Context",
",",
"rw",
"http",
".",
"ResponseWriter",
",",
"msg",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"logging",
".",
"Infof",
"(",
"c",
",",
"msg",
",",
"args",
"...",
")",
"\n",
"rw",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"fmt",
".",
"Sprintf",
"(",
"msg",
",",
"args",
"...",
")",
")",
")",
"\n",
"}"
] | // replyOK sends HTTP 200. | [
"replyOK",
"sends",
"HTTP",
"200",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/appengine/gaeauth/server/internal/authdbimpl/handlers.go#L171-L174 |
9,122 | luci/luci-go | tokenserver/appengine/impl/utils/shards/shards.go | Serialize | func (s Shard) Serialize() []byte {
sorted := make([]string, 0, len(s))
for blob := range s {
sorted = append(sorted, blob)
}
sort.Strings(sorted)
out := bytes.Buffer{}
enc := gob.NewEncoder(&out)
err := enc.Encode(sorted)
if err != nil {
panic("impossible error when encoding []string")
}
return out.Bytes()
} | go | func (s Shard) Serialize() []byte {
sorted := make([]string, 0, len(s))
for blob := range s {
sorted = append(sorted, blob)
}
sort.Strings(sorted)
out := bytes.Buffer{}
enc := gob.NewEncoder(&out)
err := enc.Encode(sorted)
if err != nil {
panic("impossible error when encoding []string")
}
return out.Bytes()
} | [
"func",
"(",
"s",
"Shard",
")",
"Serialize",
"(",
")",
"[",
"]",
"byte",
"{",
"sorted",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"s",
")",
")",
"\n",
"for",
"blob",
":=",
"range",
"s",
"{",
"sorted",
"=",
"append",
"(",
"sorted",
",",
"blob",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"sorted",
")",
"\n",
"out",
":=",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"enc",
":=",
"gob",
".",
"NewEncoder",
"(",
"&",
"out",
")",
"\n",
"err",
":=",
"enc",
".",
"Encode",
"(",
"sorted",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"out",
".",
"Bytes",
"(",
")",
"\n",
"}"
] | // Serialize serializes the shard to a byte buffer. | [
"Serialize",
"serializes",
"the",
"shard",
"to",
"a",
"byte",
"buffer",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/shards/shards.go#L46-L59 |
9,123 | luci/luci-go | tokenserver/appengine/impl/utils/shards/shards.go | Insert | func (s Set) Insert(blob []byte) {
shard := &s[ShardIndex(blob, len(s))]
if *shard == nil {
*shard = make(Shard)
}
(*shard)[string(blob)] = struct{}{}
} | go | func (s Set) Insert(blob []byte) {
shard := &s[ShardIndex(blob, len(s))]
if *shard == nil {
*shard = make(Shard)
}
(*shard)[string(blob)] = struct{}{}
} | [
"func",
"(",
"s",
"Set",
")",
"Insert",
"(",
"blob",
"[",
"]",
"byte",
")",
"{",
"shard",
":=",
"&",
"s",
"[",
"ShardIndex",
"(",
"blob",
",",
"len",
"(",
"s",
")",
")",
"]",
"\n",
"if",
"*",
"shard",
"==",
"nil",
"{",
"*",
"shard",
"=",
"make",
"(",
"Shard",
")",
"\n",
"}",
"\n",
"(",
"*",
"shard",
")",
"[",
"string",
"(",
"blob",
")",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}"
] | // Insert adds a blob into the sharded set. | [
"Insert",
"adds",
"a",
"blob",
"into",
"the",
"sharded",
"set",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/shards/shards.go#L68-L74 |
9,124 | luci/luci-go | tokenserver/appengine/impl/utils/shards/shards.go | ShardIndex | func ShardIndex(member []byte, shardCount int) int {
hash := fnv.New32()
hash.Write(member)
return int(hash.Sum32() % uint32(shardCount))
} | go | func ShardIndex(member []byte, shardCount int) int {
hash := fnv.New32()
hash.Write(member)
return int(hash.Sum32() % uint32(shardCount))
} | [
"func",
"ShardIndex",
"(",
"member",
"[",
"]",
"byte",
",",
"shardCount",
"int",
")",
"int",
"{",
"hash",
":=",
"fnv",
".",
"New32",
"(",
")",
"\n",
"hash",
".",
"Write",
"(",
"member",
")",
"\n",
"return",
"int",
"(",
"hash",
".",
"Sum32",
"(",
")",
"%",
"uint32",
"(",
"shardCount",
")",
")",
"\n",
"}"
] | // ShardIndex returns an index of a shard to use when storing given blob. | [
"ShardIndex",
"returns",
"an",
"index",
"of",
"a",
"shard",
"to",
"use",
"when",
"storing",
"given",
"blob",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tokenserver/appengine/impl/utils/shards/shards.go#L77-L81 |
9,125 | luci/luci-go | server/auth/delegation/checker.go | deserializeToken | func deserializeToken(token string) (*messages.DelegationToken, error) {
blob, err := base64.RawURLEncoding.DecodeString(token)
if err != nil {
return nil, err
}
if len(blob) > maxTokenSize {
return nil, fmt.Errorf("the delegation token is too big (%d bytes)", len(blob))
}
tok := &messages.DelegationToken{}
if err = proto.Unmarshal(blob, tok); err != nil {
return nil, err
}
return tok, nil
} | go | func deserializeToken(token string) (*messages.DelegationToken, error) {
blob, err := base64.RawURLEncoding.DecodeString(token)
if err != nil {
return nil, err
}
if len(blob) > maxTokenSize {
return nil, fmt.Errorf("the delegation token is too big (%d bytes)", len(blob))
}
tok := &messages.DelegationToken{}
if err = proto.Unmarshal(blob, tok); err != nil {
return nil, err
}
return tok, nil
} | [
"func",
"deserializeToken",
"(",
"token",
"string",
")",
"(",
"*",
"messages",
".",
"DelegationToken",
",",
"error",
")",
"{",
"blob",
",",
"err",
":=",
"base64",
".",
"RawURLEncoding",
".",
"DecodeString",
"(",
"token",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"len",
"(",
"blob",
")",
">",
"maxTokenSize",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"len",
"(",
"blob",
")",
")",
"\n",
"}",
"\n",
"tok",
":=",
"&",
"messages",
".",
"DelegationToken",
"{",
"}",
"\n",
"if",
"err",
"=",
"proto",
".",
"Unmarshal",
"(",
"blob",
",",
"tok",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"tok",
",",
"nil",
"\n",
"}"
] | // deserializeToken deserializes DelegationToken proto message. | [
"deserializeToken",
"deserializes",
"DelegationToken",
"proto",
"message",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/delegation/checker.go#L123-L136 |
9,126 | luci/luci-go | server/auth/delegation/checker.go | unsealToken | func unsealToken(c context.Context, tok *messages.DelegationToken, certsProvider CertificatesProvider) (*messages.Subtoken, error) {
// Grab the public keys of the service that signed the token, if we trust it.
signerID, err := identity.MakeIdentity(tok.SignerId)
if err != nil {
return nil, fmt.Errorf("bad signer_id %q - %s", tok.SignerId, err)
}
certs, err := certsProvider.GetCertificates(c, signerID)
switch {
case err != nil:
return nil, fmt.Errorf("failed to grab certificates of %q - %s", tok.SignerId, err)
case certs == nil:
return nil, fmt.Errorf("the signer %q is not trusted", tok.SignerId)
}
// Check the signature on the token.
err = certs.CheckSignature(tok.SigningKeyId, tok.SerializedSubtoken, tok.Pkcs1Sha256Sig)
if err != nil {
return nil, err
}
// The signature is correct! Deserialize the subtoken.
msg := &messages.Subtoken{}
if err = proto.Unmarshal(tok.SerializedSubtoken, msg); err != nil {
return nil, err
}
return msg, nil
} | go | func unsealToken(c context.Context, tok *messages.DelegationToken, certsProvider CertificatesProvider) (*messages.Subtoken, error) {
// Grab the public keys of the service that signed the token, if we trust it.
signerID, err := identity.MakeIdentity(tok.SignerId)
if err != nil {
return nil, fmt.Errorf("bad signer_id %q - %s", tok.SignerId, err)
}
certs, err := certsProvider.GetCertificates(c, signerID)
switch {
case err != nil:
return nil, fmt.Errorf("failed to grab certificates of %q - %s", tok.SignerId, err)
case certs == nil:
return nil, fmt.Errorf("the signer %q is not trusted", tok.SignerId)
}
// Check the signature on the token.
err = certs.CheckSignature(tok.SigningKeyId, tok.SerializedSubtoken, tok.Pkcs1Sha256Sig)
if err != nil {
return nil, err
}
// The signature is correct! Deserialize the subtoken.
msg := &messages.Subtoken{}
if err = proto.Unmarshal(tok.SerializedSubtoken, msg); err != nil {
return nil, err
}
return msg, nil
} | [
"func",
"unsealToken",
"(",
"c",
"context",
".",
"Context",
",",
"tok",
"*",
"messages",
".",
"DelegationToken",
",",
"certsProvider",
"CertificatesProvider",
")",
"(",
"*",
"messages",
".",
"Subtoken",
",",
"error",
")",
"{",
"// Grab the public keys of the service that signed the token, if we trust it.",
"signerID",
",",
"err",
":=",
"identity",
".",
"MakeIdentity",
"(",
"tok",
".",
"SignerId",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"tok",
".",
"SignerId",
",",
"err",
")",
"\n",
"}",
"\n",
"certs",
",",
"err",
":=",
"certsProvider",
".",
"GetCertificates",
"(",
"c",
",",
"signerID",
")",
"\n",
"switch",
"{",
"case",
"err",
"!=",
"nil",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"tok",
".",
"SignerId",
",",
"err",
")",
"\n",
"case",
"certs",
"==",
"nil",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"tok",
".",
"SignerId",
")",
"\n",
"}",
"\n\n",
"// Check the signature on the token.",
"err",
"=",
"certs",
".",
"CheckSignature",
"(",
"tok",
".",
"SigningKeyId",
",",
"tok",
".",
"SerializedSubtoken",
",",
"tok",
".",
"Pkcs1Sha256Sig",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// The signature is correct! Deserialize the subtoken.",
"msg",
":=",
"&",
"messages",
".",
"Subtoken",
"{",
"}",
"\n",
"if",
"err",
"=",
"proto",
".",
"Unmarshal",
"(",
"tok",
".",
"SerializedSubtoken",
",",
"msg",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"msg",
",",
"nil",
"\n",
"}"
] | // unsealToken verifies token's signature and deserializes the subtoken.
//
// May return transient errors. | [
"unsealToken",
"verifies",
"token",
"s",
"signature",
"and",
"deserializes",
"the",
"subtoken",
".",
"May",
"return",
"transient",
"errors",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/delegation/checker.go#L141-L168 |
9,127 | luci/luci-go | server/auth/delegation/checker.go | checkSubtoken | func checkSubtoken(c context.Context, subtoken *messages.Subtoken, params *CheckTokenParams) (identity.Identity, error) {
if subtoken.Kind != messages.Subtoken_BEARER_DELEGATION_TOKEN {
logging.Warningf(c, "auth: Invalid delegation token kind - %s", subtoken.Kind)
return "", ErrForbiddenDelegationToken
}
// Do fast checks before heavy ones.
now := clock.Now(c).Unix()
if err := checkSubtokenExpiration(subtoken, now); err != nil {
logging.Warningf(c, "auth: Bad delegation token expiration - %s", err)
return "", ErrForbiddenDelegationToken
}
if err := checkSubtokenServices(subtoken, params.OwnServiceIdentity); err != nil {
logging.Warningf(c, "auth: Forbidden delegation token - %s", err)
return "", ErrForbiddenDelegationToken
}
// Do the audience check (may use group lookups).
if err := checkSubtokenAudience(c, subtoken, params.PeerID, params.GroupsChecker); err != nil {
if transient.Tag.In(err) {
logging.Warningf(c, "auth: Transient error when checking delegation token audience - %s", err)
return "", err
}
logging.Warningf(c, "auth: Bad delegation token audience - %s", err)
return "", ErrForbiddenDelegationToken
}
// Grab delegated identity.
ident, err := identity.MakeIdentity(subtoken.DelegatedIdentity)
if err != nil {
logging.Warningf(c, "auth: Invalid delegated_identity in the delegation token - %s", err)
return "", ErrMalformedDelegationToken
}
return ident, nil
} | go | func checkSubtoken(c context.Context, subtoken *messages.Subtoken, params *CheckTokenParams) (identity.Identity, error) {
if subtoken.Kind != messages.Subtoken_BEARER_DELEGATION_TOKEN {
logging.Warningf(c, "auth: Invalid delegation token kind - %s", subtoken.Kind)
return "", ErrForbiddenDelegationToken
}
// Do fast checks before heavy ones.
now := clock.Now(c).Unix()
if err := checkSubtokenExpiration(subtoken, now); err != nil {
logging.Warningf(c, "auth: Bad delegation token expiration - %s", err)
return "", ErrForbiddenDelegationToken
}
if err := checkSubtokenServices(subtoken, params.OwnServiceIdentity); err != nil {
logging.Warningf(c, "auth: Forbidden delegation token - %s", err)
return "", ErrForbiddenDelegationToken
}
// Do the audience check (may use group lookups).
if err := checkSubtokenAudience(c, subtoken, params.PeerID, params.GroupsChecker); err != nil {
if transient.Tag.In(err) {
logging.Warningf(c, "auth: Transient error when checking delegation token audience - %s", err)
return "", err
}
logging.Warningf(c, "auth: Bad delegation token audience - %s", err)
return "", ErrForbiddenDelegationToken
}
// Grab delegated identity.
ident, err := identity.MakeIdentity(subtoken.DelegatedIdentity)
if err != nil {
logging.Warningf(c, "auth: Invalid delegated_identity in the delegation token - %s", err)
return "", ErrMalformedDelegationToken
}
return ident, nil
} | [
"func",
"checkSubtoken",
"(",
"c",
"context",
".",
"Context",
",",
"subtoken",
"*",
"messages",
".",
"Subtoken",
",",
"params",
"*",
"CheckTokenParams",
")",
"(",
"identity",
".",
"Identity",
",",
"error",
")",
"{",
"if",
"subtoken",
".",
"Kind",
"!=",
"messages",
".",
"Subtoken_BEARER_DELEGATION_TOKEN",
"{",
"logging",
".",
"Warningf",
"(",
"c",
",",
"\"",
"\"",
",",
"subtoken",
".",
"Kind",
")",
"\n",
"return",
"\"",
"\"",
",",
"ErrForbiddenDelegationToken",
"\n",
"}",
"\n\n",
"// Do fast checks before heavy ones.",
"now",
":=",
"clock",
".",
"Now",
"(",
"c",
")",
".",
"Unix",
"(",
")",
"\n",
"if",
"err",
":=",
"checkSubtokenExpiration",
"(",
"subtoken",
",",
"now",
")",
";",
"err",
"!=",
"nil",
"{",
"logging",
".",
"Warningf",
"(",
"c",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\"",
"\"",
",",
"ErrForbiddenDelegationToken",
"\n",
"}",
"\n",
"if",
"err",
":=",
"checkSubtokenServices",
"(",
"subtoken",
",",
"params",
".",
"OwnServiceIdentity",
")",
";",
"err",
"!=",
"nil",
"{",
"logging",
".",
"Warningf",
"(",
"c",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\"",
"\"",
",",
"ErrForbiddenDelegationToken",
"\n",
"}",
"\n\n",
"// Do the audience check (may use group lookups).",
"if",
"err",
":=",
"checkSubtokenAudience",
"(",
"c",
",",
"subtoken",
",",
"params",
".",
"PeerID",
",",
"params",
".",
"GroupsChecker",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"transient",
".",
"Tag",
".",
"In",
"(",
"err",
")",
"{",
"logging",
".",
"Warningf",
"(",
"c",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"logging",
".",
"Warningf",
"(",
"c",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\"",
"\"",
",",
"ErrForbiddenDelegationToken",
"\n",
"}",
"\n\n",
"// Grab delegated identity.",
"ident",
",",
"err",
":=",
"identity",
".",
"MakeIdentity",
"(",
"subtoken",
".",
"DelegatedIdentity",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logging",
".",
"Warningf",
"(",
"c",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\"",
"\"",
",",
"ErrMalformedDelegationToken",
"\n",
"}",
"\n\n",
"return",
"ident",
",",
"nil",
"\n",
"}"
] | // checkSubtoken validates the delegation subtoken.
//
// It extracts and returns original delegated_identity. | [
"checkSubtoken",
"validates",
"the",
"delegation",
"subtoken",
".",
"It",
"extracts",
"and",
"returns",
"original",
"delegated_identity",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/delegation/checker.go#L173-L208 |
9,128 | luci/luci-go | server/auth/delegation/checker.go | checkSubtokenExpiration | func checkSubtokenExpiration(t *messages.Subtoken, now int64) error {
if t.CreationTime <= 0 {
return fmt.Errorf("invalid 'creation_time' field: %d", t.CreationTime)
}
dur := int64(t.ValidityDuration)
if dur <= 0 {
return fmt.Errorf("invalid validity_duration: %d", dur)
}
if t.CreationTime >= now+allowedClockDriftSec {
return fmt.Errorf("token is not active yet (created at %d)", t.CreationTime)
}
if t.CreationTime+dur < now {
return fmt.Errorf("token has expired %d sec ago", now-(t.CreationTime+dur))
}
return nil
} | go | func checkSubtokenExpiration(t *messages.Subtoken, now int64) error {
if t.CreationTime <= 0 {
return fmt.Errorf("invalid 'creation_time' field: %d", t.CreationTime)
}
dur := int64(t.ValidityDuration)
if dur <= 0 {
return fmt.Errorf("invalid validity_duration: %d", dur)
}
if t.CreationTime >= now+allowedClockDriftSec {
return fmt.Errorf("token is not active yet (created at %d)", t.CreationTime)
}
if t.CreationTime+dur < now {
return fmt.Errorf("token has expired %d sec ago", now-(t.CreationTime+dur))
}
return nil
} | [
"func",
"checkSubtokenExpiration",
"(",
"t",
"*",
"messages",
".",
"Subtoken",
",",
"now",
"int64",
")",
"error",
"{",
"if",
"t",
".",
"CreationTime",
"<=",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"t",
".",
"CreationTime",
")",
"\n",
"}",
"\n",
"dur",
":=",
"int64",
"(",
"t",
".",
"ValidityDuration",
")",
"\n",
"if",
"dur",
"<=",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"dur",
")",
"\n",
"}",
"\n",
"if",
"t",
".",
"CreationTime",
">=",
"now",
"+",
"allowedClockDriftSec",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"t",
".",
"CreationTime",
")",
"\n",
"}",
"\n",
"if",
"t",
".",
"CreationTime",
"+",
"dur",
"<",
"now",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"now",
"-",
"(",
"t",
".",
"CreationTime",
"+",
"dur",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // checkSubtokenExpiration checks 'CreationTime' and 'ValidityDuration' fields. | [
"checkSubtokenExpiration",
"checks",
"CreationTime",
"and",
"ValidityDuration",
"fields",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/delegation/checker.go#L211-L226 |
9,129 | luci/luci-go | server/auth/delegation/checker.go | checkSubtokenServices | func checkSubtokenServices(t *messages.Subtoken, serviceID identity.Identity) error {
// Empty services field is not allowed.
if len(t.Services) == 0 {
return fmt.Errorf("the token's services list is empty")
}
// Else, make sure we are in the 'services' list or it contains '*'.
for _, allowed := range t.Services {
if allowed == "*" || allowed == string(serviceID) {
return nil
}
}
return fmt.Errorf("token is not intended for %s", serviceID)
} | go | func checkSubtokenServices(t *messages.Subtoken, serviceID identity.Identity) error {
// Empty services field is not allowed.
if len(t.Services) == 0 {
return fmt.Errorf("the token's services list is empty")
}
// Else, make sure we are in the 'services' list or it contains '*'.
for _, allowed := range t.Services {
if allowed == "*" || allowed == string(serviceID) {
return nil
}
}
return fmt.Errorf("token is not intended for %s", serviceID)
} | [
"func",
"checkSubtokenServices",
"(",
"t",
"*",
"messages",
".",
"Subtoken",
",",
"serviceID",
"identity",
".",
"Identity",
")",
"error",
"{",
"// Empty services field is not allowed.",
"if",
"len",
"(",
"t",
".",
"Services",
")",
"==",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// Else, make sure we are in the 'services' list or it contains '*'.",
"for",
"_",
",",
"allowed",
":=",
"range",
"t",
".",
"Services",
"{",
"if",
"allowed",
"==",
"\"",
"\"",
"||",
"allowed",
"==",
"string",
"(",
"serviceID",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"serviceID",
")",
"\n",
"}"
] | // checkSubtokenServices makes sure the token is usable by the current service. | [
"checkSubtokenServices",
"makes",
"sure",
"the",
"token",
"is",
"usable",
"by",
"the",
"current",
"service",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/delegation/checker.go#L229-L241 |
9,130 | luci/luci-go | server/auth/delegation/checker.go | checkSubtokenAudience | func checkSubtokenAudience(c context.Context, t *messages.Subtoken, ident identity.Identity, checker GroupsChecker) error {
// Empty audience field is not allowed.
if len(t.Audience) == 0 {
return fmt.Errorf("the token's audience list is empty")
}
// Try to find a direct hit first, to avoid calling expensive group lookups.
// Collect the groups along the way for the check below.
groups := make([]string, 0, len(t.Audience))
for _, aud := range t.Audience {
if aud == "*" || aud == string(ident) {
return nil
}
if strings.HasPrefix(aud, "group:") {
groups = append(groups, strings.TrimPrefix(aud, "group:"))
}
}
// Search through groups now.
switch ok, err := checker.IsMember(c, ident, groups); {
case err != nil:
return err // transient error during group lookup
case ok:
return nil // success, 'ident' is in the target audience
}
return fmt.Errorf("%s is not allowed to use the token", ident)
} | go | func checkSubtokenAudience(c context.Context, t *messages.Subtoken, ident identity.Identity, checker GroupsChecker) error {
// Empty audience field is not allowed.
if len(t.Audience) == 0 {
return fmt.Errorf("the token's audience list is empty")
}
// Try to find a direct hit first, to avoid calling expensive group lookups.
// Collect the groups along the way for the check below.
groups := make([]string, 0, len(t.Audience))
for _, aud := range t.Audience {
if aud == "*" || aud == string(ident) {
return nil
}
if strings.HasPrefix(aud, "group:") {
groups = append(groups, strings.TrimPrefix(aud, "group:"))
}
}
// Search through groups now.
switch ok, err := checker.IsMember(c, ident, groups); {
case err != nil:
return err // transient error during group lookup
case ok:
return nil // success, 'ident' is in the target audience
}
return fmt.Errorf("%s is not allowed to use the token", ident)
} | [
"func",
"checkSubtokenAudience",
"(",
"c",
"context",
".",
"Context",
",",
"t",
"*",
"messages",
".",
"Subtoken",
",",
"ident",
"identity",
".",
"Identity",
",",
"checker",
"GroupsChecker",
")",
"error",
"{",
"// Empty audience field is not allowed.",
"if",
"len",
"(",
"t",
".",
"Audience",
")",
"==",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// Try to find a direct hit first, to avoid calling expensive group lookups.",
"// Collect the groups along the way for the check below.",
"groups",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"t",
".",
"Audience",
")",
")",
"\n",
"for",
"_",
",",
"aud",
":=",
"range",
"t",
".",
"Audience",
"{",
"if",
"aud",
"==",
"\"",
"\"",
"||",
"aud",
"==",
"string",
"(",
"ident",
")",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"strings",
".",
"HasPrefix",
"(",
"aud",
",",
"\"",
"\"",
")",
"{",
"groups",
"=",
"append",
"(",
"groups",
",",
"strings",
".",
"TrimPrefix",
"(",
"aud",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"// Search through groups now.",
"switch",
"ok",
",",
"err",
":=",
"checker",
".",
"IsMember",
"(",
"c",
",",
"ident",
",",
"groups",
")",
";",
"{",
"case",
"err",
"!=",
"nil",
":",
"return",
"err",
"// transient error during group lookup",
"\n",
"case",
"ok",
":",
"return",
"nil",
"// success, 'ident' is in the target audience",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"ident",
")",
"\n",
"}"
] | // checkSubtokenAudience makes sure the token is intended for use by given
// identity.
//
// May return transient errors. | [
"checkSubtokenAudience",
"makes",
"sure",
"the",
"token",
"is",
"intended",
"for",
"use",
"by",
"given",
"identity",
".",
"May",
"return",
"transient",
"errors",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/delegation/checker.go#L247-L271 |
9,131 | luci/luci-go | vpython/spec/env.go | LoadEnvironment | func LoadEnvironment(path string, environment *vpython.Environment) error {
content, err := ioutil.ReadFile(path)
if err != nil {
return errors.Annotate(err, "failed to load file from: %s", path).Err()
}
return ParseEnvironment(string(content), environment)
} | go | func LoadEnvironment(path string, environment *vpython.Environment) error {
content, err := ioutil.ReadFile(path)
if err != nil {
return errors.Annotate(err, "failed to load file from: %s", path).Err()
}
return ParseEnvironment(string(content), environment)
} | [
"func",
"LoadEnvironment",
"(",
"path",
"string",
",",
"environment",
"*",
"vpython",
".",
"Environment",
")",
"error",
"{",
"content",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
",",
"path",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"ParseEnvironment",
"(",
"string",
"(",
"content",
")",
",",
"environment",
")",
"\n",
"}"
] | // LoadEnvironment loads an environment file text protobuf from the supplied
// path. | [
"LoadEnvironment",
"loads",
"an",
"environment",
"file",
"text",
"protobuf",
"from",
"the",
"supplied",
"path",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/spec/env.go#L30-L37 |
9,132 | luci/luci-go | vpython/spec/env.go | ParseEnvironment | func ParseEnvironment(content string, environment *vpython.Environment) error {
if err := proto.UnmarshalText(content, environment); err != nil {
return errors.Annotate(err, "failed to unmarshal vpython.Environment").Err()
}
return nil
} | go | func ParseEnvironment(content string, environment *vpython.Environment) error {
if err := proto.UnmarshalText(content, environment); err != nil {
return errors.Annotate(err, "failed to unmarshal vpython.Environment").Err()
}
return nil
} | [
"func",
"ParseEnvironment",
"(",
"content",
"string",
",",
"environment",
"*",
"vpython",
".",
"Environment",
")",
"error",
"{",
"if",
"err",
":=",
"proto",
".",
"UnmarshalText",
"(",
"content",
",",
"environment",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // ParseEnvironment loads a environment protobuf message from a content string. | [
"ParseEnvironment",
"loads",
"a",
"environment",
"protobuf",
"message",
"from",
"a",
"content",
"string",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/spec/env.go#L40-L45 |
9,133 | luci/luci-go | vpython/spec/env.go | NormalizeEnvironment | func NormalizeEnvironment(env *vpython.Environment) error {
if env.Spec == nil {
env.Spec = &vpython.Spec{}
}
if err := NormalizeSpec(env.Spec, env.Pep425Tag); err != nil {
return err
}
if env.Runtime == nil {
env.Runtime = &vpython.Runtime{}
}
sort.Sort(pep425TagSlice(env.Pep425Tag))
return nil
} | go | func NormalizeEnvironment(env *vpython.Environment) error {
if env.Spec == nil {
env.Spec = &vpython.Spec{}
}
if err := NormalizeSpec(env.Spec, env.Pep425Tag); err != nil {
return err
}
if env.Runtime == nil {
env.Runtime = &vpython.Runtime{}
}
sort.Sort(pep425TagSlice(env.Pep425Tag))
return nil
} | [
"func",
"NormalizeEnvironment",
"(",
"env",
"*",
"vpython",
".",
"Environment",
")",
"error",
"{",
"if",
"env",
".",
"Spec",
"==",
"nil",
"{",
"env",
".",
"Spec",
"=",
"&",
"vpython",
".",
"Spec",
"{",
"}",
"\n",
"}",
"\n",
"if",
"err",
":=",
"NormalizeSpec",
"(",
"env",
".",
"Spec",
",",
"env",
".",
"Pep425Tag",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"env",
".",
"Runtime",
"==",
"nil",
"{",
"env",
".",
"Runtime",
"=",
"&",
"vpython",
".",
"Runtime",
"{",
"}",
"\n",
"}",
"\n\n",
"sort",
".",
"Sort",
"(",
"pep425TagSlice",
"(",
"env",
".",
"Pep425Tag",
")",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // NormalizeEnvironment normalizes the supplied Environment such that two
// messages with identical meaning will have identical representation. | [
"NormalizeEnvironment",
"normalizes",
"the",
"supplied",
"Environment",
"such",
"that",
"two",
"messages",
"with",
"identical",
"meaning",
"will",
"have",
"identical",
"representation",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/spec/env.go#L49-L63 |
9,134 | luci/luci-go | server/settings/settings.go | get | func (b *Bundle) get(key string, value interface{}) error {
raw, ok := b.Values[key]
if !ok || raw == nil || len(*raw) == 0 {
return ErrNoSettings
}
typ := reflect.TypeOf(value)
// Fast path for already-in-cache values.
b.lock.RLock()
cached, ok := b.unpacked[key]
b.lock.RUnlock()
// Slow path.
if !ok {
b.lock.Lock()
defer b.lock.Unlock() // its fine to hold the lock until return
cached, ok = b.unpacked[key]
if !ok {
// 'value' must be a pointer to a struct.
if typ.Kind() != reflect.Ptr || typ.Elem().Kind() != reflect.Struct {
return ErrBadType
}
// 'cached' is &Struct{}.
cached = reflect.New(typ.Elem()).Interface()
if err := json.Unmarshal([]byte(*raw), cached); err != nil {
return err
}
if b.unpacked == nil {
b.unpacked = make(map[string]interface{}, 1)
}
b.unpacked[key] = cached
}
}
// Note: the code below may be called with b.lock in locked or unlocked state.
// All calls to 'get' must use same type consistently.
if reflect.TypeOf(cached) != typ {
return ErrBadType
}
// 'value' and 'cached' are &Struct{}, Do *value = *cached.
reflect.ValueOf(value).Elem().Set(reflect.ValueOf(cached).Elem())
return nil
} | go | func (b *Bundle) get(key string, value interface{}) error {
raw, ok := b.Values[key]
if !ok || raw == nil || len(*raw) == 0 {
return ErrNoSettings
}
typ := reflect.TypeOf(value)
// Fast path for already-in-cache values.
b.lock.RLock()
cached, ok := b.unpacked[key]
b.lock.RUnlock()
// Slow path.
if !ok {
b.lock.Lock()
defer b.lock.Unlock() // its fine to hold the lock until return
cached, ok = b.unpacked[key]
if !ok {
// 'value' must be a pointer to a struct.
if typ.Kind() != reflect.Ptr || typ.Elem().Kind() != reflect.Struct {
return ErrBadType
}
// 'cached' is &Struct{}.
cached = reflect.New(typ.Elem()).Interface()
if err := json.Unmarshal([]byte(*raw), cached); err != nil {
return err
}
if b.unpacked == nil {
b.unpacked = make(map[string]interface{}, 1)
}
b.unpacked[key] = cached
}
}
// Note: the code below may be called with b.lock in locked or unlocked state.
// All calls to 'get' must use same type consistently.
if reflect.TypeOf(cached) != typ {
return ErrBadType
}
// 'value' and 'cached' are &Struct{}, Do *value = *cached.
reflect.ValueOf(value).Elem().Set(reflect.ValueOf(cached).Elem())
return nil
} | [
"func",
"(",
"b",
"*",
"Bundle",
")",
"get",
"(",
"key",
"string",
",",
"value",
"interface",
"{",
"}",
")",
"error",
"{",
"raw",
",",
"ok",
":=",
"b",
".",
"Values",
"[",
"key",
"]",
"\n",
"if",
"!",
"ok",
"||",
"raw",
"==",
"nil",
"||",
"len",
"(",
"*",
"raw",
")",
"==",
"0",
"{",
"return",
"ErrNoSettings",
"\n",
"}",
"\n\n",
"typ",
":=",
"reflect",
".",
"TypeOf",
"(",
"value",
")",
"\n\n",
"// Fast path for already-in-cache values.",
"b",
".",
"lock",
".",
"RLock",
"(",
")",
"\n",
"cached",
",",
"ok",
":=",
"b",
".",
"unpacked",
"[",
"key",
"]",
"\n",
"b",
".",
"lock",
".",
"RUnlock",
"(",
")",
"\n\n",
"// Slow path.",
"if",
"!",
"ok",
"{",
"b",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"b",
".",
"lock",
".",
"Unlock",
"(",
")",
"// its fine to hold the lock until return",
"\n\n",
"cached",
",",
"ok",
"=",
"b",
".",
"unpacked",
"[",
"key",
"]",
"\n",
"if",
"!",
"ok",
"{",
"// 'value' must be a pointer to a struct.",
"if",
"typ",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Ptr",
"||",
"typ",
".",
"Elem",
"(",
")",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Struct",
"{",
"return",
"ErrBadType",
"\n",
"}",
"\n",
"// 'cached' is &Struct{}.",
"cached",
"=",
"reflect",
".",
"New",
"(",
"typ",
".",
"Elem",
"(",
")",
")",
".",
"Interface",
"(",
")",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"[",
"]",
"byte",
"(",
"*",
"raw",
")",
",",
"cached",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"b",
".",
"unpacked",
"==",
"nil",
"{",
"b",
".",
"unpacked",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
",",
"1",
")",
"\n",
"}",
"\n",
"b",
".",
"unpacked",
"[",
"key",
"]",
"=",
"cached",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Note: the code below may be called with b.lock in locked or unlocked state.",
"// All calls to 'get' must use same type consistently.",
"if",
"reflect",
".",
"TypeOf",
"(",
"cached",
")",
"!=",
"typ",
"{",
"return",
"ErrBadType",
"\n",
"}",
"\n\n",
"// 'value' and 'cached' are &Struct{}, Do *value = *cached.",
"reflect",
".",
"ValueOf",
"(",
"value",
")",
".",
"Elem",
"(",
")",
".",
"Set",
"(",
"reflect",
".",
"ValueOf",
"(",
"cached",
")",
".",
"Elem",
"(",
")",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // get deserializes value for given key. | [
"get",
"deserializes",
"value",
"for",
"given",
"key",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/settings/settings.go#L55-L101 |
9,135 | luci/luci-go | server/settings/settings.go | GetUncached | func (s *Settings) GetUncached(c context.Context, key string, value interface{}) error {
bundle, _, err := s.storage.FetchAllSettings(c)
if err != nil {
return err
}
return bundle.get(key, value)
} | go | func (s *Settings) GetUncached(c context.Context, key string, value interface{}) error {
bundle, _, err := s.storage.FetchAllSettings(c)
if err != nil {
return err
}
return bundle.get(key, value)
} | [
"func",
"(",
"s",
"*",
"Settings",
")",
"GetUncached",
"(",
"c",
"context",
".",
"Context",
",",
"key",
"string",
",",
"value",
"interface",
"{",
"}",
")",
"error",
"{",
"bundle",
",",
"_",
",",
"err",
":=",
"s",
".",
"storage",
".",
"FetchAllSettings",
"(",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"bundle",
".",
"get",
"(",
"key",
",",
"value",
")",
"\n",
"}"
] | // GetUncached is like Get, by always fetches settings from the storage.
//
// Do not use GetUncached in performance critical parts, it is much heavier than
// Get. | [
"GetUncached",
"is",
"like",
"Get",
"by",
"always",
"fetches",
"settings",
"from",
"the",
"storage",
".",
"Do",
"not",
"use",
"GetUncached",
"in",
"performance",
"critical",
"parts",
"it",
"is",
"much",
"heavier",
"than",
"Get",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/settings/settings.go#L184-L190 |
9,136 | luci/luci-go | server/settings/settings.go | SetIfChanged | func (s *Settings) SetIfChanged(c context.Context, key string, value interface{}, who, why string) error {
// 'value' must be a pointer to a struct. Construct a zero value of this
// kind of struct.
typ := reflect.TypeOf(value)
if typ.Kind() != reflect.Ptr || typ.Elem().Kind() != reflect.Struct {
return ErrBadType
}
existing := reflect.New(typ.Elem()).Interface()
// Fetch existing settings and compare.
switch err := s.GetUncached(c, key, existing); {
case err != nil && err != ErrNoSettings:
return err
case reflect.DeepEqual(existing, value):
return nil
}
// Log the change. Ignore JSON marshaling errors, they are not essential
// (and must not happen anyway).
existingJSON, _ := json.Marshal(existing)
modifiedJSON, _ := json.Marshal(value)
logging.Warningf(c, "Settings %q changed from %s to %s by %q", key, existingJSON, modifiedJSON, who)
return s.Set(c, key, value, who, why)
} | go | func (s *Settings) SetIfChanged(c context.Context, key string, value interface{}, who, why string) error {
// 'value' must be a pointer to a struct. Construct a zero value of this
// kind of struct.
typ := reflect.TypeOf(value)
if typ.Kind() != reflect.Ptr || typ.Elem().Kind() != reflect.Struct {
return ErrBadType
}
existing := reflect.New(typ.Elem()).Interface()
// Fetch existing settings and compare.
switch err := s.GetUncached(c, key, existing); {
case err != nil && err != ErrNoSettings:
return err
case reflect.DeepEqual(existing, value):
return nil
}
// Log the change. Ignore JSON marshaling errors, they are not essential
// (and must not happen anyway).
existingJSON, _ := json.Marshal(existing)
modifiedJSON, _ := json.Marshal(value)
logging.Warningf(c, "Settings %q changed from %s to %s by %q", key, existingJSON, modifiedJSON, who)
return s.Set(c, key, value, who, why)
} | [
"func",
"(",
"s",
"*",
"Settings",
")",
"SetIfChanged",
"(",
"c",
"context",
".",
"Context",
",",
"key",
"string",
",",
"value",
"interface",
"{",
"}",
",",
"who",
",",
"why",
"string",
")",
"error",
"{",
"// 'value' must be a pointer to a struct. Construct a zero value of this",
"// kind of struct.",
"typ",
":=",
"reflect",
".",
"TypeOf",
"(",
"value",
")",
"\n",
"if",
"typ",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Ptr",
"||",
"typ",
".",
"Elem",
"(",
")",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Struct",
"{",
"return",
"ErrBadType",
"\n",
"}",
"\n",
"existing",
":=",
"reflect",
".",
"New",
"(",
"typ",
".",
"Elem",
"(",
")",
")",
".",
"Interface",
"(",
")",
"\n\n",
"// Fetch existing settings and compare.",
"switch",
"err",
":=",
"s",
".",
"GetUncached",
"(",
"c",
",",
"key",
",",
"existing",
")",
";",
"{",
"case",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"ErrNoSettings",
":",
"return",
"err",
"\n",
"case",
"reflect",
".",
"DeepEqual",
"(",
"existing",
",",
"value",
")",
":",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Log the change. Ignore JSON marshaling errors, they are not essential",
"// (and must not happen anyway).",
"existingJSON",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"existing",
")",
"\n",
"modifiedJSON",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"value",
")",
"\n",
"logging",
".",
"Warningf",
"(",
"c",
",",
"\"",
"\"",
",",
"key",
",",
"existingJSON",
",",
"modifiedJSON",
",",
"who",
")",
"\n\n",
"return",
"s",
".",
"Set",
"(",
"c",
",",
"key",
",",
"value",
",",
"who",
",",
"why",
")",
"\n",
"}"
] | // SetIfChanged is like Set, but fetches an existing value and compares it to
// a new one before changing it.
//
// Avoids generating new revisions of settings if no changes are actually
// made. Also logs who is making the change. | [
"SetIfChanged",
"is",
"like",
"Set",
"but",
"fetches",
"an",
"existing",
"value",
"and",
"compares",
"it",
"to",
"a",
"new",
"one",
"before",
"changing",
"it",
".",
"Avoids",
"generating",
"new",
"revisions",
"of",
"settings",
"if",
"no",
"changes",
"are",
"actually",
"made",
".",
"Also",
"logs",
"who",
"is",
"making",
"the",
"change",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/settings/settings.go#L209-L233 |
9,137 | luci/luci-go | milo/frontend/ui/build.go | ShortName | func (s *Step) ShortName() string {
parts := strings.Split(s.Name, "|")
if len(parts) == 0 {
return "ERROR: EMPTY NAME"
}
return parts[len(parts)-1]
} | go | func (s *Step) ShortName() string {
parts := strings.Split(s.Name, "|")
if len(parts) == 0 {
return "ERROR: EMPTY NAME"
}
return parts[len(parts)-1]
} | [
"func",
"(",
"s",
"*",
"Step",
")",
"ShortName",
"(",
")",
"string",
"{",
"parts",
":=",
"strings",
".",
"Split",
"(",
"s",
".",
"Name",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"parts",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"parts",
"[",
"len",
"(",
"parts",
")",
"-",
"1",
"]",
"\n",
"}"
] | // ShortName returns the leaf name of a potentially nested step.
// Eg. With a name of GrandParent|Parent|Child, this returns "Child" | [
"ShortName",
"returns",
"the",
"leaf",
"name",
"of",
"a",
"potentially",
"nested",
"step",
".",
"Eg",
".",
"With",
"a",
"name",
"of",
"GrandParent|Parent|Child",
"this",
"returns",
"Child"
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/ui/build.go#L53-L59 |
9,138 | luci/luci-go | milo/frontend/ui/build.go | BuildbucketLink | func (bp *BuildPage) BuildbucketLink() *Link {
if bp.BuildbucketHost == "" {
return nil
}
u := url.URL{
Scheme: "https",
Host: bp.BuildbucketHost,
Path: "/rpcexplorer/services/buildbucket.v2.Builds/GetBuild",
RawQuery: url.Values{
"request": []string{fmt.Sprintf(`{"id":"%d"}`, bp.Id)},
}.Encode(),
}
return NewLink(
fmt.Sprintf("%d", bp.Id),
u.String(),
"Buildbucket RPC explorer for build")
} | go | func (bp *BuildPage) BuildbucketLink() *Link {
if bp.BuildbucketHost == "" {
return nil
}
u := url.URL{
Scheme: "https",
Host: bp.BuildbucketHost,
Path: "/rpcexplorer/services/buildbucket.v2.Builds/GetBuild",
RawQuery: url.Values{
"request": []string{fmt.Sprintf(`{"id":"%d"}`, bp.Id)},
}.Encode(),
}
return NewLink(
fmt.Sprintf("%d", bp.Id),
u.String(),
"Buildbucket RPC explorer for build")
} | [
"func",
"(",
"bp",
"*",
"BuildPage",
")",
"BuildbucketLink",
"(",
")",
"*",
"Link",
"{",
"if",
"bp",
".",
"BuildbucketHost",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"u",
":=",
"url",
".",
"URL",
"{",
"Scheme",
":",
"\"",
"\"",
",",
"Host",
":",
"bp",
".",
"BuildbucketHost",
",",
"Path",
":",
"\"",
"\"",
",",
"RawQuery",
":",
"url",
".",
"Values",
"{",
"\"",
"\"",
":",
"[",
"]",
"string",
"{",
"fmt",
".",
"Sprintf",
"(",
"`{\"id\":\"%d\"}`",
",",
"bp",
".",
"Id",
")",
"}",
",",
"}",
".",
"Encode",
"(",
")",
",",
"}",
"\n",
"return",
"NewLink",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"bp",
".",
"Id",
")",
",",
"u",
".",
"String",
"(",
")",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // BuildbucketLink returns a link to the buildbucket version of the page. | [
"BuildbucketLink",
"returns",
"a",
"link",
"to",
"the",
"buildbucket",
"version",
"of",
"the",
"page",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/ui/build.go#L143-L159 |
9,139 | luci/luci-go | milo/frontend/ui/build.go | HumanStatus | func (b *Build) HumanStatus() string {
switch b.Status {
case buildbucketpb.Status_SCHEDULED:
return "Pending"
case buildbucketpb.Status_STARTED:
return "Running"
case buildbucketpb.Status_SUCCESS:
return "Success"
case buildbucketpb.Status_FAILURE:
return "Failure"
case buildbucketpb.Status_INFRA_FAILURE:
return "Infra Failure"
case buildbucketpb.Status_CANCELED:
return "Cancelled"
default:
return "Unknown status"
}
} | go | func (b *Build) HumanStatus() string {
switch b.Status {
case buildbucketpb.Status_SCHEDULED:
return "Pending"
case buildbucketpb.Status_STARTED:
return "Running"
case buildbucketpb.Status_SUCCESS:
return "Success"
case buildbucketpb.Status_FAILURE:
return "Failure"
case buildbucketpb.Status_INFRA_FAILURE:
return "Infra Failure"
case buildbucketpb.Status_CANCELED:
return "Cancelled"
default:
return "Unknown status"
}
} | [
"func",
"(",
"b",
"*",
"Build",
")",
"HumanStatus",
"(",
")",
"string",
"{",
"switch",
"b",
".",
"Status",
"{",
"case",
"buildbucketpb",
".",
"Status_SCHEDULED",
":",
"return",
"\"",
"\"",
"\n",
"case",
"buildbucketpb",
".",
"Status_STARTED",
":",
"return",
"\"",
"\"",
"\n",
"case",
"buildbucketpb",
".",
"Status_SUCCESS",
":",
"return",
"\"",
"\"",
"\n",
"case",
"buildbucketpb",
".",
"Status_FAILURE",
":",
"return",
"\"",
"\"",
"\n",
"case",
"buildbucketpb",
".",
"Status_INFRA_FAILURE",
":",
"return",
"\"",
"\"",
"\n",
"case",
"buildbucketpb",
".",
"Status_CANCELED",
":",
"return",
"\"",
"\"",
"\n",
"default",
":",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"}"
] | // Status returns a human friendly string for the status. | [
"Status",
"returns",
"a",
"human",
"friendly",
"string",
"for",
"the",
"status",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/ui/build.go#L205-L222 |
9,140 | luci/luci-go | milo/frontend/ui/build.go | properties | func properties(props *structpb.Struct) []property {
if props == nil {
return nil
}
// Render the fields to JSON.
m := jsonpb.Marshaler{}
buf := bytes.NewBuffer(nil)
if err := m.Marshal(buf, props); err != nil {
panic(err) // This shouldn't happen.
}
d := json.NewDecoder(buf)
jsonProps := map[string]json.RawMessage{}
if err := d.Decode(&jsonProps); err != nil {
panic(err) // This shouldn't happen.
}
// Sort the names.
names := make([]string, 0, len(jsonProps))
for n := range jsonProps {
names = append(names, n)
}
sort.Strings(names)
// Rearrange the fields into a slice.
results := make([]property, len(jsonProps))
for i, n := range names {
buf.Reset()
json.Indent(buf, jsonProps[n], "", " ")
results[i] = property{
Name: n,
Value: buf.String(),
}
}
return results
} | go | func properties(props *structpb.Struct) []property {
if props == nil {
return nil
}
// Render the fields to JSON.
m := jsonpb.Marshaler{}
buf := bytes.NewBuffer(nil)
if err := m.Marshal(buf, props); err != nil {
panic(err) // This shouldn't happen.
}
d := json.NewDecoder(buf)
jsonProps := map[string]json.RawMessage{}
if err := d.Decode(&jsonProps); err != nil {
panic(err) // This shouldn't happen.
}
// Sort the names.
names := make([]string, 0, len(jsonProps))
for n := range jsonProps {
names = append(names, n)
}
sort.Strings(names)
// Rearrange the fields into a slice.
results := make([]property, len(jsonProps))
for i, n := range names {
buf.Reset()
json.Indent(buf, jsonProps[n], "", " ")
results[i] = property{
Name: n,
Value: buf.String(),
}
}
return results
} | [
"func",
"properties",
"(",
"props",
"*",
"structpb",
".",
"Struct",
")",
"[",
"]",
"property",
"{",
"if",
"props",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"// Render the fields to JSON.",
"m",
":=",
"jsonpb",
".",
"Marshaler",
"{",
"}",
"\n",
"buf",
":=",
"bytes",
".",
"NewBuffer",
"(",
"nil",
")",
"\n",
"if",
"err",
":=",
"m",
".",
"Marshal",
"(",
"buf",
",",
"props",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"// This shouldn't happen.",
"\n",
"}",
"\n",
"d",
":=",
"json",
".",
"NewDecoder",
"(",
"buf",
")",
"\n",
"jsonProps",
":=",
"map",
"[",
"string",
"]",
"json",
".",
"RawMessage",
"{",
"}",
"\n",
"if",
"err",
":=",
"d",
".",
"Decode",
"(",
"&",
"jsonProps",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"// This shouldn't happen.",
"\n",
"}",
"\n\n",
"// Sort the names.",
"names",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"jsonProps",
")",
")",
"\n",
"for",
"n",
":=",
"range",
"jsonProps",
"{",
"names",
"=",
"append",
"(",
"names",
",",
"n",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"names",
")",
"\n\n",
"// Rearrange the fields into a slice.",
"results",
":=",
"make",
"(",
"[",
"]",
"property",
",",
"len",
"(",
"jsonProps",
")",
")",
"\n",
"for",
"i",
",",
"n",
":=",
"range",
"names",
"{",
"buf",
".",
"Reset",
"(",
")",
"\n",
"json",
".",
"Indent",
"(",
"buf",
",",
"jsonProps",
"[",
"n",
"]",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"results",
"[",
"i",
"]",
"=",
"property",
"{",
"Name",
":",
"n",
",",
"Value",
":",
"buf",
".",
"String",
"(",
")",
",",
"}",
"\n",
"}",
"\n",
"return",
"results",
"\n",
"}"
] | // properties returns the values in the proto struct fields as
// a json rendered slice of pairs, sorted by key. | [
"properties",
"returns",
"the",
"values",
"in",
"the",
"proto",
"struct",
"fields",
"as",
"a",
"json",
"rendered",
"slice",
"of",
"pairs",
"sorted",
"by",
"key",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/ui/build.go#L234-L268 |
9,141 | luci/luci-go | milo/frontend/ui/build.go | BuilderLink | func (b *Build) BuilderLink() *Link {
if b.Builder == nil {
panic("Invalid build")
}
builder := b.Builder
return NewLink(
builder.Builder,
fmt.Sprintf("/p/%s/builders/%s/%s", builder.Project, builder.Bucket, builder.Builder),
fmt.Sprintf("Builder %s in bucket %s", builder.Builder, builder.Bucket))
} | go | func (b *Build) BuilderLink() *Link {
if b.Builder == nil {
panic("Invalid build")
}
builder := b.Builder
return NewLink(
builder.Builder,
fmt.Sprintf("/p/%s/builders/%s/%s", builder.Project, builder.Bucket, builder.Builder),
fmt.Sprintf("Builder %s in bucket %s", builder.Builder, builder.Bucket))
} | [
"func",
"(",
"b",
"*",
"Build",
")",
"BuilderLink",
"(",
")",
"*",
"Link",
"{",
"if",
"b",
".",
"Builder",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"builder",
":=",
"b",
".",
"Builder",
"\n",
"return",
"NewLink",
"(",
"builder",
".",
"Builder",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"builder",
".",
"Project",
",",
"builder",
".",
"Bucket",
",",
"builder",
".",
"Builder",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"builder",
".",
"Builder",
",",
"builder",
".",
"Bucket",
")",
")",
"\n",
"}"
] | // BuilderLink returns a link to the builder in b. | [
"BuilderLink",
"returns",
"a",
"link",
"to",
"the",
"builder",
"in",
"b",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/ui/build.go#L279-L288 |
9,142 | luci/luci-go | milo/frontend/ui/build.go | Link | func (b *Build) Link() *Link {
if b.Builder == nil {
panic("invalid build")
}
num := b.Id
if b.Number != 0 {
num = int64(b.Number)
}
builder := b.Builder
return NewLink(
fmt.Sprintf("%d", num),
fmt.Sprintf("/p/%s/builders/%s/%s/%d", builder.Project, builder.Bucket, builder.Builder, num),
fmt.Sprintf("Build %d", num))
} | go | func (b *Build) Link() *Link {
if b.Builder == nil {
panic("invalid build")
}
num := b.Id
if b.Number != 0 {
num = int64(b.Number)
}
builder := b.Builder
return NewLink(
fmt.Sprintf("%d", num),
fmt.Sprintf("/p/%s/builders/%s/%s/%d", builder.Project, builder.Bucket, builder.Builder, num),
fmt.Sprintf("Build %d", num))
} | [
"func",
"(",
"b",
"*",
"Build",
")",
"Link",
"(",
")",
"*",
"Link",
"{",
"if",
"b",
".",
"Builder",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"num",
":=",
"b",
".",
"Id",
"\n",
"if",
"b",
".",
"Number",
"!=",
"0",
"{",
"num",
"=",
"int64",
"(",
"b",
".",
"Number",
")",
"\n",
"}",
"\n",
"builder",
":=",
"b",
".",
"Builder",
"\n",
"return",
"NewLink",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"num",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"builder",
".",
"Project",
",",
"builder",
".",
"Bucket",
",",
"builder",
".",
"Builder",
",",
"num",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"num",
")",
")",
"\n",
"}"
] | // Link is a self link to the build. | [
"Link",
"is",
"a",
"self",
"link",
"to",
"the",
"build",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/ui/build.go#L291-L304 |
9,143 | luci/luci-go | milo/frontend/ui/build.go | RevisionHTML | func (c *Commit) RevisionHTML() template.HTML {
switch {
case c == nil:
return ""
case c.Revision != nil:
return c.Revision.HTML()
case c.RequestRevision != nil:
return c.RequestRevision.HTML()
default:
return ""
}
} | go | func (c *Commit) RevisionHTML() template.HTML {
switch {
case c == nil:
return ""
case c.Revision != nil:
return c.Revision.HTML()
case c.RequestRevision != nil:
return c.RequestRevision.HTML()
default:
return ""
}
} | [
"func",
"(",
"c",
"*",
"Commit",
")",
"RevisionHTML",
"(",
")",
"template",
".",
"HTML",
"{",
"switch",
"{",
"case",
"c",
"==",
"nil",
":",
"return",
"\"",
"\"",
"\n",
"case",
"c",
".",
"Revision",
"!=",
"nil",
":",
"return",
"c",
".",
"Revision",
".",
"HTML",
"(",
")",
"\n",
"case",
"c",
".",
"RequestRevision",
"!=",
"nil",
":",
"return",
"c",
".",
"RequestRevision",
".",
"HTML",
"(",
")",
"\n",
"default",
":",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"}"
] | // RevisionHTML returns a single rendered link for the revision, prioritizing
// Revision over RequestRevision. | [
"RevisionHTML",
"returns",
"a",
"single",
"rendered",
"link",
"for",
"the",
"revision",
"prioritizing",
"Revision",
"over",
"RequestRevision",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/ui/build.go#L389-L400 |
9,144 | luci/luci-go | milo/frontend/ui/build.go | Timeline | func (bp *BuildPage) Timeline() string {
// Return the cached version, if it exists already.
if bp.timelineData != "" {
return bp.timelineData
}
// stepData is extra data to deliver with the groups and items (see below) for the
// Javascript vis Timeline component. Note that the step data is encoded in markdown
// in the step.SummaryMarkdown field. We do not show this data on the timeline at this
// time.
type stepData struct {
Label string `json:"label"`
Duration string `json:"duration"`
LogURL string `json:"logUrl"`
StatusClassName string `json:"statusClassName"`
}
// group corresponds to, and matches the shape of, a Group for the Javascript
// vis Timeline component http://visjs.org/docs/timeline/#groups. Data
// rides along as an extra property (unused by vis Timeline itself) used
// in client side rendering. Each Group is rendered as its own row in the
// timeline component on to which Items are rendered. Currently we only render
// one Item per Group, that is one thing per row.
type group struct {
ID string `json:"id"`
Data stepData `json:"data"`
}
// item corresponds to, and matches the shape of, an Item for the Javascript
// vis Timeline component http://visjs.org/docs/timeline/#items. Data
// rides along as an extra property (unused by vis Timeline itself) used
// in client side rendering. Each Item is rendered to a Group which corresponds
// to a row. Currently we only render one Item per Group, that is one thing per
// row.
type item struct {
ID string `json:"id"`
Group string `json:"group"`
Start int64 `json:"start"`
End int64 `json:"end"`
Type string `json:"type"`
ClassName string `json:"className"`
Data stepData `json:"data"`
}
groups := make([]group, len(bp.Build.Steps))
items := make([]item, len(bp.Build.Steps))
for i, step := range bp.Build.Steps {
groupID := strconv.Itoa(i)
logURL := ""
if len(step.Logs) > 0 {
logURL = html.EscapeString(step.Logs[0].ViewUrl)
}
statusClassName := fmt.Sprintf("status-%s", step.Status)
data := stepData{
Label: html.EscapeString(step.Name),
Duration: common.Duration(step.StartTime, step.EndTime, bp.Now),
LogURL: logURL,
StatusClassName: statusClassName,
}
groups[i] = group{groupID, data}
start, _ := ptypes.Timestamp(step.StartTime)
end, _ := ptypes.Timestamp(step.EndTime)
items[i] = item{
ID: groupID,
Group: groupID,
Start: milliseconds(start),
End: milliseconds(end),
Type: "range",
ClassName: statusClassName,
Data: data,
}
}
timeline, err := json.Marshal(map[string]interface{}{
"groups": groups,
"items": items,
})
if err != nil {
bp.Errors = append(bp.Errors, err)
return "error"
}
return string(timeline)
} | go | func (bp *BuildPage) Timeline() string {
// Return the cached version, if it exists already.
if bp.timelineData != "" {
return bp.timelineData
}
// stepData is extra data to deliver with the groups and items (see below) for the
// Javascript vis Timeline component. Note that the step data is encoded in markdown
// in the step.SummaryMarkdown field. We do not show this data on the timeline at this
// time.
type stepData struct {
Label string `json:"label"`
Duration string `json:"duration"`
LogURL string `json:"logUrl"`
StatusClassName string `json:"statusClassName"`
}
// group corresponds to, and matches the shape of, a Group for the Javascript
// vis Timeline component http://visjs.org/docs/timeline/#groups. Data
// rides along as an extra property (unused by vis Timeline itself) used
// in client side rendering. Each Group is rendered as its own row in the
// timeline component on to which Items are rendered. Currently we only render
// one Item per Group, that is one thing per row.
type group struct {
ID string `json:"id"`
Data stepData `json:"data"`
}
// item corresponds to, and matches the shape of, an Item for the Javascript
// vis Timeline component http://visjs.org/docs/timeline/#items. Data
// rides along as an extra property (unused by vis Timeline itself) used
// in client side rendering. Each Item is rendered to a Group which corresponds
// to a row. Currently we only render one Item per Group, that is one thing per
// row.
type item struct {
ID string `json:"id"`
Group string `json:"group"`
Start int64 `json:"start"`
End int64 `json:"end"`
Type string `json:"type"`
ClassName string `json:"className"`
Data stepData `json:"data"`
}
groups := make([]group, len(bp.Build.Steps))
items := make([]item, len(bp.Build.Steps))
for i, step := range bp.Build.Steps {
groupID := strconv.Itoa(i)
logURL := ""
if len(step.Logs) > 0 {
logURL = html.EscapeString(step.Logs[0].ViewUrl)
}
statusClassName := fmt.Sprintf("status-%s", step.Status)
data := stepData{
Label: html.EscapeString(step.Name),
Duration: common.Duration(step.StartTime, step.EndTime, bp.Now),
LogURL: logURL,
StatusClassName: statusClassName,
}
groups[i] = group{groupID, data}
start, _ := ptypes.Timestamp(step.StartTime)
end, _ := ptypes.Timestamp(step.EndTime)
items[i] = item{
ID: groupID,
Group: groupID,
Start: milliseconds(start),
End: milliseconds(end),
Type: "range",
ClassName: statusClassName,
Data: data,
}
}
timeline, err := json.Marshal(map[string]interface{}{
"groups": groups,
"items": items,
})
if err != nil {
bp.Errors = append(bp.Errors, err)
return "error"
}
return string(timeline)
} | [
"func",
"(",
"bp",
"*",
"BuildPage",
")",
"Timeline",
"(",
")",
"string",
"{",
"// Return the cached version, if it exists already.",
"if",
"bp",
".",
"timelineData",
"!=",
"\"",
"\"",
"{",
"return",
"bp",
".",
"timelineData",
"\n",
"}",
"\n\n",
"// stepData is extra data to deliver with the groups and items (see below) for the",
"// Javascript vis Timeline component. Note that the step data is encoded in markdown",
"// in the step.SummaryMarkdown field. We do not show this data on the timeline at this",
"// time.",
"type",
"stepData",
"struct",
"{",
"Label",
"string",
"`json:\"label\"`",
"\n",
"Duration",
"string",
"`json:\"duration\"`",
"\n",
"LogURL",
"string",
"`json:\"logUrl\"`",
"\n",
"StatusClassName",
"string",
"`json:\"statusClassName\"`",
"\n",
"}",
"\n\n",
"// group corresponds to, and matches the shape of, a Group for the Javascript",
"// vis Timeline component http://visjs.org/docs/timeline/#groups. Data",
"// rides along as an extra property (unused by vis Timeline itself) used",
"// in client side rendering. Each Group is rendered as its own row in the",
"// timeline component on to which Items are rendered. Currently we only render",
"// one Item per Group, that is one thing per row.",
"type",
"group",
"struct",
"{",
"ID",
"string",
"`json:\"id\"`",
"\n",
"Data",
"stepData",
"`json:\"data\"`",
"\n",
"}",
"\n\n",
"// item corresponds to, and matches the shape of, an Item for the Javascript",
"// vis Timeline component http://visjs.org/docs/timeline/#items. Data",
"// rides along as an extra property (unused by vis Timeline itself) used",
"// in client side rendering. Each Item is rendered to a Group which corresponds",
"// to a row. Currently we only render one Item per Group, that is one thing per",
"// row.",
"type",
"item",
"struct",
"{",
"ID",
"string",
"`json:\"id\"`",
"\n",
"Group",
"string",
"`json:\"group\"`",
"\n",
"Start",
"int64",
"`json:\"start\"`",
"\n",
"End",
"int64",
"`json:\"end\"`",
"\n",
"Type",
"string",
"`json:\"type\"`",
"\n",
"ClassName",
"string",
"`json:\"className\"`",
"\n",
"Data",
"stepData",
"`json:\"data\"`",
"\n",
"}",
"\n\n",
"groups",
":=",
"make",
"(",
"[",
"]",
"group",
",",
"len",
"(",
"bp",
".",
"Build",
".",
"Steps",
")",
")",
"\n",
"items",
":=",
"make",
"(",
"[",
"]",
"item",
",",
"len",
"(",
"bp",
".",
"Build",
".",
"Steps",
")",
")",
"\n",
"for",
"i",
",",
"step",
":=",
"range",
"bp",
".",
"Build",
".",
"Steps",
"{",
"groupID",
":=",
"strconv",
".",
"Itoa",
"(",
"i",
")",
"\n",
"logURL",
":=",
"\"",
"\"",
"\n",
"if",
"len",
"(",
"step",
".",
"Logs",
")",
">",
"0",
"{",
"logURL",
"=",
"html",
".",
"EscapeString",
"(",
"step",
".",
"Logs",
"[",
"0",
"]",
".",
"ViewUrl",
")",
"\n",
"}",
"\n",
"statusClassName",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"step",
".",
"Status",
")",
"\n",
"data",
":=",
"stepData",
"{",
"Label",
":",
"html",
".",
"EscapeString",
"(",
"step",
".",
"Name",
")",
",",
"Duration",
":",
"common",
".",
"Duration",
"(",
"step",
".",
"StartTime",
",",
"step",
".",
"EndTime",
",",
"bp",
".",
"Now",
")",
",",
"LogURL",
":",
"logURL",
",",
"StatusClassName",
":",
"statusClassName",
",",
"}",
"\n",
"groups",
"[",
"i",
"]",
"=",
"group",
"{",
"groupID",
",",
"data",
"}",
"\n",
"start",
",",
"_",
":=",
"ptypes",
".",
"Timestamp",
"(",
"step",
".",
"StartTime",
")",
"\n",
"end",
",",
"_",
":=",
"ptypes",
".",
"Timestamp",
"(",
"step",
".",
"EndTime",
")",
"\n",
"items",
"[",
"i",
"]",
"=",
"item",
"{",
"ID",
":",
"groupID",
",",
"Group",
":",
"groupID",
",",
"Start",
":",
"milliseconds",
"(",
"start",
")",
",",
"End",
":",
"milliseconds",
"(",
"end",
")",
",",
"Type",
":",
"\"",
"\"",
",",
"ClassName",
":",
"statusClassName",
",",
"Data",
":",
"data",
",",
"}",
"\n",
"}",
"\n\n",
"timeline",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"groups",
",",
"\"",
"\"",
":",
"items",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"bp",
".",
"Errors",
"=",
"append",
"(",
"bp",
".",
"Errors",
",",
"err",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"string",
"(",
"timeline",
")",
"\n",
"}"
] | // Timeline returns a JSON parsable string that can be fed into a viz timeline component. | [
"Timeline",
"returns",
"a",
"JSON",
"parsable",
"string",
"that",
"can",
"be",
"fed",
"into",
"a",
"viz",
"timeline",
"component",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/ui/build.go#L420-L502 |
9,145 | luci/luci-go | milo/frontend/ui/build.go | HTML | func (l *Link) HTML() template.HTML {
if l == nil {
return ""
}
buf := bytes.Buffer{}
if err := linkifyTemplate.Execute(&buf, l); err != nil {
panic(err)
}
return template.HTML(buf.Bytes())
} | go | func (l *Link) HTML() template.HTML {
if l == nil {
return ""
}
buf := bytes.Buffer{}
if err := linkifyTemplate.Execute(&buf, l); err != nil {
panic(err)
}
return template.HTML(buf.Bytes())
} | [
"func",
"(",
"l",
"*",
"Link",
")",
"HTML",
"(",
")",
"template",
".",
"HTML",
"{",
"if",
"l",
"==",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"buf",
":=",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"if",
"err",
":=",
"linkifyTemplate",
".",
"Execute",
"(",
"&",
"buf",
",",
"l",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"template",
".",
"HTML",
"(",
"buf",
".",
"Bytes",
"(",
")",
")",
"\n",
"}"
] | // HTML renders this Link as HTML. | [
"HTML",
"renders",
"this",
"Link",
"as",
"HTML",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/ui/build.go#L533-L542 |
9,146 | luci/luci-go | milo/frontend/ui/build.go | HTML | func (l LinkSet) HTML() template.HTML {
if len(l) == 0 {
return ""
}
buf := bytes.Buffer{}
if err := linkifySetTemplate.Execute(&buf, l); err != nil {
panic(err)
}
return template.HTML(buf.Bytes())
} | go | func (l LinkSet) HTML() template.HTML {
if len(l) == 0 {
return ""
}
buf := bytes.Buffer{}
if err := linkifySetTemplate.Execute(&buf, l); err != nil {
panic(err)
}
return template.HTML(buf.Bytes())
} | [
"func",
"(",
"l",
"LinkSet",
")",
"HTML",
"(",
")",
"template",
".",
"HTML",
"{",
"if",
"len",
"(",
"l",
")",
"==",
"0",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"buf",
":=",
"bytes",
".",
"Buffer",
"{",
"}",
"\n",
"if",
"err",
":=",
"linkifySetTemplate",
".",
"Execute",
"(",
"&",
"buf",
",",
"l",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"template",
".",
"HTML",
"(",
"buf",
".",
"Bytes",
"(",
")",
")",
"\n",
"}"
] | // HTML renders this LinkSet as HTML. | [
"HTML",
"renders",
"this",
"LinkSet",
"as",
"HTML",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/ui/build.go#L553-L562 |
9,147 | luci/luci-go | milo/frontend/ui/build.go | NewLink | func NewLink(label, url, ariaLabel string) *Link {
return &Link{Link: model.Link{Label: label, URL: url}, AriaLabel: ariaLabel}
} | go | func NewLink(label, url, ariaLabel string) *Link {
return &Link{Link: model.Link{Label: label, URL: url}, AriaLabel: ariaLabel}
} | [
"func",
"NewLink",
"(",
"label",
",",
"url",
",",
"ariaLabel",
"string",
")",
"*",
"Link",
"{",
"return",
"&",
"Link",
"{",
"Link",
":",
"model",
".",
"Link",
"{",
"Label",
":",
"label",
",",
"URL",
":",
"url",
"}",
",",
"AriaLabel",
":",
"ariaLabel",
"}",
"\n",
"}"
] | // NewLink does just about what you'd expect. | [
"NewLink",
"does",
"just",
"about",
"what",
"you",
"d",
"expect",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/ui/build.go#L584-L586 |
9,148 | luci/luci-go | milo/frontend/ui/build.go | NewPatchLink | func NewPatchLink(cl *buildbucketpb.GerritChange) *Link {
return NewLink(
fmt.Sprintf("Gerrit CL %d (ps#%d)", cl.Change, cl.Patchset),
protoutil.GerritChangeURL(cl),
fmt.Sprintf("gerrit changelist number %d patchset %d", cl.Change, cl.Patchset))
} | go | func NewPatchLink(cl *buildbucketpb.GerritChange) *Link {
return NewLink(
fmt.Sprintf("Gerrit CL %d (ps#%d)", cl.Change, cl.Patchset),
protoutil.GerritChangeURL(cl),
fmt.Sprintf("gerrit changelist number %d patchset %d", cl.Change, cl.Patchset))
} | [
"func",
"NewPatchLink",
"(",
"cl",
"*",
"buildbucketpb",
".",
"GerritChange",
")",
"*",
"Link",
"{",
"return",
"NewLink",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"cl",
".",
"Change",
",",
"cl",
".",
"Patchset",
")",
",",
"protoutil",
".",
"GerritChangeURL",
"(",
"cl",
")",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"cl",
".",
"Change",
",",
"cl",
".",
"Patchset",
")",
")",
"\n",
"}"
] | // NewPatchLink generates a URL to a Gerrit CL. | [
"NewPatchLink",
"generates",
"a",
"URL",
"to",
"a",
"Gerrit",
"CL",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/ui/build.go#L589-L594 |
9,149 | luci/luci-go | milo/frontend/ui/build.go | NewEmptyLink | func NewEmptyLink(label string) *Link {
return &Link{Link: model.Link{Label: label}}
} | go | func NewEmptyLink(label string) *Link {
return &Link{Link: model.Link{Label: label}}
} | [
"func",
"NewEmptyLink",
"(",
"label",
"string",
")",
"*",
"Link",
"{",
"return",
"&",
"Link",
"{",
"Link",
":",
"model",
".",
"Link",
"{",
"Label",
":",
"label",
"}",
"}",
"\n",
"}"
] | // NewEmptyLink creates a Link struct acting as a pure text label. | [
"NewEmptyLink",
"creates",
"a",
"Link",
"struct",
"acting",
"as",
"a",
"pure",
"text",
"label",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/milo/frontend/ui/build.go#L597-L599 |
9,150 | luci/luci-go | server/auth/handlers.go | certsHandler | func certsHandler(c *router.Context) {
s := GetSigner(c.Context)
if s == nil {
httpReplyError(c, http.StatusNotFound, "No Signer instance available")
return
}
certs, err := s.Certificates(c.Context)
if err != nil {
httpReplyError(c, http.StatusInternalServerError, fmt.Sprintf("Can't fetch certificates - %s", err))
} else {
httpReply(c, http.StatusOK, certs)
}
} | go | func certsHandler(c *router.Context) {
s := GetSigner(c.Context)
if s == nil {
httpReplyError(c, http.StatusNotFound, "No Signer instance available")
return
}
certs, err := s.Certificates(c.Context)
if err != nil {
httpReplyError(c, http.StatusInternalServerError, fmt.Sprintf("Can't fetch certificates - %s", err))
} else {
httpReply(c, http.StatusOK, certs)
}
} | [
"func",
"certsHandler",
"(",
"c",
"*",
"router",
".",
"Context",
")",
"{",
"s",
":=",
"GetSigner",
"(",
"c",
".",
"Context",
")",
"\n",
"if",
"s",
"==",
"nil",
"{",
"httpReplyError",
"(",
"c",
",",
"http",
".",
"StatusNotFound",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"certs",
",",
"err",
":=",
"s",
".",
"Certificates",
"(",
"c",
".",
"Context",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"httpReplyError",
"(",
"c",
",",
"http",
".",
"StatusInternalServerError",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"}",
"else",
"{",
"httpReply",
"(",
"c",
",",
"http",
".",
"StatusOK",
",",
"certs",
")",
"\n",
"}",
"\n",
"}"
] | // certsHandler servers public certificates of the signer in the context. | [
"certsHandler",
"servers",
"public",
"certificates",
"of",
"the",
"signer",
"in",
"the",
"context",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/handlers.go#L38-L50 |
9,151 | luci/luci-go | server/auth/handlers.go | infoHandler | func infoHandler(c *router.Context) {
s := GetSigner(c.Context)
if s == nil {
httpReplyError(c, http.StatusNotFound, "No Signer instance available")
return
}
info, err := s.ServiceInfo(c.Context)
if err != nil {
httpReplyError(c, http.StatusInternalServerError, fmt.Sprintf("Can't grab service info - %s", err))
} else {
httpReply(c, http.StatusOK, info)
}
} | go | func infoHandler(c *router.Context) {
s := GetSigner(c.Context)
if s == nil {
httpReplyError(c, http.StatusNotFound, "No Signer instance available")
return
}
info, err := s.ServiceInfo(c.Context)
if err != nil {
httpReplyError(c, http.StatusInternalServerError, fmt.Sprintf("Can't grab service info - %s", err))
} else {
httpReply(c, http.StatusOK, info)
}
} | [
"func",
"infoHandler",
"(",
"c",
"*",
"router",
".",
"Context",
")",
"{",
"s",
":=",
"GetSigner",
"(",
"c",
".",
"Context",
")",
"\n",
"if",
"s",
"==",
"nil",
"{",
"httpReplyError",
"(",
"c",
",",
"http",
".",
"StatusNotFound",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"info",
",",
"err",
":=",
"s",
".",
"ServiceInfo",
"(",
"c",
".",
"Context",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"httpReplyError",
"(",
"c",
",",
"http",
".",
"StatusInternalServerError",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"}",
"else",
"{",
"httpReply",
"(",
"c",
",",
"http",
".",
"StatusOK",
",",
"info",
")",
"\n",
"}",
"\n",
"}"
] | // infoHandler returns information about the current service identity. | [
"infoHandler",
"returns",
"information",
"about",
"the",
"current",
"service",
"identity",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/handlers.go#L53-L65 |
9,152 | luci/luci-go | machine-db/client/cli/vlans.go | printVLANs | func printVLANs(tsv bool, vlans ...*crimson.VLAN) {
if len(vlans) > 0 {
p := newStdoutPrinter(tsv)
defer p.Flush()
if !tsv {
p.Row("ID", "Alias", "Description", "State", "CIDR Block")
}
for _, v := range vlans {
p.Row(v.Id, v.Alias, v.Description, v.State, v.CidrBlock)
}
}
} | go | func printVLANs(tsv bool, vlans ...*crimson.VLAN) {
if len(vlans) > 0 {
p := newStdoutPrinter(tsv)
defer p.Flush()
if !tsv {
p.Row("ID", "Alias", "Description", "State", "CIDR Block")
}
for _, v := range vlans {
p.Row(v.Id, v.Alias, v.Description, v.State, v.CidrBlock)
}
}
} | [
"func",
"printVLANs",
"(",
"tsv",
"bool",
",",
"vlans",
"...",
"*",
"crimson",
".",
"VLAN",
")",
"{",
"if",
"len",
"(",
"vlans",
")",
">",
"0",
"{",
"p",
":=",
"newStdoutPrinter",
"(",
"tsv",
")",
"\n",
"defer",
"p",
".",
"Flush",
"(",
")",
"\n",
"if",
"!",
"tsv",
"{",
"p",
".",
"Row",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"vlans",
"{",
"p",
".",
"Row",
"(",
"v",
".",
"Id",
",",
"v",
".",
"Alias",
",",
"v",
".",
"Description",
",",
"v",
".",
"State",
",",
"v",
".",
"CidrBlock",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // printVLANs prints VLAN data to stdout in tab-separated columns. | [
"printVLANs",
"prints",
"VLAN",
"data",
"to",
"stdout",
"in",
"tab",
"-",
"separated",
"columns",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/vlans.go#L28-L39 |
9,153 | luci/luci-go | machine-db/client/cli/vlans.go | Run | func (c *GetVLANsCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
ctx := cli.GetContext(app, c, env)
client := getClient(ctx)
resp, err := client.ListVLANs(ctx, &c.req)
if err != nil {
errors.Log(ctx, err)
return 1
}
printVLANs(c.f.tsv, resp.Vlans...)
return 0
} | go | func (c *GetVLANsCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
ctx := cli.GetContext(app, c, env)
client := getClient(ctx)
resp, err := client.ListVLANs(ctx, &c.req)
if err != nil {
errors.Log(ctx, err)
return 1
}
printVLANs(c.f.tsv, resp.Vlans...)
return 0
} | [
"func",
"(",
"c",
"*",
"GetVLANsCmd",
")",
"Run",
"(",
"app",
"subcommands",
".",
"Application",
",",
"args",
"[",
"]",
"string",
",",
"env",
"subcommands",
".",
"Env",
")",
"int",
"{",
"ctx",
":=",
"cli",
".",
"GetContext",
"(",
"app",
",",
"c",
",",
"env",
")",
"\n",
"client",
":=",
"getClient",
"(",
"ctx",
")",
"\n",
"resp",
",",
"err",
":=",
"client",
".",
"ListVLANs",
"(",
"ctx",
",",
"&",
"c",
".",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"errors",
".",
"Log",
"(",
"ctx",
",",
"err",
")",
"\n",
"return",
"1",
"\n",
"}",
"\n",
"printVLANs",
"(",
"c",
".",
"f",
".",
"tsv",
",",
"resp",
".",
"Vlans",
"...",
")",
"\n",
"return",
"0",
"\n",
"}"
] | // Run runs the command to get VLANs. | [
"Run",
"runs",
"the",
"command",
"to",
"get",
"VLANs",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/vlans.go#L48-L58 |
9,154 | luci/luci-go | machine-db/client/cli/vlans.go | getVLANsCmd | func getVLANsCmd(params *Parameters) *subcommands.Command {
return &subcommands.Command{
UsageLine: "get-vlans [-id <id>]... [-alias <alias>]...",
ShortDesc: "retrieves VLANs",
LongDesc: "Retrieves VLANs matching the given IDs or aliases, or all VLANs if IDs and aliases are omitted.\n\nExample to get all VLANs:\ncrimson get-vlans\nExample to get VLAN 1:\ncrimson get-vlans -id 1",
CommandRun: func() subcommands.CommandRun {
cmd := &GetVLANsCmd{}
cmd.Initialize(params)
cmd.Flags.Var(flag.Int64Slice(&cmd.req.Ids), "id", "ID of a VLAN to filter by. Can be specified multiple times.")
cmd.Flags.Var(flag.StringSlice(&cmd.req.Aliases), "alias", "Alias of a VLAN to filter by. Can be specified multiple times.")
return cmd
},
}
} | go | func getVLANsCmd(params *Parameters) *subcommands.Command {
return &subcommands.Command{
UsageLine: "get-vlans [-id <id>]... [-alias <alias>]...",
ShortDesc: "retrieves VLANs",
LongDesc: "Retrieves VLANs matching the given IDs or aliases, or all VLANs if IDs and aliases are omitted.\n\nExample to get all VLANs:\ncrimson get-vlans\nExample to get VLAN 1:\ncrimson get-vlans -id 1",
CommandRun: func() subcommands.CommandRun {
cmd := &GetVLANsCmd{}
cmd.Initialize(params)
cmd.Flags.Var(flag.Int64Slice(&cmd.req.Ids), "id", "ID of a VLAN to filter by. Can be specified multiple times.")
cmd.Flags.Var(flag.StringSlice(&cmd.req.Aliases), "alias", "Alias of a VLAN to filter by. Can be specified multiple times.")
return cmd
},
}
} | [
"func",
"getVLANsCmd",
"(",
"params",
"*",
"Parameters",
")",
"*",
"subcommands",
".",
"Command",
"{",
"return",
"&",
"subcommands",
".",
"Command",
"{",
"UsageLine",
":",
"\"",
"\"",
",",
"ShortDesc",
":",
"\"",
"\"",
",",
"LongDesc",
":",
"\"",
"\\n",
"\\n",
"\\n",
"\\n",
"\\n",
"\"",
",",
"CommandRun",
":",
"func",
"(",
")",
"subcommands",
".",
"CommandRun",
"{",
"cmd",
":=",
"&",
"GetVLANsCmd",
"{",
"}",
"\n",
"cmd",
".",
"Initialize",
"(",
"params",
")",
"\n",
"cmd",
".",
"Flags",
".",
"Var",
"(",
"flag",
".",
"Int64Slice",
"(",
"&",
"cmd",
".",
"req",
".",
"Ids",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"cmd",
".",
"Flags",
".",
"Var",
"(",
"flag",
".",
"StringSlice",
"(",
"&",
"cmd",
".",
"req",
".",
"Aliases",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"cmd",
"\n",
"}",
",",
"}",
"\n",
"}"
] | // getVLANsCmd returns a command to get VLANs. | [
"getVLANsCmd",
"returns",
"a",
"command",
"to",
"get",
"VLANs",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/vlans.go#L61-L74 |
9,155 | luci/luci-go | common/data/recordio/reader.go | NewReader | func NewReader(r io.Reader, maxSize int64) Reader {
br, ok := r.(io.ByteReader)
if !ok {
br = &simpleByteReader{Reader: r}
}
return &reader{
Reader: r,
ByteReader: br,
maxSize: maxSize,
}
} | go | func NewReader(r io.Reader, maxSize int64) Reader {
br, ok := r.(io.ByteReader)
if !ok {
br = &simpleByteReader{Reader: r}
}
return &reader{
Reader: r,
ByteReader: br,
maxSize: maxSize,
}
} | [
"func",
"NewReader",
"(",
"r",
"io",
".",
"Reader",
",",
"maxSize",
"int64",
")",
"Reader",
"{",
"br",
",",
"ok",
":=",
"r",
".",
"(",
"io",
".",
"ByteReader",
")",
"\n",
"if",
"!",
"ok",
"{",
"br",
"=",
"&",
"simpleByteReader",
"{",
"Reader",
":",
"r",
"}",
"\n",
"}",
"\n",
"return",
"&",
"reader",
"{",
"Reader",
":",
"r",
",",
"ByteReader",
":",
"br",
",",
"maxSize",
":",
"maxSize",
",",
"}",
"\n",
"}"
] | // NewReader creates a new Reader which reads frame data from the
// supplied Reader instance.
//
// If the Reader instance is also an io.ByteReader, its ReadByte method will
// be used directly. | [
"NewReader",
"creates",
"a",
"new",
"Reader",
"which",
"reads",
"frame",
"data",
"from",
"the",
"supplied",
"Reader",
"instance",
".",
"If",
"the",
"Reader",
"instance",
"is",
"also",
"an",
"io",
".",
"ByteReader",
"its",
"ReadByte",
"method",
"will",
"be",
"used",
"directly",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/recordio/reader.go#L59-L69 |
9,156 | luci/luci-go | common/data/recordio/reader.go | Split | func Split(data []byte) (records [][]byte, err error) {
br := bytes.NewReader(data)
for br.Len() > 0 {
var size uint64
size, err = binary.ReadUvarint(br)
if err != nil {
return
}
if size > uint64(br.Len()) {
err = ErrFrameTooLarge
return
}
// Pull out the record from the original byte stream without copying.
// Casting size to an integer is safe at this point, since we have asserted
// that it is less than the remaining length in the buffer, which is an int.
offset := len(data) - br.Len()
records = append(records, data[offset:offset+int(size)])
if _, err := br.Seek(int64(size), 1); err != nil {
// Our measurements should protect us from this being an invalid seek.
panic(err)
}
}
return records, nil
} | go | func Split(data []byte) (records [][]byte, err error) {
br := bytes.NewReader(data)
for br.Len() > 0 {
var size uint64
size, err = binary.ReadUvarint(br)
if err != nil {
return
}
if size > uint64(br.Len()) {
err = ErrFrameTooLarge
return
}
// Pull out the record from the original byte stream without copying.
// Casting size to an integer is safe at this point, since we have asserted
// that it is less than the remaining length in the buffer, which is an int.
offset := len(data) - br.Len()
records = append(records, data[offset:offset+int(size)])
if _, err := br.Seek(int64(size), 1); err != nil {
// Our measurements should protect us from this being an invalid seek.
panic(err)
}
}
return records, nil
} | [
"func",
"Split",
"(",
"data",
"[",
"]",
"byte",
")",
"(",
"records",
"[",
"]",
"[",
"]",
"byte",
",",
"err",
"error",
")",
"{",
"br",
":=",
"bytes",
".",
"NewReader",
"(",
"data",
")",
"\n\n",
"for",
"br",
".",
"Len",
"(",
")",
">",
"0",
"{",
"var",
"size",
"uint64",
"\n",
"size",
",",
"err",
"=",
"binary",
".",
"ReadUvarint",
"(",
"br",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"size",
">",
"uint64",
"(",
"br",
".",
"Len",
"(",
")",
")",
"{",
"err",
"=",
"ErrFrameTooLarge",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Pull out the record from the original byte stream without copying.",
"// Casting size to an integer is safe at this point, since we have asserted",
"// that it is less than the remaining length in the buffer, which is an int.",
"offset",
":=",
"len",
"(",
"data",
")",
"-",
"br",
".",
"Len",
"(",
")",
"\n",
"records",
"=",
"append",
"(",
"records",
",",
"data",
"[",
"offset",
":",
"offset",
"+",
"int",
"(",
"size",
")",
"]",
")",
"\n\n",
"if",
"_",
",",
"err",
":=",
"br",
".",
"Seek",
"(",
"int64",
"(",
"size",
")",
",",
"1",
")",
";",
"err",
"!=",
"nil",
"{",
"// Our measurements should protect us from this being an invalid seek.",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"records",
",",
"nil",
"\n",
"}"
] | // Split splits the supplied buffer into its component records.
//
// This method implements zero-copy segmentation, so the individual records are
// slices of the original data set. | [
"Split",
"splits",
"the",
"supplied",
"buffer",
"into",
"its",
"component",
"records",
".",
"This",
"method",
"implements",
"zero",
"-",
"copy",
"segmentation",
"so",
"the",
"individual",
"records",
"are",
"slices",
"of",
"the",
"original",
"data",
"set",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/recordio/reader.go#L121-L147 |
9,157 | luci/luci-go | auth/authctx/git.go | Write | func (gc *gitConfig) Write(path string) error {
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
if err = gitConfigTempl.Execute(f, gc); err != nil {
return err
}
return f.Close() // failure to close the file is an overall failure
} | go | func (gc *gitConfig) Write(path string) error {
f, err := os.Create(path)
if err != nil {
return err
}
defer f.Close()
if err = gitConfigTempl.Execute(f, gc); err != nil {
return err
}
return f.Close() // failure to close the file is an overall failure
} | [
"func",
"(",
"gc",
"*",
"gitConfig",
")",
"Write",
"(",
"path",
"string",
")",
"error",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Create",
"(",
"path",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"=",
"gitConfigTempl",
".",
"Execute",
"(",
"f",
",",
"gc",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"f",
".",
"Close",
"(",
")",
"// failure to close the file is an overall failure",
"\n",
"}"
] | // Write actually writes the config to 'path'. | [
"Write",
"actually",
"writes",
"the",
"config",
"to",
"path",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/auth/authctx/git.go#L122-L132 |
9,158 | luci/luci-go | common/flag/nestedflagset/lexer.go | nextToken | func (l *lexerContext) nextToken() token {
buf := new(bytes.Buffer)
index := 0
escaped := false
quoted := false
MainLoop:
for _, c := range l.value[l.index:] {
index += utf8.RuneLen(c)
if escaped {
escaped = false
buf.WriteRune(c)
continue
}
switch c {
case '\\':
escaped = true
case '"':
quoted = !quoted
case l.delim:
if quoted {
buf.WriteRune(c)
} else {
break MainLoop
}
default:
buf.WriteRune(c)
}
}
l.index += index
return token(buf.Bytes())
} | go | func (l *lexerContext) nextToken() token {
buf := new(bytes.Buffer)
index := 0
escaped := false
quoted := false
MainLoop:
for _, c := range l.value[l.index:] {
index += utf8.RuneLen(c)
if escaped {
escaped = false
buf.WriteRune(c)
continue
}
switch c {
case '\\':
escaped = true
case '"':
quoted = !quoted
case l.delim:
if quoted {
buf.WriteRune(c)
} else {
break MainLoop
}
default:
buf.WriteRune(c)
}
}
l.index += index
return token(buf.Bytes())
} | [
"func",
"(",
"l",
"*",
"lexerContext",
")",
"nextToken",
"(",
")",
"token",
"{",
"buf",
":=",
"new",
"(",
"bytes",
".",
"Buffer",
")",
"\n\n",
"index",
":=",
"0",
"\n",
"escaped",
":=",
"false",
"\n",
"quoted",
":=",
"false",
"\n\n",
"MainLoop",
":",
"for",
"_",
",",
"c",
":=",
"range",
"l",
".",
"value",
"[",
"l",
".",
"index",
":",
"]",
"{",
"index",
"+=",
"utf8",
".",
"RuneLen",
"(",
"c",
")",
"\n\n",
"if",
"escaped",
"{",
"escaped",
"=",
"false",
"\n",
"buf",
".",
"WriteRune",
"(",
"c",
")",
"\n",
"continue",
"\n",
"}",
"\n\n",
"switch",
"c",
"{",
"case",
"'\\\\'",
":",
"escaped",
"=",
"true",
"\n\n",
"case",
"'\"'",
":",
"quoted",
"=",
"!",
"quoted",
"\n\n",
"case",
"l",
".",
"delim",
":",
"if",
"quoted",
"{",
"buf",
".",
"WriteRune",
"(",
"c",
")",
"\n",
"}",
"else",
"{",
"break",
"MainLoop",
"\n",
"}",
"\n\n",
"default",
":",
"buf",
".",
"WriteRune",
"(",
"c",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"l",
".",
"index",
"+=",
"index",
"\n",
"return",
"token",
"(",
"buf",
".",
"Bytes",
"(",
")",
")",
"\n",
"}"
] | // nextToken parses and returns the next token in the string. | [
"nextToken",
"parses",
"and",
"returns",
"the",
"next",
"token",
"in",
"the",
"string",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/flag/nestedflagset/lexer.go#L30-L68 |
9,159 | luci/luci-go | common/flag/nestedflagset/lexer.go | lexer | func lexer(value string, delim rune) *lexerContext {
return &lexerContext{
value: value,
index: 0,
delim: delim,
}
} | go | func lexer(value string, delim rune) *lexerContext {
return &lexerContext{
value: value,
index: 0,
delim: delim,
}
} | [
"func",
"lexer",
"(",
"value",
"string",
",",
"delim",
"rune",
")",
"*",
"lexerContext",
"{",
"return",
"&",
"lexerContext",
"{",
"value",
":",
"value",
",",
"index",
":",
"0",
",",
"delim",
":",
"delim",
",",
"}",
"\n",
"}"
] | // Lexer creates a new lexer lexerContext. | [
"Lexer",
"creates",
"a",
"new",
"lexer",
"lexerContext",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/flag/nestedflagset/lexer.go#L71-L77 |
9,160 | luci/luci-go | common/flag/nestedflagset/lexer.go | split | func (l *lexerContext) split() []token {
result := make([]token, 0, 16)
for !l.finished() {
result = append(result, l.nextToken())
}
return result
} | go | func (l *lexerContext) split() []token {
result := make([]token, 0, 16)
for !l.finished() {
result = append(result, l.nextToken())
}
return result
} | [
"func",
"(",
"l",
"*",
"lexerContext",
")",
"split",
"(",
")",
"[",
"]",
"token",
"{",
"result",
":=",
"make",
"(",
"[",
"]",
"token",
",",
"0",
",",
"16",
")",
"\n",
"for",
"!",
"l",
".",
"finished",
"(",
")",
"{",
"result",
"=",
"append",
"(",
"result",
",",
"l",
".",
"nextToken",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"result",
"\n",
"}"
] | // split splits the Lexer's string into a slice of Tokens. | [
"split",
"splits",
"the",
"Lexer",
"s",
"string",
"into",
"a",
"slice",
"of",
"Tokens",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/flag/nestedflagset/lexer.go#L85-L91 |
9,161 | luci/luci-go | gce/api/config/v1/vm.go | SetZone | func (v *VM) SetZone(zone string) {
for _, disk := range v.GetDisk() {
disk.Type = strings.Replace(disk.Type, "{{.Zone}}", zone, -1)
}
v.MachineType = strings.Replace(v.GetMachineType(), "{{.Zone}}", zone, -1)
v.Zone = zone
} | go | func (v *VM) SetZone(zone string) {
for _, disk := range v.GetDisk() {
disk.Type = strings.Replace(disk.Type, "{{.Zone}}", zone, -1)
}
v.MachineType = strings.Replace(v.GetMachineType(), "{{.Zone}}", zone, -1)
v.Zone = zone
} | [
"func",
"(",
"v",
"*",
"VM",
")",
"SetZone",
"(",
"zone",
"string",
")",
"{",
"for",
"_",
",",
"disk",
":=",
"range",
"v",
".",
"GetDisk",
"(",
")",
"{",
"disk",
".",
"Type",
"=",
"strings",
".",
"Replace",
"(",
"disk",
".",
"Type",
",",
"\"",
"\"",
",",
"zone",
",",
"-",
"1",
")",
"\n",
"}",
"\n",
"v",
".",
"MachineType",
"=",
"strings",
".",
"Replace",
"(",
"v",
".",
"GetMachineType",
"(",
")",
",",
"\"",
"\"",
",",
"zone",
",",
"-",
"1",
")",
"\n",
"v",
".",
"Zone",
"=",
"zone",
"\n",
"}"
] | // SetZone sets the given zone throughout this VM. | [
"SetZone",
"sets",
"the",
"given",
"zone",
"throughout",
"this",
"VM",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/api/config/v1/vm.go#L43-L49 |
9,162 | luci/luci-go | gce/api/config/v1/vm.go | Validate | func (v *VM) Validate(c *validation.Context) {
if len(v.GetDisk()) == 0 {
c.Errorf("at least one disk is required")
}
if v.GetMachineType() == "" {
c.Errorf("machine type is required")
}
for i, meta := range v.GetMetadata() {
c.Enter("metadata %d", i)
// Implicitly rejects FromFile.
// FromFile must be converted to FromText before calling.
if !strings.Contains(meta.GetFromText(), ":") {
c.Errorf("metadata from text must be in key:value form")
}
c.Exit()
}
if len(v.GetNetworkInterface()) == 0 {
c.Errorf("at least one network interface is required")
}
if v.GetProject() == "" {
c.Errorf("project is required")
}
if v.GetZone() == "" {
c.Errorf("zone is required")
}
} | go | func (v *VM) Validate(c *validation.Context) {
if len(v.GetDisk()) == 0 {
c.Errorf("at least one disk is required")
}
if v.GetMachineType() == "" {
c.Errorf("machine type is required")
}
for i, meta := range v.GetMetadata() {
c.Enter("metadata %d", i)
// Implicitly rejects FromFile.
// FromFile must be converted to FromText before calling.
if !strings.Contains(meta.GetFromText(), ":") {
c.Errorf("metadata from text must be in key:value form")
}
c.Exit()
}
if len(v.GetNetworkInterface()) == 0 {
c.Errorf("at least one network interface is required")
}
if v.GetProject() == "" {
c.Errorf("project is required")
}
if v.GetZone() == "" {
c.Errorf("zone is required")
}
} | [
"func",
"(",
"v",
"*",
"VM",
")",
"Validate",
"(",
"c",
"*",
"validation",
".",
"Context",
")",
"{",
"if",
"len",
"(",
"v",
".",
"GetDisk",
"(",
")",
")",
"==",
"0",
"{",
"c",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"v",
".",
"GetMachineType",
"(",
")",
"==",
"\"",
"\"",
"{",
"c",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"i",
",",
"meta",
":=",
"range",
"v",
".",
"GetMetadata",
"(",
")",
"{",
"c",
".",
"Enter",
"(",
"\"",
"\"",
",",
"i",
")",
"\n",
"// Implicitly rejects FromFile.",
"// FromFile must be converted to FromText before calling.",
"if",
"!",
"strings",
".",
"Contains",
"(",
"meta",
".",
"GetFromText",
"(",
")",
",",
"\"",
"\"",
")",
"{",
"c",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"c",
".",
"Exit",
"(",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"v",
".",
"GetNetworkInterface",
"(",
")",
")",
"==",
"0",
"{",
"c",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"v",
".",
"GetProject",
"(",
")",
"==",
"\"",
"\"",
"{",
"c",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"v",
".",
"GetZone",
"(",
")",
"==",
"\"",
"\"",
"{",
"c",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}"
] | // Validate validates this VM description.
// Metadata FromFile must already be converted to FromText. | [
"Validate",
"validates",
"this",
"VM",
"description",
".",
"Metadata",
"FromFile",
"must",
"already",
"be",
"converted",
"to",
"FromText",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/gce/api/config/v1/vm.go#L53-L78 |
9,163 | luci/luci-go | common/isolated/isolated.go | BasicFile | func BasicFile(d HexDigest, mode int, size int64) File {
return File{
Digest: d,
Mode: &mode,
Size: &size,
}
} | go | func BasicFile(d HexDigest, mode int, size int64) File {
return File{
Digest: d,
Mode: &mode,
Size: &size,
}
} | [
"func",
"BasicFile",
"(",
"d",
"HexDigest",
",",
"mode",
"int",
",",
"size",
"int64",
")",
"File",
"{",
"return",
"File",
"{",
"Digest",
":",
"d",
",",
"Mode",
":",
"&",
"mode",
",",
"Size",
":",
"&",
"size",
",",
"}",
"\n",
"}"
] | // BasicFile returns a File populated for a basic file. | [
"BasicFile",
"returns",
"a",
"File",
"populated",
"for",
"a",
"basic",
"file",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/isolated/isolated.go#L68-L74 |
9,164 | luci/luci-go | common/isolated/isolated.go | TarFile | func TarFile(d HexDigest, size int64) File {
return File{
Digest: d,
Size: &size,
Type: TarArchive,
}
} | go | func TarFile(d HexDigest, size int64) File {
return File{
Digest: d,
Size: &size,
Type: TarArchive,
}
} | [
"func",
"TarFile",
"(",
"d",
"HexDigest",
",",
"size",
"int64",
")",
"File",
"{",
"return",
"File",
"{",
"Digest",
":",
"d",
",",
"Size",
":",
"&",
"size",
",",
"Type",
":",
"TarArchive",
",",
"}",
"\n",
"}"
] | // TarFile returns a file populated for a tar archive file. | [
"TarFile",
"returns",
"a",
"file",
"populated",
"for",
"a",
"tar",
"archive",
"file",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/isolated/isolated.go#L84-L90 |
9,165 | luci/luci-go | common/isolated/isolated.go | New | func New(h crypto.Hash) *Isolated {
a := ""
switch h {
case crypto.SHA1:
a = "sha-1"
case crypto.SHA256:
a = "sha-256"
case crypto.SHA512:
a = "sha-512"
}
return &Isolated{
Algo: a,
Version: IsolatedFormatVersion,
Files: map[string]File{},
}
} | go | func New(h crypto.Hash) *Isolated {
a := ""
switch h {
case crypto.SHA1:
a = "sha-1"
case crypto.SHA256:
a = "sha-256"
case crypto.SHA512:
a = "sha-512"
}
return &Isolated{
Algo: a,
Version: IsolatedFormatVersion,
Files: map[string]File{},
}
} | [
"func",
"New",
"(",
"h",
"crypto",
".",
"Hash",
")",
"*",
"Isolated",
"{",
"a",
":=",
"\"",
"\"",
"\n",
"switch",
"h",
"{",
"case",
"crypto",
".",
"SHA1",
":",
"a",
"=",
"\"",
"\"",
"\n",
"case",
"crypto",
".",
"SHA256",
":",
"a",
"=",
"\"",
"\"",
"\n",
"case",
"crypto",
".",
"SHA512",
":",
"a",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"&",
"Isolated",
"{",
"Algo",
":",
"a",
",",
"Version",
":",
"IsolatedFormatVersion",
",",
"Files",
":",
"map",
"[",
"string",
"]",
"File",
"{",
"}",
",",
"}",
"\n",
"}"
] | // New returns a new Isolated with the default Algo and Version. | [
"New",
"returns",
"a",
"new",
"Isolated",
"with",
"the",
"default",
"Algo",
"and",
"Version",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/isolated/isolated.go#L104-L119 |
9,166 | luci/luci-go | cipd/client/cipd/storage.go | getNextOffset | func (s *storageImpl) getNextOffset(ctx context.Context, url string, length int64) (offset int64, err error) {
r, err := http.NewRequest("PUT", url, nil)
if err != nil {
return
}
r.Header.Set("Content-Range", fmt.Sprintf("bytes */%d", length))
r.Header.Set("Content-Length", "0")
r.Header.Set("User-Agent", s.userAgent)
resp, err := ctxhttp.Do(ctx, s.client, r)
if err != nil {
if isTemporaryNetError(err) {
err = errTransientError
}
return
}
resp.Body.Close()
if resp.StatusCode == 200 {
// Fully uploaded.
offset = length
} else if resp.StatusCode == 308 {
// Partially uploaded, extract last uploaded offset from Range header.
rangeHeader := resp.Header.Get("Range")
if rangeHeader != "" {
_, err = fmt.Sscanf(rangeHeader, "bytes=0-%d", &offset)
if err == nil {
// |offset| is an *offset* of a last uploaded byte, not the data length.
offset++
}
}
} else if isTemporaryHTTPError(resp.StatusCode) {
err = errTransientError
} else {
err = fmt.Errorf("unexpected response (HTTP %d) when querying for uploaded offset", resp.StatusCode)
}
return
} | go | func (s *storageImpl) getNextOffset(ctx context.Context, url string, length int64) (offset int64, err error) {
r, err := http.NewRequest("PUT", url, nil)
if err != nil {
return
}
r.Header.Set("Content-Range", fmt.Sprintf("bytes */%d", length))
r.Header.Set("Content-Length", "0")
r.Header.Set("User-Agent", s.userAgent)
resp, err := ctxhttp.Do(ctx, s.client, r)
if err != nil {
if isTemporaryNetError(err) {
err = errTransientError
}
return
}
resp.Body.Close()
if resp.StatusCode == 200 {
// Fully uploaded.
offset = length
} else if resp.StatusCode == 308 {
// Partially uploaded, extract last uploaded offset from Range header.
rangeHeader := resp.Header.Get("Range")
if rangeHeader != "" {
_, err = fmt.Sscanf(rangeHeader, "bytes=0-%d", &offset)
if err == nil {
// |offset| is an *offset* of a last uploaded byte, not the data length.
offset++
}
}
} else if isTemporaryHTTPError(resp.StatusCode) {
err = errTransientError
} else {
err = fmt.Errorf("unexpected response (HTTP %d) when querying for uploaded offset", resp.StatusCode)
}
return
} | [
"func",
"(",
"s",
"*",
"storageImpl",
")",
"getNextOffset",
"(",
"ctx",
"context",
".",
"Context",
",",
"url",
"string",
",",
"length",
"int64",
")",
"(",
"offset",
"int64",
",",
"err",
"error",
")",
"{",
"r",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"\"",
"\"",
",",
"url",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"r",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"length",
")",
")",
"\n",
"r",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"r",
".",
"Header",
".",
"Set",
"(",
"\"",
"\"",
",",
"s",
".",
"userAgent",
")",
"\n",
"resp",
",",
"err",
":=",
"ctxhttp",
".",
"Do",
"(",
"ctx",
",",
"s",
".",
"client",
",",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"isTemporaryNetError",
"(",
"err",
")",
"{",
"err",
"=",
"errTransientError",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n\n",
"if",
"resp",
".",
"StatusCode",
"==",
"200",
"{",
"// Fully uploaded.",
"offset",
"=",
"length",
"\n",
"}",
"else",
"if",
"resp",
".",
"StatusCode",
"==",
"308",
"{",
"// Partially uploaded, extract last uploaded offset from Range header.",
"rangeHeader",
":=",
"resp",
".",
"Header",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"if",
"rangeHeader",
"!=",
"\"",
"\"",
"{",
"_",
",",
"err",
"=",
"fmt",
".",
"Sscanf",
"(",
"rangeHeader",
",",
"\"",
"\"",
",",
"&",
"offset",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"// |offset| is an *offset* of a last uploaded byte, not the data length.",
"offset",
"++",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"if",
"isTemporaryHTTPError",
"(",
"resp",
".",
"StatusCode",
")",
"{",
"err",
"=",
"errTransientError",
"\n",
"}",
"else",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"resp",
".",
"StatusCode",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // getNextOffset queries the storage for size of persisted data. | [
"getNextOffset",
"queries",
"the",
"storage",
"for",
"size",
"of",
"persisted",
"data",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/storage.go#L197-L233 |
9,167 | luci/luci-go | config/server/cfgclient/backend/backend.go | WithBackend | func WithBackend(c context.Context, b B) context.Context {
return WithFactory(c, func(context.Context) B { return b })
} | go | func WithBackend(c context.Context, b B) context.Context {
return WithFactory(c, func(context.Context) B { return b })
} | [
"func",
"WithBackend",
"(",
"c",
"context",
".",
"Context",
",",
"b",
"B",
")",
"context",
".",
"Context",
"{",
"return",
"WithFactory",
"(",
"c",
",",
"func",
"(",
"context",
".",
"Context",
")",
"B",
"{",
"return",
"b",
"}",
")",
"\n",
"}"
] | // WithBackend returns a derivative Context with the supplied Backend installed. | [
"WithBackend",
"returns",
"a",
"derivative",
"Context",
"with",
"the",
"supplied",
"Backend",
"installed",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/backend/backend.go#L59-L61 |
9,168 | luci/luci-go | config/server/cfgclient/backend/backend.go | WithFactory | func WithFactory(c context.Context, f Factory) context.Context {
return context.WithValue(c, &configBackendKey, f)
} | go | func WithFactory(c context.Context, f Factory) context.Context {
return context.WithValue(c, &configBackendKey, f)
} | [
"func",
"WithFactory",
"(",
"c",
"context",
".",
"Context",
",",
"f",
"Factory",
")",
"context",
".",
"Context",
"{",
"return",
"context",
".",
"WithValue",
"(",
"c",
",",
"&",
"configBackendKey",
",",
"f",
")",
"\n",
"}"
] | // WithFactory returns a derivative Context with the supplied BackendFactory
// installed. | [
"WithFactory",
"returns",
"a",
"derivative",
"Context",
"with",
"the",
"supplied",
"BackendFactory",
"installed",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/backend/backend.go#L65-L67 |
9,169 | luci/luci-go | config/server/cfgclient/backend/backend.go | Get | func Get(c context.Context) B {
if f, ok := c.Value(&configBackendKey).(Factory); ok {
return f(c)
}
panic("no Backend factory is installed in the Context")
} | go | func Get(c context.Context) B {
if f, ok := c.Value(&configBackendKey).(Factory); ok {
return f(c)
}
panic("no Backend factory is installed in the Context")
} | [
"func",
"Get",
"(",
"c",
"context",
".",
"Context",
")",
"B",
"{",
"if",
"f",
",",
"ok",
":=",
"c",
".",
"Value",
"(",
"&",
"configBackendKey",
")",
".",
"(",
"Factory",
")",
";",
"ok",
"{",
"return",
"f",
"(",
"c",
")",
"\n",
"}",
"\n",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // Get returns the Backend that is installed into the Context.
//
// If no Backend is installed in the Context, Get will panic. | [
"Get",
"returns",
"the",
"Backend",
"that",
"is",
"installed",
"into",
"the",
"Context",
".",
"If",
"no",
"Backend",
"is",
"installed",
"in",
"the",
"Context",
"Get",
"will",
"panic",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/backend/backend.go#L72-L77 |
9,170 | luci/luci-go | logdog/common/archive/archive.go | Archive | func Archive(m Manifest) error {
// Wrap our log source in a safeLogEntrySource to protect our index order.
m.Source = &safeLogEntrySource{
Manifest: &m,
Source: m.Source,
}
// If no constraints are applied, index every LogEntry.
if m.StreamIndexRange <= 0 && m.PrefixIndexRange <= 0 && m.ByteRange <= 0 {
m.StreamIndexRange = 1
}
// If we're constructing an index, allocate a stateful index builder.
var idx *indexBuilder
if m.IndexWriter != nil {
idx = &indexBuilder{
Manifest: &m,
index: logpb.LogIndex{
Desc: m.Desc,
},
sizeFunc: m.sizeFunc,
}
}
err := parallel.FanOutIn(func(taskC chan<- func() error) {
var logC chan *logpb.LogEntry
if m.LogWriter != nil {
logC = make(chan *logpb.LogEntry)
taskC <- func() error {
if err := archiveLogs(m.LogWriter, m.Desc, logC, idx); err != nil {
return err
}
// If we're building an index, emit it now that the log stream has
// finished.
if idx != nil {
return idx.emit(m.IndexWriter)
}
return nil
}
}
var dataC chan *logpb.LogEntry
if m.DataWriter != nil {
dataC = make(chan *logpb.LogEntry)
taskC <- func() error {
return archiveData(m.DataWriter, dataC)
}
}
// Iterate through all of our Source's logs and process them.
taskC <- func() error {
if logC != nil {
defer close(logC)
}
if dataC != nil {
defer close(dataC)
}
sendLog := func(le *logpb.LogEntry) {
if logC != nil {
logC <- le
}
if dataC != nil {
dataC <- le
}
}
for {
le, err := m.Source.NextLogEntry()
if le != nil {
sendLog(le)
}
if err != nil {
if err == io.EOF {
return nil
}
return err
}
}
}
})
return err
} | go | func Archive(m Manifest) error {
// Wrap our log source in a safeLogEntrySource to protect our index order.
m.Source = &safeLogEntrySource{
Manifest: &m,
Source: m.Source,
}
// If no constraints are applied, index every LogEntry.
if m.StreamIndexRange <= 0 && m.PrefixIndexRange <= 0 && m.ByteRange <= 0 {
m.StreamIndexRange = 1
}
// If we're constructing an index, allocate a stateful index builder.
var idx *indexBuilder
if m.IndexWriter != nil {
idx = &indexBuilder{
Manifest: &m,
index: logpb.LogIndex{
Desc: m.Desc,
},
sizeFunc: m.sizeFunc,
}
}
err := parallel.FanOutIn(func(taskC chan<- func() error) {
var logC chan *logpb.LogEntry
if m.LogWriter != nil {
logC = make(chan *logpb.LogEntry)
taskC <- func() error {
if err := archiveLogs(m.LogWriter, m.Desc, logC, idx); err != nil {
return err
}
// If we're building an index, emit it now that the log stream has
// finished.
if idx != nil {
return idx.emit(m.IndexWriter)
}
return nil
}
}
var dataC chan *logpb.LogEntry
if m.DataWriter != nil {
dataC = make(chan *logpb.LogEntry)
taskC <- func() error {
return archiveData(m.DataWriter, dataC)
}
}
// Iterate through all of our Source's logs and process them.
taskC <- func() error {
if logC != nil {
defer close(logC)
}
if dataC != nil {
defer close(dataC)
}
sendLog := func(le *logpb.LogEntry) {
if logC != nil {
logC <- le
}
if dataC != nil {
dataC <- le
}
}
for {
le, err := m.Source.NextLogEntry()
if le != nil {
sendLog(le)
}
if err != nil {
if err == io.EOF {
return nil
}
return err
}
}
}
})
return err
} | [
"func",
"Archive",
"(",
"m",
"Manifest",
")",
"error",
"{",
"// Wrap our log source in a safeLogEntrySource to protect our index order.",
"m",
".",
"Source",
"=",
"&",
"safeLogEntrySource",
"{",
"Manifest",
":",
"&",
"m",
",",
"Source",
":",
"m",
".",
"Source",
",",
"}",
"\n\n",
"// If no constraints are applied, index every LogEntry.",
"if",
"m",
".",
"StreamIndexRange",
"<=",
"0",
"&&",
"m",
".",
"PrefixIndexRange",
"<=",
"0",
"&&",
"m",
".",
"ByteRange",
"<=",
"0",
"{",
"m",
".",
"StreamIndexRange",
"=",
"1",
"\n",
"}",
"\n\n",
"// If we're constructing an index, allocate a stateful index builder.",
"var",
"idx",
"*",
"indexBuilder",
"\n",
"if",
"m",
".",
"IndexWriter",
"!=",
"nil",
"{",
"idx",
"=",
"&",
"indexBuilder",
"{",
"Manifest",
":",
"&",
"m",
",",
"index",
":",
"logpb",
".",
"LogIndex",
"{",
"Desc",
":",
"m",
".",
"Desc",
",",
"}",
",",
"sizeFunc",
":",
"m",
".",
"sizeFunc",
",",
"}",
"\n",
"}",
"\n\n",
"err",
":=",
"parallel",
".",
"FanOutIn",
"(",
"func",
"(",
"taskC",
"chan",
"<-",
"func",
"(",
")",
"error",
")",
"{",
"var",
"logC",
"chan",
"*",
"logpb",
".",
"LogEntry",
"\n",
"if",
"m",
".",
"LogWriter",
"!=",
"nil",
"{",
"logC",
"=",
"make",
"(",
"chan",
"*",
"logpb",
".",
"LogEntry",
")",
"\n\n",
"taskC",
"<-",
"func",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"archiveLogs",
"(",
"m",
".",
"LogWriter",
",",
"m",
".",
"Desc",
",",
"logC",
",",
"idx",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// If we're building an index, emit it now that the log stream has",
"// finished.",
"if",
"idx",
"!=",
"nil",
"{",
"return",
"idx",
".",
"emit",
"(",
"m",
".",
"IndexWriter",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"var",
"dataC",
"chan",
"*",
"logpb",
".",
"LogEntry",
"\n",
"if",
"m",
".",
"DataWriter",
"!=",
"nil",
"{",
"dataC",
"=",
"make",
"(",
"chan",
"*",
"logpb",
".",
"LogEntry",
")",
"\n\n",
"taskC",
"<-",
"func",
"(",
")",
"error",
"{",
"return",
"archiveData",
"(",
"m",
".",
"DataWriter",
",",
"dataC",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Iterate through all of our Source's logs and process them.",
"taskC",
"<-",
"func",
"(",
")",
"error",
"{",
"if",
"logC",
"!=",
"nil",
"{",
"defer",
"close",
"(",
"logC",
")",
"\n",
"}",
"\n",
"if",
"dataC",
"!=",
"nil",
"{",
"defer",
"close",
"(",
"dataC",
")",
"\n",
"}",
"\n\n",
"sendLog",
":=",
"func",
"(",
"le",
"*",
"logpb",
".",
"LogEntry",
")",
"{",
"if",
"logC",
"!=",
"nil",
"{",
"logC",
"<-",
"le",
"\n",
"}",
"\n",
"if",
"dataC",
"!=",
"nil",
"{",
"dataC",
"<-",
"le",
"\n",
"}",
"\n",
"}",
"\n\n",
"for",
"{",
"le",
",",
"err",
":=",
"m",
".",
"Source",
".",
"NextLogEntry",
"(",
")",
"\n",
"if",
"le",
"!=",
"nil",
"{",
"sendLog",
"(",
"le",
")",
"\n",
"}",
"\n\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"io",
".",
"EOF",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"return",
"err",
"\n",
"}",
"\n\n",
"}",
"\n",
"}",
"\n",
"}",
")",
"\n\n",
"return",
"err",
"\n",
"}"
] | // Archive performs the log archival described in the supplied Manifest. | [
"Archive",
"performs",
"the",
"log",
"archival",
"described",
"in",
"the",
"supplied",
"Manifest",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/archive/archive.go#L76-L165 |
9,171 | luci/luci-go | cipd/appengine/impl/repo/processing/reader.go | NewPackageReader | func NewPackageReader(r io.ReaderAt, size int64) (*PackageReader, error) {
zr, err := zip.NewReader(r, size)
if err != nil {
// Note: we rely here (and in other places where we return errors) on
// zip.Reader NOT wrapping errors from 'r', so they inherit transient tags
// in case of transient Google Storage errors.
return nil, err
}
return &PackageReader{zr}, nil
} | go | func NewPackageReader(r io.ReaderAt, size int64) (*PackageReader, error) {
zr, err := zip.NewReader(r, size)
if err != nil {
// Note: we rely here (and in other places where we return errors) on
// zip.Reader NOT wrapping errors from 'r', so they inherit transient tags
// in case of transient Google Storage errors.
return nil, err
}
return &PackageReader{zr}, nil
} | [
"func",
"NewPackageReader",
"(",
"r",
"io",
".",
"ReaderAt",
",",
"size",
"int64",
")",
"(",
"*",
"PackageReader",
",",
"error",
")",
"{",
"zr",
",",
"err",
":=",
"zip",
".",
"NewReader",
"(",
"r",
",",
"size",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Note: we rely here (and in other places where we return errors) on",
"// zip.Reader NOT wrapping errors from 'r', so they inherit transient tags",
"// in case of transient Google Storage errors.",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"PackageReader",
"{",
"zr",
"}",
",",
"nil",
"\n",
"}"
] | // NewPackageReader opens the package by reading its directory. | [
"NewPackageReader",
"opens",
"the",
"package",
"by",
"reading",
"its",
"directory",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/processing/reader.go#L36-L45 |
9,172 | luci/luci-go | cipd/appengine/impl/repo/processing/reader.go | Open | func (p *PackageReader) Open(path string) (io.ReadCloser, int64, error) {
for _, f := range p.zr.File {
if f.Name == path {
if f.UncompressedSize64 > math.MaxInt64 {
return nil, 0, errors.Reason("the file %q is unbelievably huge (%d bytes)", path, f.UncompressedSize64).Err()
}
rc, err := f.Open()
if err != nil {
return nil, 0, err
}
return rc, int64(f.UncompressedSize64), nil
}
}
return nil, 0, errors.Reason("no file %q inside the package", path).Err()
} | go | func (p *PackageReader) Open(path string) (io.ReadCloser, int64, error) {
for _, f := range p.zr.File {
if f.Name == path {
if f.UncompressedSize64 > math.MaxInt64 {
return nil, 0, errors.Reason("the file %q is unbelievably huge (%d bytes)", path, f.UncompressedSize64).Err()
}
rc, err := f.Open()
if err != nil {
return nil, 0, err
}
return rc, int64(f.UncompressedSize64), nil
}
}
return nil, 0, errors.Reason("no file %q inside the package", path).Err()
} | [
"func",
"(",
"p",
"*",
"PackageReader",
")",
"Open",
"(",
"path",
"string",
")",
"(",
"io",
".",
"ReadCloser",
",",
"int64",
",",
"error",
")",
"{",
"for",
"_",
",",
"f",
":=",
"range",
"p",
".",
"zr",
".",
"File",
"{",
"if",
"f",
".",
"Name",
"==",
"path",
"{",
"if",
"f",
".",
"UncompressedSize64",
">",
"math",
".",
"MaxInt64",
"{",
"return",
"nil",
",",
"0",
",",
"errors",
".",
"Reason",
"(",
"\"",
"\"",
",",
"path",
",",
"f",
".",
"UncompressedSize64",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"rc",
",",
"err",
":=",
"f",
".",
"Open",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"0",
",",
"err",
"\n",
"}",
"\n",
"return",
"rc",
",",
"int64",
"(",
"f",
".",
"UncompressedSize64",
")",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"0",
",",
"errors",
".",
"Reason",
"(",
"\"",
"\"",
",",
"path",
")",
".",
"Err",
"(",
")",
"\n",
"}"
] | // Open opens some file inside the package for reading.
//
// Returns the ReadCloser and the uncompressed file size. | [
"Open",
"opens",
"some",
"file",
"inside",
"the",
"package",
"for",
"reading",
".",
"Returns",
"the",
"ReadCloser",
"and",
"the",
"uncompressed",
"file",
"size",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/appengine/impl/repo/processing/reader.go#L50-L64 |
9,173 | luci/luci-go | common/system/filesystem/filesystem.go | MakeDirs | func MakeDirs(path string) error {
if err := os.MkdirAll(path, 0755); err != nil {
return errors.Annotate(err, "").Err()
}
return nil
} | go | func MakeDirs(path string) error {
if err := os.MkdirAll(path, 0755); err != nil {
return errors.Annotate(err, "").Err()
}
return nil
} | [
"func",
"MakeDirs",
"(",
"path",
"string",
")",
"error",
"{",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"path",
",",
"0755",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // MakeDirs is a convenience wrapper around os.MkdirAll that applies a 0755
// mask to all created directories. | [
"MakeDirs",
"is",
"a",
"convenience",
"wrapper",
"around",
"os",
".",
"MkdirAll",
"that",
"applies",
"a",
"0755",
"mask",
"to",
"all",
"created",
"directories",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/system/filesystem/filesystem.go#L33-L38 |
9,174 | luci/luci-go | common/system/filesystem/filesystem.go | AbsPath | func AbsPath(base *string) error {
v, err := filepath.Abs(*base)
if err != nil {
return errors.Annotate(err, "unable to resolve absolute path").
InternalReason("base(%q)", *base).Err()
}
*base = v
return nil
} | go | func AbsPath(base *string) error {
v, err := filepath.Abs(*base)
if err != nil {
return errors.Annotate(err, "unable to resolve absolute path").
InternalReason("base(%q)", *base).Err()
}
*base = v
return nil
} | [
"func",
"AbsPath",
"(",
"base",
"*",
"string",
")",
"error",
"{",
"v",
",",
"err",
":=",
"filepath",
".",
"Abs",
"(",
"*",
"base",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"InternalReason",
"(",
"\"",
"\"",
",",
"*",
"base",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"*",
"base",
"=",
"v",
"\n",
"return",
"nil",
"\n",
"}"
] | // AbsPath is a convenience wrapper around filepath.Abs that accepts a string
// pointer, base, and updates it on successful resolution. | [
"AbsPath",
"is",
"a",
"convenience",
"wrapper",
"around",
"filepath",
".",
"Abs",
"that",
"accepts",
"a",
"string",
"pointer",
"base",
"and",
"updates",
"it",
"on",
"successful",
"resolution",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/system/filesystem/filesystem.go#L42-L50 |
9,175 | luci/luci-go | common/system/filesystem/filesystem.go | Touch | func Touch(path string, when time.Time, mode os.FileMode) error {
// Try and create a file at the target path.
fd, err := os.OpenFile(path, (os.O_CREATE | os.O_RDWR), mode)
if err == nil {
if err := fd.Close(); err != nil {
return errors.Annotate(err, "failed to close new file").Err()
}
if when.IsZero() {
// If "now" was specified, and we created a new file, then its times will
// be now by default.
return nil
}
}
// Couldn't create a new file. Either it exists already, it is a directory,
// or there was an OS-level failure. Since we can't really distinguish
// between these cases, try opening for write (update timestamp) and error
// if this fails.
if when.IsZero() {
when = time.Now()
}
if err := os.Chtimes(path, when, when); err != nil {
return errors.Annotate(err, "failed to Chtimes").InternalReason("path(%q)", path).Err()
}
return nil
} | go | func Touch(path string, when time.Time, mode os.FileMode) error {
// Try and create a file at the target path.
fd, err := os.OpenFile(path, (os.O_CREATE | os.O_RDWR), mode)
if err == nil {
if err := fd.Close(); err != nil {
return errors.Annotate(err, "failed to close new file").Err()
}
if when.IsZero() {
// If "now" was specified, and we created a new file, then its times will
// be now by default.
return nil
}
}
// Couldn't create a new file. Either it exists already, it is a directory,
// or there was an OS-level failure. Since we can't really distinguish
// between these cases, try opening for write (update timestamp) and error
// if this fails.
if when.IsZero() {
when = time.Now()
}
if err := os.Chtimes(path, when, when); err != nil {
return errors.Annotate(err, "failed to Chtimes").InternalReason("path(%q)", path).Err()
}
return nil
} | [
"func",
"Touch",
"(",
"path",
"string",
",",
"when",
"time",
".",
"Time",
",",
"mode",
"os",
".",
"FileMode",
")",
"error",
"{",
"// Try and create a file at the target path.",
"fd",
",",
"err",
":=",
"os",
".",
"OpenFile",
"(",
"path",
",",
"(",
"os",
".",
"O_CREATE",
"|",
"os",
".",
"O_RDWR",
")",
",",
"mode",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"if",
"err",
":=",
"fd",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"if",
"when",
".",
"IsZero",
"(",
")",
"{",
"// If \"now\" was specified, and we created a new file, then its times will",
"// be now by default.",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Couldn't create a new file. Either it exists already, it is a directory,",
"// or there was an OS-level failure. Since we can't really distinguish",
"// between these cases, try opening for write (update timestamp) and error",
"// if this fails.",
"if",
"when",
".",
"IsZero",
"(",
")",
"{",
"when",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"os",
".",
"Chtimes",
"(",
"path",
",",
"when",
",",
"when",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"InternalReason",
"(",
"\"",
"\"",
",",
"path",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // Touch creates a new, empty file at the specified path.
//
// If when is zero-value, time.Now will be used. | [
"Touch",
"creates",
"a",
"new",
"empty",
"file",
"at",
"the",
"specified",
"path",
".",
"If",
"when",
"is",
"zero",
"-",
"value",
"time",
".",
"Now",
"will",
"be",
"used",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/system/filesystem/filesystem.go#L55-L81 |
9,176 | luci/luci-go | common/system/filesystem/filesystem.go | MakeReadOnly | func MakeReadOnly(path string, filter func(string) bool) error {
return recursiveChmod(path, filter, func(mode os.FileMode) os.FileMode {
return mode & (^os.FileMode(0222))
})
} | go | func MakeReadOnly(path string, filter func(string) bool) error {
return recursiveChmod(path, filter, func(mode os.FileMode) os.FileMode {
return mode & (^os.FileMode(0222))
})
} | [
"func",
"MakeReadOnly",
"(",
"path",
"string",
",",
"filter",
"func",
"(",
"string",
")",
"bool",
")",
"error",
"{",
"return",
"recursiveChmod",
"(",
"path",
",",
"filter",
",",
"func",
"(",
"mode",
"os",
".",
"FileMode",
")",
"os",
".",
"FileMode",
"{",
"return",
"mode",
"&",
"(",
"^",
"os",
".",
"FileMode",
"(",
"0222",
")",
")",
"\n",
"}",
")",
"\n",
"}"
] | // MakeReadOnly recursively iterates through all of the files and directories
// starting at path and marks them read-only. | [
"MakeReadOnly",
"recursively",
"iterates",
"through",
"all",
"of",
"the",
"files",
"and",
"directories",
"starting",
"at",
"path",
"and",
"marks",
"them",
"read",
"-",
"only",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/system/filesystem/filesystem.go#L177-L181 |
9,177 | luci/luci-go | common/system/filesystem/filesystem.go | MakePathUserWritable | func MakePathUserWritable(path string, fi os.FileInfo) error {
if fi == nil {
var err error
if fi, err = os.Stat(path); err != nil {
return errors.Annotate(err, "failed to Stat path").InternalReason("path(%q)", path).Err()
}
}
// Make user-writable, if it's not already.
mode := fi.Mode()
if (mode & 0200) == 0 {
mode |= 0200
if err := os.Chmod(path, mode); err != nil {
return errors.Annotate(err, "could not Chmod path").InternalReason("mode(%#o)/path(%q)", mode, path).Err()
}
}
return nil
} | go | func MakePathUserWritable(path string, fi os.FileInfo) error {
if fi == nil {
var err error
if fi, err = os.Stat(path); err != nil {
return errors.Annotate(err, "failed to Stat path").InternalReason("path(%q)", path).Err()
}
}
// Make user-writable, if it's not already.
mode := fi.Mode()
if (mode & 0200) == 0 {
mode |= 0200
if err := os.Chmod(path, mode); err != nil {
return errors.Annotate(err, "could not Chmod path").InternalReason("mode(%#o)/path(%q)", mode, path).Err()
}
}
return nil
} | [
"func",
"MakePathUserWritable",
"(",
"path",
"string",
",",
"fi",
"os",
".",
"FileInfo",
")",
"error",
"{",
"if",
"fi",
"==",
"nil",
"{",
"var",
"err",
"error",
"\n",
"if",
"fi",
",",
"err",
"=",
"os",
".",
"Stat",
"(",
"path",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"InternalReason",
"(",
"\"",
"\"",
",",
"path",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Make user-writable, if it's not already.",
"mode",
":=",
"fi",
".",
"Mode",
"(",
")",
"\n",
"if",
"(",
"mode",
"&",
"0200",
")",
"==",
"0",
"{",
"mode",
"|=",
"0200",
"\n",
"if",
"err",
":=",
"os",
".",
"Chmod",
"(",
"path",
",",
"mode",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"InternalReason",
"(",
"\"",
"\"",
",",
"mode",
",",
"path",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // MakePathUserWritable updates the filesystem metadata on a single file or
// directory to make it user-writable.
//
// fi is optional. If nil, os.Stat will be called on path. Otherwise, fi will
// be regarded as the results of calling os.Stat on path. This is provided as
// an optimization, since some filesystem operations automatically yield a
// FileInfo. | [
"MakePathUserWritable",
"updates",
"the",
"filesystem",
"metadata",
"on",
"a",
"single",
"file",
"or",
"directory",
"to",
"make",
"it",
"user",
"-",
"writable",
".",
"fi",
"is",
"optional",
".",
"If",
"nil",
"os",
".",
"Stat",
"will",
"be",
"called",
"on",
"path",
".",
"Otherwise",
"fi",
"will",
"be",
"regarded",
"as",
"the",
"results",
"of",
"calling",
"os",
".",
"Stat",
"on",
"path",
".",
"This",
"is",
"provided",
"as",
"an",
"optimization",
"since",
"some",
"filesystem",
"operations",
"automatically",
"yield",
"a",
"FileInfo",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/system/filesystem/filesystem.go#L190-L207 |
9,178 | luci/luci-go | logdog/appengine/cmd/coordinator/default/cron.go | add | func (r *queryResult) add(s *queryResult) {
r.lock.Lock()
defer r.lock.Unlock()
r.notArchived += s.notArchived
r.archiveTasked += s.archiveTasked
r.archivedPartial += s.archivedPartial
r.archivedComplete += s.archivedComplete
} | go | func (r *queryResult) add(s *queryResult) {
r.lock.Lock()
defer r.lock.Unlock()
r.notArchived += s.notArchived
r.archiveTasked += s.archiveTasked
r.archivedPartial += s.archivedPartial
r.archivedComplete += s.archivedComplete
} | [
"func",
"(",
"r",
"*",
"queryResult",
")",
"add",
"(",
"s",
"*",
"queryResult",
")",
"{",
"r",
".",
"lock",
".",
"Lock",
"(",
")",
"\n",
"defer",
"r",
".",
"lock",
".",
"Unlock",
"(",
")",
"\n",
"r",
".",
"notArchived",
"+=",
"s",
".",
"notArchived",
"\n",
"r",
".",
"archiveTasked",
"+=",
"s",
".",
"archiveTasked",
"\n",
"r",
".",
"archivedPartial",
"+=",
"s",
".",
"archivedPartial",
"\n",
"r",
".",
"archivedComplete",
"+=",
"s",
".",
"archivedComplete",
"\n",
"}"
] | // add adds the contents of s into r. This is goroutine safe. | [
"add",
"adds",
"the",
"contents",
"of",
"s",
"into",
"r",
".",
"This",
"is",
"goroutine",
"safe",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/cmd/coordinator/default/cron.go#L112-L119 |
9,179 | luci/luci-go | logdog/appengine/cmd/coordinator/default/cron.go | doShardedQueryStat | func doShardedQueryStat(c context.Context, ns string, stat queryStat) error {
results := &queryResult{}
if err := parallel.FanOutIn(func(ch chan<- func() error) {
for i := int64(0); i < totalShards; i++ {
i := i
ch <- func() error {
result, err := doQueryStat(c, ns, stat, i)
if err != nil {
return errors.Annotate(err, "while launching index %d: %s", i, result).Err()
}
logging.Infof(c, "For index %d got %s", i, result)
results.add(result)
return nil
}
}
}); err != nil {
return err
}
// Report
stat.metric.Set(c, results.notArchived, ns, "not_archived")
stat.metric.Set(c, results.archiveTasked, ns, "archive_tasked")
stat.metric.Set(c, results.archivedPartial, ns, "archived_partial")
stat.metric.Set(c, results.archivedComplete, ns, "archived_complete")
logging.Infof(c, "Stat %s Project %s stat: %s", stat.metric.Info().Name, ns, results)
return nil
} | go | func doShardedQueryStat(c context.Context, ns string, stat queryStat) error {
results := &queryResult{}
if err := parallel.FanOutIn(func(ch chan<- func() error) {
for i := int64(0); i < totalShards; i++ {
i := i
ch <- func() error {
result, err := doQueryStat(c, ns, stat, i)
if err != nil {
return errors.Annotate(err, "while launching index %d: %s", i, result).Err()
}
logging.Infof(c, "For index %d got %s", i, result)
results.add(result)
return nil
}
}
}); err != nil {
return err
}
// Report
stat.metric.Set(c, results.notArchived, ns, "not_archived")
stat.metric.Set(c, results.archiveTasked, ns, "archive_tasked")
stat.metric.Set(c, results.archivedPartial, ns, "archived_partial")
stat.metric.Set(c, results.archivedComplete, ns, "archived_complete")
logging.Infof(c, "Stat %s Project %s stat: %s", stat.metric.Info().Name, ns, results)
return nil
} | [
"func",
"doShardedQueryStat",
"(",
"c",
"context",
".",
"Context",
",",
"ns",
"string",
",",
"stat",
"queryStat",
")",
"error",
"{",
"results",
":=",
"&",
"queryResult",
"{",
"}",
"\n",
"if",
"err",
":=",
"parallel",
".",
"FanOutIn",
"(",
"func",
"(",
"ch",
"chan",
"<-",
"func",
"(",
")",
"error",
")",
"{",
"for",
"i",
":=",
"int64",
"(",
"0",
")",
";",
"i",
"<",
"totalShards",
";",
"i",
"++",
"{",
"i",
":=",
"i",
"\n",
"ch",
"<-",
"func",
"(",
")",
"error",
"{",
"result",
",",
"err",
":=",
"doQueryStat",
"(",
"c",
",",
"ns",
",",
"stat",
",",
"i",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
",",
"i",
",",
"result",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"logging",
".",
"Infof",
"(",
"c",
",",
"\"",
"\"",
",",
"i",
",",
"result",
")",
"\n",
"results",
".",
"add",
"(",
"result",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Report",
"stat",
".",
"metric",
".",
"Set",
"(",
"c",
",",
"results",
".",
"notArchived",
",",
"ns",
",",
"\"",
"\"",
")",
"\n",
"stat",
".",
"metric",
".",
"Set",
"(",
"c",
",",
"results",
".",
"archiveTasked",
",",
"ns",
",",
"\"",
"\"",
")",
"\n",
"stat",
".",
"metric",
".",
"Set",
"(",
"c",
",",
"results",
".",
"archivedPartial",
",",
"ns",
",",
"\"",
"\"",
")",
"\n",
"stat",
".",
"metric",
".",
"Set",
"(",
"c",
",",
"results",
".",
"archivedComplete",
",",
"ns",
",",
"\"",
"\"",
")",
"\n",
"logging",
".",
"Infof",
"(",
"c",
",",
"\"",
"\"",
",",
"stat",
".",
"metric",
".",
"Info",
"(",
")",
".",
"Name",
",",
"ns",
",",
"results",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // doShardedQueryStat launches a batch of queries, at different shard indices. | [
"doShardedQueryStat",
"launches",
"a",
"batch",
"of",
"queries",
"at",
"different",
"shard",
"indices",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/cmd/coordinator/default/cron.go#L126-L152 |
9,180 | luci/luci-go | logdog/appengine/cmd/coordinator/default/cron.go | doQueryStat | func doQueryStat(c context.Context, ns string, stat queryStat, index int64) (*queryResult, error) {
// We shard a large query into smaller time blocks.
shardSize := time.Duration((int64(stat.end) - int64(stat.start)) / totalShards)
startOffset := time.Duration(int64(shardSize) * index)
now := clock.Now(c)
start := now.Add(stat.start).Add(startOffset)
end := start.Add(shardSize)
// Gather stats for this namespace.
nc, cancel := context.WithTimeout(c, 5*time.Minute)
defer cancel()
// Make a projection query, it is cheaper.
q := datastore.NewQuery("LogStreamState").Gte("Created", start).Lt("Created", end)
q = q.Project(coordinator.ArchivalStateKey)
logging.Debugf(c, "Running query for %s (%s) at index %d: %v", ns, stat.metric.Info().Name, index, q)
result := &queryResult{}
return result, datastore.RunBatch(nc, 512, q, func(state *datastore.PropertyMap) error {
asRaws := state.Slice(coordinator.ArchivalStateKey)
if len(asRaws) != 1 {
logging.Errorf(c, "%v for %v has the wrong size", asRaws, state)
}
asRawProp := asRaws[0]
asRawInt, ok := asRawProp.Value().(int64)
if !ok {
logging.Errorf(c, "%v and %v are not archival states (ints)", asRawProp, asRawProp.Value())
return datastore.Stop
}
as := coordinator.ArchivalState(asRawInt)
switch as {
case coordinator.NotArchived:
result.notArchived++
case coordinator.ArchiveTasked:
result.archiveTasked++
case coordinator.ArchivedPartial:
result.archivedPartial++
case coordinator.ArchivedComplete:
result.archivedComplete++
default:
panic("impossible")
}
return nil
})
} | go | func doQueryStat(c context.Context, ns string, stat queryStat, index int64) (*queryResult, error) {
// We shard a large query into smaller time blocks.
shardSize := time.Duration((int64(stat.end) - int64(stat.start)) / totalShards)
startOffset := time.Duration(int64(shardSize) * index)
now := clock.Now(c)
start := now.Add(stat.start).Add(startOffset)
end := start.Add(shardSize)
// Gather stats for this namespace.
nc, cancel := context.WithTimeout(c, 5*time.Minute)
defer cancel()
// Make a projection query, it is cheaper.
q := datastore.NewQuery("LogStreamState").Gte("Created", start).Lt("Created", end)
q = q.Project(coordinator.ArchivalStateKey)
logging.Debugf(c, "Running query for %s (%s) at index %d: %v", ns, stat.metric.Info().Name, index, q)
result := &queryResult{}
return result, datastore.RunBatch(nc, 512, q, func(state *datastore.PropertyMap) error {
asRaws := state.Slice(coordinator.ArchivalStateKey)
if len(asRaws) != 1 {
logging.Errorf(c, "%v for %v has the wrong size", asRaws, state)
}
asRawProp := asRaws[0]
asRawInt, ok := asRawProp.Value().(int64)
if !ok {
logging.Errorf(c, "%v and %v are not archival states (ints)", asRawProp, asRawProp.Value())
return datastore.Stop
}
as := coordinator.ArchivalState(asRawInt)
switch as {
case coordinator.NotArchived:
result.notArchived++
case coordinator.ArchiveTasked:
result.archiveTasked++
case coordinator.ArchivedPartial:
result.archivedPartial++
case coordinator.ArchivedComplete:
result.archivedComplete++
default:
panic("impossible")
}
return nil
})
} | [
"func",
"doQueryStat",
"(",
"c",
"context",
".",
"Context",
",",
"ns",
"string",
",",
"stat",
"queryStat",
",",
"index",
"int64",
")",
"(",
"*",
"queryResult",
",",
"error",
")",
"{",
"// We shard a large query into smaller time blocks.",
"shardSize",
":=",
"time",
".",
"Duration",
"(",
"(",
"int64",
"(",
"stat",
".",
"end",
")",
"-",
"int64",
"(",
"stat",
".",
"start",
")",
")",
"/",
"totalShards",
")",
"\n",
"startOffset",
":=",
"time",
".",
"Duration",
"(",
"int64",
"(",
"shardSize",
")",
"*",
"index",
")",
"\n",
"now",
":=",
"clock",
".",
"Now",
"(",
"c",
")",
"\n",
"start",
":=",
"now",
".",
"Add",
"(",
"stat",
".",
"start",
")",
".",
"Add",
"(",
"startOffset",
")",
"\n",
"end",
":=",
"start",
".",
"Add",
"(",
"shardSize",
")",
"\n\n",
"// Gather stats for this namespace.",
"nc",
",",
"cancel",
":=",
"context",
".",
"WithTimeout",
"(",
"c",
",",
"5",
"*",
"time",
".",
"Minute",
")",
"\n",
"defer",
"cancel",
"(",
")",
"\n",
"// Make a projection query, it is cheaper.",
"q",
":=",
"datastore",
".",
"NewQuery",
"(",
"\"",
"\"",
")",
".",
"Gte",
"(",
"\"",
"\"",
",",
"start",
")",
".",
"Lt",
"(",
"\"",
"\"",
",",
"end",
")",
"\n",
"q",
"=",
"q",
".",
"Project",
"(",
"coordinator",
".",
"ArchivalStateKey",
")",
"\n",
"logging",
".",
"Debugf",
"(",
"c",
",",
"\"",
"\"",
",",
"ns",
",",
"stat",
".",
"metric",
".",
"Info",
"(",
")",
".",
"Name",
",",
"index",
",",
"q",
")",
"\n\n",
"result",
":=",
"&",
"queryResult",
"{",
"}",
"\n",
"return",
"result",
",",
"datastore",
".",
"RunBatch",
"(",
"nc",
",",
"512",
",",
"q",
",",
"func",
"(",
"state",
"*",
"datastore",
".",
"PropertyMap",
")",
"error",
"{",
"asRaws",
":=",
"state",
".",
"Slice",
"(",
"coordinator",
".",
"ArchivalStateKey",
")",
"\n",
"if",
"len",
"(",
"asRaws",
")",
"!=",
"1",
"{",
"logging",
".",
"Errorf",
"(",
"c",
",",
"\"",
"\"",
",",
"asRaws",
",",
"state",
")",
"\n",
"}",
"\n",
"asRawProp",
":=",
"asRaws",
"[",
"0",
"]",
"\n",
"asRawInt",
",",
"ok",
":=",
"asRawProp",
".",
"Value",
"(",
")",
".",
"(",
"int64",
")",
"\n",
"if",
"!",
"ok",
"{",
"logging",
".",
"Errorf",
"(",
"c",
",",
"\"",
"\"",
",",
"asRawProp",
",",
"asRawProp",
".",
"Value",
"(",
")",
")",
"\n",
"return",
"datastore",
".",
"Stop",
"\n",
"}",
"\n",
"as",
":=",
"coordinator",
".",
"ArchivalState",
"(",
"asRawInt",
")",
"\n\n",
"switch",
"as",
"{",
"case",
"coordinator",
".",
"NotArchived",
":",
"result",
".",
"notArchived",
"++",
"\n",
"case",
"coordinator",
".",
"ArchiveTasked",
":",
"result",
".",
"archiveTasked",
"++",
"\n",
"case",
"coordinator",
".",
"ArchivedPartial",
":",
"result",
".",
"archivedPartial",
"++",
"\n",
"case",
"coordinator",
".",
"ArchivedComplete",
":",
"result",
".",
"archivedComplete",
"++",
"\n",
"default",
":",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"}"
] | // doQueryStat runs a single query containing a time range, with a certain index. | [
"doQueryStat",
"runs",
"a",
"single",
"query",
"containing",
"a",
"time",
"range",
"with",
"a",
"certain",
"index",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/cmd/coordinator/default/cron.go#L155-L199 |
9,181 | luci/luci-go | logdog/appengine/cmd/coordinator/default/cron.go | cronStatsNSHandler | func cronStatsNSHandler(ctx *router.Context) {
s := ctx.Params.ByName("stat")
qs, ok := metrics[s]
if !ok {
ctx.Writer.WriteHeader(http.StatusNotFound)
return
}
ns := ctx.Params.ByName("namespace")
c := info.MustNamespace(ctx.Context, ns)
err := doShardedQueryStat(c, ns, qs)
if err != nil {
errors.Log(c, err)
ctx.Writer.WriteHeader(http.StatusInternalServerError)
}
} | go | func cronStatsNSHandler(ctx *router.Context) {
s := ctx.Params.ByName("stat")
qs, ok := metrics[s]
if !ok {
ctx.Writer.WriteHeader(http.StatusNotFound)
return
}
ns := ctx.Params.ByName("namespace")
c := info.MustNamespace(ctx.Context, ns)
err := doShardedQueryStat(c, ns, qs)
if err != nil {
errors.Log(c, err)
ctx.Writer.WriteHeader(http.StatusInternalServerError)
}
} | [
"func",
"cronStatsNSHandler",
"(",
"ctx",
"*",
"router",
".",
"Context",
")",
"{",
"s",
":=",
"ctx",
".",
"Params",
".",
"ByName",
"(",
"\"",
"\"",
")",
"\n",
"qs",
",",
"ok",
":=",
"metrics",
"[",
"s",
"]",
"\n",
"if",
"!",
"ok",
"{",
"ctx",
".",
"Writer",
".",
"WriteHeader",
"(",
"http",
".",
"StatusNotFound",
")",
"\n",
"return",
"\n",
"}",
"\n",
"ns",
":=",
"ctx",
".",
"Params",
".",
"ByName",
"(",
"\"",
"\"",
")",
"\n",
"c",
":=",
"info",
".",
"MustNamespace",
"(",
"ctx",
".",
"Context",
",",
"ns",
")",
"\n",
"err",
":=",
"doShardedQueryStat",
"(",
"c",
",",
"ns",
",",
"qs",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"errors",
".",
"Log",
"(",
"c",
",",
"err",
")",
"\n",
"ctx",
".",
"Writer",
".",
"WriteHeader",
"(",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"}",
"\n",
"}"
] | // cronStatsNSHandler gathers metrics about a metric and namespace within logdog. | [
"cronStatsNSHandler",
"gathers",
"metrics",
"about",
"a",
"metric",
"and",
"namespace",
"within",
"logdog",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/cmd/coordinator/default/cron.go#L202-L216 |
9,182 | luci/luci-go | machine-db/appengine/rpc/physical_hosts.go | CreatePhysicalHost | func (*Service) CreatePhysicalHost(c context.Context, req *crimson.CreatePhysicalHostRequest) (*crimson.PhysicalHost, error) {
return createPhysicalHost(c, req.Host)
} | go | func (*Service) CreatePhysicalHost(c context.Context, req *crimson.CreatePhysicalHostRequest) (*crimson.PhysicalHost, error) {
return createPhysicalHost(c, req.Host)
} | [
"func",
"(",
"*",
"Service",
")",
"CreatePhysicalHost",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"crimson",
".",
"CreatePhysicalHostRequest",
")",
"(",
"*",
"crimson",
".",
"PhysicalHost",
",",
"error",
")",
"{",
"return",
"createPhysicalHost",
"(",
"c",
",",
"req",
".",
"Host",
")",
"\n",
"}"
] | // CreatePhysicalHost handles a request to create a new physical host. | [
"CreatePhysicalHost",
"handles",
"a",
"request",
"to",
"create",
"a",
"new",
"physical",
"host",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/physical_hosts.go#L39-L41 |
9,183 | luci/luci-go | machine-db/appengine/rpc/physical_hosts.go | ListPhysicalHosts | func (*Service) ListPhysicalHosts(c context.Context, req *crimson.ListPhysicalHostsRequest) (*crimson.ListPhysicalHostsResponse, error) {
hosts, err := listPhysicalHosts(c, database.Get(c), req)
if err != nil {
return nil, err
}
return &crimson.ListPhysicalHostsResponse{
Hosts: hosts,
}, nil
} | go | func (*Service) ListPhysicalHosts(c context.Context, req *crimson.ListPhysicalHostsRequest) (*crimson.ListPhysicalHostsResponse, error) {
hosts, err := listPhysicalHosts(c, database.Get(c), req)
if err != nil {
return nil, err
}
return &crimson.ListPhysicalHostsResponse{
Hosts: hosts,
}, nil
} | [
"func",
"(",
"*",
"Service",
")",
"ListPhysicalHosts",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"crimson",
".",
"ListPhysicalHostsRequest",
")",
"(",
"*",
"crimson",
".",
"ListPhysicalHostsResponse",
",",
"error",
")",
"{",
"hosts",
",",
"err",
":=",
"listPhysicalHosts",
"(",
"c",
",",
"database",
".",
"Get",
"(",
"c",
")",
",",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"crimson",
".",
"ListPhysicalHostsResponse",
"{",
"Hosts",
":",
"hosts",
",",
"}",
",",
"nil",
"\n",
"}"
] | // ListPhysicalHosts handles a request to list physical hosts. | [
"ListPhysicalHosts",
"handles",
"a",
"request",
"to",
"list",
"physical",
"hosts",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/physical_hosts.go#L44-L52 |
9,184 | luci/luci-go | machine-db/appengine/rpc/physical_hosts.go | UpdatePhysicalHost | func (*Service) UpdatePhysicalHost(c context.Context, req *crimson.UpdatePhysicalHostRequest) (*crimson.PhysicalHost, error) {
return updatePhysicalHost(c, req.Host, req.UpdateMask)
} | go | func (*Service) UpdatePhysicalHost(c context.Context, req *crimson.UpdatePhysicalHostRequest) (*crimson.PhysicalHost, error) {
return updatePhysicalHost(c, req.Host, req.UpdateMask)
} | [
"func",
"(",
"*",
"Service",
")",
"UpdatePhysicalHost",
"(",
"c",
"context",
".",
"Context",
",",
"req",
"*",
"crimson",
".",
"UpdatePhysicalHostRequest",
")",
"(",
"*",
"crimson",
".",
"PhysicalHost",
",",
"error",
")",
"{",
"return",
"updatePhysicalHost",
"(",
"c",
",",
"req",
".",
"Host",
",",
"req",
".",
"UpdateMask",
")",
"\n",
"}"
] | // UpdatePhysicalHost handles a request to update an existing physical host. | [
"UpdatePhysicalHost",
"handles",
"a",
"request",
"to",
"update",
"an",
"existing",
"physical",
"host",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/physical_hosts.go#L55-L57 |
9,185 | luci/luci-go | machine-db/appengine/rpc/physical_hosts.go | validatePhysicalHostForCreation | func validatePhysicalHostForCreation(h *crimson.PhysicalHost) error {
switch {
case h == nil:
return status.Error(codes.InvalidArgument, "physical host specification is required")
case h.Name == "":
return status.Error(codes.InvalidArgument, "hostname is required and must be non-empty")
case h.Vlan != 0:
return status.Error(codes.InvalidArgument, "VLAN must not be specified, use IP address instead")
case h.Machine == "":
return status.Error(codes.InvalidArgument, "machine is required and must be non-empty")
case h.Nic == "":
return status.Error(codes.InvalidArgument, "NIC is required and must be non-empty")
case h.MacAddress != "":
return status.Error(codes.InvalidArgument, "MAC address must not be specified, use NIC instead")
case h.Os == "":
return status.Error(codes.InvalidArgument, "operating system is required and must be non-empty")
case h.VmSlots < 0:
return status.Error(codes.InvalidArgument, "VM slots must be non-negative")
default:
_, err := common.ParseIPv4(h.Ipv4)
if err != nil {
return status.Errorf(codes.InvalidArgument, "invalid IPv4 address %q", h.Ipv4)
}
return nil
}
} | go | func validatePhysicalHostForCreation(h *crimson.PhysicalHost) error {
switch {
case h == nil:
return status.Error(codes.InvalidArgument, "physical host specification is required")
case h.Name == "":
return status.Error(codes.InvalidArgument, "hostname is required and must be non-empty")
case h.Vlan != 0:
return status.Error(codes.InvalidArgument, "VLAN must not be specified, use IP address instead")
case h.Machine == "":
return status.Error(codes.InvalidArgument, "machine is required and must be non-empty")
case h.Nic == "":
return status.Error(codes.InvalidArgument, "NIC is required and must be non-empty")
case h.MacAddress != "":
return status.Error(codes.InvalidArgument, "MAC address must not be specified, use NIC instead")
case h.Os == "":
return status.Error(codes.InvalidArgument, "operating system is required and must be non-empty")
case h.VmSlots < 0:
return status.Error(codes.InvalidArgument, "VM slots must be non-negative")
default:
_, err := common.ParseIPv4(h.Ipv4)
if err != nil {
return status.Errorf(codes.InvalidArgument, "invalid IPv4 address %q", h.Ipv4)
}
return nil
}
} | [
"func",
"validatePhysicalHostForCreation",
"(",
"h",
"*",
"crimson",
".",
"PhysicalHost",
")",
"error",
"{",
"switch",
"{",
"case",
"h",
"==",
"nil",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"h",
".",
"Name",
"==",
"\"",
"\"",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"h",
".",
"Vlan",
"!=",
"0",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"h",
".",
"Machine",
"==",
"\"",
"\"",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"h",
".",
"Nic",
"==",
"\"",
"\"",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"h",
".",
"MacAddress",
"!=",
"\"",
"\"",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"h",
".",
"Os",
"==",
"\"",
"\"",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"h",
".",
"VmSlots",
"<",
"0",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"default",
":",
"_",
",",
"err",
":=",
"common",
".",
"ParseIPv4",
"(",
"h",
".",
"Ipv4",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"status",
".",
"Errorf",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
",",
"h",
".",
"Ipv4",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}"
] | // validatePhysicalHostForCreation validates a physical host for creation. | [
"validatePhysicalHostForCreation",
"validates",
"a",
"physical",
"host",
"for",
"creation",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/physical_hosts.go#L348-L373 |
9,186 | luci/luci-go | machine-db/appengine/rpc/physical_hosts.go | validatePhysicalHostForUpdate | func validatePhysicalHostForUpdate(h *crimson.PhysicalHost, mask *field_mask.FieldMask) error {
switch err := validateUpdateMask(mask); {
case h == nil:
return status.Error(codes.InvalidArgument, "physical host specification is required")
case h.Name == "":
return status.Error(codes.InvalidArgument, "hostname is required and must be non-empty")
case err != nil:
return err
}
for _, path := range mask.Paths {
// TODO(smut): Allow NIC, IPv4 address and state to be updated.
switch path {
case "name":
return status.Error(codes.InvalidArgument, "hostname cannot be updated, delete and create a new physical host instead")
case "vlan":
return status.Error(codes.InvalidArgument, "VLAN cannot be updated, delete and create a new physical host instead")
case "machine":
if h.Machine == "" {
return status.Error(codes.InvalidArgument, "machine is required and must be non-empty")
}
case "nic":
return status.Error(codes.InvalidArgument, "NIC cannot be updated, delete and create a new physical host instead")
case "mac_address":
return status.Error(codes.InvalidArgument, "MAC address cannot be updated, update NIC instead")
case "os":
if h.Os == "" {
return status.Error(codes.InvalidArgument, "operating system is required and must be non-empty")
}
case "state":
if h.State == states.State_STATE_UNSPECIFIED {
return status.Error(codes.InvalidArgument, "state is required")
}
case "vm_slots":
if h.VmSlots < 0 {
return status.Error(codes.InvalidArgument, "VM slots must be non-negative")
}
case "virtual_datacenter":
// Empty virtual datacenter is allowed, nothing to validate.
case "description":
// Empty description is allowed, nothing to validate.
case "deployment_ticket":
// Empty deployment ticket is allowed, nothing to validate.
default:
return status.Errorf(codes.InvalidArgument, "unsupported update mask path %q", path)
}
}
return nil
} | go | func validatePhysicalHostForUpdate(h *crimson.PhysicalHost, mask *field_mask.FieldMask) error {
switch err := validateUpdateMask(mask); {
case h == nil:
return status.Error(codes.InvalidArgument, "physical host specification is required")
case h.Name == "":
return status.Error(codes.InvalidArgument, "hostname is required and must be non-empty")
case err != nil:
return err
}
for _, path := range mask.Paths {
// TODO(smut): Allow NIC, IPv4 address and state to be updated.
switch path {
case "name":
return status.Error(codes.InvalidArgument, "hostname cannot be updated, delete and create a new physical host instead")
case "vlan":
return status.Error(codes.InvalidArgument, "VLAN cannot be updated, delete and create a new physical host instead")
case "machine":
if h.Machine == "" {
return status.Error(codes.InvalidArgument, "machine is required and must be non-empty")
}
case "nic":
return status.Error(codes.InvalidArgument, "NIC cannot be updated, delete and create a new physical host instead")
case "mac_address":
return status.Error(codes.InvalidArgument, "MAC address cannot be updated, update NIC instead")
case "os":
if h.Os == "" {
return status.Error(codes.InvalidArgument, "operating system is required and must be non-empty")
}
case "state":
if h.State == states.State_STATE_UNSPECIFIED {
return status.Error(codes.InvalidArgument, "state is required")
}
case "vm_slots":
if h.VmSlots < 0 {
return status.Error(codes.InvalidArgument, "VM slots must be non-negative")
}
case "virtual_datacenter":
// Empty virtual datacenter is allowed, nothing to validate.
case "description":
// Empty description is allowed, nothing to validate.
case "deployment_ticket":
// Empty deployment ticket is allowed, nothing to validate.
default:
return status.Errorf(codes.InvalidArgument, "unsupported update mask path %q", path)
}
}
return nil
} | [
"func",
"validatePhysicalHostForUpdate",
"(",
"h",
"*",
"crimson",
".",
"PhysicalHost",
",",
"mask",
"*",
"field_mask",
".",
"FieldMask",
")",
"error",
"{",
"switch",
"err",
":=",
"validateUpdateMask",
"(",
"mask",
")",
";",
"{",
"case",
"h",
"==",
"nil",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"h",
".",
"Name",
"==",
"\"",
"\"",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"err",
"!=",
"nil",
":",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"path",
":=",
"range",
"mask",
".",
"Paths",
"{",
"// TODO(smut): Allow NIC, IPv4 address and state to be updated.",
"switch",
"path",
"{",
"case",
"\"",
"\"",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"\"",
"\"",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"\"",
"\"",
":",
"if",
"h",
".",
"Machine",
"==",
"\"",
"\"",
"{",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"case",
"\"",
"\"",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"\"",
"\"",
":",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"case",
"\"",
"\"",
":",
"if",
"h",
".",
"Os",
"==",
"\"",
"\"",
"{",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"case",
"\"",
"\"",
":",
"if",
"h",
".",
"State",
"==",
"states",
".",
"State_STATE_UNSPECIFIED",
"{",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"case",
"\"",
"\"",
":",
"if",
"h",
".",
"VmSlots",
"<",
"0",
"{",
"return",
"status",
".",
"Error",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"case",
"\"",
"\"",
":",
"// Empty virtual datacenter is allowed, nothing to validate.",
"case",
"\"",
"\"",
":",
"// Empty description is allowed, nothing to validate.",
"case",
"\"",
"\"",
":",
"// Empty deployment ticket is allowed, nothing to validate.",
"default",
":",
"return",
"status",
".",
"Errorf",
"(",
"codes",
".",
"InvalidArgument",
",",
"\"",
"\"",
",",
"path",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // validatePhysicalHostForUpdate validates a physical host for update. | [
"validatePhysicalHostForUpdate",
"validates",
"a",
"physical",
"host",
"for",
"update",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/rpc/physical_hosts.go#L376-L423 |
9,187 | luci/luci-go | scheduler/appengine/engine/invocation.go | isEqual | func (e *Invocation) isEqual(other *Invocation) bool {
return e == other || (e.ID == other.ID &&
e.MutationsCount == other.MutationsCount && // compare it first, it changes most often
e.JobID == other.JobID &&
e.IndexedJobID == other.IndexedJobID &&
e.Started.Equal(other.Started) &&
e.Finished.Equal(other.Finished) &&
e.TriggeredBy == other.TriggeredBy &&
bytes.Equal(e.PropertiesRaw, other.PropertiesRaw) &&
equalSortedLists(e.Tags, other.Tags) &&
bytes.Equal(e.IncomingTriggersRaw, other.IncomingTriggersRaw) &&
bytes.Equal(e.OutgoingTriggersRaw, other.OutgoingTriggersRaw) &&
bytes.Equal(e.PendingTimersRaw, other.PendingTimersRaw) &&
e.Revision == other.Revision &&
e.RevisionURL == other.RevisionURL &&
bytes.Equal(e.Task, other.Task) &&
equalSortedLists(e.TriggeredJobIDs, other.TriggeredJobIDs) &&
e.DebugLog == other.DebugLog &&
e.RetryCount == other.RetryCount &&
e.Status == other.Status &&
e.ViewURL == other.ViewURL &&
bytes.Equal(e.TaskData, other.TaskData))
} | go | func (e *Invocation) isEqual(other *Invocation) bool {
return e == other || (e.ID == other.ID &&
e.MutationsCount == other.MutationsCount && // compare it first, it changes most often
e.JobID == other.JobID &&
e.IndexedJobID == other.IndexedJobID &&
e.Started.Equal(other.Started) &&
e.Finished.Equal(other.Finished) &&
e.TriggeredBy == other.TriggeredBy &&
bytes.Equal(e.PropertiesRaw, other.PropertiesRaw) &&
equalSortedLists(e.Tags, other.Tags) &&
bytes.Equal(e.IncomingTriggersRaw, other.IncomingTriggersRaw) &&
bytes.Equal(e.OutgoingTriggersRaw, other.OutgoingTriggersRaw) &&
bytes.Equal(e.PendingTimersRaw, other.PendingTimersRaw) &&
e.Revision == other.Revision &&
e.RevisionURL == other.RevisionURL &&
bytes.Equal(e.Task, other.Task) &&
equalSortedLists(e.TriggeredJobIDs, other.TriggeredJobIDs) &&
e.DebugLog == other.DebugLog &&
e.RetryCount == other.RetryCount &&
e.Status == other.Status &&
e.ViewURL == other.ViewURL &&
bytes.Equal(e.TaskData, other.TaskData))
} | [
"func",
"(",
"e",
"*",
"Invocation",
")",
"isEqual",
"(",
"other",
"*",
"Invocation",
")",
"bool",
"{",
"return",
"e",
"==",
"other",
"||",
"(",
"e",
".",
"ID",
"==",
"other",
".",
"ID",
"&&",
"e",
".",
"MutationsCount",
"==",
"other",
".",
"MutationsCount",
"&&",
"// compare it first, it changes most often",
"e",
".",
"JobID",
"==",
"other",
".",
"JobID",
"&&",
"e",
".",
"IndexedJobID",
"==",
"other",
".",
"IndexedJobID",
"&&",
"e",
".",
"Started",
".",
"Equal",
"(",
"other",
".",
"Started",
")",
"&&",
"e",
".",
"Finished",
".",
"Equal",
"(",
"other",
".",
"Finished",
")",
"&&",
"e",
".",
"TriggeredBy",
"==",
"other",
".",
"TriggeredBy",
"&&",
"bytes",
".",
"Equal",
"(",
"e",
".",
"PropertiesRaw",
",",
"other",
".",
"PropertiesRaw",
")",
"&&",
"equalSortedLists",
"(",
"e",
".",
"Tags",
",",
"other",
".",
"Tags",
")",
"&&",
"bytes",
".",
"Equal",
"(",
"e",
".",
"IncomingTriggersRaw",
",",
"other",
".",
"IncomingTriggersRaw",
")",
"&&",
"bytes",
".",
"Equal",
"(",
"e",
".",
"OutgoingTriggersRaw",
",",
"other",
".",
"OutgoingTriggersRaw",
")",
"&&",
"bytes",
".",
"Equal",
"(",
"e",
".",
"PendingTimersRaw",
",",
"other",
".",
"PendingTimersRaw",
")",
"&&",
"e",
".",
"Revision",
"==",
"other",
".",
"Revision",
"&&",
"e",
".",
"RevisionURL",
"==",
"other",
".",
"RevisionURL",
"&&",
"bytes",
".",
"Equal",
"(",
"e",
".",
"Task",
",",
"other",
".",
"Task",
")",
"&&",
"equalSortedLists",
"(",
"e",
".",
"TriggeredJobIDs",
",",
"other",
".",
"TriggeredJobIDs",
")",
"&&",
"e",
".",
"DebugLog",
"==",
"other",
".",
"DebugLog",
"&&",
"e",
".",
"RetryCount",
"==",
"other",
".",
"RetryCount",
"&&",
"e",
".",
"Status",
"==",
"other",
".",
"Status",
"&&",
"e",
".",
"ViewURL",
"==",
"other",
".",
"ViewURL",
"&&",
"bytes",
".",
"Equal",
"(",
"e",
".",
"TaskData",
",",
"other",
".",
"TaskData",
")",
")",
"\n",
"}"
] | // isEqual returns true iff 'e' is equal to 'other' | [
"isEqual",
"returns",
"true",
"iff",
"e",
"is",
"equal",
"to",
"other"
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/invocation.go#L246-L268 |
9,188 | luci/luci-go | scheduler/appengine/engine/invocation.go | GetProjectID | func (e *Invocation) GetProjectID() string {
parts := strings.Split(e.JobID, "/")
return parts[0]
} | go | func (e *Invocation) GetProjectID() string {
parts := strings.Split(e.JobID, "/")
return parts[0]
} | [
"func",
"(",
"e",
"*",
"Invocation",
")",
"GetProjectID",
"(",
")",
"string",
"{",
"parts",
":=",
"strings",
".",
"Split",
"(",
"e",
".",
"JobID",
",",
"\"",
"\"",
")",
"\n",
"return",
"parts",
"[",
"0",
"]",
"\n",
"}"
] | // GetProjectID parses the ProjectID from the JobID and returns it. | [
"GetProjectID",
"parses",
"the",
"ProjectID",
"from",
"the",
"JobID",
"and",
"returns",
"it",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/invocation.go#L271-L274 |
9,189 | luci/luci-go | scheduler/appengine/engine/invocation.go | debugLog | func (e *Invocation) debugLog(c context.Context, format string, args ...interface{}) {
debugLog(c, &e.DebugLog, format, args...)
} | go | func (e *Invocation) debugLog(c context.Context, format string, args ...interface{}) {
debugLog(c, &e.DebugLog, format, args...)
} | [
"func",
"(",
"e",
"*",
"Invocation",
")",
"debugLog",
"(",
"c",
"context",
".",
"Context",
",",
"format",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"debugLog",
"(",
"c",
",",
"&",
"e",
".",
"DebugLog",
",",
"format",
",",
"args",
"...",
")",
"\n",
"}"
] | // debugLog appends a line to DebugLog field. | [
"debugLog",
"appends",
"a",
"line",
"to",
"DebugLog",
"field",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/invocation.go#L277-L279 |
9,190 | luci/luci-go | scheduler/appengine/engine/invocation.go | trimDebugLog | func (e *Invocation) trimDebugLog() {
if len(e.DebugLog) <= debugLogSizeLimit {
return
}
const cutMsg = "--- the log has been cut here ---"
giveUp := func() {
e.DebugLog = e.DebugLog[:debugLogSizeLimit-len(cutMsg)-2] + "\n" + cutMsg + "\n"
}
// We take last debugLogTailLines lines of log and move them "up", so that
// the total log size is less than debugLogSizeLimit. We then put a line with
// the message that some log lines have been cut. If these operations are not
// possible (e.g. we have some giant lines or something), we give up and just
// cut the end of the log.
// Find debugLogTailLines-th "\n" from the end, e.DebugLog[tailStart:] is the
// log tail.
tailStart := len(e.DebugLog)
for i := 0; i < debugLogTailLines; i++ {
tailStart = strings.LastIndex(e.DebugLog[:tailStart-1], "\n")
if tailStart <= 0 {
giveUp()
return
}
}
tailStart++
// Figure out how many bytes of head we can keep to make trimmed log small
// enough.
tailLen := len(e.DebugLog) - tailStart + len(cutMsg) + 1
headSize := debugLogSizeLimit - tailLen
if headSize <= 0 {
giveUp()
return
}
// Find last "\n" in the head.
headEnd := strings.LastIndex(e.DebugLog[:headSize], "\n")
if headEnd <= 0 {
giveUp()
return
}
// We want to keep 50 lines of the head no matter what.
headLines := strings.Count(e.DebugLog[:headEnd], "\n")
if headLines < 50 {
giveUp()
return
}
// Remove duplicated 'cutMsg' lines. They may appear if 'debugLog' (followed
// by 'trimDebugLog') is called on already trimmed log multiple times.
lines := strings.Split(e.DebugLog[:headEnd], "\n")
lines = append(lines, cutMsg)
lines = append(lines, strings.Split(e.DebugLog[tailStart:], "\n")...)
trimmed := make([]byte, 0, debugLogSizeLimit)
trimmed = append(trimmed, lines[0]...)
for i := 1; i < len(lines); i++ {
if !(lines[i-1] == cutMsg && lines[i] == cutMsg) {
trimmed = append(trimmed, '\n')
trimmed = append(trimmed, lines[i]...)
}
}
e.DebugLog = string(trimmed)
} | go | func (e *Invocation) trimDebugLog() {
if len(e.DebugLog) <= debugLogSizeLimit {
return
}
const cutMsg = "--- the log has been cut here ---"
giveUp := func() {
e.DebugLog = e.DebugLog[:debugLogSizeLimit-len(cutMsg)-2] + "\n" + cutMsg + "\n"
}
// We take last debugLogTailLines lines of log and move them "up", so that
// the total log size is less than debugLogSizeLimit. We then put a line with
// the message that some log lines have been cut. If these operations are not
// possible (e.g. we have some giant lines or something), we give up and just
// cut the end of the log.
// Find debugLogTailLines-th "\n" from the end, e.DebugLog[tailStart:] is the
// log tail.
tailStart := len(e.DebugLog)
for i := 0; i < debugLogTailLines; i++ {
tailStart = strings.LastIndex(e.DebugLog[:tailStart-1], "\n")
if tailStart <= 0 {
giveUp()
return
}
}
tailStart++
// Figure out how many bytes of head we can keep to make trimmed log small
// enough.
tailLen := len(e.DebugLog) - tailStart + len(cutMsg) + 1
headSize := debugLogSizeLimit - tailLen
if headSize <= 0 {
giveUp()
return
}
// Find last "\n" in the head.
headEnd := strings.LastIndex(e.DebugLog[:headSize], "\n")
if headEnd <= 0 {
giveUp()
return
}
// We want to keep 50 lines of the head no matter what.
headLines := strings.Count(e.DebugLog[:headEnd], "\n")
if headLines < 50 {
giveUp()
return
}
// Remove duplicated 'cutMsg' lines. They may appear if 'debugLog' (followed
// by 'trimDebugLog') is called on already trimmed log multiple times.
lines := strings.Split(e.DebugLog[:headEnd], "\n")
lines = append(lines, cutMsg)
lines = append(lines, strings.Split(e.DebugLog[tailStart:], "\n")...)
trimmed := make([]byte, 0, debugLogSizeLimit)
trimmed = append(trimmed, lines[0]...)
for i := 1; i < len(lines); i++ {
if !(lines[i-1] == cutMsg && lines[i] == cutMsg) {
trimmed = append(trimmed, '\n')
trimmed = append(trimmed, lines[i]...)
}
}
e.DebugLog = string(trimmed)
} | [
"func",
"(",
"e",
"*",
"Invocation",
")",
"trimDebugLog",
"(",
")",
"{",
"if",
"len",
"(",
"e",
".",
"DebugLog",
")",
"<=",
"debugLogSizeLimit",
"{",
"return",
"\n",
"}",
"\n\n",
"const",
"cutMsg",
"=",
"\"",
"\"",
"\n",
"giveUp",
":=",
"func",
"(",
")",
"{",
"e",
".",
"DebugLog",
"=",
"e",
".",
"DebugLog",
"[",
":",
"debugLogSizeLimit",
"-",
"len",
"(",
"cutMsg",
")",
"-",
"2",
"]",
"+",
"\"",
"\\n",
"\"",
"+",
"cutMsg",
"+",
"\"",
"\\n",
"\"",
"\n",
"}",
"\n\n",
"// We take last debugLogTailLines lines of log and move them \"up\", so that",
"// the total log size is less than debugLogSizeLimit. We then put a line with",
"// the message that some log lines have been cut. If these operations are not",
"// possible (e.g. we have some giant lines or something), we give up and just",
"// cut the end of the log.",
"// Find debugLogTailLines-th \"\\n\" from the end, e.DebugLog[tailStart:] is the",
"// log tail.",
"tailStart",
":=",
"len",
"(",
"e",
".",
"DebugLog",
")",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"debugLogTailLines",
";",
"i",
"++",
"{",
"tailStart",
"=",
"strings",
".",
"LastIndex",
"(",
"e",
".",
"DebugLog",
"[",
":",
"tailStart",
"-",
"1",
"]",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"if",
"tailStart",
"<=",
"0",
"{",
"giveUp",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"tailStart",
"++",
"\n\n",
"// Figure out how many bytes of head we can keep to make trimmed log small",
"// enough.",
"tailLen",
":=",
"len",
"(",
"e",
".",
"DebugLog",
")",
"-",
"tailStart",
"+",
"len",
"(",
"cutMsg",
")",
"+",
"1",
"\n",
"headSize",
":=",
"debugLogSizeLimit",
"-",
"tailLen",
"\n",
"if",
"headSize",
"<=",
"0",
"{",
"giveUp",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Find last \"\\n\" in the head.",
"headEnd",
":=",
"strings",
".",
"LastIndex",
"(",
"e",
".",
"DebugLog",
"[",
":",
"headSize",
"]",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"if",
"headEnd",
"<=",
"0",
"{",
"giveUp",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// We want to keep 50 lines of the head no matter what.",
"headLines",
":=",
"strings",
".",
"Count",
"(",
"e",
".",
"DebugLog",
"[",
":",
"headEnd",
"]",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"if",
"headLines",
"<",
"50",
"{",
"giveUp",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Remove duplicated 'cutMsg' lines. They may appear if 'debugLog' (followed",
"// by 'trimDebugLog') is called on already trimmed log multiple times.",
"lines",
":=",
"strings",
".",
"Split",
"(",
"e",
".",
"DebugLog",
"[",
":",
"headEnd",
"]",
",",
"\"",
"\\n",
"\"",
")",
"\n",
"lines",
"=",
"append",
"(",
"lines",
",",
"cutMsg",
")",
"\n",
"lines",
"=",
"append",
"(",
"lines",
",",
"strings",
".",
"Split",
"(",
"e",
".",
"DebugLog",
"[",
"tailStart",
":",
"]",
",",
"\"",
"\\n",
"\"",
")",
"...",
")",
"\n",
"trimmed",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"0",
",",
"debugLogSizeLimit",
")",
"\n",
"trimmed",
"=",
"append",
"(",
"trimmed",
",",
"lines",
"[",
"0",
"]",
"...",
")",
"\n",
"for",
"i",
":=",
"1",
";",
"i",
"<",
"len",
"(",
"lines",
")",
";",
"i",
"++",
"{",
"if",
"!",
"(",
"lines",
"[",
"i",
"-",
"1",
"]",
"==",
"cutMsg",
"&&",
"lines",
"[",
"i",
"]",
"==",
"cutMsg",
")",
"{",
"trimmed",
"=",
"append",
"(",
"trimmed",
",",
"'\\n'",
")",
"\n",
"trimmed",
"=",
"append",
"(",
"trimmed",
",",
"lines",
"[",
"i",
"]",
"...",
")",
"\n",
"}",
"\n",
"}",
"\n",
"e",
".",
"DebugLog",
"=",
"string",
"(",
"trimmed",
")",
"\n",
"}"
] | // trimDebugLog makes sure DebugLog field doesn't exceed limits.
//
// It cuts the middle of the log. We need to do this to keep the entity small
// enough to fit the datastore limits. | [
"trimDebugLog",
"makes",
"sure",
"DebugLog",
"field",
"doesn",
"t",
"exceed",
"limits",
".",
"It",
"cuts",
"the",
"middle",
"of",
"the",
"log",
".",
"We",
"need",
"to",
"do",
"this",
"to",
"keep",
"the",
"entity",
"small",
"enough",
"to",
"fit",
"the",
"datastore",
"limits",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/invocation.go#L285-L350 |
9,191 | luci/luci-go | scheduler/appengine/engine/invocation.go | cleanupUnreferencedInvocations | func cleanupUnreferencedInvocations(c context.Context, invs []*Invocation) {
keysToKill := make([]*datastore.Key, 0, len(invs))
for _, inv := range invs {
if inv != nil {
logging.Warningf(c, "Cleaning up inv %d of job %q", inv.ID, inv.JobID)
keysToKill = append(keysToKill, datastore.KeyForObj(c, inv))
}
}
if err := datastore.Delete(datastore.WithoutTransaction(c), keysToKill); err != nil {
logging.WithError(err).Warningf(c, "Invocation cleanup failed")
}
} | go | func cleanupUnreferencedInvocations(c context.Context, invs []*Invocation) {
keysToKill := make([]*datastore.Key, 0, len(invs))
for _, inv := range invs {
if inv != nil {
logging.Warningf(c, "Cleaning up inv %d of job %q", inv.ID, inv.JobID)
keysToKill = append(keysToKill, datastore.KeyForObj(c, inv))
}
}
if err := datastore.Delete(datastore.WithoutTransaction(c), keysToKill); err != nil {
logging.WithError(err).Warningf(c, "Invocation cleanup failed")
}
} | [
"func",
"cleanupUnreferencedInvocations",
"(",
"c",
"context",
".",
"Context",
",",
"invs",
"[",
"]",
"*",
"Invocation",
")",
"{",
"keysToKill",
":=",
"make",
"(",
"[",
"]",
"*",
"datastore",
".",
"Key",
",",
"0",
",",
"len",
"(",
"invs",
")",
")",
"\n",
"for",
"_",
",",
"inv",
":=",
"range",
"invs",
"{",
"if",
"inv",
"!=",
"nil",
"{",
"logging",
".",
"Warningf",
"(",
"c",
",",
"\"",
"\"",
",",
"inv",
".",
"ID",
",",
"inv",
".",
"JobID",
")",
"\n",
"keysToKill",
"=",
"append",
"(",
"keysToKill",
",",
"datastore",
".",
"KeyForObj",
"(",
"c",
",",
"inv",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"err",
":=",
"datastore",
".",
"Delete",
"(",
"datastore",
".",
"WithoutTransaction",
"(",
"c",
")",
",",
"keysToKill",
")",
";",
"err",
"!=",
"nil",
"{",
"logging",
".",
"WithError",
"(",
"err",
")",
".",
"Warningf",
"(",
"c",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}"
] | // cleanupUnreferencedInvocations tries to delete given invocations.
//
// This is best effort cleanup after failures. It logs errors, but doesn't
// return them, to indicate that there's nothing we can actually do.
//
// 'invs' is allowed to have nils, they are skipped. Allowed to be called
// within a transaction, ignores it. | [
"cleanupUnreferencedInvocations",
"tries",
"to",
"delete",
"given",
"invocations",
".",
"This",
"is",
"best",
"effort",
"cleanup",
"after",
"failures",
".",
"It",
"logs",
"errors",
"but",
"doesn",
"t",
"return",
"them",
"to",
"indicate",
"that",
"there",
"s",
"nothing",
"we",
"can",
"actually",
"do",
".",
"invs",
"is",
"allowed",
"to",
"have",
"nils",
"they",
"are",
"skipped",
".",
"Allowed",
"to",
"be",
"called",
"within",
"a",
"transaction",
"ignores",
"it",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/invocation.go#L380-L391 |
9,192 | luci/luci-go | scheduler/appengine/engine/invocation.go | reportOverrunMetrics | func (e *Invocation) reportOverrunMetrics(c context.Context) {
metricInvocationsOverrun.Add(c, 1, e.JobID)
} | go | func (e *Invocation) reportOverrunMetrics(c context.Context) {
metricInvocationsOverrun.Add(c, 1, e.JobID)
} | [
"func",
"(",
"e",
"*",
"Invocation",
")",
"reportOverrunMetrics",
"(",
"c",
"context",
".",
"Context",
")",
"{",
"metricInvocationsOverrun",
".",
"Add",
"(",
"c",
",",
"1",
",",
"e",
".",
"JobID",
")",
"\n",
"}"
] | // reportOverrunMetrics reports overrun to monitoring.
// Should be called after transaction to save this invocation is completed. | [
"reportOverrunMetrics",
"reports",
"overrun",
"to",
"monitoring",
".",
"Should",
"be",
"called",
"after",
"transaction",
"to",
"save",
"this",
"invocation",
"is",
"completed",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/invocation.go#L395-L397 |
9,193 | luci/luci-go | scheduler/appengine/engine/invocation.go | reportCompletionMetrics | func (e *Invocation) reportCompletionMetrics(c context.Context) {
if !e.Status.Final() || e.Finished.IsZero() {
panic(fmt.Errorf("reportCompletionMetrics on incomplete invocation: %v", e))
}
duration := e.Finished.Sub(e.Started)
metricInvocationsDurations.Add(c, duration.Seconds(), e.JobID, string(e.Status))
} | go | func (e *Invocation) reportCompletionMetrics(c context.Context) {
if !e.Status.Final() || e.Finished.IsZero() {
panic(fmt.Errorf("reportCompletionMetrics on incomplete invocation: %v", e))
}
duration := e.Finished.Sub(e.Started)
metricInvocationsDurations.Add(c, duration.Seconds(), e.JobID, string(e.Status))
} | [
"func",
"(",
"e",
"*",
"Invocation",
")",
"reportCompletionMetrics",
"(",
"c",
"context",
".",
"Context",
")",
"{",
"if",
"!",
"e",
".",
"Status",
".",
"Final",
"(",
")",
"||",
"e",
".",
"Finished",
".",
"IsZero",
"(",
")",
"{",
"panic",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"e",
")",
")",
"\n",
"}",
"\n",
"duration",
":=",
"e",
".",
"Finished",
".",
"Sub",
"(",
"e",
".",
"Started",
")",
"\n",
"metricInvocationsDurations",
".",
"Add",
"(",
"c",
",",
"duration",
".",
"Seconds",
"(",
")",
",",
"e",
".",
"JobID",
",",
"string",
"(",
"e",
".",
"Status",
")",
")",
"\n",
"}"
] | // reportCompletionMetrics reports invocation stats to monitoring.
// Should be called after transaction to save this invocation is completed. | [
"reportCompletionMetrics",
"reports",
"invocation",
"stats",
"to",
"monitoring",
".",
"Should",
"be",
"called",
"after",
"transaction",
"to",
"save",
"this",
"invocation",
"is",
"completed",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/invocation.go#L401-L407 |
9,194 | luci/luci-go | machine-db/appengine/settings/settings.go | New | func New(c context.Context) *DatabaseSettings {
return &DatabaseSettings{
Server: "",
Username: "",
Password: "",
Database: "",
}
} | go | func New(c context.Context) *DatabaseSettings {
return &DatabaseSettings{
Server: "",
Username: "",
Password: "",
Database: "",
}
} | [
"func",
"New",
"(",
"c",
"context",
".",
"Context",
")",
"*",
"DatabaseSettings",
"{",
"return",
"&",
"DatabaseSettings",
"{",
"Server",
":",
"\"",
"\"",
",",
"Username",
":",
"\"",
"\"",
",",
"Password",
":",
"\"",
"\"",
",",
"Database",
":",
"\"",
"\"",
",",
"}",
"\n",
"}"
] | // New returns a new instance of DatabaseSettings. | [
"New",
"returns",
"a",
"new",
"instance",
"of",
"DatabaseSettings",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/settings/settings.go#L41-L48 |
9,195 | luci/luci-go | machine-db/appengine/settings/settings.go | Get | func Get(c context.Context) (*DatabaseSettings, error) {
databaseSettings := &DatabaseSettings{}
switch err := settings.Get(c, settingsKey, databaseSettings); err {
case nil:
return databaseSettings, nil
case settings.ErrNoSettings:
return New(c), nil
default:
return nil, err
}
} | go | func Get(c context.Context) (*DatabaseSettings, error) {
databaseSettings := &DatabaseSettings{}
switch err := settings.Get(c, settingsKey, databaseSettings); err {
case nil:
return databaseSettings, nil
case settings.ErrNoSettings:
return New(c), nil
default:
return nil, err
}
} | [
"func",
"Get",
"(",
"c",
"context",
".",
"Context",
")",
"(",
"*",
"DatabaseSettings",
",",
"error",
")",
"{",
"databaseSettings",
":=",
"&",
"DatabaseSettings",
"{",
"}",
"\n",
"switch",
"err",
":=",
"settings",
".",
"Get",
"(",
"c",
",",
"settingsKey",
",",
"databaseSettings",
")",
";",
"err",
"{",
"case",
"nil",
":",
"return",
"databaseSettings",
",",
"nil",
"\n",
"case",
"settings",
".",
"ErrNoSettings",
":",
"return",
"New",
"(",
"c",
")",
",",
"nil",
"\n",
"default",
":",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}"
] | // Get returns the current settings. This may hit an outdated cache. | [
"Get",
"returns",
"the",
"current",
"settings",
".",
"This",
"may",
"hit",
"an",
"outdated",
"cache",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/settings/settings.go#L51-L61 |
9,196 | luci/luci-go | machine-db/appengine/settings/settings.go | Fields | func (*DatabaseSettings) Fields(c context.Context) ([]portal.Field, error) {
fields := []portal.Field{
{
ID: "Server",
Title: "Server",
Type: portal.FieldText,
Help: "<p>Server to use (for Cloud SQL should be of the form project:region:database)</p>",
},
{
ID: "Username",
Title: "Username",
Type: portal.FieldText,
Help: "<p>Username to authenticate to the SQL database with</p>",
},
{
ID: "Password",
Title: "Password",
Type: portal.FieldPassword,
Help: "<p>Password to authenticate to the SQL database with</p>",
},
{
ID: "Database",
Title: "Database",
Type: portal.FieldText,
Help: "<p>SQL database to use</p>",
},
}
return fields, nil
} | go | func (*DatabaseSettings) Fields(c context.Context) ([]portal.Field, error) {
fields := []portal.Field{
{
ID: "Server",
Title: "Server",
Type: portal.FieldText,
Help: "<p>Server to use (for Cloud SQL should be of the form project:region:database)</p>",
},
{
ID: "Username",
Title: "Username",
Type: portal.FieldText,
Help: "<p>Username to authenticate to the SQL database with</p>",
},
{
ID: "Password",
Title: "Password",
Type: portal.FieldPassword,
Help: "<p>Password to authenticate to the SQL database with</p>",
},
{
ID: "Database",
Title: "Database",
Type: portal.FieldText,
Help: "<p>SQL database to use</p>",
},
}
return fields, nil
} | [
"func",
"(",
"*",
"DatabaseSettings",
")",
"Fields",
"(",
"c",
"context",
".",
"Context",
")",
"(",
"[",
"]",
"portal",
".",
"Field",
",",
"error",
")",
"{",
"fields",
":=",
"[",
"]",
"portal",
".",
"Field",
"{",
"{",
"ID",
":",
"\"",
"\"",
",",
"Title",
":",
"\"",
"\"",
",",
"Type",
":",
"portal",
".",
"FieldText",
",",
"Help",
":",
"\"",
"\"",
",",
"}",
",",
"{",
"ID",
":",
"\"",
"\"",
",",
"Title",
":",
"\"",
"\"",
",",
"Type",
":",
"portal",
".",
"FieldText",
",",
"Help",
":",
"\"",
"\"",
",",
"}",
",",
"{",
"ID",
":",
"\"",
"\"",
",",
"Title",
":",
"\"",
"\"",
",",
"Type",
":",
"portal",
".",
"FieldPassword",
",",
"Help",
":",
"\"",
"\"",
",",
"}",
",",
"{",
"ID",
":",
"\"",
"\"",
",",
"Title",
":",
"\"",
"\"",
",",
"Type",
":",
"portal",
".",
"FieldText",
",",
"Help",
":",
"\"",
"\"",
",",
"}",
",",
"}",
"\n",
"return",
"fields",
",",
"nil",
"\n",
"}"
] | // Fields returns the form fields for configuring these settings. | [
"Fields",
"returns",
"the",
"form",
"fields",
"for",
"configuring",
"these",
"settings",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/settings/settings.go#L87-L115 |
9,197 | luci/luci-go | machine-db/appengine/settings/settings.go | Actions | func (*DatabaseSettings) Actions(c context.Context) ([]portal.Action, error) {
return nil, nil
} | go | func (*DatabaseSettings) Actions(c context.Context) ([]portal.Action, error) {
return nil, nil
} | [
"func",
"(",
"*",
"DatabaseSettings",
")",
"Actions",
"(",
"c",
"context",
".",
"Context",
")",
"(",
"[",
"]",
"portal",
".",
"Action",
",",
"error",
")",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}"
] | // Actions is additional list of actions to present on the page. | [
"Actions",
"is",
"additional",
"list",
"of",
"actions",
"to",
"present",
"on",
"the",
"page",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/settings/settings.go#L118-L120 |
9,198 | luci/luci-go | machine-db/appengine/settings/settings.go | ReadSettings | func (*DatabaseSettings) ReadSettings(c context.Context) (map[string]string, error) {
databaseSettings, err := GetUncached(c)
if err != nil {
return nil, err
}
return map[string]string{
"Server": databaseSettings.Server,
"Username": databaseSettings.Username,
"Password": databaseSettings.Password,
"Database": databaseSettings.Database,
}, nil
} | go | func (*DatabaseSettings) ReadSettings(c context.Context) (map[string]string, error) {
databaseSettings, err := GetUncached(c)
if err != nil {
return nil, err
}
return map[string]string{
"Server": databaseSettings.Server,
"Username": databaseSettings.Username,
"Password": databaseSettings.Password,
"Database": databaseSettings.Database,
}, nil
} | [
"func",
"(",
"*",
"DatabaseSettings",
")",
"ReadSettings",
"(",
"c",
"context",
".",
"Context",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"databaseSettings",
",",
"err",
":=",
"GetUncached",
"(",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"map",
"[",
"string",
"]",
"string",
"{",
"\"",
"\"",
":",
"databaseSettings",
".",
"Server",
",",
"\"",
"\"",
":",
"databaseSettings",
".",
"Username",
",",
"\"",
"\"",
":",
"databaseSettings",
".",
"Password",
",",
"\"",
"\"",
":",
"databaseSettings",
".",
"Database",
",",
"}",
",",
"nil",
"\n",
"}"
] | // ReadSettings returns settings for display. | [
"ReadSettings",
"returns",
"settings",
"for",
"display",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/settings/settings.go#L123-L135 |
9,199 | luci/luci-go | machine-db/appengine/settings/settings.go | WriteSettings | func (*DatabaseSettings) WriteSettings(c context.Context, values map[string]string, who, why string) error {
databaseSettings := &DatabaseSettings{
Server: values["Server"],
Username: values["Username"],
Password: values["Password"],
Database: values["Database"],
}
return settings.SetIfChanged(c, settingsKey, databaseSettings, who, why)
} | go | func (*DatabaseSettings) WriteSettings(c context.Context, values map[string]string, who, why string) error {
databaseSettings := &DatabaseSettings{
Server: values["Server"],
Username: values["Username"],
Password: values["Password"],
Database: values["Database"],
}
return settings.SetIfChanged(c, settingsKey, databaseSettings, who, why)
} | [
"func",
"(",
"*",
"DatabaseSettings",
")",
"WriteSettings",
"(",
"c",
"context",
".",
"Context",
",",
"values",
"map",
"[",
"string",
"]",
"string",
",",
"who",
",",
"why",
"string",
")",
"error",
"{",
"databaseSettings",
":=",
"&",
"DatabaseSettings",
"{",
"Server",
":",
"values",
"[",
"\"",
"\"",
"]",
",",
"Username",
":",
"values",
"[",
"\"",
"\"",
"]",
",",
"Password",
":",
"values",
"[",
"\"",
"\"",
"]",
",",
"Database",
":",
"values",
"[",
"\"",
"\"",
"]",
",",
"}",
"\n\n",
"return",
"settings",
".",
"SetIfChanged",
"(",
"c",
",",
"settingsKey",
",",
"databaseSettings",
",",
"who",
",",
"why",
")",
"\n",
"}"
] | // WriteSettings commits any changes to the settings. | [
"WriteSettings",
"commits",
"any",
"changes",
"to",
"the",
"settings",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/appengine/settings/settings.go#L138-L147 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.