id
int32 0
167k
| repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
sequence | docstring
stringlengths 6
2.61k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 85
252
|
---|---|---|---|---|---|---|---|---|---|---|---|
7,600 | luci/luci-go | common/data/text/templateproto/normalize.go | Accepts | func (s *Schema) Accepts(v *Value) error {
typ := reflect.TypeOf(s.Schema)
if typ == typeOfSchemaEnum {
typ = typeOfSchemaStr
}
if typ != reflect.TypeOf(v.schemaType()) {
return fmt.Errorf("type is %q, expected %q", schemaTypeStr(v.schemaType()), schemaTypeStr(s.Schema))
}
return nil
} | go | func (s *Schema) Accepts(v *Value) error {
typ := reflect.TypeOf(s.Schema)
if typ == typeOfSchemaEnum {
typ = typeOfSchemaStr
}
if typ != reflect.TypeOf(v.schemaType()) {
return fmt.Errorf("type is %q, expected %q", schemaTypeStr(v.schemaType()), schemaTypeStr(s.Schema))
}
return nil
} | [
"func",
"(",
"s",
"*",
"Schema",
")",
"Accepts",
"(",
"v",
"*",
"Value",
")",
"error",
"{",
"typ",
":=",
"reflect",
".",
"TypeOf",
"(",
"s",
".",
"Schema",
")",
"\n",
"if",
"typ",
"==",
"typeOfSchemaEnum",
"{",
"typ",
"=",
"typeOfSchemaStr",
"\n",
"}",
"\n",
"if",
"typ",
"!=",
"reflect",
".",
"TypeOf",
"(",
"v",
".",
"schemaType",
"(",
")",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"schemaTypeStr",
"(",
"v",
".",
"schemaType",
"(",
")",
")",
",",
"schemaTypeStr",
"(",
"s",
".",
"Schema",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Accepts returns nil if this Schema can accept the Value. | [
"Accepts",
"returns",
"nil",
"if",
"this",
"Schema",
"can",
"accept",
"the",
"Value",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/text/templateproto/normalize.go#L266-L275 |
7,601 | luci/luci-go | common/data/text/templateproto/normalize.go | Normalize | func (s *Specifier) Normalize() error {
if s.TemplateName == "" {
return errors.New("empty template_name")
}
for k, v := range s.Params {
if k == "" {
return errors.New("empty param key")
}
if err := v.Normalize(); err != nil {
return fmt.Errorf("param %q: %s", k, err)
}
}
return nil
} | go | func (s *Specifier) Normalize() error {
if s.TemplateName == "" {
return errors.New("empty template_name")
}
for k, v := range s.Params {
if k == "" {
return errors.New("empty param key")
}
if err := v.Normalize(); err != nil {
return fmt.Errorf("param %q: %s", k, err)
}
}
return nil
} | [
"func",
"(",
"s",
"*",
"Specifier",
")",
"Normalize",
"(",
")",
"error",
"{",
"if",
"s",
".",
"TemplateName",
"==",
"\"",
"\"",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"s",
".",
"Params",
"{",
"if",
"k",
"==",
"\"",
"\"",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"v",
".",
"Normalize",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"k",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Normalize will normalize this Specifier | [
"Normalize",
"will",
"normalize",
"this",
"Specifier"
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/text/templateproto/normalize.go#L342-L355 |
7,602 | luci/luci-go | server/tokens/tokens.go | hash | func (a TokenAlgo) hash(secret []byte) hash.Hash {
switch a {
case TokenAlgoHmacSHA256:
return hmac.New(sha256.New, secret)
}
return nil
} | go | func (a TokenAlgo) hash(secret []byte) hash.Hash {
switch a {
case TokenAlgoHmacSHA256:
return hmac.New(sha256.New, secret)
}
return nil
} | [
"func",
"(",
"a",
"TokenAlgo",
")",
"hash",
"(",
"secret",
"[",
"]",
"byte",
")",
"hash",
".",
"Hash",
"{",
"switch",
"a",
"{",
"case",
"TokenAlgoHmacSHA256",
":",
"return",
"hmac",
".",
"New",
"(",
"sha256",
".",
"New",
",",
"secret",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // hash returns hash.Hash that computes the digest or nil if algo is unknown. | [
"hash",
"returns",
"hash",
".",
"Hash",
"that",
"computes",
"the",
"digest",
"or",
"nil",
"if",
"algo",
"is",
"unknown",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/tokens/tokens.go#L49-L55 |
7,603 | luci/luci-go | server/tokens/tokens.go | Validate | func (k *TokenKind) Validate(c context.Context, token string, state []byte) (map[string]string, error) {
digestLen := k.Algo.digestLen()
if digestLen == 0 {
return nil, fmt.Errorf("tokens: unknown algo %q", k.Algo)
}
blob, err := base64.RawURLEncoding.DecodeString(token)
if err != nil {
return nil, err
}
// One byte for version, at least one byte for public embedded dict portion,
// the rest is MAC digest.
if len(blob) < digestLen+2 {
return nil, fmt.Errorf("tokens: the token is too small")
}
// Data inside the token.
version := blob[0]
public := blob[1 : len(blob)-digestLen]
tokenMac := blob[len(blob)-digestLen:]
// Data that should have been used to generate HMAC.
toAuth := dataToAuth(version, public, state)
// Token could have been generated by previous value of the secret, so check
// them too.
secret, err := secrets.GetSecret(c, k.SecretKey)
if err != nil {
return nil, err
}
goodToken := false
for _, blob := range secret.Blobs() {
goodMac, err := computeMAC(k.Algo, blob.Blob, toAuth)
if err != nil {
return nil, err
}
if hmac.Equal(tokenMac, goodMac) {
goodToken = true
break
}
}
if !goodToken {
return nil, fmt.Errorf("tokens: bad token MAC")
}
// Token is authenticated, now check the rest.
if version != k.Version {
return nil, fmt.Errorf("tokens: bad version %q, expecting %q", version, k.Version)
}
embedded := map[string]string{}
if err := json.Unmarshal(public, &embedded); err != nil {
return nil, err
}
// Grab issued time, reject token from the future.
now := clock.Now(c)
issuedMs, err := popInt(embedded, "_i")
if err != nil {
return nil, err
}
issuedTs := time.Unix(0, issuedMs*1e6)
if issuedTs.After(now.Add(allowedClockDrift)) {
return nil, fmt.Errorf("tokens: issued timestamp is in the future")
}
// Grab expiration time embedded into the token, if any.
expiration := k.Expiration
if _, ok := embedded["_x"]; ok {
expirationMs, err := popInt(embedded, "_x")
if err != nil {
return nil, err
}
expiration = time.Duration(expirationMs) * time.Millisecond
}
if expiration < 0 {
return nil, fmt.Errorf("tokens: bad token, expiration can't be negative")
}
// Check token expiration.
expired := now.Sub(issuedTs.Add(expiration))
if expired > 0 {
return nil, fmt.Errorf("tokens: token expired %s ago", expired)
}
return embedded, nil
} | go | func (k *TokenKind) Validate(c context.Context, token string, state []byte) (map[string]string, error) {
digestLen := k.Algo.digestLen()
if digestLen == 0 {
return nil, fmt.Errorf("tokens: unknown algo %q", k.Algo)
}
blob, err := base64.RawURLEncoding.DecodeString(token)
if err != nil {
return nil, err
}
// One byte for version, at least one byte for public embedded dict portion,
// the rest is MAC digest.
if len(blob) < digestLen+2 {
return nil, fmt.Errorf("tokens: the token is too small")
}
// Data inside the token.
version := blob[0]
public := blob[1 : len(blob)-digestLen]
tokenMac := blob[len(blob)-digestLen:]
// Data that should have been used to generate HMAC.
toAuth := dataToAuth(version, public, state)
// Token could have been generated by previous value of the secret, so check
// them too.
secret, err := secrets.GetSecret(c, k.SecretKey)
if err != nil {
return nil, err
}
goodToken := false
for _, blob := range secret.Blobs() {
goodMac, err := computeMAC(k.Algo, blob.Blob, toAuth)
if err != nil {
return nil, err
}
if hmac.Equal(tokenMac, goodMac) {
goodToken = true
break
}
}
if !goodToken {
return nil, fmt.Errorf("tokens: bad token MAC")
}
// Token is authenticated, now check the rest.
if version != k.Version {
return nil, fmt.Errorf("tokens: bad version %q, expecting %q", version, k.Version)
}
embedded := map[string]string{}
if err := json.Unmarshal(public, &embedded); err != nil {
return nil, err
}
// Grab issued time, reject token from the future.
now := clock.Now(c)
issuedMs, err := popInt(embedded, "_i")
if err != nil {
return nil, err
}
issuedTs := time.Unix(0, issuedMs*1e6)
if issuedTs.After(now.Add(allowedClockDrift)) {
return nil, fmt.Errorf("tokens: issued timestamp is in the future")
}
// Grab expiration time embedded into the token, if any.
expiration := k.Expiration
if _, ok := embedded["_x"]; ok {
expirationMs, err := popInt(embedded, "_x")
if err != nil {
return nil, err
}
expiration = time.Duration(expirationMs) * time.Millisecond
}
if expiration < 0 {
return nil, fmt.Errorf("tokens: bad token, expiration can't be negative")
}
// Check token expiration.
expired := now.Sub(issuedTs.Add(expiration))
if expired > 0 {
return nil, fmt.Errorf("tokens: token expired %s ago", expired)
}
return embedded, nil
} | [
"func",
"(",
"k",
"*",
"TokenKind",
")",
"Validate",
"(",
"c",
"context",
".",
"Context",
",",
"token",
"string",
",",
"state",
"[",
"]",
"byte",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"digestLen",
":=",
"k",
".",
"Algo",
".",
"digestLen",
"(",
")",
"\n",
"if",
"digestLen",
"==",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"k",
".",
"Algo",
")",
"\n",
"}",
"\n",
"blob",
",",
"err",
":=",
"base64",
".",
"RawURLEncoding",
".",
"DecodeString",
"(",
"token",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// One byte for version, at least one byte for public embedded dict portion,",
"// the rest is MAC digest.",
"if",
"len",
"(",
"blob",
")",
"<",
"digestLen",
"+",
"2",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Data inside the token.",
"version",
":=",
"blob",
"[",
"0",
"]",
"\n",
"public",
":=",
"blob",
"[",
"1",
":",
"len",
"(",
"blob",
")",
"-",
"digestLen",
"]",
"\n",
"tokenMac",
":=",
"blob",
"[",
"len",
"(",
"blob",
")",
"-",
"digestLen",
":",
"]",
"\n\n",
"// Data that should have been used to generate HMAC.",
"toAuth",
":=",
"dataToAuth",
"(",
"version",
",",
"public",
",",
"state",
")",
"\n\n",
"// Token could have been generated by previous value of the secret, so check",
"// them too.",
"secret",
",",
"err",
":=",
"secrets",
".",
"GetSecret",
"(",
"c",
",",
"k",
".",
"SecretKey",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"goodToken",
":=",
"false",
"\n",
"for",
"_",
",",
"blob",
":=",
"range",
"secret",
".",
"Blobs",
"(",
")",
"{",
"goodMac",
",",
"err",
":=",
"computeMAC",
"(",
"k",
".",
"Algo",
",",
"blob",
".",
"Blob",
",",
"toAuth",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"hmac",
".",
"Equal",
"(",
"tokenMac",
",",
"goodMac",
")",
"{",
"goodToken",
"=",
"true",
"\n",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"!",
"goodToken",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Token is authenticated, now check the rest.",
"if",
"version",
"!=",
"k",
".",
"Version",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"version",
",",
"k",
".",
"Version",
")",
"\n",
"}",
"\n",
"embedded",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"}",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"public",
",",
"&",
"embedded",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// Grab issued time, reject token from the future.",
"now",
":=",
"clock",
".",
"Now",
"(",
"c",
")",
"\n",
"issuedMs",
",",
"err",
":=",
"popInt",
"(",
"embedded",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"issuedTs",
":=",
"time",
".",
"Unix",
"(",
"0",
",",
"issuedMs",
"*",
"1e6",
")",
"\n",
"if",
"issuedTs",
".",
"After",
"(",
"now",
".",
"Add",
"(",
"allowedClockDrift",
")",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Grab expiration time embedded into the token, if any.",
"expiration",
":=",
"k",
".",
"Expiration",
"\n",
"if",
"_",
",",
"ok",
":=",
"embedded",
"[",
"\"",
"\"",
"]",
";",
"ok",
"{",
"expirationMs",
",",
"err",
":=",
"popInt",
"(",
"embedded",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"expiration",
"=",
"time",
".",
"Duration",
"(",
"expirationMs",
")",
"*",
"time",
".",
"Millisecond",
"\n",
"}",
"\n",
"if",
"expiration",
"<",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Check token expiration.",
"expired",
":=",
"now",
".",
"Sub",
"(",
"issuedTs",
".",
"Add",
"(",
"expiration",
")",
")",
"\n",
"if",
"expired",
">",
"0",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"expired",
")",
"\n",
"}",
"\n\n",
"return",
"embedded",
",",
"nil",
"\n",
"}"
] | // Validate checks token MAC and expiration, decodes data embedded into it.
//
// 'state' must be exactly the same as passed to Generate when creating a token.
// If it's different, the token is considered invalid. It usually contains some
// implicitly passed state that should be the same when token is generated and
// validated. For example, it may be an account ID of a current caller. Then if
// such token is used by another account, it is considered invalid.
//
// The context is used to grab secrets.Store and the current time. | [
"Validate",
"checks",
"token",
"MAC",
"and",
"expiration",
"decodes",
"data",
"embedded",
"into",
"it",
".",
"state",
"must",
"be",
"exactly",
"the",
"same",
"as",
"passed",
"to",
"Generate",
"when",
"creating",
"a",
"token",
".",
"If",
"it",
"s",
"different",
"the",
"token",
"is",
"considered",
"invalid",
".",
"It",
"usually",
"contains",
"some",
"implicitly",
"passed",
"state",
"that",
"should",
"be",
"the",
"same",
"when",
"token",
"is",
"generated",
"and",
"validated",
".",
"For",
"example",
"it",
"may",
"be",
"an",
"account",
"ID",
"of",
"a",
"current",
"caller",
".",
"Then",
"if",
"such",
"token",
"is",
"used",
"by",
"another",
"account",
"it",
"is",
"considered",
"invalid",
".",
"The",
"context",
"is",
"used",
"to",
"grab",
"secrets",
".",
"Store",
"and",
"the",
"current",
"time",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/tokens/tokens.go#L142-L227 |
7,604 | luci/luci-go | server/tokens/tokens.go | popInt | func popInt(m map[string]string, key string) (int64, error) {
str, ok := m[key]
if !ok {
return 0, fmt.Errorf("tokens: bad token, missing %q key", key)
}
asInt, err := strconv.ParseInt(str, 10, 64)
if err != nil {
return 0, fmt.Errorf("tokens: bad token, %q is not a number", str)
}
delete(m, key)
return asInt, nil
} | go | func popInt(m map[string]string, key string) (int64, error) {
str, ok := m[key]
if !ok {
return 0, fmt.Errorf("tokens: bad token, missing %q key", key)
}
asInt, err := strconv.ParseInt(str, 10, 64)
if err != nil {
return 0, fmt.Errorf("tokens: bad token, %q is not a number", str)
}
delete(m, key)
return asInt, nil
} | [
"func",
"popInt",
"(",
"m",
"map",
"[",
"string",
"]",
"string",
",",
"key",
"string",
")",
"(",
"int64",
",",
"error",
")",
"{",
"str",
",",
"ok",
":=",
"m",
"[",
"key",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"key",
")",
"\n",
"}",
"\n",
"asInt",
",",
"err",
":=",
"strconv",
".",
"ParseInt",
"(",
"str",
",",
"10",
",",
"64",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"str",
")",
"\n",
"}",
"\n",
"delete",
"(",
"m",
",",
"key",
")",
"\n",
"return",
"asInt",
",",
"nil",
"\n",
"}"
] | // extractInt pops integer value from the map. | [
"extractInt",
"pops",
"integer",
"value",
"from",
"the",
"map",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/tokens/tokens.go#L230-L241 |
7,605 | luci/luci-go | server/tokens/tokens.go | dataToAuth | func dataToAuth(version byte, public []byte, state []byte) [][]byte {
out := [][]byte{
{version},
public,
}
if len(state) != 0 {
out = append(out, state)
}
return out
} | go | func dataToAuth(version byte, public []byte, state []byte) [][]byte {
out := [][]byte{
{version},
public,
}
if len(state) != 0 {
out = append(out, state)
}
return out
} | [
"func",
"dataToAuth",
"(",
"version",
"byte",
",",
"public",
"[",
"]",
"byte",
",",
"state",
"[",
"]",
"byte",
")",
"[",
"]",
"[",
"]",
"byte",
"{",
"out",
":=",
"[",
"]",
"[",
"]",
"byte",
"{",
"{",
"version",
"}",
",",
"public",
",",
"}",
"\n",
"if",
"len",
"(",
"state",
")",
"!=",
"0",
"{",
"out",
"=",
"append",
"(",
"out",
",",
"state",
")",
"\n",
"}",
"\n",
"return",
"out",
"\n",
"}"
] | // dataToAuth generates list of byte blobs authenticated by MAC. | [
"dataToAuth",
"generates",
"list",
"of",
"byte",
"blobs",
"authenticated",
"by",
"MAC",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/tokens/tokens.go#L244-L253 |
7,606 | luci/luci-go | server/tokens/tokens.go | computeMAC | func computeMAC(algo TokenAlgo, secret []byte, dataToAuth [][]byte) ([]byte, error) {
hash := algo.hash(secret)
if hash == nil {
return nil, fmt.Errorf("tokens: unknown algo %q", algo)
}
for _, chunk := range dataToAuth {
// Separator between length header and the body is needed because length
// encoding is variable-length (decimal string).
if _, err := fmt.Fprintf(hash, "%d\n", len(chunk)); err != nil {
return nil, err
}
if _, err := hash.Write(chunk); err != nil {
return nil, err
}
}
return hash.Sum(nil), nil
} | go | func computeMAC(algo TokenAlgo, secret []byte, dataToAuth [][]byte) ([]byte, error) {
hash := algo.hash(secret)
if hash == nil {
return nil, fmt.Errorf("tokens: unknown algo %q", algo)
}
for _, chunk := range dataToAuth {
// Separator between length header and the body is needed because length
// encoding is variable-length (decimal string).
if _, err := fmt.Fprintf(hash, "%d\n", len(chunk)); err != nil {
return nil, err
}
if _, err := hash.Write(chunk); err != nil {
return nil, err
}
}
return hash.Sum(nil), nil
} | [
"func",
"computeMAC",
"(",
"algo",
"TokenAlgo",
",",
"secret",
"[",
"]",
"byte",
",",
"dataToAuth",
"[",
"]",
"[",
"]",
"byte",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"hash",
":=",
"algo",
".",
"hash",
"(",
"secret",
")",
"\n",
"if",
"hash",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"algo",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"chunk",
":=",
"range",
"dataToAuth",
"{",
"// Separator between length header and the body is needed because length",
"// encoding is variable-length (decimal string).",
"if",
"_",
",",
"err",
":=",
"fmt",
".",
"Fprintf",
"(",
"hash",
",",
"\"",
"\\n",
"\"",
",",
"len",
"(",
"chunk",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"hash",
".",
"Write",
"(",
"chunk",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"hash",
".",
"Sum",
"(",
"nil",
")",
",",
"nil",
"\n",
"}"
] | // computeMAC packs dataToAuth into single blob and computes its MAC. | [
"computeMAC",
"packs",
"dataToAuth",
"into",
"single",
"blob",
"and",
"computes",
"its",
"MAC",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/tokens/tokens.go#L256-L272 |
7,607 | luci/luci-go | config/server/cfgclient/backend/caching/codec.go | Encode | func Encode(v interface{}) ([]byte, error) {
var buf bytes.Buffer
zw := zlib.NewWriter(&buf)
enc := json.NewEncoder(zw)
if err := enc.Encode(v); err != nil {
zw.Close()
return nil, errors.Annotate(err, "failed to JSON-encode").Err()
}
if err := zw.Close(); err != nil {
return nil, errors.Annotate(err, "failed to Close zlib Writer").Err()
}
return buf.Bytes(), nil
} | go | func Encode(v interface{}) ([]byte, error) {
var buf bytes.Buffer
zw := zlib.NewWriter(&buf)
enc := json.NewEncoder(zw)
if err := enc.Encode(v); err != nil {
zw.Close()
return nil, errors.Annotate(err, "failed to JSON-encode").Err()
}
if err := zw.Close(); err != nil {
return nil, errors.Annotate(err, "failed to Close zlib Writer").Err()
}
return buf.Bytes(), nil
} | [
"func",
"Encode",
"(",
"v",
"interface",
"{",
"}",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"zw",
":=",
"zlib",
".",
"NewWriter",
"(",
"&",
"buf",
")",
"\n",
"enc",
":=",
"json",
".",
"NewEncoder",
"(",
"zw",
")",
"\n\n",
"if",
"err",
":=",
"enc",
".",
"Encode",
"(",
"v",
")",
";",
"err",
"!=",
"nil",
"{",
"zw",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"zw",
".",
"Close",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"return",
"buf",
".",
"Bytes",
"(",
")",
",",
"nil",
"\n",
"}"
] | // Encode is a convenience method for generating a ZLIB-compressed JSON-encoded
// object. | [
"Encode",
"is",
"a",
"convenience",
"method",
"for",
"generating",
"a",
"ZLIB",
"-",
"compressed",
"JSON",
"-",
"encoded",
"object",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/backend/caching/codec.go#L30-L43 |
7,608 | luci/luci-go | config/server/cfgclient/backend/caching/codec.go | Decode | func Decode(d []byte, v interface{}) error {
zr, err := zlib.NewReader(bytes.NewReader(d))
if err != nil {
return errors.Annotate(err, "failed to create zlib Reader").Err()
}
defer zr.Close()
if err := json.NewDecoder(zr).Decode(v); err != nil {
return errors.Annotate(err, "failed to JSON-decode").Err()
}
return nil
} | go | func Decode(d []byte, v interface{}) error {
zr, err := zlib.NewReader(bytes.NewReader(d))
if err != nil {
return errors.Annotate(err, "failed to create zlib Reader").Err()
}
defer zr.Close()
if err := json.NewDecoder(zr).Decode(v); err != nil {
return errors.Annotate(err, "failed to JSON-decode").Err()
}
return nil
} | [
"func",
"Decode",
"(",
"d",
"[",
"]",
"byte",
",",
"v",
"interface",
"{",
"}",
")",
"error",
"{",
"zr",
",",
"err",
":=",
"zlib",
".",
"NewReader",
"(",
"bytes",
".",
"NewReader",
"(",
"d",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"defer",
"zr",
".",
"Close",
"(",
")",
"\n\n",
"if",
"err",
":=",
"json",
".",
"NewDecoder",
"(",
"zr",
")",
".",
"Decode",
"(",
"v",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Decode is a convenience method for decoding a ZLIB-compressed JSON-encoded
// object encoded by Encode. | [
"Decode",
"is",
"a",
"convenience",
"method",
"for",
"decoding",
"a",
"ZLIB",
"-",
"compressed",
"JSON",
"-",
"encoded",
"object",
"encoded",
"by",
"Encode",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/server/cfgclient/backend/caching/codec.go#L47-L58 |
7,609 | luci/luci-go | logdog/common/storage/bigtable/rowKey.go | newRowKey | func newRowKey(project, path string, index, count int64) *rowKey {
h := sha256.New()
_, _ = h.Write([]byte(project))
_, _ = h.Write([]byte("/"))
_, _ = h.Write([]byte(path))
return &rowKey{
pathHash: h.Sum(nil),
index: index,
count: count,
}
} | go | func newRowKey(project, path string, index, count int64) *rowKey {
h := sha256.New()
_, _ = h.Write([]byte(project))
_, _ = h.Write([]byte("/"))
_, _ = h.Write([]byte(path))
return &rowKey{
pathHash: h.Sum(nil),
index: index,
count: count,
}
} | [
"func",
"newRowKey",
"(",
"project",
",",
"path",
"string",
",",
"index",
",",
"count",
"int64",
")",
"*",
"rowKey",
"{",
"h",
":=",
"sha256",
".",
"New",
"(",
")",
"\n\n",
"_",
",",
"_",
"=",
"h",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"project",
")",
")",
"\n",
"_",
",",
"_",
"=",
"h",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
"\n",
"_",
",",
"_",
"=",
"h",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"path",
")",
")",
"\n",
"return",
"&",
"rowKey",
"{",
"pathHash",
":",
"h",
".",
"Sum",
"(",
"nil",
")",
",",
"index",
":",
"index",
",",
"count",
":",
"count",
",",
"}",
"\n",
"}"
] | // newRowKey generates the row key matching a given entry path and index. | [
"newRowKey",
"generates",
"the",
"row",
"key",
"matching",
"a",
"given",
"entry",
"path",
"and",
"index",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/storage/bigtable/rowKey.go#L119-L130 |
7,610 | luci/luci-go | logdog/common/storage/bigtable/rowKey.go | decodeRowKey | func decodeRowKey(v string) (*rowKey, error) {
keyParts := strings.SplitN(v, "~", 3)
if len(keyParts) != 3 {
return nil, errMalformedRowKey
}
hashEnc, idxEnc, countEnc := keyParts[0], keyParts[1], keyParts[2]
if base64.URLEncoding.DecodedLen(len(hashEnc)) < sha256.Size {
return nil, errMalformedRowKey
}
// Decode encoded project/path hash.
var err error
rk := rowKey{}
rk.pathHash, err = base64.URLEncoding.DecodeString(hashEnc)
if err != nil {
return nil, errMalformedRowKey
}
// Decode index.
rk.index, err = readHexInt64(idxEnc)
if err != nil {
return nil, err
}
// If a count is available, decode that as well.
rk.count, err = readHexInt64(countEnc)
if err != nil {
return nil, err
}
return &rk, nil
} | go | func decodeRowKey(v string) (*rowKey, error) {
keyParts := strings.SplitN(v, "~", 3)
if len(keyParts) != 3 {
return nil, errMalformedRowKey
}
hashEnc, idxEnc, countEnc := keyParts[0], keyParts[1], keyParts[2]
if base64.URLEncoding.DecodedLen(len(hashEnc)) < sha256.Size {
return nil, errMalformedRowKey
}
// Decode encoded project/path hash.
var err error
rk := rowKey{}
rk.pathHash, err = base64.URLEncoding.DecodeString(hashEnc)
if err != nil {
return nil, errMalformedRowKey
}
// Decode index.
rk.index, err = readHexInt64(idxEnc)
if err != nil {
return nil, err
}
// If a count is available, decode that as well.
rk.count, err = readHexInt64(countEnc)
if err != nil {
return nil, err
}
return &rk, nil
} | [
"func",
"decodeRowKey",
"(",
"v",
"string",
")",
"(",
"*",
"rowKey",
",",
"error",
")",
"{",
"keyParts",
":=",
"strings",
".",
"SplitN",
"(",
"v",
",",
"\"",
"\"",
",",
"3",
")",
"\n",
"if",
"len",
"(",
"keyParts",
")",
"!=",
"3",
"{",
"return",
"nil",
",",
"errMalformedRowKey",
"\n",
"}",
"\n\n",
"hashEnc",
",",
"idxEnc",
",",
"countEnc",
":=",
"keyParts",
"[",
"0",
"]",
",",
"keyParts",
"[",
"1",
"]",
",",
"keyParts",
"[",
"2",
"]",
"\n",
"if",
"base64",
".",
"URLEncoding",
".",
"DecodedLen",
"(",
"len",
"(",
"hashEnc",
")",
")",
"<",
"sha256",
".",
"Size",
"{",
"return",
"nil",
",",
"errMalformedRowKey",
"\n",
"}",
"\n\n",
"// Decode encoded project/path hash.",
"var",
"err",
"error",
"\n",
"rk",
":=",
"rowKey",
"{",
"}",
"\n",
"rk",
".",
"pathHash",
",",
"err",
"=",
"base64",
".",
"URLEncoding",
".",
"DecodeString",
"(",
"hashEnc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"errMalformedRowKey",
"\n",
"}",
"\n\n",
"// Decode index.",
"rk",
".",
"index",
",",
"err",
"=",
"readHexInt64",
"(",
"idxEnc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"// If a count is available, decode that as well.",
"rk",
".",
"count",
",",
"err",
"=",
"readHexInt64",
"(",
"countEnc",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"rk",
",",
"nil",
"\n",
"}"
] | // decodeRowKey decodes an encoded row key into its structural components. | [
"decodeRowKey",
"decodes",
"an",
"encoded",
"row",
"key",
"into",
"its",
"structural",
"components",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/storage/bigtable/rowKey.go#L133-L165 |
7,611 | luci/luci-go | logdog/common/storage/bigtable/rowKey.go | encode | func (rk *rowKey) encode() (v string) {
// Write the final key to "key": (base64(HASH)~hex(INDEX))
withRowKeyBuffers(func(rkb *rowKeyBuffers) {
rkb.appendPathPrefix(rk.pathHash)
rkb.appendBytes([]byte("~"))
rkb.appendInt64(rk.index)
rkb.appendBytes([]byte("~"))
rkb.appendInt64(rk.count)
v = rkb.value()
})
return
} | go | func (rk *rowKey) encode() (v string) {
// Write the final key to "key": (base64(HASH)~hex(INDEX))
withRowKeyBuffers(func(rkb *rowKeyBuffers) {
rkb.appendPathPrefix(rk.pathHash)
rkb.appendBytes([]byte("~"))
rkb.appendInt64(rk.index)
rkb.appendBytes([]byte("~"))
rkb.appendInt64(rk.count)
v = rkb.value()
})
return
} | [
"func",
"(",
"rk",
"*",
"rowKey",
")",
"encode",
"(",
")",
"(",
"v",
"string",
")",
"{",
"// Write the final key to \"key\": (base64(HASH)~hex(INDEX))",
"withRowKeyBuffers",
"(",
"func",
"(",
"rkb",
"*",
"rowKeyBuffers",
")",
"{",
"rkb",
".",
"appendPathPrefix",
"(",
"rk",
".",
"pathHash",
")",
"\n",
"rkb",
".",
"appendBytes",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
"\n",
"rkb",
".",
"appendInt64",
"(",
"rk",
".",
"index",
")",
"\n",
"rkb",
".",
"appendBytes",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
"\n",
"rkb",
".",
"appendInt64",
"(",
"rk",
".",
"count",
")",
"\n",
"v",
"=",
"rkb",
".",
"value",
"(",
")",
"\n",
"}",
")",
"\n",
"return",
"\n",
"}"
] | // newRowKey instantiates a new rowKey from its components. | [
"newRowKey",
"instantiates",
"a",
"new",
"rowKey",
"from",
"its",
"components",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/storage/bigtable/rowKey.go#L172-L183 |
7,612 | luci/luci-go | logdog/common/storage/bigtable/rowKey.go | sharesPathWith | func (rk *rowKey) sharesPathWith(o *rowKey) bool {
return bytes.Equal(rk.pathHash, o.pathHash)
} | go | func (rk *rowKey) sharesPathWith(o *rowKey) bool {
return bytes.Equal(rk.pathHash, o.pathHash)
} | [
"func",
"(",
"rk",
"*",
"rowKey",
")",
"sharesPathWith",
"(",
"o",
"*",
"rowKey",
")",
"bool",
"{",
"return",
"bytes",
".",
"Equal",
"(",
"rk",
".",
"pathHash",
",",
"o",
".",
"pathHash",
")",
"\n",
"}"
] | // sharesPrefixWith tests if the "path" component of the row key "rk" matches
// the "path" component of "o". | [
"sharesPrefixWith",
"tests",
"if",
"the",
"path",
"component",
"of",
"the",
"row",
"key",
"rk",
"matches",
"the",
"path",
"component",
"of",
"o",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/common/storage/bigtable/rowKey.go#L220-L222 |
7,613 | luci/luci-go | cipd/client/cipd/client.go | LoadFromEnv | func (opts *ClientOptions) LoadFromEnv(getEnv func(string) string) error {
if opts.CacheDir == "" {
if v := getEnv(EnvCacheDir); v != "" {
if !filepath.IsAbs(v) {
return fmt.Errorf("bad %s: not an absolute path - %s", EnvCacheDir, v)
}
opts.CacheDir = v
}
}
if opts.UserAgent == "" {
if v := getEnv(EnvHTTPUserAgentPrefix); v != "" {
opts.UserAgent = fmt.Sprintf("%s/%s", v, UserAgent)
}
}
return nil
} | go | func (opts *ClientOptions) LoadFromEnv(getEnv func(string) string) error {
if opts.CacheDir == "" {
if v := getEnv(EnvCacheDir); v != "" {
if !filepath.IsAbs(v) {
return fmt.Errorf("bad %s: not an absolute path - %s", EnvCacheDir, v)
}
opts.CacheDir = v
}
}
if opts.UserAgent == "" {
if v := getEnv(EnvHTTPUserAgentPrefix); v != "" {
opts.UserAgent = fmt.Sprintf("%s/%s", v, UserAgent)
}
}
return nil
} | [
"func",
"(",
"opts",
"*",
"ClientOptions",
")",
"LoadFromEnv",
"(",
"getEnv",
"func",
"(",
"string",
")",
"string",
")",
"error",
"{",
"if",
"opts",
".",
"CacheDir",
"==",
"\"",
"\"",
"{",
"if",
"v",
":=",
"getEnv",
"(",
"EnvCacheDir",
")",
";",
"v",
"!=",
"\"",
"\"",
"{",
"if",
"!",
"filepath",
".",
"IsAbs",
"(",
"v",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"EnvCacheDir",
",",
"v",
")",
"\n",
"}",
"\n",
"opts",
".",
"CacheDir",
"=",
"v",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"opts",
".",
"UserAgent",
"==",
"\"",
"\"",
"{",
"if",
"v",
":=",
"getEnv",
"(",
"EnvHTTPUserAgentPrefix",
")",
";",
"v",
"!=",
"\"",
"\"",
"{",
"opts",
".",
"UserAgent",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"v",
",",
"UserAgent",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // LoadFromEnv loads supplied default values from an environment into opts.
//
// The supplied getEnv function is used to access named enviornment variables,
// and should return an empty string if the enviornment variable is not defined. | [
"LoadFromEnv",
"loads",
"supplied",
"default",
"values",
"from",
"an",
"environment",
"into",
"opts",
".",
"The",
"supplied",
"getEnv",
"function",
"is",
"used",
"to",
"access",
"named",
"enviornment",
"variables",
"and",
"should",
"return",
"an",
"empty",
"string",
"if",
"the",
"enviornment",
"variable",
"is",
"not",
"defined",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/client.go#L365-L380 |
7,614 | luci/luci-go | cipd/client/cipd/client.go | NewClient | func NewClient(opts ClientOptions) (Client, error) {
if opts.AnonymousClient == nil {
opts.AnonymousClient = http.DefaultClient
}
if opts.AuthenticatedClient == nil {
opts.AuthenticatedClient = opts.AnonymousClient
}
if opts.UserAgent == "" {
opts.UserAgent = UserAgent
}
// Validate and normalize service URL.
if opts.ServiceURL == "" {
return nil, fmt.Errorf("ServiceURL is required")
}
parsed, err := url.Parse(opts.ServiceURL)
if err != nil {
return nil, fmt.Errorf("not a valid URL %q - %s", opts.ServiceURL, err)
}
if parsed.Path != "" && parsed.Path != "/" {
return nil, fmt.Errorf("expecting a root URL, not %q", opts.ServiceURL)
}
opts.ServiceURL = fmt.Sprintf("%s://%s", parsed.Scheme, parsed.Host)
prpcC := &prpc.Client{
C: opts.AuthenticatedClient,
Host: parsed.Host,
Options: &prpc.Options{
UserAgent: opts.UserAgent,
Insecure: parsed.Scheme == "http", // for testing with local dev server
Retry: func() retry.Iterator {
return &retry.ExponentialBackoff{
Limited: retry.Limited{
Delay: time.Second,
Retries: 10,
},
}
},
},
}
cas := opts.casMock
if cas == nil {
cas = api.NewStoragePRPCClient(prpcC)
}
repo := opts.repoMock
if repo == nil {
repo = api.NewRepositoryPRPCClient(prpcC)
}
storage := opts.storageMock
if storage == nil {
storage = &storageImpl{
chunkSize: uploadChunkSize,
userAgent: opts.UserAgent,
client: opts.AnonymousClient,
}
}
return &clientImpl{
ClientOptions: opts,
cas: cas,
repo: repo,
storage: storage,
deployer: deployer.New(opts.Root),
}, nil
} | go | func NewClient(opts ClientOptions) (Client, error) {
if opts.AnonymousClient == nil {
opts.AnonymousClient = http.DefaultClient
}
if opts.AuthenticatedClient == nil {
opts.AuthenticatedClient = opts.AnonymousClient
}
if opts.UserAgent == "" {
opts.UserAgent = UserAgent
}
// Validate and normalize service URL.
if opts.ServiceURL == "" {
return nil, fmt.Errorf("ServiceURL is required")
}
parsed, err := url.Parse(opts.ServiceURL)
if err != nil {
return nil, fmt.Errorf("not a valid URL %q - %s", opts.ServiceURL, err)
}
if parsed.Path != "" && parsed.Path != "/" {
return nil, fmt.Errorf("expecting a root URL, not %q", opts.ServiceURL)
}
opts.ServiceURL = fmt.Sprintf("%s://%s", parsed.Scheme, parsed.Host)
prpcC := &prpc.Client{
C: opts.AuthenticatedClient,
Host: parsed.Host,
Options: &prpc.Options{
UserAgent: opts.UserAgent,
Insecure: parsed.Scheme == "http", // for testing with local dev server
Retry: func() retry.Iterator {
return &retry.ExponentialBackoff{
Limited: retry.Limited{
Delay: time.Second,
Retries: 10,
},
}
},
},
}
cas := opts.casMock
if cas == nil {
cas = api.NewStoragePRPCClient(prpcC)
}
repo := opts.repoMock
if repo == nil {
repo = api.NewRepositoryPRPCClient(prpcC)
}
storage := opts.storageMock
if storage == nil {
storage = &storageImpl{
chunkSize: uploadChunkSize,
userAgent: opts.UserAgent,
client: opts.AnonymousClient,
}
}
return &clientImpl{
ClientOptions: opts,
cas: cas,
repo: repo,
storage: storage,
deployer: deployer.New(opts.Root),
}, nil
} | [
"func",
"NewClient",
"(",
"opts",
"ClientOptions",
")",
"(",
"Client",
",",
"error",
")",
"{",
"if",
"opts",
".",
"AnonymousClient",
"==",
"nil",
"{",
"opts",
".",
"AnonymousClient",
"=",
"http",
".",
"DefaultClient",
"\n",
"}",
"\n",
"if",
"opts",
".",
"AuthenticatedClient",
"==",
"nil",
"{",
"opts",
".",
"AuthenticatedClient",
"=",
"opts",
".",
"AnonymousClient",
"\n",
"}",
"\n",
"if",
"opts",
".",
"UserAgent",
"==",
"\"",
"\"",
"{",
"opts",
".",
"UserAgent",
"=",
"UserAgent",
"\n",
"}",
"\n\n",
"// Validate and normalize service URL.",
"if",
"opts",
".",
"ServiceURL",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"parsed",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"opts",
".",
"ServiceURL",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"opts",
".",
"ServiceURL",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"parsed",
".",
"Path",
"!=",
"\"",
"\"",
"&&",
"parsed",
".",
"Path",
"!=",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"opts",
".",
"ServiceURL",
")",
"\n",
"}",
"\n",
"opts",
".",
"ServiceURL",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"parsed",
".",
"Scheme",
",",
"parsed",
".",
"Host",
")",
"\n\n",
"prpcC",
":=",
"&",
"prpc",
".",
"Client",
"{",
"C",
":",
"opts",
".",
"AuthenticatedClient",
",",
"Host",
":",
"parsed",
".",
"Host",
",",
"Options",
":",
"&",
"prpc",
".",
"Options",
"{",
"UserAgent",
":",
"opts",
".",
"UserAgent",
",",
"Insecure",
":",
"parsed",
".",
"Scheme",
"==",
"\"",
"\"",
",",
"// for testing with local dev server",
"Retry",
":",
"func",
"(",
")",
"retry",
".",
"Iterator",
"{",
"return",
"&",
"retry",
".",
"ExponentialBackoff",
"{",
"Limited",
":",
"retry",
".",
"Limited",
"{",
"Delay",
":",
"time",
".",
"Second",
",",
"Retries",
":",
"10",
",",
"}",
",",
"}",
"\n",
"}",
",",
"}",
",",
"}",
"\n\n",
"cas",
":=",
"opts",
".",
"casMock",
"\n",
"if",
"cas",
"==",
"nil",
"{",
"cas",
"=",
"api",
".",
"NewStoragePRPCClient",
"(",
"prpcC",
")",
"\n",
"}",
"\n",
"repo",
":=",
"opts",
".",
"repoMock",
"\n",
"if",
"repo",
"==",
"nil",
"{",
"repo",
"=",
"api",
".",
"NewRepositoryPRPCClient",
"(",
"prpcC",
")",
"\n",
"}",
"\n",
"storage",
":=",
"opts",
".",
"storageMock",
"\n",
"if",
"storage",
"==",
"nil",
"{",
"storage",
"=",
"&",
"storageImpl",
"{",
"chunkSize",
":",
"uploadChunkSize",
",",
"userAgent",
":",
"opts",
".",
"UserAgent",
",",
"client",
":",
"opts",
".",
"AnonymousClient",
",",
"}",
"\n",
"}",
"\n\n",
"return",
"&",
"clientImpl",
"{",
"ClientOptions",
":",
"opts",
",",
"cas",
":",
"cas",
",",
"repo",
":",
"repo",
",",
"storage",
":",
"storage",
",",
"deployer",
":",
"deployer",
".",
"New",
"(",
"opts",
".",
"Root",
")",
",",
"}",
",",
"nil",
"\n",
"}"
] | // NewClient initializes CIPD client object. | [
"NewClient",
"initializes",
"CIPD",
"client",
"object",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/client.go#L383-L448 |
7,615 | luci/luci-go | cipd/client/cipd/client.go | getTagCache | func (client *clientImpl) getTagCache() *internal.TagCache {
client.tagCacheInit.Do(func() {
var dir string
switch {
case client.CacheDir != "":
dir = client.CacheDir
case client.Root != "":
dir = filepath.Join(client.Root, fs.SiteServiceDir)
default:
return
}
parsed, err := url.Parse(client.ServiceURL)
if err != nil {
panic(err) // the URL has been validated in NewClient already
}
client.tagCache = internal.NewTagCache(fs.NewFileSystem(dir, ""), parsed.Host)
})
return client.tagCache
} | go | func (client *clientImpl) getTagCache() *internal.TagCache {
client.tagCacheInit.Do(func() {
var dir string
switch {
case client.CacheDir != "":
dir = client.CacheDir
case client.Root != "":
dir = filepath.Join(client.Root, fs.SiteServiceDir)
default:
return
}
parsed, err := url.Parse(client.ServiceURL)
if err != nil {
panic(err) // the URL has been validated in NewClient already
}
client.tagCache = internal.NewTagCache(fs.NewFileSystem(dir, ""), parsed.Host)
})
return client.tagCache
} | [
"func",
"(",
"client",
"*",
"clientImpl",
")",
"getTagCache",
"(",
")",
"*",
"internal",
".",
"TagCache",
"{",
"client",
".",
"tagCacheInit",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"var",
"dir",
"string",
"\n",
"switch",
"{",
"case",
"client",
".",
"CacheDir",
"!=",
"\"",
"\"",
":",
"dir",
"=",
"client",
".",
"CacheDir",
"\n",
"case",
"client",
".",
"Root",
"!=",
"\"",
"\"",
":",
"dir",
"=",
"filepath",
".",
"Join",
"(",
"client",
".",
"Root",
",",
"fs",
".",
"SiteServiceDir",
")",
"\n",
"default",
":",
"return",
"\n",
"}",
"\n",
"parsed",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"client",
".",
"ServiceURL",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"// the URL has been validated in NewClient already",
"\n",
"}",
"\n",
"client",
".",
"tagCache",
"=",
"internal",
".",
"NewTagCache",
"(",
"fs",
".",
"NewFileSystem",
"(",
"dir",
",",
"\"",
"\"",
")",
",",
"parsed",
".",
"Host",
")",
"\n",
"}",
")",
"\n",
"return",
"client",
".",
"tagCache",
"\n",
"}"
] | // getTagCache lazy-initializes tagCache and returns it.
//
// May return nil if tag cache is disabled. | [
"getTagCache",
"lazy",
"-",
"initializes",
"tagCache",
"and",
"returns",
"it",
".",
"May",
"return",
"nil",
"if",
"tag",
"cache",
"is",
"disabled",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/client.go#L542-L560 |
7,616 | luci/luci-go | cipd/client/cipd/client.go | getInstanceCache | func (client *clientImpl) getInstanceCache(ctx context.Context) *internal.InstanceCache {
client.instanceCacheInit.Do(func() {
if client.CacheDir == "" {
return
}
path := filepath.Join(client.CacheDir, "instances")
client.instanceCache = internal.NewInstanceCache(fs.NewFileSystem(path, ""))
logging.Infof(ctx, "cipd: using instance cache at %q", path)
})
return client.instanceCache
} | go | func (client *clientImpl) getInstanceCache(ctx context.Context) *internal.InstanceCache {
client.instanceCacheInit.Do(func() {
if client.CacheDir == "" {
return
}
path := filepath.Join(client.CacheDir, "instances")
client.instanceCache = internal.NewInstanceCache(fs.NewFileSystem(path, ""))
logging.Infof(ctx, "cipd: using instance cache at %q", path)
})
return client.instanceCache
} | [
"func",
"(",
"client",
"*",
"clientImpl",
")",
"getInstanceCache",
"(",
"ctx",
"context",
".",
"Context",
")",
"*",
"internal",
".",
"InstanceCache",
"{",
"client",
".",
"instanceCacheInit",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"if",
"client",
".",
"CacheDir",
"==",
"\"",
"\"",
"{",
"return",
"\n",
"}",
"\n",
"path",
":=",
"filepath",
".",
"Join",
"(",
"client",
".",
"CacheDir",
",",
"\"",
"\"",
")",
"\n",
"client",
".",
"instanceCache",
"=",
"internal",
".",
"NewInstanceCache",
"(",
"fs",
".",
"NewFileSystem",
"(",
"path",
",",
"\"",
"\"",
")",
")",
"\n",
"logging",
".",
"Infof",
"(",
"ctx",
",",
"\"",
"\"",
",",
"path",
")",
"\n",
"}",
")",
"\n",
"return",
"client",
".",
"instanceCache",
"\n",
"}"
] | // getInstanceCache lazy-initializes instanceCache and returns it.
//
// May return nil if instance cache is disabled. | [
"getInstanceCache",
"lazy",
"-",
"initializes",
"instanceCache",
"and",
"returns",
"it",
".",
"May",
"return",
"nil",
"if",
"instance",
"cache",
"is",
"disabled",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/client.go#L565-L575 |
7,617 | luci/luci-go | cipd/client/cipd/client.go | ensureClientVersionInfo | func (client *clientImpl) ensureClientVersionInfo(ctx context.Context, fs fs.FileSystem, pin common.Pin, clientExe string) {
expect, err := json.Marshal(version.Info{
PackageName: pin.PackageName,
InstanceID: pin.InstanceID,
})
if err != nil {
// Should never occur; only error could be if version.Info is not JSON
// serializable.
logging.WithError(err).Errorf(ctx, "Unable to generate version file content")
return
}
verFile := version.GetVersionFile(clientExe)
if data, err := ioutil.ReadFile(verFile); err == nil && bytes.Equal(expect, data) {
return // up to date
}
// There was an error reading the existing version file, or its content does
// not match. Proceed with EnsureFile.
err = fs.EnsureFile(ctx, verFile, func(of *os.File) error {
_, err := of.Write(expect)
return err
})
if err != nil {
logging.WithError(err).Warningf(ctx, "Unable to update version info %q", verFile)
}
} | go | func (client *clientImpl) ensureClientVersionInfo(ctx context.Context, fs fs.FileSystem, pin common.Pin, clientExe string) {
expect, err := json.Marshal(version.Info{
PackageName: pin.PackageName,
InstanceID: pin.InstanceID,
})
if err != nil {
// Should never occur; only error could be if version.Info is not JSON
// serializable.
logging.WithError(err).Errorf(ctx, "Unable to generate version file content")
return
}
verFile := version.GetVersionFile(clientExe)
if data, err := ioutil.ReadFile(verFile); err == nil && bytes.Equal(expect, data) {
return // up to date
}
// There was an error reading the existing version file, or its content does
// not match. Proceed with EnsureFile.
err = fs.EnsureFile(ctx, verFile, func(of *os.File) error {
_, err := of.Write(expect)
return err
})
if err != nil {
logging.WithError(err).Warningf(ctx, "Unable to update version info %q", verFile)
}
} | [
"func",
"(",
"client",
"*",
"clientImpl",
")",
"ensureClientVersionInfo",
"(",
"ctx",
"context",
".",
"Context",
",",
"fs",
"fs",
".",
"FileSystem",
",",
"pin",
"common",
".",
"Pin",
",",
"clientExe",
"string",
")",
"{",
"expect",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"version",
".",
"Info",
"{",
"PackageName",
":",
"pin",
".",
"PackageName",
",",
"InstanceID",
":",
"pin",
".",
"InstanceID",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Should never occur; only error could be if version.Info is not JSON",
"// serializable.",
"logging",
".",
"WithError",
"(",
"err",
")",
".",
"Errorf",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"verFile",
":=",
"version",
".",
"GetVersionFile",
"(",
"clientExe",
")",
"\n",
"if",
"data",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"verFile",
")",
";",
"err",
"==",
"nil",
"&&",
"bytes",
".",
"Equal",
"(",
"expect",
",",
"data",
")",
"{",
"return",
"// up to date",
"\n",
"}",
"\n\n",
"// There was an error reading the existing version file, or its content does",
"// not match. Proceed with EnsureFile.",
"err",
"=",
"fs",
".",
"EnsureFile",
"(",
"ctx",
",",
"verFile",
",",
"func",
"(",
"of",
"*",
"os",
".",
"File",
")",
"error",
"{",
"_",
",",
"err",
":=",
"of",
".",
"Write",
"(",
"expect",
")",
"\n",
"return",
"err",
"\n",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logging",
".",
"WithError",
"(",
"err",
")",
".",
"Warningf",
"(",
"ctx",
",",
"\"",
"\"",
",",
"verFile",
")",
"\n",
"}",
"\n",
"}"
] | // ensureClientVersionInfo is called only with the specially constructed client,
// see MaybeUpdateClient function. | [
"ensureClientVersionInfo",
"is",
"called",
"only",
"with",
"the",
"specially",
"constructed",
"client",
"see",
"MaybeUpdateClient",
"function",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/client.go#L760-L786 |
7,618 | luci/luci-go | cipd/client/cipd/client.go | finalizeUpload | func (client *clientImpl) finalizeUpload(ctx context.Context, opID string, timeout time.Duration) error {
ctx, cancel := clock.WithTimeout(ctx, timeout)
defer cancel()
sleep := time.Second
for {
select {
case <-ctx.Done():
return ErrFinalizationTimeout
default:
}
op, err := client.cas.FinishUpload(ctx, &api.FinishUploadRequest{
UploadOperationId: opID,
})
switch {
case err == context.DeadlineExceeded:
continue // this may be short RPC deadline, try again
case err != nil:
return humanErr(err)
case op.Status == api.UploadStatus_PUBLISHED:
return nil // verified!
case op.Status == api.UploadStatus_ERRORED:
return errors.New(op.ErrorMessage) // fatal verification error
case op.Status == api.UploadStatus_UPLOADING || op.Status == api.UploadStatus_VERIFYING:
logging.Infof(ctx, "cipd: uploading - verifying")
if clock.Sleep(clock.Tag(ctx, "cipd-sleeping"), sleep).Incomplete() {
return ErrFinalizationTimeout
}
if sleep < 10*time.Second {
sleep += 500 * time.Millisecond
}
default:
return fmt.Errorf("unrecognized upload operation status %s", op.Status)
}
}
} | go | func (client *clientImpl) finalizeUpload(ctx context.Context, opID string, timeout time.Duration) error {
ctx, cancel := clock.WithTimeout(ctx, timeout)
defer cancel()
sleep := time.Second
for {
select {
case <-ctx.Done():
return ErrFinalizationTimeout
default:
}
op, err := client.cas.FinishUpload(ctx, &api.FinishUploadRequest{
UploadOperationId: opID,
})
switch {
case err == context.DeadlineExceeded:
continue // this may be short RPC deadline, try again
case err != nil:
return humanErr(err)
case op.Status == api.UploadStatus_PUBLISHED:
return nil // verified!
case op.Status == api.UploadStatus_ERRORED:
return errors.New(op.ErrorMessage) // fatal verification error
case op.Status == api.UploadStatus_UPLOADING || op.Status == api.UploadStatus_VERIFYING:
logging.Infof(ctx, "cipd: uploading - verifying")
if clock.Sleep(clock.Tag(ctx, "cipd-sleeping"), sleep).Incomplete() {
return ErrFinalizationTimeout
}
if sleep < 10*time.Second {
sleep += 500 * time.Millisecond
}
default:
return fmt.Errorf("unrecognized upload operation status %s", op.Status)
}
}
} | [
"func",
"(",
"client",
"*",
"clientImpl",
")",
"finalizeUpload",
"(",
"ctx",
"context",
".",
"Context",
",",
"opID",
"string",
",",
"timeout",
"time",
".",
"Duration",
")",
"error",
"{",
"ctx",
",",
"cancel",
":=",
"clock",
".",
"WithTimeout",
"(",
"ctx",
",",
"timeout",
")",
"\n",
"defer",
"cancel",
"(",
")",
"\n\n",
"sleep",
":=",
"time",
".",
"Second",
"\n",
"for",
"{",
"select",
"{",
"case",
"<-",
"ctx",
".",
"Done",
"(",
")",
":",
"return",
"ErrFinalizationTimeout",
"\n",
"default",
":",
"}",
"\n\n",
"op",
",",
"err",
":=",
"client",
".",
"cas",
".",
"FinishUpload",
"(",
"ctx",
",",
"&",
"api",
".",
"FinishUploadRequest",
"{",
"UploadOperationId",
":",
"opID",
",",
"}",
")",
"\n",
"switch",
"{",
"case",
"err",
"==",
"context",
".",
"DeadlineExceeded",
":",
"continue",
"// this may be short RPC deadline, try again",
"\n",
"case",
"err",
"!=",
"nil",
":",
"return",
"humanErr",
"(",
"err",
")",
"\n",
"case",
"op",
".",
"Status",
"==",
"api",
".",
"UploadStatus_PUBLISHED",
":",
"return",
"nil",
"// verified!",
"\n",
"case",
"op",
".",
"Status",
"==",
"api",
".",
"UploadStatus_ERRORED",
":",
"return",
"errors",
".",
"New",
"(",
"op",
".",
"ErrorMessage",
")",
"// fatal verification error",
"\n",
"case",
"op",
".",
"Status",
"==",
"api",
".",
"UploadStatus_UPLOADING",
"||",
"op",
".",
"Status",
"==",
"api",
".",
"UploadStatus_VERIFYING",
":",
"logging",
".",
"Infof",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"if",
"clock",
".",
"Sleep",
"(",
"clock",
".",
"Tag",
"(",
"ctx",
",",
"\"",
"\"",
")",
",",
"sleep",
")",
".",
"Incomplete",
"(",
")",
"{",
"return",
"ErrFinalizationTimeout",
"\n",
"}",
"\n",
"if",
"sleep",
"<",
"10",
"*",
"time",
".",
"Second",
"{",
"sleep",
"+=",
"500",
"*",
"time",
".",
"Millisecond",
"\n",
"}",
"\n",
"default",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"op",
".",
"Status",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // finalizeUpload repeatedly calls FinishUpload RPC until server reports that
// the uploaded file has been verified. | [
"finalizeUpload",
"repeatedly",
"calls",
"FinishUpload",
"RPC",
"until",
"server",
"reports",
"that",
"the",
"uploaded",
"file",
"has",
"been",
"verified",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/client.go#L994-L1030 |
7,619 | luci/luci-go | cipd/client/cipd/client.go | remoteFetchInstance | func (client *clientImpl) remoteFetchInstance(ctx context.Context, pin common.Pin, output io.WriteSeeker) (err error) {
startTS := clock.Now(ctx)
defer func() {
if err != nil {
logging.Errorf(ctx, "cipd: failed to fetch %s - %s", pin, err)
} else {
logging.Infof(ctx, "cipd: successfully fetched %s in %.1fs", pin, clock.Now(ctx).Sub(startTS).Seconds())
}
}()
objRef := common.InstanceIDToObjectRef(pin.InstanceID)
logging.Infof(ctx, "cipd: resolving fetch URL for %s", pin)
resp, err := client.repo.GetInstanceURL(ctx, &api.GetInstanceURLRequest{
Package: pin.PackageName,
Instance: objRef,
}, expectedCodes)
if err != nil {
return humanErr(err)
}
hash := common.MustNewHash(objRef.HashAlgo)
if err = client.storage.download(ctx, resp.SignedUrl, output, hash); err != nil {
return
}
// Make sure we fetched what we've asked for.
if digest := common.HexDigest(hash); objRef.HexDigest != digest {
err = fmt.Errorf("package hash mismatch: expecting %q, got %q", objRef.HexDigest, digest)
}
return
} | go | func (client *clientImpl) remoteFetchInstance(ctx context.Context, pin common.Pin, output io.WriteSeeker) (err error) {
startTS := clock.Now(ctx)
defer func() {
if err != nil {
logging.Errorf(ctx, "cipd: failed to fetch %s - %s", pin, err)
} else {
logging.Infof(ctx, "cipd: successfully fetched %s in %.1fs", pin, clock.Now(ctx).Sub(startTS).Seconds())
}
}()
objRef := common.InstanceIDToObjectRef(pin.InstanceID)
logging.Infof(ctx, "cipd: resolving fetch URL for %s", pin)
resp, err := client.repo.GetInstanceURL(ctx, &api.GetInstanceURLRequest{
Package: pin.PackageName,
Instance: objRef,
}, expectedCodes)
if err != nil {
return humanErr(err)
}
hash := common.MustNewHash(objRef.HashAlgo)
if err = client.storage.download(ctx, resp.SignedUrl, output, hash); err != nil {
return
}
// Make sure we fetched what we've asked for.
if digest := common.HexDigest(hash); objRef.HexDigest != digest {
err = fmt.Errorf("package hash mismatch: expecting %q, got %q", objRef.HexDigest, digest)
}
return
} | [
"func",
"(",
"client",
"*",
"clientImpl",
")",
"remoteFetchInstance",
"(",
"ctx",
"context",
".",
"Context",
",",
"pin",
"common",
".",
"Pin",
",",
"output",
"io",
".",
"WriteSeeker",
")",
"(",
"err",
"error",
")",
"{",
"startTS",
":=",
"clock",
".",
"Now",
"(",
"ctx",
")",
"\n",
"defer",
"func",
"(",
")",
"{",
"if",
"err",
"!=",
"nil",
"{",
"logging",
".",
"Errorf",
"(",
"ctx",
",",
"\"",
"\"",
",",
"pin",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"logging",
".",
"Infof",
"(",
"ctx",
",",
"\"",
"\"",
",",
"pin",
",",
"clock",
".",
"Now",
"(",
"ctx",
")",
".",
"Sub",
"(",
"startTS",
")",
".",
"Seconds",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"objRef",
":=",
"common",
".",
"InstanceIDToObjectRef",
"(",
"pin",
".",
"InstanceID",
")",
"\n\n",
"logging",
".",
"Infof",
"(",
"ctx",
",",
"\"",
"\"",
",",
"pin",
")",
"\n",
"resp",
",",
"err",
":=",
"client",
".",
"repo",
".",
"GetInstanceURL",
"(",
"ctx",
",",
"&",
"api",
".",
"GetInstanceURLRequest",
"{",
"Package",
":",
"pin",
".",
"PackageName",
",",
"Instance",
":",
"objRef",
",",
"}",
",",
"expectedCodes",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"humanErr",
"(",
"err",
")",
"\n",
"}",
"\n\n",
"hash",
":=",
"common",
".",
"MustNewHash",
"(",
"objRef",
".",
"HashAlgo",
")",
"\n",
"if",
"err",
"=",
"client",
".",
"storage",
".",
"download",
"(",
"ctx",
",",
"resp",
".",
"SignedUrl",
",",
"output",
",",
"hash",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"// Make sure we fetched what we've asked for.",
"if",
"digest",
":=",
"common",
".",
"HexDigest",
"(",
"hash",
")",
";",
"objRef",
".",
"HexDigest",
"!=",
"digest",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"objRef",
".",
"HexDigest",
",",
"digest",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // remoteFetchInstance fetches the package file into 'output' and verifies its
// hash along the way. Assumes 'pin' is already validated. | [
"remoteFetchInstance",
"fetches",
"the",
"package",
"file",
"into",
"output",
"and",
"verifies",
"its",
"hash",
"along",
"the",
"way",
".",
"Assumes",
"pin",
"is",
"already",
"validated",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/client.go#L1371-L1402 |
7,620 | luci/luci-go | cipd/client/cipd/client.go | fetchAndDo | func (client *clientImpl) fetchAndDo(ctx context.Context, pin common.Pin, cb func(pkg.Instance) error) error {
if err := common.ValidatePin(pin, common.KnownHash); err != nil {
return err
}
doit := func() (err error) {
// Fetch the package (verifying its hash) and obtain a pointer to its data.
instanceFile, err := client.FetchInstance(ctx, pin)
if err != nil {
return
}
// Notify the underlying object if 'err' is a corruption error.
type corruptable interface {
Close(ctx context.Context, corrupt bool) error
}
closeMaybeCorrupted := func(f corruptable) {
corrupt := reader.IsCorruptionError(err)
if clErr := f.Close(ctx, corrupt); clErr != nil && clErr != os.ErrClosed {
logging.Warningf(ctx, "cipd: failed to close the package file - %s", clErr)
}
}
// Open the instance. This reads its manifest. 'FetchInstance' has verified
// the hash already, so skip the verification.
instance, err := reader.OpenInstance(ctx, instanceFile, reader.OpenInstanceOpts{
VerificationMode: reader.SkipHashVerification,
InstanceID: pin.InstanceID,
})
if err != nil {
closeMaybeCorrupted(instanceFile)
return
}
defer client.doBatchAwareOp(ctx, batchAwareOpCleanupTrash)
defer closeMaybeCorrupted(instance)
// Use it. 'defer' will take care of removing the temp file if needed.
return cb(instance)
}
err := doit()
if err != nil && reader.IsCorruptionError(err) {
logging.WithError(err).Warningf(ctx, "cipd: unpacking failed, retrying.")
err = doit()
}
return err
} | go | func (client *clientImpl) fetchAndDo(ctx context.Context, pin common.Pin, cb func(pkg.Instance) error) error {
if err := common.ValidatePin(pin, common.KnownHash); err != nil {
return err
}
doit := func() (err error) {
// Fetch the package (verifying its hash) and obtain a pointer to its data.
instanceFile, err := client.FetchInstance(ctx, pin)
if err != nil {
return
}
// Notify the underlying object if 'err' is a corruption error.
type corruptable interface {
Close(ctx context.Context, corrupt bool) error
}
closeMaybeCorrupted := func(f corruptable) {
corrupt := reader.IsCorruptionError(err)
if clErr := f.Close(ctx, corrupt); clErr != nil && clErr != os.ErrClosed {
logging.Warningf(ctx, "cipd: failed to close the package file - %s", clErr)
}
}
// Open the instance. This reads its manifest. 'FetchInstance' has verified
// the hash already, so skip the verification.
instance, err := reader.OpenInstance(ctx, instanceFile, reader.OpenInstanceOpts{
VerificationMode: reader.SkipHashVerification,
InstanceID: pin.InstanceID,
})
if err != nil {
closeMaybeCorrupted(instanceFile)
return
}
defer client.doBatchAwareOp(ctx, batchAwareOpCleanupTrash)
defer closeMaybeCorrupted(instance)
// Use it. 'defer' will take care of removing the temp file if needed.
return cb(instance)
}
err := doit()
if err != nil && reader.IsCorruptionError(err) {
logging.WithError(err).Warningf(ctx, "cipd: unpacking failed, retrying.")
err = doit()
}
return err
} | [
"func",
"(",
"client",
"*",
"clientImpl",
")",
"fetchAndDo",
"(",
"ctx",
"context",
".",
"Context",
",",
"pin",
"common",
".",
"Pin",
",",
"cb",
"func",
"(",
"pkg",
".",
"Instance",
")",
"error",
")",
"error",
"{",
"if",
"err",
":=",
"common",
".",
"ValidatePin",
"(",
"pin",
",",
"common",
".",
"KnownHash",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"doit",
":=",
"func",
"(",
")",
"(",
"err",
"error",
")",
"{",
"// Fetch the package (verifying its hash) and obtain a pointer to its data.",
"instanceFile",
",",
"err",
":=",
"client",
".",
"FetchInstance",
"(",
"ctx",
",",
"pin",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"// Notify the underlying object if 'err' is a corruption error.",
"type",
"corruptable",
"interface",
"{",
"Close",
"(",
"ctx",
"context",
".",
"Context",
",",
"corrupt",
"bool",
")",
"error",
"\n",
"}",
"\n",
"closeMaybeCorrupted",
":=",
"func",
"(",
"f",
"corruptable",
")",
"{",
"corrupt",
":=",
"reader",
".",
"IsCorruptionError",
"(",
"err",
")",
"\n",
"if",
"clErr",
":=",
"f",
".",
"Close",
"(",
"ctx",
",",
"corrupt",
")",
";",
"clErr",
"!=",
"nil",
"&&",
"clErr",
"!=",
"os",
".",
"ErrClosed",
"{",
"logging",
".",
"Warningf",
"(",
"ctx",
",",
"\"",
"\"",
",",
"clErr",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Open the instance. This reads its manifest. 'FetchInstance' has verified",
"// the hash already, so skip the verification.",
"instance",
",",
"err",
":=",
"reader",
".",
"OpenInstance",
"(",
"ctx",
",",
"instanceFile",
",",
"reader",
".",
"OpenInstanceOpts",
"{",
"VerificationMode",
":",
"reader",
".",
"SkipHashVerification",
",",
"InstanceID",
":",
"pin",
".",
"InstanceID",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"closeMaybeCorrupted",
"(",
"instanceFile",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"defer",
"client",
".",
"doBatchAwareOp",
"(",
"ctx",
",",
"batchAwareOpCleanupTrash",
")",
"\n",
"defer",
"closeMaybeCorrupted",
"(",
"instance",
")",
"\n\n",
"// Use it. 'defer' will take care of removing the temp file if needed.",
"return",
"cb",
"(",
"instance",
")",
"\n",
"}",
"\n\n",
"err",
":=",
"doit",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"reader",
".",
"IsCorruptionError",
"(",
"err",
")",
"{",
"logging",
".",
"WithError",
"(",
"err",
")",
".",
"Warningf",
"(",
"ctx",
",",
"\"",
"\"",
")",
"\n",
"err",
"=",
"doit",
"(",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // fetchAndDo will fetch and open an instance and pass it to the callback.
//
// If the callback fails with an error that indicates a corrupted instance, will
// delete the instance from the cache, refetch it and call the callback again,
// thus the callback should be idempotent.
//
// Any other error from the callback is propagated as is. | [
"fetchAndDo",
"will",
"fetch",
"and",
"open",
"an",
"instance",
"and",
"pass",
"it",
"to",
"the",
"callback",
".",
"If",
"the",
"callback",
"fails",
"with",
"an",
"error",
"that",
"indicates",
"a",
"corrupted",
"instance",
"will",
"delete",
"the",
"instance",
"from",
"the",
"cache",
"refetch",
"it",
"and",
"call",
"the",
"callback",
"again",
"thus",
"the",
"callback",
"should",
"be",
"idempotent",
".",
"Any",
"other",
"error",
"from",
"the",
"callback",
"is",
"propagated",
"as",
"is",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/client.go#L1411-L1458 |
7,621 | luci/luci-go | cipd/client/cipd/client.go | makeRepairChecker | func (client *clientImpl) makeRepairChecker(ctx context.Context, paranoia ParanoidMode) repairCB {
if paranoia == NotParanoid {
return func(string, common.Pin) *RepairPlan { return nil }
}
return func(subdir string, pin common.Pin) *RepairPlan {
switch state, err := client.deployer.CheckDeployed(ctx, subdir, pin.PackageName, paranoia, WithoutManifest); {
case err != nil:
// This error is probably non-recoverable, but we'll try anyway and
// properly fail later.
return &RepairPlan{
NeedsReinstall: true,
ReinstallReason: fmt.Sprintf("failed to check the package state - %s", err),
}
case !state.Deployed:
// This should generally not happen. Can probably happen if two clients
// are messing with same .cipd/* directory concurrently.
return &RepairPlan{
NeedsReinstall: true,
ReinstallReason: "the package is not deployed at all",
}
case state.Pin.InstanceID != pin.InstanceID:
// Same here.
return &RepairPlan{
NeedsReinstall: true,
ReinstallReason: fmt.Sprintf("expected to see instance %q, but saw %q", pin.InstanceID, state.Pin.InstanceID),
}
case len(state.ToRedeploy) != 0 || len(state.ToRelink) != 0:
// Have some corrupted files that need to be repaired.
return &RepairPlan{
ToRedeploy: state.ToRedeploy,
ToRelink: state.ToRelink,
}
default:
return nil // the package needs no repairs
}
}
} | go | func (client *clientImpl) makeRepairChecker(ctx context.Context, paranoia ParanoidMode) repairCB {
if paranoia == NotParanoid {
return func(string, common.Pin) *RepairPlan { return nil }
}
return func(subdir string, pin common.Pin) *RepairPlan {
switch state, err := client.deployer.CheckDeployed(ctx, subdir, pin.PackageName, paranoia, WithoutManifest); {
case err != nil:
// This error is probably non-recoverable, but we'll try anyway and
// properly fail later.
return &RepairPlan{
NeedsReinstall: true,
ReinstallReason: fmt.Sprintf("failed to check the package state - %s", err),
}
case !state.Deployed:
// This should generally not happen. Can probably happen if two clients
// are messing with same .cipd/* directory concurrently.
return &RepairPlan{
NeedsReinstall: true,
ReinstallReason: "the package is not deployed at all",
}
case state.Pin.InstanceID != pin.InstanceID:
// Same here.
return &RepairPlan{
NeedsReinstall: true,
ReinstallReason: fmt.Sprintf("expected to see instance %q, but saw %q", pin.InstanceID, state.Pin.InstanceID),
}
case len(state.ToRedeploy) != 0 || len(state.ToRelink) != 0:
// Have some corrupted files that need to be repaired.
return &RepairPlan{
ToRedeploy: state.ToRedeploy,
ToRelink: state.ToRelink,
}
default:
return nil // the package needs no repairs
}
}
} | [
"func",
"(",
"client",
"*",
"clientImpl",
")",
"makeRepairChecker",
"(",
"ctx",
"context",
".",
"Context",
",",
"paranoia",
"ParanoidMode",
")",
"repairCB",
"{",
"if",
"paranoia",
"==",
"NotParanoid",
"{",
"return",
"func",
"(",
"string",
",",
"common",
".",
"Pin",
")",
"*",
"RepairPlan",
"{",
"return",
"nil",
"}",
"\n",
"}",
"\n\n",
"return",
"func",
"(",
"subdir",
"string",
",",
"pin",
"common",
".",
"Pin",
")",
"*",
"RepairPlan",
"{",
"switch",
"state",
",",
"err",
":=",
"client",
".",
"deployer",
".",
"CheckDeployed",
"(",
"ctx",
",",
"subdir",
",",
"pin",
".",
"PackageName",
",",
"paranoia",
",",
"WithoutManifest",
")",
";",
"{",
"case",
"err",
"!=",
"nil",
":",
"// This error is probably non-recoverable, but we'll try anyway and",
"// properly fail later.",
"return",
"&",
"RepairPlan",
"{",
"NeedsReinstall",
":",
"true",
",",
"ReinstallReason",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
",",
"}",
"\n",
"case",
"!",
"state",
".",
"Deployed",
":",
"// This should generally not happen. Can probably happen if two clients",
"// are messing with same .cipd/* directory concurrently.",
"return",
"&",
"RepairPlan",
"{",
"NeedsReinstall",
":",
"true",
",",
"ReinstallReason",
":",
"\"",
"\"",
",",
"}",
"\n",
"case",
"state",
".",
"Pin",
".",
"InstanceID",
"!=",
"pin",
".",
"InstanceID",
":",
"// Same here.",
"return",
"&",
"RepairPlan",
"{",
"NeedsReinstall",
":",
"true",
",",
"ReinstallReason",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"pin",
".",
"InstanceID",
",",
"state",
".",
"Pin",
".",
"InstanceID",
")",
",",
"}",
"\n",
"case",
"len",
"(",
"state",
".",
"ToRedeploy",
")",
"!=",
"0",
"||",
"len",
"(",
"state",
".",
"ToRelink",
")",
"!=",
"0",
":",
"// Have some corrupted files that need to be repaired.",
"return",
"&",
"RepairPlan",
"{",
"ToRedeploy",
":",
"state",
".",
"ToRedeploy",
",",
"ToRelink",
":",
"state",
".",
"ToRelink",
",",
"}",
"\n",
"default",
":",
"return",
"nil",
"// the package needs no repairs",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // makeRepairChecker returns a function that decided whether we should attempt
// to repair an already installed package.
//
// The implementation depends on selected paranoia mode. | [
"makeRepairChecker",
"returns",
"a",
"function",
"that",
"decided",
"whether",
"we",
"should",
"attempt",
"to",
"repair",
"an",
"already",
"installed",
"package",
".",
"The",
"implementation",
"depends",
"on",
"selected",
"paranoia",
"mode",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/client.go#L1606-L1643 |
7,622 | luci/luci-go | cipd/client/cipd/client.go | humanErr | func humanErr(err error) error {
if err != nil {
if status, ok := status.FromError(err); ok {
return errors.New(status.Message())
}
}
return err
} | go | func humanErr(err error) error {
if err != nil {
if status, ok := status.FromError(err); ok {
return errors.New(status.Message())
}
}
return err
} | [
"func",
"humanErr",
"(",
"err",
"error",
")",
"error",
"{",
"if",
"err",
"!=",
"nil",
"{",
"if",
"status",
",",
"ok",
":=",
"status",
".",
"FromError",
"(",
"err",
")",
";",
"ok",
"{",
"return",
"errors",
".",
"New",
"(",
"status",
".",
"Message",
"(",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // humanErr takes gRPC errors and returns a human readable error that can be
// presented in the CLI.
//
// It basically strips scary looking gRPC framing around the error message. | [
"humanErr",
"takes",
"gRPC",
"errors",
"and",
"returns",
"a",
"human",
"readable",
"error",
"that",
"can",
"be",
"presented",
"in",
"the",
"CLI",
".",
"It",
"basically",
"strips",
"scary",
"looking",
"gRPC",
"framing",
"around",
"the",
"error",
"message",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/client.go#L1680-L1687 |
7,623 | luci/luci-go | server/pprof/pprof.go | InstallHandlers | func InstallHandlers(r *router.Router, base router.MiddlewareChain) {
// Pprof native routing structure is not supported by julienschmidt/httprouter
// since it mixes prefix matches and direct matches. So we'll have to do some
// manual routing for paths under /debug/pprof :(
r.GET("/debug/pprof/*path", base, func(c *router.Context) {
// Validate the token generated through the portal page.
tok := c.Request.FormValue("tok")
if tok == "" {
sendError(c.Writer, "Missing 'tok' query parameter with a pprof token", http.StatusBadRequest)
return
}
switch err := checkToken(c.Context, tok); {
case transient.Tag.In(err):
sendError(c.Writer, fmt.Sprintf("Transient error, please retry: %s", err), http.StatusInternalServerError)
return
case err != nil:
sendError(c.Writer, fmt.Sprintf("Bad pprof token: %s", err), http.StatusBadRequest)
return
}
// Manually route. See init() in go/src/net/http/pprof/pprof.go.
h := pprofRoutes[c.Params.ByName("path")]
if h == nil {
h = internal.Index
}
h(c.Writer, c.Request)
})
} | go | func InstallHandlers(r *router.Router, base router.MiddlewareChain) {
// Pprof native routing structure is not supported by julienschmidt/httprouter
// since it mixes prefix matches and direct matches. So we'll have to do some
// manual routing for paths under /debug/pprof :(
r.GET("/debug/pprof/*path", base, func(c *router.Context) {
// Validate the token generated through the portal page.
tok := c.Request.FormValue("tok")
if tok == "" {
sendError(c.Writer, "Missing 'tok' query parameter with a pprof token", http.StatusBadRequest)
return
}
switch err := checkToken(c.Context, tok); {
case transient.Tag.In(err):
sendError(c.Writer, fmt.Sprintf("Transient error, please retry: %s", err), http.StatusInternalServerError)
return
case err != nil:
sendError(c.Writer, fmt.Sprintf("Bad pprof token: %s", err), http.StatusBadRequest)
return
}
// Manually route. See init() in go/src/net/http/pprof/pprof.go.
h := pprofRoutes[c.Params.ByName("path")]
if h == nil {
h = internal.Index
}
h(c.Writer, c.Request)
})
} | [
"func",
"InstallHandlers",
"(",
"r",
"*",
"router",
".",
"Router",
",",
"base",
"router",
".",
"MiddlewareChain",
")",
"{",
"// Pprof native routing structure is not supported by julienschmidt/httprouter",
"// since it mixes prefix matches and direct matches. So we'll have to do some",
"// manual routing for paths under /debug/pprof :(",
"r",
".",
"GET",
"(",
"\"",
"\"",
",",
"base",
",",
"func",
"(",
"c",
"*",
"router",
".",
"Context",
")",
"{",
"// Validate the token generated through the portal page.",
"tok",
":=",
"c",
".",
"Request",
".",
"FormValue",
"(",
"\"",
"\"",
")",
"\n",
"if",
"tok",
"==",
"\"",
"\"",
"{",
"sendError",
"(",
"c",
".",
"Writer",
",",
"\"",
"\"",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n",
"switch",
"err",
":=",
"checkToken",
"(",
"c",
".",
"Context",
",",
"tok",
")",
";",
"{",
"case",
"transient",
".",
"Tag",
".",
"In",
"(",
"err",
")",
":",
"sendError",
"(",
"c",
".",
"Writer",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"case",
"err",
"!=",
"nil",
":",
"sendError",
"(",
"c",
".",
"Writer",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
",",
"http",
".",
"StatusBadRequest",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"// Manually route. See init() in go/src/net/http/pprof/pprof.go.",
"h",
":=",
"pprofRoutes",
"[",
"c",
".",
"Params",
".",
"ByName",
"(",
"\"",
"\"",
")",
"]",
"\n",
"if",
"h",
"==",
"nil",
"{",
"h",
"=",
"internal",
".",
"Index",
"\n",
"}",
"\n",
"h",
"(",
"c",
".",
"Writer",
",",
"c",
".",
"Request",
")",
"\n",
"}",
")",
"\n",
"}"
] | // InstallHandlers installs HTTP handlers for pprof routes. | [
"InstallHandlers",
"installs",
"HTTP",
"handlers",
"for",
"pprof",
"routes",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/pprof/pprof.go#L43-L70 |
7,624 | luci/luci-go | buildbucket/luciexe/logdog_posix.go | newLogDogStreamServerForPlatform | func newLogDogStreamServerForPlatform(ctx context.Context, workDir string) (streamserver.StreamServer, error) {
// POSIX, use UNIX domain socket.
return streamserver.NewUNIXDomainSocketServer(ctx, filepath.Join(workDir, "ld.sock"))
} | go | func newLogDogStreamServerForPlatform(ctx context.Context, workDir string) (streamserver.StreamServer, error) {
// POSIX, use UNIX domain socket.
return streamserver.NewUNIXDomainSocketServer(ctx, filepath.Join(workDir, "ld.sock"))
} | [
"func",
"newLogDogStreamServerForPlatform",
"(",
"ctx",
"context",
".",
"Context",
",",
"workDir",
"string",
")",
"(",
"streamserver",
".",
"StreamServer",
",",
"error",
")",
"{",
"// POSIX, use UNIX domain socket.",
"return",
"streamserver",
".",
"NewUNIXDomainSocketServer",
"(",
"ctx",
",",
"filepath",
".",
"Join",
"(",
"workDir",
",",
"\"",
"\"",
")",
")",
"\n",
"}"
] | // newLogDogStreamServerForPlatform creates a StreamServer instance usable on
// POSIX. | [
"newLogDogStreamServerForPlatform",
"creates",
"a",
"StreamServer",
"instance",
"usable",
"on",
"POSIX",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/buildbucket/luciexe/logdog_posix.go#L28-L31 |
7,625 | luci/luci-go | server/middleware/middleware.go | WithContextTimeout | func WithContextTimeout(timeout time.Duration) router.Middleware {
return func(c *router.Context, next router.Handler) {
c.Context, _ = clock.WithTimeout(c.Context, timeout)
next(c)
}
} | go | func WithContextTimeout(timeout time.Duration) router.Middleware {
return func(c *router.Context, next router.Handler) {
c.Context, _ = clock.WithTimeout(c.Context, timeout)
next(c)
}
} | [
"func",
"WithContextTimeout",
"(",
"timeout",
"time",
".",
"Duration",
")",
"router",
".",
"Middleware",
"{",
"return",
"func",
"(",
"c",
"*",
"router",
".",
"Context",
",",
"next",
"router",
".",
"Handler",
")",
"{",
"c",
".",
"Context",
",",
"_",
"=",
"clock",
".",
"WithTimeout",
"(",
"c",
".",
"Context",
",",
"timeout",
")",
"\n",
"next",
"(",
"c",
")",
"\n",
"}",
"\n",
"}"
] | // WithContextTimeout returns a middleware that adds a timeout to the context. | [
"WithContextTimeout",
"returns",
"a",
"middleware",
"that",
"adds",
"a",
"timeout",
"to",
"the",
"context",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/middleware/middleware.go#L54-L59 |
7,626 | luci/luci-go | scheduler/appengine/engine/request.go | putRequestIntoInv | func putRequestIntoInv(inv *Invocation, req *task.Request) error {
var props []byte
if req.Properties != nil {
var err error
if props, err = proto.Marshal(req.Properties); err != nil {
return errors.Annotate(err, "can't marshal Properties").Err()
}
}
if err := utils.ValidateKVList("tag", req.Tags, ':'); err != nil {
return errors.Annotate(err, "rejecting bad tags").Err()
}
sortedTags := append([]string(nil), req.Tags...)
sort.Strings(sortedTags)
// Note: DebugLog is handled in a special way by initInvocation.
inv.TriggeredBy = req.TriggeredBy
inv.IncomingTriggersRaw = marshalTriggersList(req.IncomingTriggers)
inv.PropertiesRaw = props
inv.Tags = sortedTags
return nil
} | go | func putRequestIntoInv(inv *Invocation, req *task.Request) error {
var props []byte
if req.Properties != nil {
var err error
if props, err = proto.Marshal(req.Properties); err != nil {
return errors.Annotate(err, "can't marshal Properties").Err()
}
}
if err := utils.ValidateKVList("tag", req.Tags, ':'); err != nil {
return errors.Annotate(err, "rejecting bad tags").Err()
}
sortedTags := append([]string(nil), req.Tags...)
sort.Strings(sortedTags)
// Note: DebugLog is handled in a special way by initInvocation.
inv.TriggeredBy = req.TriggeredBy
inv.IncomingTriggersRaw = marshalTriggersList(req.IncomingTriggers)
inv.PropertiesRaw = props
inv.Tags = sortedTags
return nil
} | [
"func",
"putRequestIntoInv",
"(",
"inv",
"*",
"Invocation",
",",
"req",
"*",
"task",
".",
"Request",
")",
"error",
"{",
"var",
"props",
"[",
"]",
"byte",
"\n",
"if",
"req",
".",
"Properties",
"!=",
"nil",
"{",
"var",
"err",
"error",
"\n",
"if",
"props",
",",
"err",
"=",
"proto",
".",
"Marshal",
"(",
"req",
".",
"Properties",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"utils",
".",
"ValidateKVList",
"(",
"\"",
"\"",
",",
"req",
".",
"Tags",
",",
"':'",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"sortedTags",
":=",
"append",
"(",
"[",
"]",
"string",
"(",
"nil",
")",
",",
"req",
".",
"Tags",
"...",
")",
"\n",
"sort",
".",
"Strings",
"(",
"sortedTags",
")",
"\n\n",
"// Note: DebugLog is handled in a special way by initInvocation.",
"inv",
".",
"TriggeredBy",
"=",
"req",
".",
"TriggeredBy",
"\n",
"inv",
".",
"IncomingTriggersRaw",
"=",
"marshalTriggersList",
"(",
"req",
".",
"IncomingTriggers",
")",
"\n",
"inv",
".",
"PropertiesRaw",
"=",
"props",
"\n",
"inv",
".",
"Tags",
"=",
"sortedTags",
"\n",
"return",
"nil",
"\n",
"}"
] | // putRequestIntoInv copies task.Request fields into Invocation.
//
// See getRequestFromInv for reverse. Fails only on serialization errors,
// this should be rare. | [
"putRequestIntoInv",
"copies",
"task",
".",
"Request",
"fields",
"into",
"Invocation",
".",
"See",
"getRequestFromInv",
"for",
"reverse",
".",
"Fails",
"only",
"on",
"serialization",
"errors",
"this",
"should",
"be",
"rare",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/request.go#L33-L54 |
7,627 | luci/luci-go | scheduler/appengine/engine/request.go | getRequestFromInv | func getRequestFromInv(inv *Invocation) (r task.Request, err error) {
r.TriggeredBy = inv.TriggeredBy
if r.IncomingTriggers, err = inv.IncomingTriggers(); err != nil {
return r, errors.Annotate(err, "failed to deserialize incoming triggers").Err()
}
if len(inv.PropertiesRaw) != 0 {
props := &structpb.Struct{}
if err = proto.Unmarshal(inv.PropertiesRaw, props); err != nil {
return r, errors.Annotate(err, "failed to deserialize properties").Err()
}
r.Properties = props
}
r.Tags = inv.Tags
return
} | go | func getRequestFromInv(inv *Invocation) (r task.Request, err error) {
r.TriggeredBy = inv.TriggeredBy
if r.IncomingTriggers, err = inv.IncomingTriggers(); err != nil {
return r, errors.Annotate(err, "failed to deserialize incoming triggers").Err()
}
if len(inv.PropertiesRaw) != 0 {
props := &structpb.Struct{}
if err = proto.Unmarshal(inv.PropertiesRaw, props); err != nil {
return r, errors.Annotate(err, "failed to deserialize properties").Err()
}
r.Properties = props
}
r.Tags = inv.Tags
return
} | [
"func",
"getRequestFromInv",
"(",
"inv",
"*",
"Invocation",
")",
"(",
"r",
"task",
".",
"Request",
",",
"err",
"error",
")",
"{",
"r",
".",
"TriggeredBy",
"=",
"inv",
".",
"TriggeredBy",
"\n",
"if",
"r",
".",
"IncomingTriggers",
",",
"err",
"=",
"inv",
".",
"IncomingTriggers",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"r",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"inv",
".",
"PropertiesRaw",
")",
"!=",
"0",
"{",
"props",
":=",
"&",
"structpb",
".",
"Struct",
"{",
"}",
"\n",
"if",
"err",
"=",
"proto",
".",
"Unmarshal",
"(",
"inv",
".",
"PropertiesRaw",
",",
"props",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"r",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"r",
".",
"Properties",
"=",
"props",
"\n",
"}",
"\n",
"r",
".",
"Tags",
"=",
"inv",
".",
"Tags",
"\n",
"return",
"\n",
"}"
] | // getRequestFromInv constructs task.Request from Invocation fields.
//
// It is reverse of putRequestIntoInv. Fails only on deserialization errors,
// this should be rare. | [
"getRequestFromInv",
"constructs",
"task",
".",
"Request",
"from",
"Invocation",
"fields",
".",
"It",
"is",
"reverse",
"of",
"putRequestIntoInv",
".",
"Fails",
"only",
"on",
"deserialization",
"errors",
"this",
"should",
"be",
"rare",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/engine/request.go#L60-L74 |
7,628 | luci/luci-go | dm/appengine/distributor/fake/fake.go | Activate | func (t *Task) Activate(c context.Context, s dm.DepsServer) (*ActivatedTask, error) {
newTok := model.MakeRandomToken(c, 32)
_, err := s.ActivateExecution(c, &dm.ActivateExecutionReq{
Auth: t.Auth, ExecutionToken: newTok})
if err != nil {
return nil, err
}
return &ActivatedTask{
s,
c,
&dm.Execution_Auth{Id: t.Auth.Id, Token: newTok},
t.Desc,
t.State,
}, nil
} | go | func (t *Task) Activate(c context.Context, s dm.DepsServer) (*ActivatedTask, error) {
newTok := model.MakeRandomToken(c, 32)
_, err := s.ActivateExecution(c, &dm.ActivateExecutionReq{
Auth: t.Auth, ExecutionToken: newTok})
if err != nil {
return nil, err
}
return &ActivatedTask{
s,
c,
&dm.Execution_Auth{Id: t.Auth.Id, Token: newTok},
t.Desc,
t.State,
}, nil
} | [
"func",
"(",
"t",
"*",
"Task",
")",
"Activate",
"(",
"c",
"context",
".",
"Context",
",",
"s",
"dm",
".",
"DepsServer",
")",
"(",
"*",
"ActivatedTask",
",",
"error",
")",
"{",
"newTok",
":=",
"model",
".",
"MakeRandomToken",
"(",
"c",
",",
"32",
")",
"\n",
"_",
",",
"err",
":=",
"s",
".",
"ActivateExecution",
"(",
"c",
",",
"&",
"dm",
".",
"ActivateExecutionReq",
"{",
"Auth",
":",
"t",
".",
"Auth",
",",
"ExecutionToken",
":",
"newTok",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n\n",
"return",
"&",
"ActivatedTask",
"{",
"s",
",",
"c",
",",
"&",
"dm",
".",
"Execution_Auth",
"{",
"Id",
":",
"t",
".",
"Auth",
".",
"Id",
",",
"Token",
":",
"newTok",
"}",
",",
"t",
".",
"Desc",
",",
"t",
".",
"State",
",",
"}",
",",
"nil",
"\n",
"}"
] | // Activate does the activation handshake with the provided DepsServer and
// returns an ActivatedTask. | [
"Activate",
"does",
"the",
"activation",
"handshake",
"with",
"the",
"provided",
"DepsServer",
"and",
"returns",
"an",
"ActivatedTask",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/distributor/fake/fake.go#L119-L134 |
7,629 | luci/luci-go | dm/appengine/distributor/fake/fake.go | MustActivate | func (t *Task) MustActivate(c context.Context, s dm.DepsServer) *ActivatedTask {
ret, err := t.Activate(c, s)
panicIf(err)
return ret
} | go | func (t *Task) MustActivate(c context.Context, s dm.DepsServer) *ActivatedTask {
ret, err := t.Activate(c, s)
panicIf(err)
return ret
} | [
"func",
"(",
"t",
"*",
"Task",
")",
"MustActivate",
"(",
"c",
"context",
".",
"Context",
",",
"s",
"dm",
".",
"DepsServer",
")",
"*",
"ActivatedTask",
"{",
"ret",
",",
"err",
":=",
"t",
".",
"Activate",
"(",
"c",
",",
"s",
")",
"\n",
"panicIf",
"(",
"err",
")",
"\n",
"return",
"ret",
"\n",
"}"
] | // MustActivate does the same thing as Activate, but panics if err != nil. | [
"MustActivate",
"does",
"the",
"same",
"thing",
"as",
"Activate",
"but",
"panics",
"if",
"err",
"!",
"=",
"nil",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/distributor/fake/fake.go#L137-L141 |
7,630 | luci/luci-go | dm/appengine/distributor/fake/fake.go | WalkGraph | func (t *ActivatedTask) WalkGraph(req *dm.WalkGraphReq) (*dm.GraphData, error) {
newReq := *req
newReq.Auth = t.Auth
return t.s.WalkGraph(t.c, &newReq)
} | go | func (t *ActivatedTask) WalkGraph(req *dm.WalkGraphReq) (*dm.GraphData, error) {
newReq := *req
newReq.Auth = t.Auth
return t.s.WalkGraph(t.c, &newReq)
} | [
"func",
"(",
"t",
"*",
"ActivatedTask",
")",
"WalkGraph",
"(",
"req",
"*",
"dm",
".",
"WalkGraphReq",
")",
"(",
"*",
"dm",
".",
"GraphData",
",",
"error",
")",
"{",
"newReq",
":=",
"*",
"req",
"\n",
"newReq",
".",
"Auth",
"=",
"t",
".",
"Auth",
"\n",
"return",
"t",
".",
"s",
".",
"WalkGraph",
"(",
"t",
".",
"c",
",",
"&",
"newReq",
")",
"\n",
"}"
] | // WalkGraph calls the bound DepsServer's WalkGraph method with the activated
// Auth field. | [
"WalkGraph",
"calls",
"the",
"bound",
"DepsServer",
"s",
"WalkGraph",
"method",
"with",
"the",
"activated",
"Auth",
"field",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/distributor/fake/fake.go#L161-L165 |
7,631 | luci/luci-go | dm/appengine/distributor/fake/fake.go | EnsureGraphData | func (t *ActivatedTask) EnsureGraphData(req *dm.EnsureGraphDataReq) (*dm.EnsureGraphDataRsp, error) {
newReq := *req
newReq.ForExecution = t.Auth
return t.s.EnsureGraphData(t.c, &newReq)
} | go | func (t *ActivatedTask) EnsureGraphData(req *dm.EnsureGraphDataReq) (*dm.EnsureGraphDataRsp, error) {
newReq := *req
newReq.ForExecution = t.Auth
return t.s.EnsureGraphData(t.c, &newReq)
} | [
"func",
"(",
"t",
"*",
"ActivatedTask",
")",
"EnsureGraphData",
"(",
"req",
"*",
"dm",
".",
"EnsureGraphDataReq",
")",
"(",
"*",
"dm",
".",
"EnsureGraphDataRsp",
",",
"error",
")",
"{",
"newReq",
":=",
"*",
"req",
"\n",
"newReq",
".",
"ForExecution",
"=",
"t",
".",
"Auth",
"\n",
"return",
"t",
".",
"s",
".",
"EnsureGraphData",
"(",
"t",
".",
"c",
",",
"&",
"newReq",
")",
"\n",
"}"
] | // EnsureGraphData calls the bound DepsServer's EnsureGraphData method with the
// activated Auth field in ForExecution. | [
"EnsureGraphData",
"calls",
"the",
"bound",
"DepsServer",
"s",
"EnsureGraphData",
"method",
"with",
"the",
"activated",
"Auth",
"field",
"in",
"ForExecution",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/distributor/fake/fake.go#L169-L173 |
7,632 | luci/luci-go | dm/appengine/distributor/fake/fake.go | MustDepOn | func (t *ActivatedTask) MustDepOn(to ...*dm.Attempt_ID) (halt bool) {
halt, err := t.DepOn(to...)
panicIf(err)
return
} | go | func (t *ActivatedTask) MustDepOn(to ...*dm.Attempt_ID) (halt bool) {
halt, err := t.DepOn(to...)
panicIf(err)
return
} | [
"func",
"(",
"t",
"*",
"ActivatedTask",
")",
"MustDepOn",
"(",
"to",
"...",
"*",
"dm",
".",
"Attempt_ID",
")",
"(",
"halt",
"bool",
")",
"{",
"halt",
",",
"err",
":=",
"t",
".",
"DepOn",
"(",
"to",
"...",
")",
"\n",
"panicIf",
"(",
"err",
")",
"\n",
"return",
"\n",
"}"
] | // MustDepOn is the same as DepOn but will panic if DepOn would have returned
// a non-nil error. | [
"MustDepOn",
"is",
"the",
"same",
"as",
"DepOn",
"but",
"will",
"panic",
"if",
"DepOn",
"would",
"have",
"returned",
"a",
"non",
"-",
"nil",
"error",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/distributor/fake/fake.go#L189-L193 |
7,633 | luci/luci-go | dm/appengine/distributor/fake/fake.go | Run | func (d *BoundDistributor) Run(desc *dm.Quest_Desc, exAuth *dm.Execution_Auth, prev *dm.JsonResult) (tok distributor.Token, pollbackTime time.Duration, err error) {
if err = d.RunError; err != nil {
return
}
pollbackTime = d.PollbackTime
tok = MakeToken(exAuth.Id)
tsk := &DistributorData{
Auth: exAuth,
Desc: desc,
State: prev,
}
tsk.NotifyTopic, tsk.NotifyAuth, err = d.cfg.PrepareTopic(d.c, exAuth.Id)
panicIf(err)
d.Lock()
defer d.Unlock()
if d.tasks == nil {
d.tasks = map[distributor.Token]*DistributorData{}
}
d.tasks[tok] = tsk
return
} | go | func (d *BoundDistributor) Run(desc *dm.Quest_Desc, exAuth *dm.Execution_Auth, prev *dm.JsonResult) (tok distributor.Token, pollbackTime time.Duration, err error) {
if err = d.RunError; err != nil {
return
}
pollbackTime = d.PollbackTime
tok = MakeToken(exAuth.Id)
tsk := &DistributorData{
Auth: exAuth,
Desc: desc,
State: prev,
}
tsk.NotifyTopic, tsk.NotifyAuth, err = d.cfg.PrepareTopic(d.c, exAuth.Id)
panicIf(err)
d.Lock()
defer d.Unlock()
if d.tasks == nil {
d.tasks = map[distributor.Token]*DistributorData{}
}
d.tasks[tok] = tsk
return
} | [
"func",
"(",
"d",
"*",
"BoundDistributor",
")",
"Run",
"(",
"desc",
"*",
"dm",
".",
"Quest_Desc",
",",
"exAuth",
"*",
"dm",
".",
"Execution_Auth",
",",
"prev",
"*",
"dm",
".",
"JsonResult",
")",
"(",
"tok",
"distributor",
".",
"Token",
",",
"pollbackTime",
"time",
".",
"Duration",
",",
"err",
"error",
")",
"{",
"if",
"err",
"=",
"d",
".",
"RunError",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"pollbackTime",
"=",
"d",
".",
"PollbackTime",
"\n\n",
"tok",
"=",
"MakeToken",
"(",
"exAuth",
".",
"Id",
")",
"\n\n",
"tsk",
":=",
"&",
"DistributorData",
"{",
"Auth",
":",
"exAuth",
",",
"Desc",
":",
"desc",
",",
"State",
":",
"prev",
",",
"}",
"\n",
"tsk",
".",
"NotifyTopic",
",",
"tsk",
".",
"NotifyAuth",
",",
"err",
"=",
"d",
".",
"cfg",
".",
"PrepareTopic",
"(",
"d",
".",
"c",
",",
"exAuth",
".",
"Id",
")",
"\n",
"panicIf",
"(",
"err",
")",
"\n\n",
"d",
".",
"Lock",
"(",
")",
"\n",
"defer",
"d",
".",
"Unlock",
"(",
")",
"\n",
"if",
"d",
".",
"tasks",
"==",
"nil",
"{",
"d",
".",
"tasks",
"=",
"map",
"[",
"distributor",
".",
"Token",
"]",
"*",
"DistributorData",
"{",
"}",
"\n",
"}",
"\n",
"d",
".",
"tasks",
"[",
"tok",
"]",
"=",
"tsk",
"\n",
"return",
"\n",
"}"
] | // Run implements distributor.D | [
"Run",
"implements",
"distributor",
".",
"D"
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/distributor/fake/fake.go#L264-L287 |
7,634 | luci/luci-go | dm/appengine/distributor/fake/fake.go | Cancel | func (d *BoundDistributor) Cancel(_ *dm.Quest_Desc, tok distributor.Token) (err error) {
d.Lock()
defer d.Unlock()
if tsk, ok := d.tasks[tok]; ok {
tsk.done = true
tsk.abnorm = &dm.AbnormalFinish{
Status: dm.AbnormalFinish_CANCELLED,
Reason: "cancelled via Cancel()"}
} else {
err = fmt.Errorf("MISSING task %q", tok)
}
return
} | go | func (d *BoundDistributor) Cancel(_ *dm.Quest_Desc, tok distributor.Token) (err error) {
d.Lock()
defer d.Unlock()
if tsk, ok := d.tasks[tok]; ok {
tsk.done = true
tsk.abnorm = &dm.AbnormalFinish{
Status: dm.AbnormalFinish_CANCELLED,
Reason: "cancelled via Cancel()"}
} else {
err = fmt.Errorf("MISSING task %q", tok)
}
return
} | [
"func",
"(",
"d",
"*",
"BoundDistributor",
")",
"Cancel",
"(",
"_",
"*",
"dm",
".",
"Quest_Desc",
",",
"tok",
"distributor",
".",
"Token",
")",
"(",
"err",
"error",
")",
"{",
"d",
".",
"Lock",
"(",
")",
"\n",
"defer",
"d",
".",
"Unlock",
"(",
")",
"\n",
"if",
"tsk",
",",
"ok",
":=",
"d",
".",
"tasks",
"[",
"tok",
"]",
";",
"ok",
"{",
"tsk",
".",
"done",
"=",
"true",
"\n",
"tsk",
".",
"abnorm",
"=",
"&",
"dm",
".",
"AbnormalFinish",
"{",
"Status",
":",
"dm",
".",
"AbnormalFinish_CANCELLED",
",",
"Reason",
":",
"\"",
"\"",
"}",
"\n",
"}",
"else",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"tok",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Cancel implements distributor.D | [
"Cancel",
"implements",
"distributor",
".",
"D"
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/distributor/fake/fake.go#L290-L302 |
7,635 | luci/luci-go | dm/appengine/distributor/fake/fake.go | GetStatus | func (d *BoundDistributor) GetStatus(_ *dm.Quest_Desc, tok distributor.Token) (rslt *dm.Result, err error) {
d.Lock()
defer d.Unlock()
if tsk, ok := d.tasks[tok]; ok {
if tsk.done {
if tsk.abnorm != nil {
rslt = &dm.Result{AbnormalFinish: tsk.abnorm}
} else {
rslt = &dm.Result{Data: tsk.State}
}
}
} else {
rslt = &dm.Result{
AbnormalFinish: &dm.AbnormalFinish{
Status: dm.AbnormalFinish_MISSING,
Reason: fmt.Sprintf("unknown token: %s", tok)},
}
}
return
} | go | func (d *BoundDistributor) GetStatus(_ *dm.Quest_Desc, tok distributor.Token) (rslt *dm.Result, err error) {
d.Lock()
defer d.Unlock()
if tsk, ok := d.tasks[tok]; ok {
if tsk.done {
if tsk.abnorm != nil {
rslt = &dm.Result{AbnormalFinish: tsk.abnorm}
} else {
rslt = &dm.Result{Data: tsk.State}
}
}
} else {
rslt = &dm.Result{
AbnormalFinish: &dm.AbnormalFinish{
Status: dm.AbnormalFinish_MISSING,
Reason: fmt.Sprintf("unknown token: %s", tok)},
}
}
return
} | [
"func",
"(",
"d",
"*",
"BoundDistributor",
")",
"GetStatus",
"(",
"_",
"*",
"dm",
".",
"Quest_Desc",
",",
"tok",
"distributor",
".",
"Token",
")",
"(",
"rslt",
"*",
"dm",
".",
"Result",
",",
"err",
"error",
")",
"{",
"d",
".",
"Lock",
"(",
")",
"\n",
"defer",
"d",
".",
"Unlock",
"(",
")",
"\n",
"if",
"tsk",
",",
"ok",
":=",
"d",
".",
"tasks",
"[",
"tok",
"]",
";",
"ok",
"{",
"if",
"tsk",
".",
"done",
"{",
"if",
"tsk",
".",
"abnorm",
"!=",
"nil",
"{",
"rslt",
"=",
"&",
"dm",
".",
"Result",
"{",
"AbnormalFinish",
":",
"tsk",
".",
"abnorm",
"}",
"\n",
"}",
"else",
"{",
"rslt",
"=",
"&",
"dm",
".",
"Result",
"{",
"Data",
":",
"tsk",
".",
"State",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"else",
"{",
"rslt",
"=",
"&",
"dm",
".",
"Result",
"{",
"AbnormalFinish",
":",
"&",
"dm",
".",
"AbnormalFinish",
"{",
"Status",
":",
"dm",
".",
"AbnormalFinish_MISSING",
",",
"Reason",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"tok",
")",
"}",
",",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // GetStatus implements distributor.D | [
"GetStatus",
"implements",
"distributor",
".",
"D"
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/distributor/fake/fake.go#L305-L324 |
7,636 | luci/luci-go | dm/appengine/distributor/fake/fake.go | InfoURL | func (d *BoundDistributor) InfoURL(tok distributor.Token) string {
return FakeURLPrefix + string(tok)
} | go | func (d *BoundDistributor) InfoURL(tok distributor.Token) string {
return FakeURLPrefix + string(tok)
} | [
"func",
"(",
"d",
"*",
"BoundDistributor",
")",
"InfoURL",
"(",
"tok",
"distributor",
".",
"Token",
")",
"string",
"{",
"return",
"FakeURLPrefix",
"+",
"string",
"(",
"tok",
")",
"\n",
"}"
] | // InfoURL implements distributor.D | [
"InfoURL",
"implements",
"distributor",
".",
"D"
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/distributor/fake/fake.go#L335-L337 |
7,637 | luci/luci-go | dm/appengine/distributor/fake/fake.go | HandleNotification | func (d *BoundDistributor) HandleNotification(q *dm.Quest_Desc, n *distributor.Notification) (rslt *dm.Result, err error) {
return d.GetStatus(q, distributor.Token(n.Attrs["token"]))
} | go | func (d *BoundDistributor) HandleNotification(q *dm.Quest_Desc, n *distributor.Notification) (rslt *dm.Result, err error) {
return d.GetStatus(q, distributor.Token(n.Attrs["token"]))
} | [
"func",
"(",
"d",
"*",
"BoundDistributor",
")",
"HandleNotification",
"(",
"q",
"*",
"dm",
".",
"Quest_Desc",
",",
"n",
"*",
"distributor",
".",
"Notification",
")",
"(",
"rslt",
"*",
"dm",
".",
"Result",
",",
"err",
"error",
")",
"{",
"return",
"d",
".",
"GetStatus",
"(",
"q",
",",
"distributor",
".",
"Token",
"(",
"n",
".",
"Attrs",
"[",
"\"",
"\"",
"]",
")",
")",
"\n",
"}"
] | // HandleNotification implements distributor.D | [
"HandleNotification",
"implements",
"distributor",
".",
"D"
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/distributor/fake/fake.go#L340-L342 |
7,638 | luci/luci-go | dm/appengine/distributor/fake/fake.go | HandleTaskQueueTask | func (d *BoundDistributor) HandleTaskQueueTask(r *http.Request) ([]*distributor.Notification, error) {
panic("not implemented")
} | go | func (d *BoundDistributor) HandleTaskQueueTask(r *http.Request) ([]*distributor.Notification, error) {
panic("not implemented")
} | [
"func",
"(",
"d",
"*",
"BoundDistributor",
")",
"HandleTaskQueueTask",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"[",
"]",
"*",
"distributor",
".",
"Notification",
",",
"error",
")",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // HandleTaskQueueTask is not implemented, and shouldn't be needed for most
// tests. It could be implemented if some new test required it, however. | [
"HandleTaskQueueTask",
"is",
"not",
"implemented",
"and",
"shouldn",
"t",
"be",
"needed",
"for",
"most",
"tests",
".",
"It",
"could",
"be",
"implemented",
"if",
"some",
"new",
"test",
"required",
"it",
"however",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/distributor/fake/fake.go#L346-L348 |
7,639 | luci/luci-go | lucicfg/gens.go | add | func (g *generators) add(cb starlark.Callable) error {
if g.runningNow {
return fmt.Errorf("can't add a generator while already running them")
}
g.gen = append(g.gen, cb)
return nil
} | go | func (g *generators) add(cb starlark.Callable) error {
if g.runningNow {
return fmt.Errorf("can't add a generator while already running them")
}
g.gen = append(g.gen, cb)
return nil
} | [
"func",
"(",
"g",
"*",
"generators",
")",
"add",
"(",
"cb",
"starlark",
".",
"Callable",
")",
"error",
"{",
"if",
"g",
".",
"runningNow",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"g",
".",
"gen",
"=",
"append",
"(",
"g",
".",
"gen",
",",
"cb",
")",
"\n",
"return",
"nil",
"\n",
"}"
] | // add registers a new generator callback. | [
"add",
"registers",
"a",
"new",
"generator",
"callback",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/gens.go#L36-L42 |
7,640 | luci/luci-go | lucicfg/gens.go | call | func (g *generators) call(th *starlark.Thread, ctx *genCtx) (errs errors.MultiError) {
if g.runningNow {
return errors.MultiError{
fmt.Errorf("can't call generators while they are already running"),
}
}
g.runningNow = true
defer func() { g.runningNow = false }()
fc := builtins.GetFailureCollector(th)
for _, cb := range g.gen {
if fc != nil {
fc.Clear()
}
if _, err := starlark.Call(th, cb, starlark.Tuple{ctx}, nil); err != nil {
if fc != nil && fc.LatestFailure() != nil {
// Prefer this error, it has custom stack trace.
errs = append(errs, fc.LatestFailure())
} else {
errs = append(errs, err)
}
}
}
return
} | go | func (g *generators) call(th *starlark.Thread, ctx *genCtx) (errs errors.MultiError) {
if g.runningNow {
return errors.MultiError{
fmt.Errorf("can't call generators while they are already running"),
}
}
g.runningNow = true
defer func() { g.runningNow = false }()
fc := builtins.GetFailureCollector(th)
for _, cb := range g.gen {
if fc != nil {
fc.Clear()
}
if _, err := starlark.Call(th, cb, starlark.Tuple{ctx}, nil); err != nil {
if fc != nil && fc.LatestFailure() != nil {
// Prefer this error, it has custom stack trace.
errs = append(errs, fc.LatestFailure())
} else {
errs = append(errs, err)
}
}
}
return
} | [
"func",
"(",
"g",
"*",
"generators",
")",
"call",
"(",
"th",
"*",
"starlark",
".",
"Thread",
",",
"ctx",
"*",
"genCtx",
")",
"(",
"errs",
"errors",
".",
"MultiError",
")",
"{",
"if",
"g",
".",
"runningNow",
"{",
"return",
"errors",
".",
"MultiError",
"{",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
",",
"}",
"\n",
"}",
"\n",
"g",
".",
"runningNow",
"=",
"true",
"\n",
"defer",
"func",
"(",
")",
"{",
"g",
".",
"runningNow",
"=",
"false",
"}",
"(",
")",
"\n\n",
"fc",
":=",
"builtins",
".",
"GetFailureCollector",
"(",
"th",
")",
"\n\n",
"for",
"_",
",",
"cb",
":=",
"range",
"g",
".",
"gen",
"{",
"if",
"fc",
"!=",
"nil",
"{",
"fc",
".",
"Clear",
"(",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"starlark",
".",
"Call",
"(",
"th",
",",
"cb",
",",
"starlark",
".",
"Tuple",
"{",
"ctx",
"}",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"fc",
"!=",
"nil",
"&&",
"fc",
".",
"LatestFailure",
"(",
")",
"!=",
"nil",
"{",
"// Prefer this error, it has custom stack trace.",
"errs",
"=",
"append",
"(",
"errs",
",",
"fc",
".",
"LatestFailure",
"(",
")",
")",
"\n",
"}",
"else",
"{",
"errs",
"=",
"append",
"(",
"errs",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // call calls all registered callbacks sequentially, collecting all errors. | [
"call",
"calls",
"all",
"registered",
"callbacks",
"sequentially",
"collecting",
"all",
"errors",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/lucicfg/gens.go#L45-L70 |
7,641 | luci/luci-go | server/auth/config.go | Initialize | func Initialize(c context.Context, cfg *Config) context.Context {
if getConfig(c) != nil {
panic("auth.Initialize is called twice on same context")
}
return setConfig(c, cfg)
} | go | func Initialize(c context.Context, cfg *Config) context.Context {
if getConfig(c) != nil {
panic("auth.Initialize is called twice on same context")
}
return setConfig(c, cfg)
} | [
"func",
"Initialize",
"(",
"c",
"context",
".",
"Context",
",",
"cfg",
"*",
"Config",
")",
"context",
".",
"Context",
"{",
"if",
"getConfig",
"(",
"c",
")",
"!=",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"setConfig",
"(",
"c",
",",
"cfg",
")",
"\n",
"}"
] | // Initialize inserts authentication configuration into the context.
//
// An initialized context is required by any other function in the package. They
// return ErrNotConfigured otherwise.
//
// Calling Initialize twice causes a panic. | [
"Initialize",
"inserts",
"authentication",
"configuration",
"into",
"the",
"context",
".",
"An",
"initialized",
"context",
"is",
"required",
"by",
"any",
"other",
"function",
"in",
"the",
"package",
".",
"They",
"return",
"ErrNotConfigured",
"otherwise",
".",
"Calling",
"Initialize",
"twice",
"causes",
"a",
"panic",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/config.go#L91-L96 |
7,642 | luci/luci-go | server/auth/config.go | adjustedTimeout | func (cfg *Config) adjustedTimeout(t time.Duration) time.Duration {
if !cfg.IsDevMode {
return t
}
if t > time.Minute {
return t
}
return time.Minute
} | go | func (cfg *Config) adjustedTimeout(t time.Duration) time.Duration {
if !cfg.IsDevMode {
return t
}
if t > time.Minute {
return t
}
return time.Minute
} | [
"func",
"(",
"cfg",
"*",
"Config",
")",
"adjustedTimeout",
"(",
"t",
"time",
".",
"Duration",
")",
"time",
".",
"Duration",
"{",
"if",
"!",
"cfg",
".",
"IsDevMode",
"{",
"return",
"t",
"\n",
"}",
"\n",
"if",
"t",
">",
"time",
".",
"Minute",
"{",
"return",
"t",
"\n",
"}",
"\n",
"return",
"time",
".",
"Minute",
"\n",
"}"
] | // adjustedTimeout returns `t` if IsDevMode is false or >=1 min if true. | [
"adjustedTimeout",
"returns",
"t",
"if",
"IsDevMode",
"is",
"false",
"or",
">",
"=",
"1",
"min",
"if",
"true",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/config.go#L116-L124 |
7,643 | luci/luci-go | server/auth/config.go | setConfig | func setConfig(c context.Context, cfg *Config) context.Context {
return context.WithValue(c, &cfgContextKey, cfg)
} | go | func setConfig(c context.Context, cfg *Config) context.Context {
return context.WithValue(c, &cfgContextKey, cfg)
} | [
"func",
"setConfig",
"(",
"c",
"context",
".",
"Context",
",",
"cfg",
"*",
"Config",
")",
"context",
".",
"Context",
"{",
"return",
"context",
".",
"WithValue",
"(",
"c",
",",
"&",
"cfgContextKey",
",",
"cfg",
")",
"\n",
"}"
] | // setConfig completely replaces the configuration in the context. | [
"setConfig",
"completely",
"replaces",
"the",
"configuration",
"in",
"the",
"context",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/config.go#L127-L129 |
7,644 | luci/luci-go | server/auth/config.go | GetSigner | func GetSigner(c context.Context) signing.Signer {
if cfg := getConfig(c); cfg != nil {
return cfg.Signer
}
return nil
} | go | func GetSigner(c context.Context) signing.Signer {
if cfg := getConfig(c); cfg != nil {
return cfg.Signer
}
return nil
} | [
"func",
"GetSigner",
"(",
"c",
"context",
".",
"Context",
")",
"signing",
".",
"Signer",
"{",
"if",
"cfg",
":=",
"getConfig",
"(",
"c",
")",
";",
"cfg",
"!=",
"nil",
"{",
"return",
"cfg",
".",
"Signer",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // GetSigner returns the signing.Signer instance representing the service.
//
// It is injected into the context as part of Config. It can be used to grab
// a service account the service is running as or its current public
// certificates.
//
// Returns nil if the signer is not available. | [
"GetSigner",
"returns",
"the",
"signing",
".",
"Signer",
"instance",
"representing",
"the",
"service",
".",
"It",
"is",
"injected",
"into",
"the",
"context",
"as",
"part",
"of",
"Config",
".",
"It",
"can",
"be",
"used",
"to",
"grab",
"a",
"service",
"account",
"the",
"service",
"is",
"running",
"as",
"or",
"its",
"current",
"public",
"certificates",
".",
"Returns",
"nil",
"if",
"the",
"signer",
"is",
"not",
"available",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/server/auth/config.go#L160-L165 |
7,645 | luci/luci-go | common/api/gitiles/json.go | MarshalJSON | func (t ts) MarshalJSON() ([]byte, error) {
stringTime := t.Format(time.ANSIC)
return json.Marshal(stringTime)
} | go | func (t ts) MarshalJSON() ([]byte, error) {
stringTime := t.Format(time.ANSIC)
return json.Marshal(stringTime)
} | [
"func",
"(",
"t",
"ts",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"stringTime",
":=",
"t",
".",
"Format",
"(",
"time",
".",
"ANSIC",
")",
"\n",
"return",
"json",
".",
"Marshal",
"(",
"stringTime",
")",
"\n",
"}"
] | // MarshalJSON converts Time to an ANSIC string before marshalling. | [
"MarshalJSON",
"converts",
"Time",
"to",
"an",
"ANSIC",
"string",
"before",
"marshalling",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/api/gitiles/json.go#L41-L44 |
7,646 | luci/luci-go | common/api/gitiles/json.go | UnmarshalJSON | func (t *ts) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
parsedTime, err := time.Parse(time.ANSIC, s)
if err != nil {
// Try it with the appended timezone version.
parsedTime, err = time.Parse(time.ANSIC+" -0700", s)
}
t.Time = parsedTime
return err
} | go | func (t *ts) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
parsedTime, err := time.Parse(time.ANSIC, s)
if err != nil {
// Try it with the appended timezone version.
parsedTime, err = time.Parse(time.ANSIC+" -0700", s)
}
t.Time = parsedTime
return err
} | [
"func",
"(",
"t",
"*",
"ts",
")",
"UnmarshalJSON",
"(",
"b",
"[",
"]",
"byte",
")",
"error",
"{",
"var",
"s",
"string",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"b",
",",
"&",
"s",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"parsedTime",
",",
"err",
":=",
"time",
".",
"Parse",
"(",
"time",
".",
"ANSIC",
",",
"s",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Try it with the appended timezone version.",
"parsedTime",
",",
"err",
"=",
"time",
".",
"Parse",
"(",
"time",
".",
"ANSIC",
"+",
"\"",
"\"",
",",
"s",
")",
"\n",
"}",
"\n",
"t",
".",
"Time",
"=",
"parsedTime",
"\n",
"return",
"err",
"\n",
"}"
] | // UnmarshalJSON unmarshals an ANSIC string before parsing it into a Time. | [
"UnmarshalJSON",
"unmarshals",
"an",
"ANSIC",
"string",
"before",
"parsing",
"it",
"into",
"a",
"Time",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/api/gitiles/json.go#L47-L59 |
7,647 | luci/luci-go | common/api/gitiles/json.go | Proto | func (u *user) Proto() (ret *git.Commit_User, err error) {
ret = &git.Commit_User{
Name: u.Name,
Email: u.Email,
}
if !u.Time.IsZero() {
ret.Time, err = ptypes.TimestampProto(u.Time.Time)
err = errors.Annotate(err, "encoding time").Err()
}
return
} | go | func (u *user) Proto() (ret *git.Commit_User, err error) {
ret = &git.Commit_User{
Name: u.Name,
Email: u.Email,
}
if !u.Time.IsZero() {
ret.Time, err = ptypes.TimestampProto(u.Time.Time)
err = errors.Annotate(err, "encoding time").Err()
}
return
} | [
"func",
"(",
"u",
"*",
"user",
")",
"Proto",
"(",
")",
"(",
"ret",
"*",
"git",
".",
"Commit_User",
",",
"err",
"error",
")",
"{",
"ret",
"=",
"&",
"git",
".",
"Commit_User",
"{",
"Name",
":",
"u",
".",
"Name",
",",
"Email",
":",
"u",
".",
"Email",
",",
"}",
"\n",
"if",
"!",
"u",
".",
"Time",
".",
"IsZero",
"(",
")",
"{",
"ret",
".",
"Time",
",",
"err",
"=",
"ptypes",
".",
"TimestampProto",
"(",
"u",
".",
"Time",
".",
"Time",
")",
"\n",
"err",
"=",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] | // Proto converts this User to its protobuf equivalent. | [
"Proto",
"converts",
"this",
"User",
"to",
"its",
"protobuf",
"equivalent",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/api/gitiles/json.go#L69-L79 |
7,648 | luci/luci-go | common/api/gitiles/json.go | Proto | func (c *commit) Proto() (ret *git.Commit, err error) {
ret = &git.Commit{
Id: c.Commit,
Tree: c.Tree,
Parents: c.Parents,
Message: c.Message,
TreeDiff: c.TreeDiff,
}
if ret.Author, err = c.Author.Proto(); err != nil {
err = errors.Annotate(err, "decoding author").Err()
return
}
if ret.Committer, err = c.Committer.Proto(); err != nil {
err = errors.Annotate(err, "decoding committer").Err()
return
}
return
} | go | func (c *commit) Proto() (ret *git.Commit, err error) {
ret = &git.Commit{
Id: c.Commit,
Tree: c.Tree,
Parents: c.Parents,
Message: c.Message,
TreeDiff: c.TreeDiff,
}
if ret.Author, err = c.Author.Proto(); err != nil {
err = errors.Annotate(err, "decoding author").Err()
return
}
if ret.Committer, err = c.Committer.Proto(); err != nil {
err = errors.Annotate(err, "decoding committer").Err()
return
}
return
} | [
"func",
"(",
"c",
"*",
"commit",
")",
"Proto",
"(",
")",
"(",
"ret",
"*",
"git",
".",
"Commit",
",",
"err",
"error",
")",
"{",
"ret",
"=",
"&",
"git",
".",
"Commit",
"{",
"Id",
":",
"c",
".",
"Commit",
",",
"Tree",
":",
"c",
".",
"Tree",
",",
"Parents",
":",
"c",
".",
"Parents",
",",
"Message",
":",
"c",
".",
"Message",
",",
"TreeDiff",
":",
"c",
".",
"TreeDiff",
",",
"}",
"\n\n",
"if",
"ret",
".",
"Author",
",",
"err",
"=",
"c",
".",
"Author",
".",
"Proto",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"err",
"=",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"ret",
".",
"Committer",
",",
"err",
"=",
"c",
".",
"Committer",
".",
"Proto",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"err",
"=",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"return",
"\n",
"}"
] | // Proto converts this git.Commit to its protobuf equivalent. | [
"Proto",
"converts",
"this",
"git",
".",
"Commit",
"to",
"its",
"protobuf",
"equivalent",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/api/gitiles/json.go#L93-L112 |
7,649 | luci/luci-go | machine-db/client/cli/platforms.go | printPlatforms | func printPlatforms(tsv bool, platforms ...*crimson.Platform) {
if len(platforms) > 0 {
p := newStdoutPrinter(tsv)
defer p.Flush()
if !tsv {
p.Row("Name", "Description", "Manufacturer")
}
for _, plat := range platforms {
p.Row(plat.Name, plat.Description, plat.Manufacturer)
}
}
} | go | func printPlatforms(tsv bool, platforms ...*crimson.Platform) {
if len(platforms) > 0 {
p := newStdoutPrinter(tsv)
defer p.Flush()
if !tsv {
p.Row("Name", "Description", "Manufacturer")
}
for _, plat := range platforms {
p.Row(plat.Name, plat.Description, plat.Manufacturer)
}
}
} | [
"func",
"printPlatforms",
"(",
"tsv",
"bool",
",",
"platforms",
"...",
"*",
"crimson",
".",
"Platform",
")",
"{",
"if",
"len",
"(",
"platforms",
")",
">",
"0",
"{",
"p",
":=",
"newStdoutPrinter",
"(",
"tsv",
")",
"\n",
"defer",
"p",
".",
"Flush",
"(",
")",
"\n",
"if",
"!",
"tsv",
"{",
"p",
".",
"Row",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"plat",
":=",
"range",
"platforms",
"{",
"p",
".",
"Row",
"(",
"plat",
".",
"Name",
",",
"plat",
".",
"Description",
",",
"plat",
".",
"Manufacturer",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // printPlatforms prints platform data to stdout in tab-separated columns. | [
"printPlatforms",
"prints",
"platform",
"data",
"to",
"stdout",
"in",
"tab",
"-",
"separated",
"columns",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/platforms.go#L28-L39 |
7,650 | luci/luci-go | machine-db/client/cli/platforms.go | Run | func (c *GetPlatformsCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
ctx := cli.GetContext(app, c, env)
client := getClient(ctx)
resp, err := client.ListPlatforms(ctx, &c.req)
if err != nil {
errors.Log(ctx, err)
return 1
}
printPlatforms(c.f.tsv, resp.Platforms...)
return 0
} | go | func (c *GetPlatformsCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
ctx := cli.GetContext(app, c, env)
client := getClient(ctx)
resp, err := client.ListPlatforms(ctx, &c.req)
if err != nil {
errors.Log(ctx, err)
return 1
}
printPlatforms(c.f.tsv, resp.Platforms...)
return 0
} | [
"func",
"(",
"c",
"*",
"GetPlatformsCmd",
")",
"Run",
"(",
"app",
"subcommands",
".",
"Application",
",",
"args",
"[",
"]",
"string",
",",
"env",
"subcommands",
".",
"Env",
")",
"int",
"{",
"ctx",
":=",
"cli",
".",
"GetContext",
"(",
"app",
",",
"c",
",",
"env",
")",
"\n",
"client",
":=",
"getClient",
"(",
"ctx",
")",
"\n",
"resp",
",",
"err",
":=",
"client",
".",
"ListPlatforms",
"(",
"ctx",
",",
"&",
"c",
".",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"errors",
".",
"Log",
"(",
"ctx",
",",
"err",
")",
"\n",
"return",
"1",
"\n",
"}",
"\n",
"printPlatforms",
"(",
"c",
".",
"f",
".",
"tsv",
",",
"resp",
".",
"Platforms",
"...",
")",
"\n",
"return",
"0",
"\n",
"}"
] | // Run runs the command to get platforms. | [
"Run",
"runs",
"the",
"command",
"to",
"get",
"platforms",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/platforms.go#L48-L58 |
7,651 | luci/luci-go | machine-db/client/cli/platforms.go | getPlatformsCmd | func getPlatformsCmd(params *Parameters) *subcommands.Command {
return &subcommands.Command{
UsageLine: "get-platforms [-name <name>]... [-man <manufacturer>]...",
ShortDesc: "retrieves platforms",
LongDesc: "Retrieves platforms matching the given names, or all platforms if names and manufacturers are omitted.\n\nExample to get all platforms:\ncrimson get-platforms\nExample to get all Apple platforms:\ncrimson get-platforms -man apple",
CommandRun: func() subcommands.CommandRun {
cmd := &GetPlatformsCmd{}
cmd.Initialize(params)
cmd.Flags.Var(flag.StringSlice(&cmd.req.Names), "name", "Name of a platform to filter by. Can be specified multiple times.")
cmd.Flags.Var(flag.StringSlice(&cmd.req.Manufacturers), "man", "Manufacturer to filter by. Can be specified multiple times.")
return cmd
},
}
} | go | func getPlatformsCmd(params *Parameters) *subcommands.Command {
return &subcommands.Command{
UsageLine: "get-platforms [-name <name>]... [-man <manufacturer>]...",
ShortDesc: "retrieves platforms",
LongDesc: "Retrieves platforms matching the given names, or all platforms if names and manufacturers are omitted.\n\nExample to get all platforms:\ncrimson get-platforms\nExample to get all Apple platforms:\ncrimson get-platforms -man apple",
CommandRun: func() subcommands.CommandRun {
cmd := &GetPlatformsCmd{}
cmd.Initialize(params)
cmd.Flags.Var(flag.StringSlice(&cmd.req.Names), "name", "Name of a platform to filter by. Can be specified multiple times.")
cmd.Flags.Var(flag.StringSlice(&cmd.req.Manufacturers), "man", "Manufacturer to filter by. Can be specified multiple times.")
return cmd
},
}
} | [
"func",
"getPlatformsCmd",
"(",
"params",
"*",
"Parameters",
")",
"*",
"subcommands",
".",
"Command",
"{",
"return",
"&",
"subcommands",
".",
"Command",
"{",
"UsageLine",
":",
"\"",
"\"",
",",
"ShortDesc",
":",
"\"",
"\"",
",",
"LongDesc",
":",
"\"",
"\\n",
"\\n",
"\\n",
"\\n",
"\\n",
"\"",
",",
"CommandRun",
":",
"func",
"(",
")",
"subcommands",
".",
"CommandRun",
"{",
"cmd",
":=",
"&",
"GetPlatformsCmd",
"{",
"}",
"\n",
"cmd",
".",
"Initialize",
"(",
"params",
")",
"\n",
"cmd",
".",
"Flags",
".",
"Var",
"(",
"flag",
".",
"StringSlice",
"(",
"&",
"cmd",
".",
"req",
".",
"Names",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"cmd",
".",
"Flags",
".",
"Var",
"(",
"flag",
".",
"StringSlice",
"(",
"&",
"cmd",
".",
"req",
".",
"Manufacturers",
")",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"return",
"cmd",
"\n",
"}",
",",
"}",
"\n",
"}"
] | // getPlatformsCmd returns a command to get platforms. | [
"getPlatformsCmd",
"returns",
"a",
"command",
"to",
"get",
"platforms",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/machine-db/client/cli/platforms.go#L61-L74 |
7,652 | luci/luci-go | dm/api/distributor/jobsim/validate.go | Normalize | func (p *Phrase) Normalize() error {
if p != nil {
if p.Name == "" {
return fmt.Errorf("empty ID")
}
for _, s := range p.Stages {
if err := s.Normalize(); err != nil {
return err
}
}
if p.ReturnStage == nil {
p.ReturnStage = &ReturnStage{Retval: 1}
}
}
return nil
} | go | func (p *Phrase) Normalize() error {
if p != nil {
if p.Name == "" {
return fmt.Errorf("empty ID")
}
for _, s := range p.Stages {
if err := s.Normalize(); err != nil {
return err
}
}
if p.ReturnStage == nil {
p.ReturnStage = &ReturnStage{Retval: 1}
}
}
return nil
} | [
"func",
"(",
"p",
"*",
"Phrase",
")",
"Normalize",
"(",
")",
"error",
"{",
"if",
"p",
"!=",
"nil",
"{",
"if",
"p",
".",
"Name",
"==",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"s",
":=",
"range",
"p",
".",
"Stages",
"{",
"if",
"err",
":=",
"s",
".",
"Normalize",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"p",
".",
"ReturnStage",
"==",
"nil",
"{",
"p",
".",
"ReturnStage",
"=",
"&",
"ReturnStage",
"{",
"Retval",
":",
"1",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Normalize checks Phrase for errors and converts it to its normalized form. | [
"Normalize",
"checks",
"Phrase",
"for",
"errors",
"and",
"converts",
"it",
"to",
"its",
"normalized",
"form",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/distributor/jobsim/validate.go#L26-L41 |
7,653 | luci/luci-go | dm/api/distributor/jobsim/validate.go | Normalize | func (s *Stage) Normalize() error {
switch st := s.GetStageType().(type) {
case *Stage_Failure:
return st.Failure.Normalize()
case *Stage_Stall:
return st.Stall.Normalize()
case *Stage_Deps:
return st.Deps.Normalize()
}
return fmt.Errorf("empty stage")
} | go | func (s *Stage) Normalize() error {
switch st := s.GetStageType().(type) {
case *Stage_Failure:
return st.Failure.Normalize()
case *Stage_Stall:
return st.Stall.Normalize()
case *Stage_Deps:
return st.Deps.Normalize()
}
return fmt.Errorf("empty stage")
} | [
"func",
"(",
"s",
"*",
"Stage",
")",
"Normalize",
"(",
")",
"error",
"{",
"switch",
"st",
":=",
"s",
".",
"GetStageType",
"(",
")",
".",
"(",
"type",
")",
"{",
"case",
"*",
"Stage_Failure",
":",
"return",
"st",
".",
"Failure",
".",
"Normalize",
"(",
")",
"\n",
"case",
"*",
"Stage_Stall",
":",
"return",
"st",
".",
"Stall",
".",
"Normalize",
"(",
")",
"\n",
"case",
"*",
"Stage_Deps",
":",
"return",
"st",
".",
"Deps",
".",
"Normalize",
"(",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}"
] | // Normalize checks Stage for errors and converts it to its normalized form. | [
"Normalize",
"checks",
"Stage",
"for",
"errors",
"and",
"converts",
"it",
"to",
"its",
"normalized",
"form",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/distributor/jobsim/validate.go#L44-L54 |
7,654 | luci/luci-go | dm/api/distributor/jobsim/validate.go | Normalize | func (f *FailureStage) Normalize() error {
if f.Chance < 0 {
return fmt.Errorf("too small FailureStage chance")
}
if f.Chance > 1 {
return fmt.Errorf("too large FailureStage chance")
}
return nil
} | go | func (f *FailureStage) Normalize() error {
if f.Chance < 0 {
return fmt.Errorf("too small FailureStage chance")
}
if f.Chance > 1 {
return fmt.Errorf("too large FailureStage chance")
}
return nil
} | [
"func",
"(",
"f",
"*",
"FailureStage",
")",
"Normalize",
"(",
")",
"error",
"{",
"if",
"f",
".",
"Chance",
"<",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"f",
".",
"Chance",
">",
"1",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Normalize checks FailureStage for errors and converts it to its normalized
// form. | [
"Normalize",
"checks",
"FailureStage",
"for",
"errors",
"and",
"converts",
"it",
"to",
"its",
"normalized",
"form",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/distributor/jobsim/validate.go#L58-L66 |
7,655 | luci/luci-go | dm/api/distributor/jobsim/validate.go | Normalize | func (d *DepsStage) Normalize() error {
for _, d := range d.Deps {
if err := d.Normalize(); err != nil {
return err
}
}
return nil
} | go | func (d *DepsStage) Normalize() error {
for _, d := range d.Deps {
if err := d.Normalize(); err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"d",
"*",
"DepsStage",
")",
"Normalize",
"(",
")",
"error",
"{",
"for",
"_",
",",
"d",
":=",
"range",
"d",
".",
"Deps",
"{",
"if",
"err",
":=",
"d",
".",
"Normalize",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Normalize checks DepsStage for errors and converts it to its normalized form. | [
"Normalize",
"checks",
"DepsStage",
"for",
"errors",
"and",
"converts",
"it",
"to",
"its",
"normalized",
"form",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/distributor/jobsim/validate.go#L75-L82 |
7,656 | luci/luci-go | dm/api/distributor/jobsim/validate.go | Normalize | func (d *Dependency) Normalize() error {
if d.Shards == 0 {
d.Shards = 1
}
if err := d.GetAttempts().Normalize(); err != nil {
return err
}
return d.Phrase.Normalize()
} | go | func (d *Dependency) Normalize() error {
if d.Shards == 0 {
d.Shards = 1
}
if err := d.GetAttempts().Normalize(); err != nil {
return err
}
return d.Phrase.Normalize()
} | [
"func",
"(",
"d",
"*",
"Dependency",
")",
"Normalize",
"(",
")",
"error",
"{",
"if",
"d",
".",
"Shards",
"==",
"0",
"{",
"d",
".",
"Shards",
"=",
"1",
"\n",
"}",
"\n",
"if",
"err",
":=",
"d",
".",
"GetAttempts",
"(",
")",
".",
"Normalize",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"d",
".",
"Phrase",
".",
"Normalize",
"(",
")",
"\n",
"}"
] | // Normalize checks Dependency for errors and converts it to its normalized form. | [
"Normalize",
"checks",
"Dependency",
"for",
"errors",
"and",
"converts",
"it",
"to",
"its",
"normalized",
"form",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/distributor/jobsim/validate.go#L85-L93 |
7,657 | luci/luci-go | dm/api/distributor/jobsim/validate.go | Normalize | func (s *SparseRange) Normalize() error {
if len(s.Items) == 0 {
s.Items = []*RangeItem{{RangeItem: &RangeItem_Single{1}}}
return nil
}
current := uint32(0)
for _, itm := range s.Items {
switch i := itm.RangeItem.(type) {
case *RangeItem_Single:
if i.Single <= current {
return fmt.Errorf("malformed SparseRange")
}
current = i.Single
case *RangeItem_Range:
if err := i.Range.Normalize(); err != nil {
return err
}
if i.Range.Low <= current {
return fmt.Errorf("malformed SparseRange")
}
current = i.Range.High
default:
return fmt.Errorf("unknown SparseRange entry")
}
}
return nil
} | go | func (s *SparseRange) Normalize() error {
if len(s.Items) == 0 {
s.Items = []*RangeItem{{RangeItem: &RangeItem_Single{1}}}
return nil
}
current := uint32(0)
for _, itm := range s.Items {
switch i := itm.RangeItem.(type) {
case *RangeItem_Single:
if i.Single <= current {
return fmt.Errorf("malformed SparseRange")
}
current = i.Single
case *RangeItem_Range:
if err := i.Range.Normalize(); err != nil {
return err
}
if i.Range.Low <= current {
return fmt.Errorf("malformed SparseRange")
}
current = i.Range.High
default:
return fmt.Errorf("unknown SparseRange entry")
}
}
return nil
} | [
"func",
"(",
"s",
"*",
"SparseRange",
")",
"Normalize",
"(",
")",
"error",
"{",
"if",
"len",
"(",
"s",
".",
"Items",
")",
"==",
"0",
"{",
"s",
".",
"Items",
"=",
"[",
"]",
"*",
"RangeItem",
"{",
"{",
"RangeItem",
":",
"&",
"RangeItem_Single",
"{",
"1",
"}",
"}",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"current",
":=",
"uint32",
"(",
"0",
")",
"\n",
"for",
"_",
",",
"itm",
":=",
"range",
"s",
".",
"Items",
"{",
"switch",
"i",
":=",
"itm",
".",
"RangeItem",
".",
"(",
"type",
")",
"{",
"case",
"*",
"RangeItem_Single",
":",
"if",
"i",
".",
"Single",
"<=",
"current",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"current",
"=",
"i",
".",
"Single",
"\n",
"case",
"*",
"RangeItem_Range",
":",
"if",
"err",
":=",
"i",
".",
"Range",
".",
"Normalize",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"i",
".",
"Range",
".",
"Low",
"<=",
"current",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"current",
"=",
"i",
".",
"Range",
".",
"High",
"\n",
"default",
":",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Normalize checks SparseRange for errors and converts it to its normalized form. | [
"Normalize",
"checks",
"SparseRange",
"for",
"errors",
"and",
"converts",
"it",
"to",
"its",
"normalized",
"form",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/distributor/jobsim/validate.go#L96-L122 |
7,658 | luci/luci-go | dm/api/distributor/jobsim/validate.go | Normalize | func (r *Range) Normalize() error {
if r.High <= r.Low {
return fmt.Errorf("malformed Range")
}
return nil
} | go | func (r *Range) Normalize() error {
if r.High <= r.Low {
return fmt.Errorf("malformed Range")
}
return nil
} | [
"func",
"(",
"r",
"*",
"Range",
")",
"Normalize",
"(",
")",
"error",
"{",
"if",
"r",
".",
"High",
"<=",
"r",
".",
"Low",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Normalize checks Range for errors and converts it to its normalized form. | [
"Normalize",
"checks",
"Range",
"for",
"errors",
"and",
"converts",
"it",
"to",
"its",
"normalized",
"form",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/api/distributor/jobsim/validate.go#L125-L130 |
7,659 | luci/luci-go | tools/cmd/bqschemaupdater/schema.go | schema | func (c *schemaConverter) schema(messageName string) (schema bigquery.Schema, description string, err error) {
file, obj, _ := descutil.Resolve(c.desc, messageName)
if obj == nil {
return nil, "", fmt.Errorf("message %q is not found", messageName)
}
msg, isMsg := obj.(*descriptor.DescriptorProto)
if !isMsg {
return nil, "", fmt.Errorf("expected %q to be a message, but it is %T", messageName, obj)
}
schema = make(bigquery.Schema, 0, len(msg.Field))
for _, field := range msg.Field {
switch s, err := c.field(file, field); {
case err != nil:
return nil, "", errors.Annotate(err, "failed to derive schema for field %q in message %q", field.GetName(), msg.GetName()).Err()
case s != nil:
schema = append(schema, s)
}
}
return schema, c.description(file, msg), nil
} | go | func (c *schemaConverter) schema(messageName string) (schema bigquery.Schema, description string, err error) {
file, obj, _ := descutil.Resolve(c.desc, messageName)
if obj == nil {
return nil, "", fmt.Errorf("message %q is not found", messageName)
}
msg, isMsg := obj.(*descriptor.DescriptorProto)
if !isMsg {
return nil, "", fmt.Errorf("expected %q to be a message, but it is %T", messageName, obj)
}
schema = make(bigquery.Schema, 0, len(msg.Field))
for _, field := range msg.Field {
switch s, err := c.field(file, field); {
case err != nil:
return nil, "", errors.Annotate(err, "failed to derive schema for field %q in message %q", field.GetName(), msg.GetName()).Err()
case s != nil:
schema = append(schema, s)
}
}
return schema, c.description(file, msg), nil
} | [
"func",
"(",
"c",
"*",
"schemaConverter",
")",
"schema",
"(",
"messageName",
"string",
")",
"(",
"schema",
"bigquery",
".",
"Schema",
",",
"description",
"string",
",",
"err",
"error",
")",
"{",
"file",
",",
"obj",
",",
"_",
":=",
"descutil",
".",
"Resolve",
"(",
"c",
".",
"desc",
",",
"messageName",
")",
"\n",
"if",
"obj",
"==",
"nil",
"{",
"return",
"nil",
",",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"messageName",
")",
"\n",
"}",
"\n",
"msg",
",",
"isMsg",
":=",
"obj",
".",
"(",
"*",
"descriptor",
".",
"DescriptorProto",
")",
"\n",
"if",
"!",
"isMsg",
"{",
"return",
"nil",
",",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"messageName",
",",
"obj",
")",
"\n",
"}",
"\n\n",
"schema",
"=",
"make",
"(",
"bigquery",
".",
"Schema",
",",
"0",
",",
"len",
"(",
"msg",
".",
"Field",
")",
")",
"\n",
"for",
"_",
",",
"field",
":=",
"range",
"msg",
".",
"Field",
"{",
"switch",
"s",
",",
"err",
":=",
"c",
".",
"field",
"(",
"file",
",",
"field",
")",
";",
"{",
"case",
"err",
"!=",
"nil",
":",
"return",
"nil",
",",
"\"",
"\"",
",",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
",",
"field",
".",
"GetName",
"(",
")",
",",
"msg",
".",
"GetName",
"(",
")",
")",
".",
"Err",
"(",
")",
"\n",
"case",
"s",
"!=",
"nil",
":",
"schema",
"=",
"append",
"(",
"schema",
",",
"s",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"schema",
",",
"c",
".",
"description",
"(",
"file",
",",
"msg",
")",
",",
"nil",
"\n",
"}"
] | // schema constructs a bigquery.Schema from a named message. | [
"schema",
"constructs",
"a",
"bigquery",
".",
"Schema",
"from",
"a",
"named",
"message",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tools/cmd/bqschemaupdater/schema.go#L45-L65 |
7,660 | luci/luci-go | tools/cmd/bqschemaupdater/schema.go | field | func (c *schemaConverter) field(file *descriptor.FileDescriptorProto, field *descriptor.FieldDescriptorProto) (*bigquery.FieldSchema, error) {
schema := &bigquery.FieldSchema{
Name: field.GetName(),
Description: c.description(file, field),
Repeated: descutil.Repeated(field),
Required: descutil.Required(field),
}
typeName := strings.TrimPrefix(field.GetTypeName(), ".")
switch field.GetType() {
case
descriptor.FieldDescriptorProto_TYPE_DOUBLE,
descriptor.FieldDescriptorProto_TYPE_FLOAT:
schema.Type = bigquery.FloatFieldType
case
descriptor.FieldDescriptorProto_TYPE_INT64,
descriptor.FieldDescriptorProto_TYPE_UINT64,
descriptor.FieldDescriptorProto_TYPE_INT32,
descriptor.FieldDescriptorProto_TYPE_FIXED64,
descriptor.FieldDescriptorProto_TYPE_FIXED32,
descriptor.FieldDescriptorProto_TYPE_UINT32,
descriptor.FieldDescriptorProto_TYPE_SFIXED32,
descriptor.FieldDescriptorProto_TYPE_SFIXED64,
descriptor.FieldDescriptorProto_TYPE_SINT32,
descriptor.FieldDescriptorProto_TYPE_SINT64:
schema.Type = bigquery.IntegerFieldType
case descriptor.FieldDescriptorProto_TYPE_BOOL:
schema.Type = bigquery.BooleanFieldType
case descriptor.FieldDescriptorProto_TYPE_STRING:
schema.Type = bigquery.StringFieldType
case descriptor.FieldDescriptorProto_TYPE_BYTES:
schema.Type = bigquery.BytesFieldType
case descriptor.FieldDescriptorProto_TYPE_ENUM:
schema.Type = bigquery.StringFieldType
case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
switch typeName {
case "google.protobuf.Duration":
schema.Type = bigquery.FloatFieldType
case "google.protobuf.Timestamp":
schema.Type = bigquery.TimestampFieldType
case "google.protobuf.Struct":
// google.protobuf.Struct is persisted as JSONPB string.
// See also https://bit.ly/chromium-bq-struct
schema.Type = bigquery.StringFieldType
default:
switch s, _, err := c.schema(typeName); {
case err != nil:
return nil, err
case len(s) == 0:
// BigQuery does not like empty record fields.
return nil, nil
default:
schema.Type = bigquery.RecordFieldType
schema.Schema = s
}
}
default:
return nil, fmt.Errorf("not supported field type %q", field.GetType())
}
return schema, nil
} | go | func (c *schemaConverter) field(file *descriptor.FileDescriptorProto, field *descriptor.FieldDescriptorProto) (*bigquery.FieldSchema, error) {
schema := &bigquery.FieldSchema{
Name: field.GetName(),
Description: c.description(file, field),
Repeated: descutil.Repeated(field),
Required: descutil.Required(field),
}
typeName := strings.TrimPrefix(field.GetTypeName(), ".")
switch field.GetType() {
case
descriptor.FieldDescriptorProto_TYPE_DOUBLE,
descriptor.FieldDescriptorProto_TYPE_FLOAT:
schema.Type = bigquery.FloatFieldType
case
descriptor.FieldDescriptorProto_TYPE_INT64,
descriptor.FieldDescriptorProto_TYPE_UINT64,
descriptor.FieldDescriptorProto_TYPE_INT32,
descriptor.FieldDescriptorProto_TYPE_FIXED64,
descriptor.FieldDescriptorProto_TYPE_FIXED32,
descriptor.FieldDescriptorProto_TYPE_UINT32,
descriptor.FieldDescriptorProto_TYPE_SFIXED32,
descriptor.FieldDescriptorProto_TYPE_SFIXED64,
descriptor.FieldDescriptorProto_TYPE_SINT32,
descriptor.FieldDescriptorProto_TYPE_SINT64:
schema.Type = bigquery.IntegerFieldType
case descriptor.FieldDescriptorProto_TYPE_BOOL:
schema.Type = bigquery.BooleanFieldType
case descriptor.FieldDescriptorProto_TYPE_STRING:
schema.Type = bigquery.StringFieldType
case descriptor.FieldDescriptorProto_TYPE_BYTES:
schema.Type = bigquery.BytesFieldType
case descriptor.FieldDescriptorProto_TYPE_ENUM:
schema.Type = bigquery.StringFieldType
case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
switch typeName {
case "google.protobuf.Duration":
schema.Type = bigquery.FloatFieldType
case "google.protobuf.Timestamp":
schema.Type = bigquery.TimestampFieldType
case "google.protobuf.Struct":
// google.protobuf.Struct is persisted as JSONPB string.
// See also https://bit.ly/chromium-bq-struct
schema.Type = bigquery.StringFieldType
default:
switch s, _, err := c.schema(typeName); {
case err != nil:
return nil, err
case len(s) == 0:
// BigQuery does not like empty record fields.
return nil, nil
default:
schema.Type = bigquery.RecordFieldType
schema.Schema = s
}
}
default:
return nil, fmt.Errorf("not supported field type %q", field.GetType())
}
return schema, nil
} | [
"func",
"(",
"c",
"*",
"schemaConverter",
")",
"field",
"(",
"file",
"*",
"descriptor",
".",
"FileDescriptorProto",
",",
"field",
"*",
"descriptor",
".",
"FieldDescriptorProto",
")",
"(",
"*",
"bigquery",
".",
"FieldSchema",
",",
"error",
")",
"{",
"schema",
":=",
"&",
"bigquery",
".",
"FieldSchema",
"{",
"Name",
":",
"field",
".",
"GetName",
"(",
")",
",",
"Description",
":",
"c",
".",
"description",
"(",
"file",
",",
"field",
")",
",",
"Repeated",
":",
"descutil",
".",
"Repeated",
"(",
"field",
")",
",",
"Required",
":",
"descutil",
".",
"Required",
"(",
"field",
")",
",",
"}",
"\n\n",
"typeName",
":=",
"strings",
".",
"TrimPrefix",
"(",
"field",
".",
"GetTypeName",
"(",
")",
",",
"\"",
"\"",
")",
"\n",
"switch",
"field",
".",
"GetType",
"(",
")",
"{",
"case",
"descriptor",
".",
"FieldDescriptorProto_TYPE_DOUBLE",
",",
"descriptor",
".",
"FieldDescriptorProto_TYPE_FLOAT",
":",
"schema",
".",
"Type",
"=",
"bigquery",
".",
"FloatFieldType",
"\n\n",
"case",
"descriptor",
".",
"FieldDescriptorProto_TYPE_INT64",
",",
"descriptor",
".",
"FieldDescriptorProto_TYPE_UINT64",
",",
"descriptor",
".",
"FieldDescriptorProto_TYPE_INT32",
",",
"descriptor",
".",
"FieldDescriptorProto_TYPE_FIXED64",
",",
"descriptor",
".",
"FieldDescriptorProto_TYPE_FIXED32",
",",
"descriptor",
".",
"FieldDescriptorProto_TYPE_UINT32",
",",
"descriptor",
".",
"FieldDescriptorProto_TYPE_SFIXED32",
",",
"descriptor",
".",
"FieldDescriptorProto_TYPE_SFIXED64",
",",
"descriptor",
".",
"FieldDescriptorProto_TYPE_SINT32",
",",
"descriptor",
".",
"FieldDescriptorProto_TYPE_SINT64",
":",
"schema",
".",
"Type",
"=",
"bigquery",
".",
"IntegerFieldType",
"\n\n",
"case",
"descriptor",
".",
"FieldDescriptorProto_TYPE_BOOL",
":",
"schema",
".",
"Type",
"=",
"bigquery",
".",
"BooleanFieldType",
"\n\n",
"case",
"descriptor",
".",
"FieldDescriptorProto_TYPE_STRING",
":",
"schema",
".",
"Type",
"=",
"bigquery",
".",
"StringFieldType",
"\n\n",
"case",
"descriptor",
".",
"FieldDescriptorProto_TYPE_BYTES",
":",
"schema",
".",
"Type",
"=",
"bigquery",
".",
"BytesFieldType",
"\n\n",
"case",
"descriptor",
".",
"FieldDescriptorProto_TYPE_ENUM",
":",
"schema",
".",
"Type",
"=",
"bigquery",
".",
"StringFieldType",
"\n\n",
"case",
"descriptor",
".",
"FieldDescriptorProto_TYPE_MESSAGE",
":",
"switch",
"typeName",
"{",
"case",
"\"",
"\"",
":",
"schema",
".",
"Type",
"=",
"bigquery",
".",
"FloatFieldType",
"\n",
"case",
"\"",
"\"",
":",
"schema",
".",
"Type",
"=",
"bigquery",
".",
"TimestampFieldType",
"\n",
"case",
"\"",
"\"",
":",
"// google.protobuf.Struct is persisted as JSONPB string.",
"// See also https://bit.ly/chromium-bq-struct",
"schema",
".",
"Type",
"=",
"bigquery",
".",
"StringFieldType",
"\n",
"default",
":",
"switch",
"s",
",",
"_",
",",
"err",
":=",
"c",
".",
"schema",
"(",
"typeName",
")",
";",
"{",
"case",
"err",
"!=",
"nil",
":",
"return",
"nil",
",",
"err",
"\n",
"case",
"len",
"(",
"s",
")",
"==",
"0",
":",
"// BigQuery does not like empty record fields.",
"return",
"nil",
",",
"nil",
"\n",
"default",
":",
"schema",
".",
"Type",
"=",
"bigquery",
".",
"RecordFieldType",
"\n",
"schema",
".",
"Schema",
"=",
"s",
"\n",
"}",
"\n",
"}",
"\n",
"default",
":",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"field",
".",
"GetType",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"schema",
",",
"nil",
"\n",
"}"
] | // field constructs bigquery.FieldSchema from proto field descriptor. | [
"field",
"constructs",
"bigquery",
".",
"FieldSchema",
"from",
"proto",
"field",
"descriptor",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tools/cmd/bqschemaupdater/schema.go#L68-L136 |
7,661 | luci/luci-go | tools/cmd/bqschemaupdater/schema.go | schemaDiff | func schemaDiff(before, after bigquery.Schema) string {
ret, err := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
A: difflib.SplitLines(schemaString(before)),
B: difflib.SplitLines(schemaString(after)),
FromFile: "Current",
ToFile: "New",
Context: 3,
Eol: "\n",
})
if err != nil {
// GetUnifiedDiffString returns an error only if it fails
// to write to a bytes.Buffer, which either cannot happen or we better
// panic.
panic(err)
}
return ret
} | go | func schemaDiff(before, after bigquery.Schema) string {
ret, err := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
A: difflib.SplitLines(schemaString(before)),
B: difflib.SplitLines(schemaString(after)),
FromFile: "Current",
ToFile: "New",
Context: 3,
Eol: "\n",
})
if err != nil {
// GetUnifiedDiffString returns an error only if it fails
// to write to a bytes.Buffer, which either cannot happen or we better
// panic.
panic(err)
}
return ret
} | [
"func",
"schemaDiff",
"(",
"before",
",",
"after",
"bigquery",
".",
"Schema",
")",
"string",
"{",
"ret",
",",
"err",
":=",
"difflib",
".",
"GetUnifiedDiffString",
"(",
"difflib",
".",
"UnifiedDiff",
"{",
"A",
":",
"difflib",
".",
"SplitLines",
"(",
"schemaString",
"(",
"before",
")",
")",
",",
"B",
":",
"difflib",
".",
"SplitLines",
"(",
"schemaString",
"(",
"after",
")",
")",
",",
"FromFile",
":",
"\"",
"\"",
",",
"ToFile",
":",
"\"",
"\"",
",",
"Context",
":",
"3",
",",
"Eol",
":",
"\"",
"\\n",
"\"",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// GetUnifiedDiffString returns an error only if it fails",
"// to write to a bytes.Buffer, which either cannot happen or we better",
"// panic.",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"ret",
"\n",
"}"
] | // schemaDiff returns unified diff of two schemas.
// Returns "" if there is no difference. | [
"schemaDiff",
"returns",
"unified",
"diff",
"of",
"two",
"schemas",
".",
"Returns",
"if",
"there",
"is",
"no",
"difference",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tools/cmd/bqschemaupdater/schema.go#L243-L259 |
7,662 | luci/luci-go | tools/cmd/bqschemaupdater/schema.go | addMissingFields | func addMissingFields(dest *bigquery.Schema, src bigquery.Schema) {
destFields := indexFields(*dest)
for _, sf := range src {
switch df := destFields[sf.Name]; {
case df == nil:
*dest = append(*dest, sf)
default:
addMissingFields(&df.Schema, sf.Schema)
}
}
} | go | func addMissingFields(dest *bigquery.Schema, src bigquery.Schema) {
destFields := indexFields(*dest)
for _, sf := range src {
switch df := destFields[sf.Name]; {
case df == nil:
*dest = append(*dest, sf)
default:
addMissingFields(&df.Schema, sf.Schema)
}
}
} | [
"func",
"addMissingFields",
"(",
"dest",
"*",
"bigquery",
".",
"Schema",
",",
"src",
"bigquery",
".",
"Schema",
")",
"{",
"destFields",
":=",
"indexFields",
"(",
"*",
"dest",
")",
"\n",
"for",
"_",
",",
"sf",
":=",
"range",
"src",
"{",
"switch",
"df",
":=",
"destFields",
"[",
"sf",
".",
"Name",
"]",
";",
"{",
"case",
"df",
"==",
"nil",
":",
"*",
"dest",
"=",
"append",
"(",
"*",
"dest",
",",
"sf",
")",
"\n",
"default",
":",
"addMissingFields",
"(",
"&",
"df",
".",
"Schema",
",",
"sf",
".",
"Schema",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // addMissingFields copies fields from src to dest if they are not present in
// dest. | [
"addMissingFields",
"copies",
"fields",
"from",
"src",
"to",
"dest",
"if",
"they",
"are",
"not",
"present",
"in",
"dest",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/tools/cmd/bqschemaupdater/schema.go#L263-L273 |
7,663 | luci/luci-go | logdog/client/cmd/logdog_butler/main.go | getOutputFactory | func (a *application) getOutputFactory() (outputFactory, error) {
factory := a.outputConfig.getFactory()
if factory == nil {
return nil, errors.New("main: No output is configured")
}
return factory, nil
} | go | func (a *application) getOutputFactory() (outputFactory, error) {
factory := a.outputConfig.getFactory()
if factory == nil {
return nil, errors.New("main: No output is configured")
}
return factory, nil
} | [
"func",
"(",
"a",
"*",
"application",
")",
"getOutputFactory",
"(",
")",
"(",
"outputFactory",
",",
"error",
")",
"{",
"factory",
":=",
"a",
".",
"outputConfig",
".",
"getFactory",
"(",
")",
"\n",
"if",
"factory",
"==",
"nil",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"factory",
",",
"nil",
"\n",
"}"
] | // getOutputFactory returns the currently-configured output factory. | [
"getOutputFactory",
"returns",
"the",
"currently",
"-",
"configured",
"output",
"factory",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/cmd/logdog_butler/main.go#L138-L144 |
7,664 | luci/luci-go | logdog/client/cmd/logdog_butler/main.go | runWithButler | func (a *application) runWithButler(out output.Output, runFunc func(*butler.Butler) error) error {
// Start our Profiler.
a.prof.Logger = log.Get(a)
if err := a.prof.Start(); err != nil {
return fmt.Errorf("failed to start Profiler: %v", err)
}
defer a.prof.Stop()
// Instantiate our Butler.
butlerOpts := butler.Config{
Project: a.project,
Prefix: a.prefix,
GlobalTags: a.globalTags,
MaxBufferAge: time.Duration(a.maxBufferAge),
BufferLogs: !a.noBufferLogs,
Output: out,
OutputWorkers: a.outputWorkers,
TeeStdout: os.Stdout,
TeeStderr: os.Stderr,
IOKeepAliveInterval: time.Duration(a.ioKeepAliveInterval),
IOKeepAliveWriter: os.Stderr,
}
b, err := butler.New(a, butlerOpts)
if err != nil {
return err
}
// Log the Butler's emitted streams.
defer func() {
if r := out.Record(); r != nil {
// Log detail stream record.
streams := make([]string, 0, len(r.Streams))
for k := range r.Streams {
streams = append(streams, string(k))
}
sort.Strings(streams)
for i, stream := range streams {
rec := r.Streams[types.StreamPath(stream)]
ranges := make([]string, len(rec.Ranges))
for i, rng := range rec.Ranges {
ranges[i] = rng.String()
}
log.Infof(a, "%d) Stream [%s]: %s", i, stream, strings.Join(ranges, " "))
}
} else {
// No record; display stream overview.
s := b.Streams()
paths := make([]types.StreamPath, len(s))
for i, sn := range s {
paths[i] = a.prefix.Join(sn)
}
log.Fields{
"count": len(paths),
"streams": paths,
}.Infof(a, "Butler emitted %d stream(s).", len(paths))
}
}()
// Execute our Butler run function with the instantiated Butler.
if err := runFunc(b); err != nil {
log.Fields{
log.ErrorKey: err,
}.Errorf(a, "Butler terminated with error.")
a.cancelFunc()
return err
}
return nil
} | go | func (a *application) runWithButler(out output.Output, runFunc func(*butler.Butler) error) error {
// Start our Profiler.
a.prof.Logger = log.Get(a)
if err := a.prof.Start(); err != nil {
return fmt.Errorf("failed to start Profiler: %v", err)
}
defer a.prof.Stop()
// Instantiate our Butler.
butlerOpts := butler.Config{
Project: a.project,
Prefix: a.prefix,
GlobalTags: a.globalTags,
MaxBufferAge: time.Duration(a.maxBufferAge),
BufferLogs: !a.noBufferLogs,
Output: out,
OutputWorkers: a.outputWorkers,
TeeStdout: os.Stdout,
TeeStderr: os.Stderr,
IOKeepAliveInterval: time.Duration(a.ioKeepAliveInterval),
IOKeepAliveWriter: os.Stderr,
}
b, err := butler.New(a, butlerOpts)
if err != nil {
return err
}
// Log the Butler's emitted streams.
defer func() {
if r := out.Record(); r != nil {
// Log detail stream record.
streams := make([]string, 0, len(r.Streams))
for k := range r.Streams {
streams = append(streams, string(k))
}
sort.Strings(streams)
for i, stream := range streams {
rec := r.Streams[types.StreamPath(stream)]
ranges := make([]string, len(rec.Ranges))
for i, rng := range rec.Ranges {
ranges[i] = rng.String()
}
log.Infof(a, "%d) Stream [%s]: %s", i, stream, strings.Join(ranges, " "))
}
} else {
// No record; display stream overview.
s := b.Streams()
paths := make([]types.StreamPath, len(s))
for i, sn := range s {
paths[i] = a.prefix.Join(sn)
}
log.Fields{
"count": len(paths),
"streams": paths,
}.Infof(a, "Butler emitted %d stream(s).", len(paths))
}
}()
// Execute our Butler run function with the instantiated Butler.
if err := runFunc(b); err != nil {
log.Fields{
log.ErrorKey: err,
}.Errorf(a, "Butler terminated with error.")
a.cancelFunc()
return err
}
return nil
} | [
"func",
"(",
"a",
"*",
"application",
")",
"runWithButler",
"(",
"out",
"output",
".",
"Output",
",",
"runFunc",
"func",
"(",
"*",
"butler",
".",
"Butler",
")",
"error",
")",
"error",
"{",
"// Start our Profiler.",
"a",
".",
"prof",
".",
"Logger",
"=",
"log",
".",
"Get",
"(",
"a",
")",
"\n",
"if",
"err",
":=",
"a",
".",
"prof",
".",
"Start",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"a",
".",
"prof",
".",
"Stop",
"(",
")",
"\n\n",
"// Instantiate our Butler.",
"butlerOpts",
":=",
"butler",
".",
"Config",
"{",
"Project",
":",
"a",
".",
"project",
",",
"Prefix",
":",
"a",
".",
"prefix",
",",
"GlobalTags",
":",
"a",
".",
"globalTags",
",",
"MaxBufferAge",
":",
"time",
".",
"Duration",
"(",
"a",
".",
"maxBufferAge",
")",
",",
"BufferLogs",
":",
"!",
"a",
".",
"noBufferLogs",
",",
"Output",
":",
"out",
",",
"OutputWorkers",
":",
"a",
".",
"outputWorkers",
",",
"TeeStdout",
":",
"os",
".",
"Stdout",
",",
"TeeStderr",
":",
"os",
".",
"Stderr",
",",
"IOKeepAliveInterval",
":",
"time",
".",
"Duration",
"(",
"a",
".",
"ioKeepAliveInterval",
")",
",",
"IOKeepAliveWriter",
":",
"os",
".",
"Stderr",
",",
"}",
"\n",
"b",
",",
"err",
":=",
"butler",
".",
"New",
"(",
"a",
",",
"butlerOpts",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"// Log the Butler's emitted streams.",
"defer",
"func",
"(",
")",
"{",
"if",
"r",
":=",
"out",
".",
"Record",
"(",
")",
";",
"r",
"!=",
"nil",
"{",
"// Log detail stream record.",
"streams",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"r",
".",
"Streams",
")",
")",
"\n",
"for",
"k",
":=",
"range",
"r",
".",
"Streams",
"{",
"streams",
"=",
"append",
"(",
"streams",
",",
"string",
"(",
"k",
")",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"streams",
")",
"\n\n",
"for",
"i",
",",
"stream",
":=",
"range",
"streams",
"{",
"rec",
":=",
"r",
".",
"Streams",
"[",
"types",
".",
"StreamPath",
"(",
"stream",
")",
"]",
"\n\n",
"ranges",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"len",
"(",
"rec",
".",
"Ranges",
")",
")",
"\n",
"for",
"i",
",",
"rng",
":=",
"range",
"rec",
".",
"Ranges",
"{",
"ranges",
"[",
"i",
"]",
"=",
"rng",
".",
"String",
"(",
")",
"\n",
"}",
"\n",
"log",
".",
"Infof",
"(",
"a",
",",
"\"",
"\"",
",",
"i",
",",
"stream",
",",
"strings",
".",
"Join",
"(",
"ranges",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"}",
"else",
"{",
"// No record; display stream overview.",
"s",
":=",
"b",
".",
"Streams",
"(",
")",
"\n",
"paths",
":=",
"make",
"(",
"[",
"]",
"types",
".",
"StreamPath",
",",
"len",
"(",
"s",
")",
")",
"\n",
"for",
"i",
",",
"sn",
":=",
"range",
"s",
"{",
"paths",
"[",
"i",
"]",
"=",
"a",
".",
"prefix",
".",
"Join",
"(",
"sn",
")",
"\n",
"}",
"\n",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"len",
"(",
"paths",
")",
",",
"\"",
"\"",
":",
"paths",
",",
"}",
".",
"Infof",
"(",
"a",
",",
"\"",
"\"",
",",
"len",
"(",
"paths",
")",
")",
"\n",
"}",
"\n",
"}",
"(",
")",
"\n\n",
"// Execute our Butler run function with the instantiated Butler.",
"if",
"err",
":=",
"runFunc",
"(",
"b",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fields",
"{",
"log",
".",
"ErrorKey",
":",
"err",
",",
"}",
".",
"Errorf",
"(",
"a",
",",
"\"",
"\"",
")",
"\n",
"a",
".",
"cancelFunc",
"(",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // runWithButler is an execution harness that adds application-level management
// to a Butler run. | [
"runWithButler",
"is",
"an",
"execution",
"harness",
"that",
"adds",
"application",
"-",
"level",
"management",
"to",
"a",
"Butler",
"run",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/cmd/logdog_butler/main.go#L148-L219 |
7,665 | luci/luci-go | logdog/client/cmd/logdog_butler/main.go | logAnnotatedErr | func logAnnotatedErr(ctx context.Context, err error, f string, args ...interface{}) {
if err == nil {
return
}
nargs := make([]interface{}, len(args)+1)
nargs[copy(nargs, args)] = strings.Join(errors.RenderStack(err), "\n")
if f == "" {
f = "Captured error stack:"
}
log.Errorf(ctx, f+"\n%s", nargs...)
} | go | func logAnnotatedErr(ctx context.Context, err error, f string, args ...interface{}) {
if err == nil {
return
}
nargs := make([]interface{}, len(args)+1)
nargs[copy(nargs, args)] = strings.Join(errors.RenderStack(err), "\n")
if f == "" {
f = "Captured error stack:"
}
log.Errorf(ctx, f+"\n%s", nargs...)
} | [
"func",
"logAnnotatedErr",
"(",
"ctx",
"context",
".",
"Context",
",",
"err",
"error",
",",
"f",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"if",
"err",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"nargs",
":=",
"make",
"(",
"[",
"]",
"interface",
"{",
"}",
",",
"len",
"(",
"args",
")",
"+",
"1",
")",
"\n",
"nargs",
"[",
"copy",
"(",
"nargs",
",",
"args",
")",
"]",
"=",
"strings",
".",
"Join",
"(",
"errors",
".",
"RenderStack",
"(",
"err",
")",
",",
"\"",
"\\n",
"\"",
")",
"\n\n",
"if",
"f",
"==",
"\"",
"\"",
"{",
"f",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"log",
".",
"Errorf",
"(",
"ctx",
",",
"f",
"+",
"\"",
"\\n",
"\"",
",",
"nargs",
"...",
")",
"\n",
"}"
] | // logAnnotatedErr logs the full stack trace from an annotated error to the
// installed logger at error level. | [
"logAnnotatedErr",
"logs",
"the",
"full",
"stack",
"trace",
"from",
"an",
"annotated",
"error",
"to",
"the",
"installed",
"logger",
"at",
"error",
"level",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/cmd/logdog_butler/main.go#L223-L235 |
7,666 | luci/luci-go | logdog/client/cmd/logdog_butler/main.go | main | func main() {
mathrand.SeedRandomly()
ctx := context.Background()
ctx = gologger.StdConfig.Use(ctx)
// Exit with the specified return code.
rc := 0
defer func() {
log.Infof(log.SetField(ctx, "returnCode", rc), "Terminating.")
os.Exit(rc)
}()
paniccatcher.Do(func() {
rc = mainImpl(ctx, chromeinfra.DefaultAuthOptions(), os.Args[1:])
}, func(p *paniccatcher.Panic) {
log.Fields{
"panic.error": p.Reason,
}.Errorf(ctx, "Panic caught in main:\n%s", p.Stack)
rc = runtimeErrorReturnCode
})
} | go | func main() {
mathrand.SeedRandomly()
ctx := context.Background()
ctx = gologger.StdConfig.Use(ctx)
// Exit with the specified return code.
rc := 0
defer func() {
log.Infof(log.SetField(ctx, "returnCode", rc), "Terminating.")
os.Exit(rc)
}()
paniccatcher.Do(func() {
rc = mainImpl(ctx, chromeinfra.DefaultAuthOptions(), os.Args[1:])
}, func(p *paniccatcher.Panic) {
log.Fields{
"panic.error": p.Reason,
}.Errorf(ctx, "Panic caught in main:\n%s", p.Stack)
rc = runtimeErrorReturnCode
})
} | [
"func",
"main",
"(",
")",
"{",
"mathrand",
".",
"SeedRandomly",
"(",
")",
"\n\n",
"ctx",
":=",
"context",
".",
"Background",
"(",
")",
"\n",
"ctx",
"=",
"gologger",
".",
"StdConfig",
".",
"Use",
"(",
"ctx",
")",
"\n\n",
"// Exit with the specified return code.",
"rc",
":=",
"0",
"\n",
"defer",
"func",
"(",
")",
"{",
"log",
".",
"Infof",
"(",
"log",
".",
"SetField",
"(",
"ctx",
",",
"\"",
"\"",
",",
"rc",
")",
",",
"\"",
"\"",
")",
"\n",
"os",
".",
"Exit",
"(",
"rc",
")",
"\n",
"}",
"(",
")",
"\n\n",
"paniccatcher",
".",
"Do",
"(",
"func",
"(",
")",
"{",
"rc",
"=",
"mainImpl",
"(",
"ctx",
",",
"chromeinfra",
".",
"DefaultAuthOptions",
"(",
")",
",",
"os",
".",
"Args",
"[",
"1",
":",
"]",
")",
"\n",
"}",
",",
"func",
"(",
"p",
"*",
"paniccatcher",
".",
"Panic",
")",
"{",
"log",
".",
"Fields",
"{",
"\"",
"\"",
":",
"p",
".",
"Reason",
",",
"}",
".",
"Errorf",
"(",
"ctx",
",",
"\"",
"\\n",
"\"",
",",
"p",
".",
"Stack",
")",
"\n",
"rc",
"=",
"runtimeErrorReturnCode",
"\n",
"}",
")",
"\n",
"}"
] | // Main execution function. This immediately jumps to 'mainImpl' and uses its
// result as an exit code. | [
"Main",
"execution",
"function",
".",
"This",
"immediately",
"jumps",
"to",
"mainImpl",
"and",
"uses",
"its",
"result",
"as",
"an",
"exit",
"code",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/client/cmd/logdog_butler/main.go#L347-L368 |
7,667 | luci/luci-go | vpython/venv/iterator.go | ForEach | func (it *Iterator) ForEach(c context.Context, cfg *Config, cb func(context.Context, *Env) error) error {
return iterDir(c, cfg.BaseDir, func(fileInfos []os.FileInfo) error {
if it.Shuffle {
for i := range fileInfos {
j := mathrand.Intn(c, i+1)
fileInfos[i], fileInfos[j] = fileInfos[j], fileInfos[i]
}
}
for _, fi := range fileInfos {
// Ignore hidden files.
if !fi.IsDir() || strings.HasPrefix(fi.Name(), ".") {
continue
}
e := cfg.envForName(fi.Name(), nil)
if it.OnlyComplete {
if err := e.AssertCompleteAndLoad(); err != nil {
logging.WithError(err).Debugf(c, "Skipping VirtualEnv %s; not complete.", fi.Name())
continue
}
}
if err := cb(c, e); err != nil {
return err
}
}
return nil
})
} | go | func (it *Iterator) ForEach(c context.Context, cfg *Config, cb func(context.Context, *Env) error) error {
return iterDir(c, cfg.BaseDir, func(fileInfos []os.FileInfo) error {
if it.Shuffle {
for i := range fileInfos {
j := mathrand.Intn(c, i+1)
fileInfos[i], fileInfos[j] = fileInfos[j], fileInfos[i]
}
}
for _, fi := range fileInfos {
// Ignore hidden files.
if !fi.IsDir() || strings.HasPrefix(fi.Name(), ".") {
continue
}
e := cfg.envForName(fi.Name(), nil)
if it.OnlyComplete {
if err := e.AssertCompleteAndLoad(); err != nil {
logging.WithError(err).Debugf(c, "Skipping VirtualEnv %s; not complete.", fi.Name())
continue
}
}
if err := cb(c, e); err != nil {
return err
}
}
return nil
})
} | [
"func",
"(",
"it",
"*",
"Iterator",
")",
"ForEach",
"(",
"c",
"context",
".",
"Context",
",",
"cfg",
"*",
"Config",
",",
"cb",
"func",
"(",
"context",
".",
"Context",
",",
"*",
"Env",
")",
"error",
")",
"error",
"{",
"return",
"iterDir",
"(",
"c",
",",
"cfg",
".",
"BaseDir",
",",
"func",
"(",
"fileInfos",
"[",
"]",
"os",
".",
"FileInfo",
")",
"error",
"{",
"if",
"it",
".",
"Shuffle",
"{",
"for",
"i",
":=",
"range",
"fileInfos",
"{",
"j",
":=",
"mathrand",
".",
"Intn",
"(",
"c",
",",
"i",
"+",
"1",
")",
"\n",
"fileInfos",
"[",
"i",
"]",
",",
"fileInfos",
"[",
"j",
"]",
"=",
"fileInfos",
"[",
"j",
"]",
",",
"fileInfos",
"[",
"i",
"]",
"\n",
"}",
"\n",
"}",
"\n\n",
"for",
"_",
",",
"fi",
":=",
"range",
"fileInfos",
"{",
"// Ignore hidden files.",
"if",
"!",
"fi",
".",
"IsDir",
"(",
")",
"||",
"strings",
".",
"HasPrefix",
"(",
"fi",
".",
"Name",
"(",
")",
",",
"\"",
"\"",
")",
"{",
"continue",
"\n",
"}",
"\n\n",
"e",
":=",
"cfg",
".",
"envForName",
"(",
"fi",
".",
"Name",
"(",
")",
",",
"nil",
")",
"\n",
"if",
"it",
".",
"OnlyComplete",
"{",
"if",
"err",
":=",
"e",
".",
"AssertCompleteAndLoad",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"logging",
".",
"WithError",
"(",
"err",
")",
".",
"Debugf",
"(",
"c",
",",
"\"",
"\"",
",",
"fi",
".",
"Name",
"(",
")",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"cb",
"(",
"c",
",",
"e",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}",
")",
"\n",
"}"
] | // ForEach iterates over all VirtualEnv installations for the supplied "cfg".
//
// "cb" will be invoked for each VirtualEnv, regardless of its completion
// status. The callback may perform additional operations on the VirtualEnv to
// determine its actual status. If the callback returns an error, iteration will
// stop and the error will be forwarded.
//
// If the supplied Context is cancelled, iteration will stop prematurely and
// return the Context's error. | [
"ForEach",
"iterates",
"over",
"all",
"VirtualEnv",
"installations",
"for",
"the",
"supplied",
"cfg",
".",
"cb",
"will",
"be",
"invoked",
"for",
"each",
"VirtualEnv",
"regardless",
"of",
"its",
"completion",
"status",
".",
"The",
"callback",
"may",
"perform",
"additional",
"operations",
"on",
"the",
"VirtualEnv",
"to",
"determine",
"its",
"actual",
"status",
".",
"If",
"the",
"callback",
"returns",
"an",
"error",
"iteration",
"will",
"stop",
"and",
"the",
"error",
"will",
"be",
"forwarded",
".",
"If",
"the",
"supplied",
"Context",
"is",
"cancelled",
"iteration",
"will",
"stop",
"prematurely",
"and",
"return",
"the",
"Context",
"s",
"error",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/venv/iterator.go#L51-L81 |
7,668 | luci/luci-go | dm/appengine/distributor/handlers.go | InstallHandlers | func InstallHandlers(r *router.Router, base router.MiddlewareChain) {
r.POST(handlerPattern, base.Extend(gaemiddleware.RequireTaskQueue("")), TaskQueueHandler)
r.POST("/_ah/push-handlers/"+notifyTopicSuffix, base, PubsubReceiver)
} | go | func InstallHandlers(r *router.Router, base router.MiddlewareChain) {
r.POST(handlerPattern, base.Extend(gaemiddleware.RequireTaskQueue("")), TaskQueueHandler)
r.POST("/_ah/push-handlers/"+notifyTopicSuffix, base, PubsubReceiver)
} | [
"func",
"InstallHandlers",
"(",
"r",
"*",
"router",
".",
"Router",
",",
"base",
"router",
".",
"MiddlewareChain",
")",
"{",
"r",
".",
"POST",
"(",
"handlerPattern",
",",
"base",
".",
"Extend",
"(",
"gaemiddleware",
".",
"RequireTaskQueue",
"(",
"\"",
"\"",
")",
")",
",",
"TaskQueueHandler",
")",
"\n",
"r",
".",
"POST",
"(",
"\"",
"\"",
"+",
"notifyTopicSuffix",
",",
"base",
",",
"PubsubReceiver",
")",
"\n",
"}"
] | // InstallHandlers installs the taskqueue callback handler.
//
// The `base` middleware must have a registry installed with WithRegistry. | [
"InstallHandlers",
"installs",
"the",
"taskqueue",
"callback",
"handler",
".",
"The",
"base",
"middleware",
"must",
"have",
"a",
"registry",
"installed",
"with",
"WithRegistry",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/distributor/handlers.go#L25-L28 |
7,669 | luci/luci-go | vpython/python/interpreter.go | GetVersion | func (i *Interpreter) GetVersion(c context.Context) (v Version, err error) {
i.cachedVersionMu.Lock()
defer i.cachedVersionMu.Unlock()
// Check again, under write-lock.
if i.cachedVersion != nil {
v = *i.cachedVersion
return
}
cmd := i.IsolatedCommand(c, CommandTarget{
"import platform, sys; sys.stdout.write(platform.python_version())",
})
out, err := cmd.Output()
if err != nil {
err = errors.Annotate(err, "").Err()
return
}
if v, err = ParseVersion(string(out)); err != nil {
return
}
if v.IsZero() {
err = errors.Reason("unknown version output").Err()
return
}
i.cachedVersion = &v
return
} | go | func (i *Interpreter) GetVersion(c context.Context) (v Version, err error) {
i.cachedVersionMu.Lock()
defer i.cachedVersionMu.Unlock()
// Check again, under write-lock.
if i.cachedVersion != nil {
v = *i.cachedVersion
return
}
cmd := i.IsolatedCommand(c, CommandTarget{
"import platform, sys; sys.stdout.write(platform.python_version())",
})
out, err := cmd.Output()
if err != nil {
err = errors.Annotate(err, "").Err()
return
}
if v, err = ParseVersion(string(out)); err != nil {
return
}
if v.IsZero() {
err = errors.Reason("unknown version output").Err()
return
}
i.cachedVersion = &v
return
} | [
"func",
"(",
"i",
"*",
"Interpreter",
")",
"GetVersion",
"(",
"c",
"context",
".",
"Context",
")",
"(",
"v",
"Version",
",",
"err",
"error",
")",
"{",
"i",
".",
"cachedVersionMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"i",
".",
"cachedVersionMu",
".",
"Unlock",
"(",
")",
"\n\n",
"// Check again, under write-lock.",
"if",
"i",
".",
"cachedVersion",
"!=",
"nil",
"{",
"v",
"=",
"*",
"i",
".",
"cachedVersion",
"\n",
"return",
"\n",
"}",
"\n\n",
"cmd",
":=",
"i",
".",
"IsolatedCommand",
"(",
"c",
",",
"CommandTarget",
"{",
"\"",
"\"",
",",
"}",
")",
"\n\n",
"out",
",",
"err",
":=",
"cmd",
".",
"Output",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"err",
"=",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"if",
"v",
",",
"err",
"=",
"ParseVersion",
"(",
"string",
"(",
"out",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"v",
".",
"IsZero",
"(",
")",
"{",
"err",
"=",
"errors",
".",
"Reason",
"(",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"i",
".",
"cachedVersion",
"=",
"&",
"v",
"\n",
"return",
"\n",
"}"
] | // GetVersion runs the specified Python interpreter to extract its version
// from `platform.python_version` and maps it to a known specification verison. | [
"GetVersion",
"runs",
"the",
"specified",
"Python",
"interpreter",
"to",
"extract",
"its",
"version",
"from",
"platform",
".",
"python_version",
"and",
"maps",
"it",
"to",
"a",
"known",
"specification",
"verison",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/python/interpreter.go#L73-L103 |
7,670 | luci/luci-go | vpython/python/interpreter.go | IsolateEnvironment | func IsolateEnvironment(e *environ.Env, keepPythonPath bool) {
if e == nil {
return
}
// Remove PYTHONPATH if instructed.
if !keepPythonPath {
e.Remove("PYTHONPATH")
}
// Remove PYTHONHOME from the environment. PYTHONHOME is used to set the
// location of standard Python libraries, which we make a point of overriding.
//
// https://docs.python.org/2/using/cmdline.html#envvar-PYTHONHOME
e.Remove("PYTHONHOME")
// set PYTHONNOUSERSITE, which prevents a user's "site" configuration
// from influencing Python startup. The system "site" should already be
// ignored b/c we're using the VirtualEnv Python interpreter.
e.Set("PYTHONNOUSERSITE", "1")
} | go | func IsolateEnvironment(e *environ.Env, keepPythonPath bool) {
if e == nil {
return
}
// Remove PYTHONPATH if instructed.
if !keepPythonPath {
e.Remove("PYTHONPATH")
}
// Remove PYTHONHOME from the environment. PYTHONHOME is used to set the
// location of standard Python libraries, which we make a point of overriding.
//
// https://docs.python.org/2/using/cmdline.html#envvar-PYTHONHOME
e.Remove("PYTHONHOME")
// set PYTHONNOUSERSITE, which prevents a user's "site" configuration
// from influencing Python startup. The system "site" should already be
// ignored b/c we're using the VirtualEnv Python interpreter.
e.Set("PYTHONNOUSERSITE", "1")
} | [
"func",
"IsolateEnvironment",
"(",
"e",
"*",
"environ",
".",
"Env",
",",
"keepPythonPath",
"bool",
")",
"{",
"if",
"e",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n\n",
"// Remove PYTHONPATH if instructed.",
"if",
"!",
"keepPythonPath",
"{",
"e",
".",
"Remove",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n\n",
"// Remove PYTHONHOME from the environment. PYTHONHOME is used to set the",
"// location of standard Python libraries, which we make a point of overriding.",
"//",
"// https://docs.python.org/2/using/cmdline.html#envvar-PYTHONHOME",
"e",
".",
"Remove",
"(",
"\"",
"\"",
")",
"\n\n",
"// set PYTHONNOUSERSITE, which prevents a user's \"site\" configuration",
"// from influencing Python startup. The system \"site\" should already be",
"// ignored b/c we're using the VirtualEnv Python interpreter.",
"e",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // IsolateEnvironment mutates e to remove any environmental influence over
// the Python interpreter.
//
// If keepPythonPath is true, PYTHONPATH will not be cleared. This is used
// by the actual VirtualEnv Python invocation to preserve PYTHONPATH since it is
// a form of user input.
//
// If e is nil, no operation will be performed. | [
"IsolateEnvironment",
"mutates",
"e",
"to",
"remove",
"any",
"environmental",
"influence",
"over",
"the",
"Python",
"interpreter",
".",
"If",
"keepPythonPath",
"is",
"true",
"PYTHONPATH",
"will",
"not",
"be",
"cleared",
".",
"This",
"is",
"used",
"by",
"the",
"actual",
"VirtualEnv",
"Python",
"invocation",
"to",
"preserve",
"PYTHONPATH",
"since",
"it",
"is",
"a",
"form",
"of",
"user",
"input",
".",
"If",
"e",
"is",
"nil",
"no",
"operation",
"will",
"be",
"performed",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/vpython/python/interpreter.go#L113-L133 |
7,671 | luci/luci-go | dm/appengine/model/fwddep.go | Edge | func (f *FwdDep) Edge() *FwdEdge {
ret := &FwdEdge{To: &f.Dependee, From: &dm.Attempt_ID{}}
if err := ret.From.SetDMEncoded(f.Depender.StringID()); err != nil {
panic(err)
}
return ret
} | go | func (f *FwdDep) Edge() *FwdEdge {
ret := &FwdEdge{To: &f.Dependee, From: &dm.Attempt_ID{}}
if err := ret.From.SetDMEncoded(f.Depender.StringID()); err != nil {
panic(err)
}
return ret
} | [
"func",
"(",
"f",
"*",
"FwdDep",
")",
"Edge",
"(",
")",
"*",
"FwdEdge",
"{",
"ret",
":=",
"&",
"FwdEdge",
"{",
"To",
":",
"&",
"f",
".",
"Dependee",
",",
"From",
":",
"&",
"dm",
".",
"Attempt_ID",
"{",
"}",
"}",
"\n",
"if",
"err",
":=",
"ret",
".",
"From",
".",
"SetDMEncoded",
"(",
"f",
".",
"Depender",
".",
"StringID",
"(",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"ret",
"\n",
"}"
] | // Edge produces a edge object which points 'forwards' from the depending
// attempt to the depended-on attempt. | [
"Edge",
"produces",
"a",
"edge",
"object",
"which",
"points",
"forwards",
"from",
"the",
"depending",
"attempt",
"to",
"the",
"depended",
"-",
"on",
"attempt",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/dm/appengine/model/fwddep.go#L57-L63 |
7,672 | luci/luci-go | common/gcloud/pubsub/resource.go | resourceProjectName | func resourceProjectName(v string) (p, n string, err error) {
parts := splitResource(v)
if len(parts) != 4 {
err = errors.New("malformed resource")
return
}
p, n = parts[1], parts[3]
return
} | go | func resourceProjectName(v string) (p, n string, err error) {
parts := splitResource(v)
if len(parts) != 4 {
err = errors.New("malformed resource")
return
}
p, n = parts[1], parts[3]
return
} | [
"func",
"resourceProjectName",
"(",
"v",
"string",
")",
"(",
"p",
",",
"n",
"string",
",",
"err",
"error",
")",
"{",
"parts",
":=",
"splitResource",
"(",
"v",
")",
"\n",
"if",
"len",
"(",
"parts",
")",
"!=",
"4",
"{",
"err",
"=",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"p",
",",
"n",
"=",
"parts",
"[",
"1",
"]",
",",
"parts",
"[",
"3",
"]",
"\n",
"return",
"\n",
"}"
] | // resourceProjectName returns the resource's project and name components. | [
"resourceProjectName",
"returns",
"the",
"resource",
"s",
"project",
"and",
"name",
"components",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/gcloud/pubsub/resource.go#L33-L41 |
7,673 | luci/luci-go | common/system/exitcode/exitcode.go | Get | func Get(err error) (int, bool) {
err = errors.Unwrap(err)
if err == nil {
return 0, true
}
if ee, ok := err.(*exec.ExitError); ok {
return ee.Sys().(syscall.WaitStatus).ExitStatus(), true
}
return 0, false
} | go | func Get(err error) (int, bool) {
err = errors.Unwrap(err)
if err == nil {
return 0, true
}
if ee, ok := err.(*exec.ExitError); ok {
return ee.Sys().(syscall.WaitStatus).ExitStatus(), true
}
return 0, false
} | [
"func",
"Get",
"(",
"err",
"error",
")",
"(",
"int",
",",
"bool",
")",
"{",
"err",
"=",
"errors",
".",
"Unwrap",
"(",
"err",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"0",
",",
"true",
"\n",
"}",
"\n\n",
"if",
"ee",
",",
"ok",
":=",
"err",
".",
"(",
"*",
"exec",
".",
"ExitError",
")",
";",
"ok",
"{",
"return",
"ee",
".",
"Sys",
"(",
")",
".",
"(",
"syscall",
".",
"WaitStatus",
")",
".",
"ExitStatus",
"(",
")",
",",
"true",
"\n",
"}",
"\n",
"return",
"0",
",",
"false",
"\n",
"}"
] | // Get returns the process process exit return code given an error returned by
// exec.Cmd's Wait or Run methods. If no exit code is present, Get will return
// false. | [
"Get",
"returns",
"the",
"process",
"process",
"exit",
"return",
"code",
"given",
"an",
"error",
"returned",
"by",
"exec",
".",
"Cmd",
"s",
"Wait",
"or",
"Run",
"methods",
".",
"If",
"no",
"exit",
"code",
"is",
"present",
"Get",
"will",
"return",
"false",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/system/exitcode/exitcode.go#L29-L39 |
7,674 | luci/luci-go | cipd/client/cipd/template/template.go | ParsePlatform | func ParsePlatform(v string) (Platform, error) {
parts := strings.Split(v, "-")
if len(parts) != 2 {
return Platform{}, errors.Reason("platform must be <os>-<arch>: %q", v).Err()
}
return Platform{parts[0], parts[1]}, nil
} | go | func ParsePlatform(v string) (Platform, error) {
parts := strings.Split(v, "-")
if len(parts) != 2 {
return Platform{}, errors.Reason("platform must be <os>-<arch>: %q", v).Err()
}
return Platform{parts[0], parts[1]}, nil
} | [
"func",
"ParsePlatform",
"(",
"v",
"string",
")",
"(",
"Platform",
",",
"error",
")",
"{",
"parts",
":=",
"strings",
".",
"Split",
"(",
"v",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"parts",
")",
"!=",
"2",
"{",
"return",
"Platform",
"{",
"}",
",",
"errors",
".",
"Reason",
"(",
"\"",
"\"",
",",
"v",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n",
"return",
"Platform",
"{",
"parts",
"[",
"0",
"]",
",",
"parts",
"[",
"1",
"]",
"}",
",",
"nil",
"\n",
"}"
] | // ParsePlatform parses a Platform from its string representation. | [
"ParsePlatform",
"parses",
"a",
"Platform",
"from",
"its",
"string",
"representation",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/template/template.go#L133-L139 |
7,675 | luci/luci-go | cipd/client/cipd/template/template.go | Expander | func (tp Platform) Expander() Expander {
return Expander{
"os": tp.OS,
"arch": tp.Arch,
"platform": tp.String(),
}
} | go | func (tp Platform) Expander() Expander {
return Expander{
"os": tp.OS,
"arch": tp.Arch,
"platform": tp.String(),
}
} | [
"func",
"(",
"tp",
"Platform",
")",
"Expander",
"(",
")",
"Expander",
"{",
"return",
"Expander",
"{",
"\"",
"\"",
":",
"tp",
".",
"OS",
",",
"\"",
"\"",
":",
"tp",
".",
"Arch",
",",
"\"",
"\"",
":",
"tp",
".",
"String",
"(",
")",
",",
"}",
"\n",
"}"
] | // Expander returns an Expander populated with tp's fields. | [
"Expander",
"returns",
"an",
"Expander",
"populated",
"with",
"tp",
"s",
"fields",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/cipd/client/cipd/template/template.go#L146-L152 |
7,676 | luci/luci-go | common/system/prober/probe.go | ResolveSelf | func (p *Probe) ResolveSelf(argv0 string) error {
if p.Self != "" {
return nil
}
// Get the authoritative executable from the system.
exec, err := os.Executable()
if err != nil {
return errors.Annotate(err, "failed to get executable").Err()
}
execStat, err := os.Stat(exec)
if err != nil {
return errors.Annotate(err, "failed to stat executable: %s", exec).Err()
}
// Before using "os.Executable" result, which is known to resolve symlinks on
// Linux, try and identify via argv0.
if argv0 != "" && filesystem.AbsPath(&argv0) == nil {
if st, err := os.Stat(argv0); err == nil && os.SameFile(execStat, st) {
// argv[0] is the same file as our executable, but may be an unresolved
// symlink. Prefer it.
p.Self, p.SelfStat = argv0, st
return nil
}
}
p.Self, p.SelfStat = exec, execStat
return nil
} | go | func (p *Probe) ResolveSelf(argv0 string) error {
if p.Self != "" {
return nil
}
// Get the authoritative executable from the system.
exec, err := os.Executable()
if err != nil {
return errors.Annotate(err, "failed to get executable").Err()
}
execStat, err := os.Stat(exec)
if err != nil {
return errors.Annotate(err, "failed to stat executable: %s", exec).Err()
}
// Before using "os.Executable" result, which is known to resolve symlinks on
// Linux, try and identify via argv0.
if argv0 != "" && filesystem.AbsPath(&argv0) == nil {
if st, err := os.Stat(argv0); err == nil && os.SameFile(execStat, st) {
// argv[0] is the same file as our executable, but may be an unresolved
// symlink. Prefer it.
p.Self, p.SelfStat = argv0, st
return nil
}
}
p.Self, p.SelfStat = exec, execStat
return nil
} | [
"func",
"(",
"p",
"*",
"Probe",
")",
"ResolveSelf",
"(",
"argv0",
"string",
")",
"error",
"{",
"if",
"p",
".",
"Self",
"!=",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n\n",
"// Get the authoritative executable from the system.",
"exec",
",",
"err",
":=",
"os",
".",
"Executable",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n\n",
"execStat",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"exec",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"errors",
".",
"Annotate",
"(",
"err",
",",
"\"",
"\"",
",",
"exec",
")",
".",
"Err",
"(",
")",
"\n",
"}",
"\n\n",
"// Before using \"os.Executable\" result, which is known to resolve symlinks on",
"// Linux, try and identify via argv0.",
"if",
"argv0",
"!=",
"\"",
"\"",
"&&",
"filesystem",
".",
"AbsPath",
"(",
"&",
"argv0",
")",
"==",
"nil",
"{",
"if",
"st",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"argv0",
")",
";",
"err",
"==",
"nil",
"&&",
"os",
".",
"SameFile",
"(",
"execStat",
",",
"st",
")",
"{",
"// argv[0] is the same file as our executable, but may be an unresolved",
"// symlink. Prefer it.",
"p",
".",
"Self",
",",
"p",
".",
"SelfStat",
"=",
"argv0",
",",
"st",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"p",
".",
"Self",
",",
"p",
".",
"SelfStat",
"=",
"exec",
",",
"execStat",
"\n",
"return",
"nil",
"\n",
"}"
] | // ResolveSelf attempts to identify the current process. If successful, p's
// Self will be set to an absolute path reference to Self, and its SelfStat
// field will be set to the os.FileInfo for that path.
//
// If this process was invoked via symlink, the path to the symlink will be
// returned if possible. | [
"ResolveSelf",
"attempts",
"to",
"identify",
"the",
"current",
"process",
".",
"If",
"successful",
"p",
"s",
"Self",
"will",
"be",
"set",
"to",
"an",
"absolute",
"path",
"reference",
"to",
"Self",
"and",
"its",
"SelfStat",
"field",
"will",
"be",
"set",
"to",
"the",
"os",
".",
"FileInfo",
"for",
"that",
"path",
".",
"If",
"this",
"process",
"was",
"invoked",
"via",
"symlink",
"the",
"path",
"to",
"the",
"symlink",
"will",
"be",
"returned",
"if",
"possible",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/system/prober/probe.go#L89-L118 |
7,677 | luci/luci-go | common/system/prober/probe.go | Locate | func (p *Probe) Locate(c context.Context, cached string, env environ.Env) (string, error) {
// If we have a cached path, check that it exists and is executable and use it
// if it is.
if cached != "" {
switch cachedStat, err := os.Stat(cached); {
case err == nil:
// Use the cached path. First, pass it through a sanity check to ensure
// that it is not self.
if p.SelfStat == nil || !os.SameFile(p.SelfStat, cachedStat) {
logging.Debugf(c, "Using cached value: %s", cached)
return cached, nil
}
logging.Debugf(c, "Cached value [%s] is this wrapper [%s]; ignoring.", cached, p.Self)
case os.IsNotExist(err):
// Our cached path doesn't exist, so we will have to look for a new one.
case err != nil:
// We couldn't check our cached path, so we will have to look for a new
// one. This is an unexpected error, though, so emit it.
logging.Debugf(c, "Failed to stat cached [%s]: %s", cached, err)
}
}
// Get stats on our parent directory. This may fail; if so, we'll skip the
// SameFile check.
var selfDir string
var selfDirStat os.FileInfo
if p.Self != "" {
selfDir = filepath.Dir(p.Self)
var err error
if selfDirStat, err = os.Stat(selfDir); err != nil {
logging.Debugf(c, "Failed to stat self directory [%s]: %s", selfDir, err)
}
}
// Walk through PATH. Our goal is to find the first program named Target that
// isn't self and doesn't identify as a wrapper.
pathDirs := p.PathDirs
if pathDirs == nil {
pathDirs = strings.Split(env.GetEmpty("PATH"), string(os.PathListSeparator))
}
// Build our list of directories to check for Target.
checkDirs := make([]string, 0, len(pathDirs)+len(p.RelativePathOverride))
if selfDir != "" {
for _, rpo := range p.RelativePathOverride {
checkDirs = append(checkDirs, filepath.Join(selfDir, filepath.FromSlash(rpo)))
}
}
checkDirs = append(checkDirs, pathDirs...)
// Iterate through each check directory and look for a Target candidate within
// it.
checked := make(map[string]struct{}, len(checkDirs))
for _, dir := range checkDirs {
if _, ok := checked[dir]; ok {
continue
}
checked[dir] = struct{}{}
path := p.checkDir(c, dir, selfDirStat, env)
if path != "" {
return path, nil
}
}
return "", errors.Reason("could not find target in system").
InternalReason("target(%s)/dirs(%v)", p.Target, pathDirs).Err()
} | go | func (p *Probe) Locate(c context.Context, cached string, env environ.Env) (string, error) {
// If we have a cached path, check that it exists and is executable and use it
// if it is.
if cached != "" {
switch cachedStat, err := os.Stat(cached); {
case err == nil:
// Use the cached path. First, pass it through a sanity check to ensure
// that it is not self.
if p.SelfStat == nil || !os.SameFile(p.SelfStat, cachedStat) {
logging.Debugf(c, "Using cached value: %s", cached)
return cached, nil
}
logging.Debugf(c, "Cached value [%s] is this wrapper [%s]; ignoring.", cached, p.Self)
case os.IsNotExist(err):
// Our cached path doesn't exist, so we will have to look for a new one.
case err != nil:
// We couldn't check our cached path, so we will have to look for a new
// one. This is an unexpected error, though, so emit it.
logging.Debugf(c, "Failed to stat cached [%s]: %s", cached, err)
}
}
// Get stats on our parent directory. This may fail; if so, we'll skip the
// SameFile check.
var selfDir string
var selfDirStat os.FileInfo
if p.Self != "" {
selfDir = filepath.Dir(p.Self)
var err error
if selfDirStat, err = os.Stat(selfDir); err != nil {
logging.Debugf(c, "Failed to stat self directory [%s]: %s", selfDir, err)
}
}
// Walk through PATH. Our goal is to find the first program named Target that
// isn't self and doesn't identify as a wrapper.
pathDirs := p.PathDirs
if pathDirs == nil {
pathDirs = strings.Split(env.GetEmpty("PATH"), string(os.PathListSeparator))
}
// Build our list of directories to check for Target.
checkDirs := make([]string, 0, len(pathDirs)+len(p.RelativePathOverride))
if selfDir != "" {
for _, rpo := range p.RelativePathOverride {
checkDirs = append(checkDirs, filepath.Join(selfDir, filepath.FromSlash(rpo)))
}
}
checkDirs = append(checkDirs, pathDirs...)
// Iterate through each check directory and look for a Target candidate within
// it.
checked := make(map[string]struct{}, len(checkDirs))
for _, dir := range checkDirs {
if _, ok := checked[dir]; ok {
continue
}
checked[dir] = struct{}{}
path := p.checkDir(c, dir, selfDirStat, env)
if path != "" {
return path, nil
}
}
return "", errors.Reason("could not find target in system").
InternalReason("target(%s)/dirs(%v)", p.Target, pathDirs).Err()
} | [
"func",
"(",
"p",
"*",
"Probe",
")",
"Locate",
"(",
"c",
"context",
".",
"Context",
",",
"cached",
"string",
",",
"env",
"environ",
".",
"Env",
")",
"(",
"string",
",",
"error",
")",
"{",
"// If we have a cached path, check that it exists and is executable and use it",
"// if it is.",
"if",
"cached",
"!=",
"\"",
"\"",
"{",
"switch",
"cachedStat",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"cached",
")",
";",
"{",
"case",
"err",
"==",
"nil",
":",
"// Use the cached path. First, pass it through a sanity check to ensure",
"// that it is not self.",
"if",
"p",
".",
"SelfStat",
"==",
"nil",
"||",
"!",
"os",
".",
"SameFile",
"(",
"p",
".",
"SelfStat",
",",
"cachedStat",
")",
"{",
"logging",
".",
"Debugf",
"(",
"c",
",",
"\"",
"\"",
",",
"cached",
")",
"\n",
"return",
"cached",
",",
"nil",
"\n",
"}",
"\n",
"logging",
".",
"Debugf",
"(",
"c",
",",
"\"",
"\"",
",",
"cached",
",",
"p",
".",
"Self",
")",
"\n\n",
"case",
"os",
".",
"IsNotExist",
"(",
"err",
")",
":",
"// Our cached path doesn't exist, so we will have to look for a new one.",
"case",
"err",
"!=",
"nil",
":",
"// We couldn't check our cached path, so we will have to look for a new",
"// one. This is an unexpected error, though, so emit it.",
"logging",
".",
"Debugf",
"(",
"c",
",",
"\"",
"\"",
",",
"cached",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Get stats on our parent directory. This may fail; if so, we'll skip the",
"// SameFile check.",
"var",
"selfDir",
"string",
"\n",
"var",
"selfDirStat",
"os",
".",
"FileInfo",
"\n",
"if",
"p",
".",
"Self",
"!=",
"\"",
"\"",
"{",
"selfDir",
"=",
"filepath",
".",
"Dir",
"(",
"p",
".",
"Self",
")",
"\n\n",
"var",
"err",
"error",
"\n",
"if",
"selfDirStat",
",",
"err",
"=",
"os",
".",
"Stat",
"(",
"selfDir",
")",
";",
"err",
"!=",
"nil",
"{",
"logging",
".",
"Debugf",
"(",
"c",
",",
"\"",
"\"",
",",
"selfDir",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"// Walk through PATH. Our goal is to find the first program named Target that",
"// isn't self and doesn't identify as a wrapper.",
"pathDirs",
":=",
"p",
".",
"PathDirs",
"\n",
"if",
"pathDirs",
"==",
"nil",
"{",
"pathDirs",
"=",
"strings",
".",
"Split",
"(",
"env",
".",
"GetEmpty",
"(",
"\"",
"\"",
")",
",",
"string",
"(",
"os",
".",
"PathListSeparator",
")",
")",
"\n",
"}",
"\n\n",
"// Build our list of directories to check for Target.",
"checkDirs",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"pathDirs",
")",
"+",
"len",
"(",
"p",
".",
"RelativePathOverride",
")",
")",
"\n",
"if",
"selfDir",
"!=",
"\"",
"\"",
"{",
"for",
"_",
",",
"rpo",
":=",
"range",
"p",
".",
"RelativePathOverride",
"{",
"checkDirs",
"=",
"append",
"(",
"checkDirs",
",",
"filepath",
".",
"Join",
"(",
"selfDir",
",",
"filepath",
".",
"FromSlash",
"(",
"rpo",
")",
")",
")",
"\n",
"}",
"\n",
"}",
"\n",
"checkDirs",
"=",
"append",
"(",
"checkDirs",
",",
"pathDirs",
"...",
")",
"\n\n",
"// Iterate through each check directory and look for a Target candidate within",
"// it.",
"checked",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
",",
"len",
"(",
"checkDirs",
")",
")",
"\n",
"for",
"_",
",",
"dir",
":=",
"range",
"checkDirs",
"{",
"if",
"_",
",",
"ok",
":=",
"checked",
"[",
"dir",
"]",
";",
"ok",
"{",
"continue",
"\n",
"}",
"\n",
"checked",
"[",
"dir",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n\n",
"path",
":=",
"p",
".",
"checkDir",
"(",
"c",
",",
"dir",
",",
"selfDirStat",
",",
"env",
")",
"\n",
"if",
"path",
"!=",
"\"",
"\"",
"{",
"return",
"path",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"\"",
"\"",
",",
"errors",
".",
"Reason",
"(",
"\"",
"\"",
")",
".",
"InternalReason",
"(",
"\"",
"\"",
",",
"p",
".",
"Target",
",",
"pathDirs",
")",
".",
"Err",
"(",
")",
"\n",
"}"
] | // Locate attempts to locate the system's Target by traversing the available
// PATH.
//
// cached is the cached path, passed from wrapper to wrapper through the a
// State struct in the environment. This may be empty, if there was no cached
// path or if the cached path was invalid.
//
// env is the environment to operate with, and will not be modified during
// execution. | [
"Locate",
"attempts",
"to",
"locate",
"the",
"system",
"s",
"Target",
"by",
"traversing",
"the",
"available",
"PATH",
".",
"cached",
"is",
"the",
"cached",
"path",
"passed",
"from",
"wrapper",
"to",
"wrapper",
"through",
"the",
"a",
"State",
"struct",
"in",
"the",
"environment",
".",
"This",
"may",
"be",
"empty",
"if",
"there",
"was",
"no",
"cached",
"path",
"or",
"if",
"the",
"cached",
"path",
"was",
"invalid",
".",
"env",
"is",
"the",
"environment",
"to",
"operate",
"with",
"and",
"will",
"not",
"be",
"modified",
"during",
"execution",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/system/prober/probe.go#L129-L199 |
7,678 | luci/luci-go | common/system/prober/probe.go | checkDir | func (p *Probe) checkDir(c context.Context, dir string, selfDir os.FileInfo, env environ.Env) string {
// If we have a self directory defined, ensure that "dir" isn't the same
// directory. If it is, we will ignore this option, since we are looking for
// something outside of the wrapper directory.
if selfDir != nil {
switch checkDirStat, err := os.Stat(dir); {
case err == nil:
// "dir" exists; if it is the same as "selfDir", we can ignore it.
if os.SameFile(selfDir, checkDirStat) {
logging.Debugf(c, "Candidate shares wrapper directory [%s]; skipping...", dir)
return ""
}
case os.IsNotExist(err):
logging.Debugf(c, "Candidate directory does not exist [%s]; skipping...", dir)
return ""
default:
logging.Debugf(c, "Failed to stat candidate directory [%s]: %s", dir, err)
return ""
}
}
t, err := findInDir(p.Target, dir, env)
if err != nil {
return ""
}
// Make sure this file isn't the same as "self", if available.
if p.SelfStat != nil {
switch st, err := os.Stat(t); {
case err == nil:
if os.SameFile(p.SelfStat, st) {
logging.Debugf(c, "Candidate [%s] is same file as wrapper; skipping...", t)
return ""
}
case os.IsNotExist(err):
// "t" no longer exists, so we can't use it.
return ""
default:
logging.Debugf(c, "Failed to stat candidate path [%s]: %s", t, err)
return ""
}
}
if err := filesystem.AbsPath(&t); err != nil {
logging.Debugf(c, "Failed to normalize candidate path [%s]: %s", t, err)
return ""
}
// Try running the candidate command and confirm that it is not a wrapper.
if p.CheckWrapper != nil {
switch isWrapper, err := p.CheckWrapper(c, t, env); {
case err != nil:
logging.Debugf(c, "Failed to check if [%s] is a wrapper: %s", t, err)
return ""
case isWrapper:
logging.Debugf(c, "Candidate is a wrapper: %s", t)
return ""
}
}
return t
} | go | func (p *Probe) checkDir(c context.Context, dir string, selfDir os.FileInfo, env environ.Env) string {
// If we have a self directory defined, ensure that "dir" isn't the same
// directory. If it is, we will ignore this option, since we are looking for
// something outside of the wrapper directory.
if selfDir != nil {
switch checkDirStat, err := os.Stat(dir); {
case err == nil:
// "dir" exists; if it is the same as "selfDir", we can ignore it.
if os.SameFile(selfDir, checkDirStat) {
logging.Debugf(c, "Candidate shares wrapper directory [%s]; skipping...", dir)
return ""
}
case os.IsNotExist(err):
logging.Debugf(c, "Candidate directory does not exist [%s]; skipping...", dir)
return ""
default:
logging.Debugf(c, "Failed to stat candidate directory [%s]: %s", dir, err)
return ""
}
}
t, err := findInDir(p.Target, dir, env)
if err != nil {
return ""
}
// Make sure this file isn't the same as "self", if available.
if p.SelfStat != nil {
switch st, err := os.Stat(t); {
case err == nil:
if os.SameFile(p.SelfStat, st) {
logging.Debugf(c, "Candidate [%s] is same file as wrapper; skipping...", t)
return ""
}
case os.IsNotExist(err):
// "t" no longer exists, so we can't use it.
return ""
default:
logging.Debugf(c, "Failed to stat candidate path [%s]: %s", t, err)
return ""
}
}
if err := filesystem.AbsPath(&t); err != nil {
logging.Debugf(c, "Failed to normalize candidate path [%s]: %s", t, err)
return ""
}
// Try running the candidate command and confirm that it is not a wrapper.
if p.CheckWrapper != nil {
switch isWrapper, err := p.CheckWrapper(c, t, env); {
case err != nil:
logging.Debugf(c, "Failed to check if [%s] is a wrapper: %s", t, err)
return ""
case isWrapper:
logging.Debugf(c, "Candidate is a wrapper: %s", t)
return ""
}
}
return t
} | [
"func",
"(",
"p",
"*",
"Probe",
")",
"checkDir",
"(",
"c",
"context",
".",
"Context",
",",
"dir",
"string",
",",
"selfDir",
"os",
".",
"FileInfo",
",",
"env",
"environ",
".",
"Env",
")",
"string",
"{",
"// If we have a self directory defined, ensure that \"dir\" isn't the same",
"// directory. If it is, we will ignore this option, since we are looking for",
"// something outside of the wrapper directory.",
"if",
"selfDir",
"!=",
"nil",
"{",
"switch",
"checkDirStat",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"dir",
")",
";",
"{",
"case",
"err",
"==",
"nil",
":",
"// \"dir\" exists; if it is the same as \"selfDir\", we can ignore it.",
"if",
"os",
".",
"SameFile",
"(",
"selfDir",
",",
"checkDirStat",
")",
"{",
"logging",
".",
"Debugf",
"(",
"c",
",",
"\"",
"\"",
",",
"dir",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"case",
"os",
".",
"IsNotExist",
"(",
"err",
")",
":",
"logging",
".",
"Debugf",
"(",
"c",
",",
"\"",
"\"",
",",
"dir",
")",
"\n",
"return",
"\"",
"\"",
"\n\n",
"default",
":",
"logging",
".",
"Debugf",
"(",
"c",
",",
"\"",
"\"",
",",
"dir",
",",
"err",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"}",
"\n\n",
"t",
",",
"err",
":=",
"findInDir",
"(",
"p",
".",
"Target",
",",
"dir",
",",
"env",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"// Make sure this file isn't the same as \"self\", if available.",
"if",
"p",
".",
"SelfStat",
"!=",
"nil",
"{",
"switch",
"st",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"t",
")",
";",
"{",
"case",
"err",
"==",
"nil",
":",
"if",
"os",
".",
"SameFile",
"(",
"p",
".",
"SelfStat",
",",
"st",
")",
"{",
"logging",
".",
"Debugf",
"(",
"c",
",",
"\"",
"\"",
",",
"t",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"case",
"os",
".",
"IsNotExist",
"(",
"err",
")",
":",
"// \"t\" no longer exists, so we can't use it.",
"return",
"\"",
"\"",
"\n\n",
"default",
":",
"logging",
".",
"Debugf",
"(",
"c",
",",
"\"",
"\"",
",",
"t",
",",
"err",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"filesystem",
".",
"AbsPath",
"(",
"&",
"t",
")",
";",
"err",
"!=",
"nil",
"{",
"logging",
".",
"Debugf",
"(",
"c",
",",
"\"",
"\"",
",",
"t",
",",
"err",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}",
"\n\n",
"// Try running the candidate command and confirm that it is not a wrapper.",
"if",
"p",
".",
"CheckWrapper",
"!=",
"nil",
"{",
"switch",
"isWrapper",
",",
"err",
":=",
"p",
".",
"CheckWrapper",
"(",
"c",
",",
"t",
",",
"env",
")",
";",
"{",
"case",
"err",
"!=",
"nil",
":",
"logging",
".",
"Debugf",
"(",
"c",
",",
"\"",
"\"",
",",
"t",
",",
"err",
")",
"\n",
"return",
"\"",
"\"",
"\n\n",
"case",
"isWrapper",
":",
"logging",
".",
"Debugf",
"(",
"c",
",",
"\"",
"\"",
",",
"t",
")",
"\n",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"t",
"\n",
"}"
] | // checkDir checks "checkDir" for our Target executable. It ignores
// executables whose target is the same file or shares the same parent directory
// as "self". | [
"checkDir",
"checks",
"checkDir",
"for",
"our",
"Target",
"executable",
".",
"It",
"ignores",
"executables",
"whose",
"target",
"is",
"the",
"same",
"file",
"or",
"shares",
"the",
"same",
"parent",
"directory",
"as",
"self",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/system/prober/probe.go#L204-L270 |
7,679 | luci/luci-go | logdog/appengine/coordinator/flex/services.go | Base | func (gsvc *GlobalServices) Base(c *router.Context, next router.Handler) {
services := flexServicesInst{
GlobalServices: gsvc,
}
c.Context = coordinator.WithConfigProvider(c.Context, &services)
c.Context = WithServices(c.Context, &services)
next(c)
} | go | func (gsvc *GlobalServices) Base(c *router.Context, next router.Handler) {
services := flexServicesInst{
GlobalServices: gsvc,
}
c.Context = coordinator.WithConfigProvider(c.Context, &services)
c.Context = WithServices(c.Context, &services)
next(c)
} | [
"func",
"(",
"gsvc",
"*",
"GlobalServices",
")",
"Base",
"(",
"c",
"*",
"router",
".",
"Context",
",",
"next",
"router",
".",
"Handler",
")",
"{",
"services",
":=",
"flexServicesInst",
"{",
"GlobalServices",
":",
"gsvc",
",",
"}",
"\n\n",
"c",
".",
"Context",
"=",
"coordinator",
".",
"WithConfigProvider",
"(",
"c",
".",
"Context",
",",
"&",
"services",
")",
"\n",
"c",
".",
"Context",
"=",
"WithServices",
"(",
"c",
".",
"Context",
",",
"&",
"services",
")",
"\n",
"next",
"(",
"c",
")",
"\n",
"}"
] | // Base is Middleware used by Coordinator Flex services.
//
// It installs a production Services instance into the Context. | [
"Base",
"is",
"Middleware",
"used",
"by",
"Coordinator",
"Flex",
"services",
".",
"It",
"installs",
"a",
"production",
"Services",
"instance",
"into",
"the",
"Context",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/logdog/appengine/coordinator/flex/services.go#L192-L200 |
7,680 | luci/luci-go | config/set.go | RefSet | func RefSet(project string, ref string) Set {
if ref == "" {
return Set("projects/" + project)
}
return Set(strings.Join([]string{"projects", project, ref}, "/"))
} | go | func RefSet(project string, ref string) Set {
if ref == "" {
return Set("projects/" + project)
}
return Set(strings.Join([]string{"projects", project, ref}, "/"))
} | [
"func",
"RefSet",
"(",
"project",
"string",
",",
"ref",
"string",
")",
"Set",
"{",
"if",
"ref",
"==",
"\"",
"\"",
"{",
"return",
"Set",
"(",
"\"",
"\"",
"+",
"project",
")",
"\n",
"}",
"\n",
"return",
"Set",
"(",
"strings",
".",
"Join",
"(",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"project",
",",
"ref",
"}",
",",
"\"",
"\"",
")",
")",
"\n",
"}"
] | // RefSet returns the config set for the specified project and ref. If ref
// is empty, this will equal the ProjectSet value. | [
"RefSet",
"returns",
"the",
"config",
"set",
"for",
"the",
"specified",
"project",
"and",
"ref",
".",
"If",
"ref",
"is",
"empty",
"this",
"will",
"equal",
"the",
"ProjectSet",
"value",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/set.go#L41-L46 |
7,681 | luci/luci-go | config/set.go | Split | func (cs Set) Split() (domain, target, ref string) {
switch p := strings.SplitN(string(cs), "/", 3); len(p) {
case 1:
return p[0], "", ""
case 2:
return p[0], p[1], ""
default:
return p[0], p[1], p[2]
}
} | go | func (cs Set) Split() (domain, target, ref string) {
switch p := strings.SplitN(string(cs), "/", 3); len(p) {
case 1:
return p[0], "", ""
case 2:
return p[0], p[1], ""
default:
return p[0], p[1], p[2]
}
} | [
"func",
"(",
"cs",
"Set",
")",
"Split",
"(",
")",
"(",
"domain",
",",
"target",
",",
"ref",
"string",
")",
"{",
"switch",
"p",
":=",
"strings",
".",
"SplitN",
"(",
"string",
"(",
"cs",
")",
",",
"\"",
"\"",
",",
"3",
")",
";",
"len",
"(",
"p",
")",
"{",
"case",
"1",
":",
"return",
"p",
"[",
"0",
"]",
",",
"\"",
"\"",
",",
"\"",
"\"",
"\n",
"case",
"2",
":",
"return",
"p",
"[",
"0",
"]",
",",
"p",
"[",
"1",
"]",
",",
"\"",
"\"",
"\n",
"default",
":",
"return",
"p",
"[",
"0",
"]",
",",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"2",
"]",
"\n",
"}",
"\n",
"}"
] | // Split splits a Set into its domain, target, and ref components. | [
"Split",
"splits",
"a",
"Set",
"into",
"its",
"domain",
"target",
"and",
"ref",
"components",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/set.go#L49-L58 |
7,682 | luci/luci-go | config/set.go | Service | func (cs Set) Service() string {
domain, target, _ := cs.Split()
if domain == "services" {
return target
}
return ""
} | go | func (cs Set) Service() string {
domain, target, _ := cs.Split()
if domain == "services" {
return target
}
return ""
} | [
"func",
"(",
"cs",
"Set",
")",
"Service",
"(",
")",
"string",
"{",
"domain",
",",
"target",
",",
"_",
":=",
"cs",
".",
"Split",
"(",
")",
"\n",
"if",
"domain",
"==",
"\"",
"\"",
"{",
"return",
"target",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // Service returns a service name for a service-rooted config set or empty
// string for all other sets. | [
"Service",
"returns",
"a",
"service",
"name",
"for",
"a",
"service",
"-",
"rooted",
"config",
"set",
"or",
"empty",
"string",
"for",
"all",
"other",
"sets",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/set.go#L62-L68 |
7,683 | luci/luci-go | config/set.go | Project | func (cs Set) Project() string {
domain, target, _ := cs.Split()
if domain == "projects" {
return target
}
return ""
} | go | func (cs Set) Project() string {
domain, target, _ := cs.Split()
if domain == "projects" {
return target
}
return ""
} | [
"func",
"(",
"cs",
"Set",
")",
"Project",
"(",
")",
"string",
"{",
"domain",
",",
"target",
",",
"_",
":=",
"cs",
".",
"Split",
"(",
")",
"\n",
"if",
"domain",
"==",
"\"",
"\"",
"{",
"return",
"target",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // Project returns a project name for a project-rooted config set or empty
// string for all other sets.
//
// Use ProjectAndRef if you need to get both the project name and the ref. | [
"Project",
"returns",
"a",
"project",
"name",
"for",
"a",
"project",
"-",
"rooted",
"config",
"set",
"or",
"empty",
"string",
"for",
"all",
"other",
"sets",
".",
"Use",
"ProjectAndRef",
"if",
"you",
"need",
"to",
"get",
"both",
"the",
"project",
"name",
"and",
"the",
"ref",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/set.go#L74-L80 |
7,684 | luci/luci-go | config/set.go | Ref | func (cs Set) Ref() string {
domain, _, ref := cs.Split()
if domain == "projects" {
return ref
}
return ""
} | go | func (cs Set) Ref() string {
domain, _, ref := cs.Split()
if domain == "projects" {
return ref
}
return ""
} | [
"func",
"(",
"cs",
"Set",
")",
"Ref",
"(",
")",
"string",
"{",
"domain",
",",
"_",
",",
"ref",
":=",
"cs",
".",
"Split",
"(",
")",
"\n",
"if",
"domain",
"==",
"\"",
"\"",
"{",
"return",
"ref",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] | // Ref returns a ref component of a project-rooted config set or empty string
// for all other sets.
//
// Use ProjectAndRef if you need to get both the project name and the ref. | [
"Ref",
"returns",
"a",
"ref",
"component",
"of",
"a",
"project",
"-",
"rooted",
"config",
"set",
"or",
"empty",
"string",
"for",
"all",
"other",
"sets",
".",
"Use",
"ProjectAndRef",
"if",
"you",
"need",
"to",
"get",
"both",
"the",
"project",
"name",
"and",
"the",
"ref",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/config/set.go#L86-L92 |
7,685 | luci/luci-go | common/data/jsontime/jsontime.go | UnmarshalJSON | func (jt *Time) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
var err error
jt.Time, err = time.Parse(time.RFC3339Nano, s)
return err
} | go | func (jt *Time) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
var err error
jt.Time, err = time.Parse(time.RFC3339Nano, s)
return err
} | [
"func",
"(",
"jt",
"*",
"Time",
")",
"UnmarshalJSON",
"(",
"b",
"[",
"]",
"byte",
")",
"error",
"{",
"var",
"s",
"string",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"b",
",",
"&",
"s",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"var",
"err",
"error",
"\n",
"jt",
".",
"Time",
",",
"err",
"=",
"time",
".",
"Parse",
"(",
"time",
".",
"RFC3339Nano",
",",
"s",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // MarshalJSON implements json.Unmarshaler. | [
"MarshalJSON",
"implements",
"json",
".",
"Unmarshaler",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/common/data/jsontime/jsontime.go#L41-L50 |
7,686 | luci/luci-go | grpc/prpc/options.go | DefaultOptions | func DefaultOptions() *Options {
return &Options{
Retry: func() retry.Iterator {
return &retry.ExponentialBackoff{
Limited: retry.Limited{
Delay: time.Second,
Retries: 5,
},
}
},
}
} | go | func DefaultOptions() *Options {
return &Options{
Retry: func() retry.Iterator {
return &retry.ExponentialBackoff{
Limited: retry.Limited{
Delay: time.Second,
Retries: 5,
},
}
},
}
} | [
"func",
"DefaultOptions",
"(",
")",
"*",
"Options",
"{",
"return",
"&",
"Options",
"{",
"Retry",
":",
"func",
"(",
")",
"retry",
".",
"Iterator",
"{",
"return",
"&",
"retry",
".",
"ExponentialBackoff",
"{",
"Limited",
":",
"retry",
".",
"Limited",
"{",
"Delay",
":",
"time",
".",
"Second",
",",
"Retries",
":",
"5",
",",
"}",
",",
"}",
"\n",
"}",
",",
"}",
"\n",
"}"
] | // DefaultOptions are used if no options are specified in Client. | [
"DefaultOptions",
"are",
"used",
"if",
"no",
"options",
"are",
"specified",
"in",
"Client",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/prpc/options.go#L52-L63 |
7,687 | luci/luci-go | grpc/prpc/options.go | Header | func Header(md *metadata.MD) *CallOption {
return &CallOption{
grpc.Header(md),
func(o *Options) {
o.resHeaderMetadata = md
},
}
} | go | func Header(md *metadata.MD) *CallOption {
return &CallOption{
grpc.Header(md),
func(o *Options) {
o.resHeaderMetadata = md
},
}
} | [
"func",
"Header",
"(",
"md",
"*",
"metadata",
".",
"MD",
")",
"*",
"CallOption",
"{",
"return",
"&",
"CallOption",
"{",
"grpc",
".",
"Header",
"(",
"md",
")",
",",
"func",
"(",
"o",
"*",
"Options",
")",
"{",
"o",
".",
"resHeaderMetadata",
"=",
"md",
"\n",
"}",
",",
"}",
"\n",
"}"
] | // Header returns a CallOption that retrieves the header metadata.
// Can be used instead of with grpc.Header. | [
"Header",
"returns",
"a",
"CallOption",
"that",
"retrieves",
"the",
"header",
"metadata",
".",
"Can",
"be",
"used",
"instead",
"of",
"with",
"grpc",
".",
"Header",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/prpc/options.go#L85-L92 |
7,688 | luci/luci-go | grpc/prpc/options.go | Trailer | func Trailer(md *metadata.MD) *CallOption {
return &CallOption{
grpc.Trailer(md),
func(o *Options) {
o.resTrailerMetadata = md
},
}
} | go | func Trailer(md *metadata.MD) *CallOption {
return &CallOption{
grpc.Trailer(md),
func(o *Options) {
o.resTrailerMetadata = md
},
}
} | [
"func",
"Trailer",
"(",
"md",
"*",
"metadata",
".",
"MD",
")",
"*",
"CallOption",
"{",
"return",
"&",
"CallOption",
"{",
"grpc",
".",
"Trailer",
"(",
"md",
")",
",",
"func",
"(",
"o",
"*",
"Options",
")",
"{",
"o",
".",
"resTrailerMetadata",
"=",
"md",
"\n",
"}",
",",
"}",
"\n",
"}"
] | // Trailer returns a CallOption that retrieves the trailer metadata.
// Can be used instead of grpc.Trailer. | [
"Trailer",
"returns",
"a",
"CallOption",
"that",
"retrieves",
"the",
"trailer",
"metadata",
".",
"Can",
"be",
"used",
"instead",
"of",
"grpc",
".",
"Trailer",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/prpc/options.go#L96-L103 |
7,689 | luci/luci-go | grpc/prpc/options.go | ExpectedCode | func ExpectedCode(codes ...codes.Code) *CallOption {
return &CallOption{
grpc.EmptyCallOption{},
func(o *Options) {
o.expectedCodes = append(o.expectedCodes, codes...)
},
}
} | go | func ExpectedCode(codes ...codes.Code) *CallOption {
return &CallOption{
grpc.EmptyCallOption{},
func(o *Options) {
o.expectedCodes = append(o.expectedCodes, codes...)
},
}
} | [
"func",
"ExpectedCode",
"(",
"codes",
"...",
"codes",
".",
"Code",
")",
"*",
"CallOption",
"{",
"return",
"&",
"CallOption",
"{",
"grpc",
".",
"EmptyCallOption",
"{",
"}",
",",
"func",
"(",
"o",
"*",
"Options",
")",
"{",
"o",
".",
"expectedCodes",
"=",
"append",
"(",
"o",
".",
"expectedCodes",
",",
"codes",
"...",
")",
"\n",
"}",
",",
"}",
"\n",
"}"
] | // ExpectedCode can be used to indicate that given non-OK codes may appear
// during normal successful call flow, and thus they must not be logged as
// erroneous.
//
// Only affects local logging, nothing else. | [
"ExpectedCode",
"can",
"be",
"used",
"to",
"indicate",
"that",
"given",
"non",
"-",
"OK",
"codes",
"may",
"appear",
"during",
"normal",
"successful",
"call",
"flow",
"and",
"thus",
"they",
"must",
"not",
"be",
"logged",
"as",
"erroneous",
".",
"Only",
"affects",
"local",
"logging",
"nothing",
"else",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/prpc/options.go#L110-L117 |
7,690 | luci/luci-go | scheduler/appengine/frontend/handler.go | fail | func (c *requestContext) fail(code int, msg string, args ...interface{}) {
body := fmt.Sprintf(msg, args...)
logging.Errorf(c.Context, "HTTP %d: %s", code, body)
http.Error(c.Writer, body, code)
} | go | func (c *requestContext) fail(code int, msg string, args ...interface{}) {
body := fmt.Sprintf(msg, args...)
logging.Errorf(c.Context, "HTTP %d: %s", code, body)
http.Error(c.Writer, body, code)
} | [
"func",
"(",
"c",
"*",
"requestContext",
")",
"fail",
"(",
"code",
"int",
",",
"msg",
"string",
",",
"args",
"...",
"interface",
"{",
"}",
")",
"{",
"body",
":=",
"fmt",
".",
"Sprintf",
"(",
"msg",
",",
"args",
"...",
")",
"\n",
"logging",
".",
"Errorf",
"(",
"c",
".",
"Context",
",",
"\"",
"\"",
",",
"code",
",",
"body",
")",
"\n",
"http",
".",
"Error",
"(",
"c",
".",
"Writer",
",",
"body",
",",
"code",
")",
"\n",
"}"
] | // fail writes error message to the log and the response and sets status code. | [
"fail",
"writes",
"error",
"message",
"to",
"the",
"log",
"and",
"the",
"response",
"and",
"sets",
"status",
"code",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/frontend/handler.go#L95-L99 |
7,691 | luci/luci-go | scheduler/appengine/frontend/handler.go | ok | func (c *requestContext) ok() {
c.Writer.Header().Set("Content-Type", "text/plain; charset=utf-8")
c.Writer.WriteHeader(200)
fmt.Fprintln(c.Writer, "OK")
} | go | func (c *requestContext) ok() {
c.Writer.Header().Set("Content-Type", "text/plain; charset=utf-8")
c.Writer.WriteHeader(200)
fmt.Fprintln(c.Writer, "OK")
} | [
"func",
"(",
"c",
"*",
"requestContext",
")",
"ok",
"(",
")",
"{",
"c",
".",
"Writer",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"c",
".",
"Writer",
".",
"WriteHeader",
"(",
"200",
")",
"\n",
"fmt",
".",
"Fprintln",
"(",
"c",
".",
"Writer",
",",
"\"",
"\"",
")",
"\n",
"}"
] | // ok sets status to 200 and puts "OK" in response. | [
"ok",
"sets",
"status",
"to",
"200",
"and",
"puts",
"OK",
"in",
"response",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/frontend/handler.go#L121-L125 |
7,692 | luci/luci-go | scheduler/appengine/frontend/handler.go | initializeGlobalState | func initializeGlobalState(c context.Context) {
if info.IsDevAppServer(c) {
// Dev app server doesn't preserve the state of task queues across restarts,
// need to reset datastore state accordingly, otherwise everything gets stuck.
if err := globalEngine.ResetAllJobsOnDevServer(c); err != nil {
logging.Errorf(c, "Failed to reset jobs: %s", err)
}
}
} | go | func initializeGlobalState(c context.Context) {
if info.IsDevAppServer(c) {
// Dev app server doesn't preserve the state of task queues across restarts,
// need to reset datastore state accordingly, otherwise everything gets stuck.
if err := globalEngine.ResetAllJobsOnDevServer(c); err != nil {
logging.Errorf(c, "Failed to reset jobs: %s", err)
}
}
} | [
"func",
"initializeGlobalState",
"(",
"c",
"context",
".",
"Context",
")",
"{",
"if",
"info",
".",
"IsDevAppServer",
"(",
"c",
")",
"{",
"// Dev app server doesn't preserve the state of task queues across restarts,",
"// need to reset datastore state accordingly, otherwise everything gets stuck.",
"if",
"err",
":=",
"globalEngine",
".",
"ResetAllJobsOnDevServer",
"(",
"c",
")",
";",
"err",
"!=",
"nil",
"{",
"logging",
".",
"Errorf",
"(",
"c",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // initializeGlobalState does one time initialization for stuff that needs
// active GAE context. | [
"initializeGlobalState",
"does",
"one",
"time",
"initialization",
"for",
"stuff",
"that",
"needs",
"active",
"GAE",
"context",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/frontend/handler.go#L133-L141 |
7,693 | luci/luci-go | scheduler/appengine/frontend/handler.go | pubsubPushHandler | func pubsubPushHandler(c *router.Context) {
rc := requestContext(*c)
body, err := ioutil.ReadAll(rc.Request.Body)
if err != nil {
rc.fail(500, "Failed to read the request: %s", err)
return
}
if err = globalEngine.ProcessPubSubPush(rc.Context, body); err != nil {
rc.err(err, "Failed to process incoming PubSub push")
return
}
rc.ok()
} | go | func pubsubPushHandler(c *router.Context) {
rc := requestContext(*c)
body, err := ioutil.ReadAll(rc.Request.Body)
if err != nil {
rc.fail(500, "Failed to read the request: %s", err)
return
}
if err = globalEngine.ProcessPubSubPush(rc.Context, body); err != nil {
rc.err(err, "Failed to process incoming PubSub push")
return
}
rc.ok()
} | [
"func",
"pubsubPushHandler",
"(",
"c",
"*",
"router",
".",
"Context",
")",
"{",
"rc",
":=",
"requestContext",
"(",
"*",
"c",
")",
"\n",
"body",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"rc",
".",
"Request",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"rc",
".",
"fail",
"(",
"500",
",",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"err",
"=",
"globalEngine",
".",
"ProcessPubSubPush",
"(",
"rc",
".",
"Context",
",",
"body",
")",
";",
"err",
"!=",
"nil",
"{",
"rc",
".",
"err",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"rc",
".",
"ok",
"(",
")",
"\n",
"}"
] | // pubsubPushHandler handles incoming PubSub messages. | [
"pubsubPushHandler",
"handles",
"incoming",
"PubSub",
"messages",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/frontend/handler.go#L214-L226 |
7,694 | luci/luci-go | scheduler/appengine/frontend/handler.go | pubsubPullHandler | func pubsubPullHandler(c *router.Context) {
rc := requestContext(*c)
if !appengine.IsDevAppServer() {
rc.fail(403, "Not a dev server")
return
}
err := globalEngine.PullPubSubOnDevServer(
rc.Context, rc.Params.ByName("ManagerName"), rc.Params.ByName("Publisher"))
if err != nil {
rc.err(err, "Failed to pull PubSub messages")
} else {
rc.ok()
}
} | go | func pubsubPullHandler(c *router.Context) {
rc := requestContext(*c)
if !appengine.IsDevAppServer() {
rc.fail(403, "Not a dev server")
return
}
err := globalEngine.PullPubSubOnDevServer(
rc.Context, rc.Params.ByName("ManagerName"), rc.Params.ByName("Publisher"))
if err != nil {
rc.err(err, "Failed to pull PubSub messages")
} else {
rc.ok()
}
} | [
"func",
"pubsubPullHandler",
"(",
"c",
"*",
"router",
".",
"Context",
")",
"{",
"rc",
":=",
"requestContext",
"(",
"*",
"c",
")",
"\n",
"if",
"!",
"appengine",
".",
"IsDevAppServer",
"(",
")",
"{",
"rc",
".",
"fail",
"(",
"403",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"err",
":=",
"globalEngine",
".",
"PullPubSubOnDevServer",
"(",
"rc",
".",
"Context",
",",
"rc",
".",
"Params",
".",
"ByName",
"(",
"\"",
"\"",
")",
",",
"rc",
".",
"Params",
".",
"ByName",
"(",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"rc",
".",
"err",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"rc",
".",
"ok",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // pubsubPullHandler is called on dev server by developer to pull pubsub
// messages from a topic created for a publisher. | [
"pubsubPullHandler",
"is",
"called",
"on",
"dev",
"server",
"by",
"developer",
"to",
"pull",
"pubsub",
"messages",
"from",
"a",
"topic",
"created",
"for",
"a",
"publisher",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/frontend/handler.go#L230-L243 |
7,695 | luci/luci-go | scheduler/appengine/frontend/handler.go | readConfigCron | func readConfigCron(c *router.Context) {
rc := requestContext(*c)
projectsToVisit := map[string]bool{}
// Visit all projects in the catalog.
ctx, _ := context.WithTimeout(rc.Context, 150*time.Second)
projects, err := globalCatalog.GetAllProjects(ctx)
if err != nil {
rc.err(err, "Failed to grab a list of project IDs from catalog")
return
}
for _, id := range projects {
projectsToVisit[id] = true
}
// Also visit all registered projects that do not show up in the catalog
// listing anymore. It will unregister all jobs belonging to them.
existing, err := globalEngine.GetAllProjects(rc.Context)
if err != nil {
rc.err(err, "Failed to grab a list of project IDs from datastore")
return
}
for _, id := range existing {
projectsToVisit[id] = true
}
// Handle each project in its own task to avoid "bad" projects (e.g. ones with
// lots of jobs) to slow down "good" ones.
tasks := make([]*tq.Task, 0, len(projectsToVisit))
for projectID := range projectsToVisit {
tasks = append(tasks, &tq.Task{
Payload: &internal.ReadProjectConfigTask{ProjectId: projectID},
})
}
if err = globalDispatcher.AddTask(rc.Context, tasks...); err != nil {
rc.err(err, "Failed to add tasks to task queue")
} else {
rc.ok()
}
} | go | func readConfigCron(c *router.Context) {
rc := requestContext(*c)
projectsToVisit := map[string]bool{}
// Visit all projects in the catalog.
ctx, _ := context.WithTimeout(rc.Context, 150*time.Second)
projects, err := globalCatalog.GetAllProjects(ctx)
if err != nil {
rc.err(err, "Failed to grab a list of project IDs from catalog")
return
}
for _, id := range projects {
projectsToVisit[id] = true
}
// Also visit all registered projects that do not show up in the catalog
// listing anymore. It will unregister all jobs belonging to them.
existing, err := globalEngine.GetAllProjects(rc.Context)
if err != nil {
rc.err(err, "Failed to grab a list of project IDs from datastore")
return
}
for _, id := range existing {
projectsToVisit[id] = true
}
// Handle each project in its own task to avoid "bad" projects (e.g. ones with
// lots of jobs) to slow down "good" ones.
tasks := make([]*tq.Task, 0, len(projectsToVisit))
for projectID := range projectsToVisit {
tasks = append(tasks, &tq.Task{
Payload: &internal.ReadProjectConfigTask{ProjectId: projectID},
})
}
if err = globalDispatcher.AddTask(rc.Context, tasks...); err != nil {
rc.err(err, "Failed to add tasks to task queue")
} else {
rc.ok()
}
} | [
"func",
"readConfigCron",
"(",
"c",
"*",
"router",
".",
"Context",
")",
"{",
"rc",
":=",
"requestContext",
"(",
"*",
"c",
")",
"\n",
"projectsToVisit",
":=",
"map",
"[",
"string",
"]",
"bool",
"{",
"}",
"\n\n",
"// Visit all projects in the catalog.",
"ctx",
",",
"_",
":=",
"context",
".",
"WithTimeout",
"(",
"rc",
".",
"Context",
",",
"150",
"*",
"time",
".",
"Second",
")",
"\n",
"projects",
",",
"err",
":=",
"globalCatalog",
".",
"GetAllProjects",
"(",
"ctx",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"rc",
".",
"err",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"for",
"_",
",",
"id",
":=",
"range",
"projects",
"{",
"projectsToVisit",
"[",
"id",
"]",
"=",
"true",
"\n",
"}",
"\n\n",
"// Also visit all registered projects that do not show up in the catalog",
"// listing anymore. It will unregister all jobs belonging to them.",
"existing",
",",
"err",
":=",
"globalEngine",
".",
"GetAllProjects",
"(",
"rc",
".",
"Context",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"rc",
".",
"err",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"return",
"\n",
"}",
"\n",
"for",
"_",
",",
"id",
":=",
"range",
"existing",
"{",
"projectsToVisit",
"[",
"id",
"]",
"=",
"true",
"\n",
"}",
"\n\n",
"// Handle each project in its own task to avoid \"bad\" projects (e.g. ones with",
"// lots of jobs) to slow down \"good\" ones.",
"tasks",
":=",
"make",
"(",
"[",
"]",
"*",
"tq",
".",
"Task",
",",
"0",
",",
"len",
"(",
"projectsToVisit",
")",
")",
"\n",
"for",
"projectID",
":=",
"range",
"projectsToVisit",
"{",
"tasks",
"=",
"append",
"(",
"tasks",
",",
"&",
"tq",
".",
"Task",
"{",
"Payload",
":",
"&",
"internal",
".",
"ReadProjectConfigTask",
"{",
"ProjectId",
":",
"projectID",
"}",
",",
"}",
")",
"\n",
"}",
"\n",
"if",
"err",
"=",
"globalDispatcher",
".",
"AddTask",
"(",
"rc",
".",
"Context",
",",
"tasks",
"...",
")",
";",
"err",
"!=",
"nil",
"{",
"rc",
".",
"err",
"(",
"err",
",",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"rc",
".",
"ok",
"(",
")",
"\n",
"}",
"\n",
"}"
] | // readConfigCron grabs a list of projects from the catalog and datastore and
// dispatches task queue tasks to update each project's cron jobs. | [
"readConfigCron",
"grabs",
"a",
"list",
"of",
"projects",
"from",
"the",
"catalog",
"and",
"datastore",
"and",
"dispatches",
"task",
"queue",
"tasks",
"to",
"update",
"each",
"project",
"s",
"cron",
"jobs",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/frontend/handler.go#L247-L286 |
7,696 | luci/luci-go | scheduler/appengine/frontend/handler.go | readProjectConfig | func readProjectConfig(c context.Context, task proto.Message) error {
projectID := task.(*internal.ReadProjectConfigTask).ProjectId
ctx, cancel := context.WithTimeout(c, 150*time.Second)
defer cancel()
jobs, err := globalCatalog.GetProjectJobs(ctx, projectID)
if err != nil {
logging.WithError(err).Errorf(c, "Failed to query for a list of jobs")
return err
}
if err := globalEngine.UpdateProjectJobs(ctx, projectID, jobs); err != nil {
logging.WithError(err).Errorf(c, "Failed to update some jobs")
return err
}
return nil
} | go | func readProjectConfig(c context.Context, task proto.Message) error {
projectID := task.(*internal.ReadProjectConfigTask).ProjectId
ctx, cancel := context.WithTimeout(c, 150*time.Second)
defer cancel()
jobs, err := globalCatalog.GetProjectJobs(ctx, projectID)
if err != nil {
logging.WithError(err).Errorf(c, "Failed to query for a list of jobs")
return err
}
if err := globalEngine.UpdateProjectJobs(ctx, projectID, jobs); err != nil {
logging.WithError(err).Errorf(c, "Failed to update some jobs")
return err
}
return nil
} | [
"func",
"readProjectConfig",
"(",
"c",
"context",
".",
"Context",
",",
"task",
"proto",
".",
"Message",
")",
"error",
"{",
"projectID",
":=",
"task",
".",
"(",
"*",
"internal",
".",
"ReadProjectConfigTask",
")",
".",
"ProjectId",
"\n\n",
"ctx",
",",
"cancel",
":=",
"context",
".",
"WithTimeout",
"(",
"c",
",",
"150",
"*",
"time",
".",
"Second",
")",
"\n",
"defer",
"cancel",
"(",
")",
"\n\n",
"jobs",
",",
"err",
":=",
"globalCatalog",
".",
"GetProjectJobs",
"(",
"ctx",
",",
"projectID",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logging",
".",
"WithError",
"(",
"err",
")",
".",
"Errorf",
"(",
"c",
",",
"\"",
"\"",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"if",
"err",
":=",
"globalEngine",
".",
"UpdateProjectJobs",
"(",
"ctx",
",",
"projectID",
",",
"jobs",
")",
";",
"err",
"!=",
"nil",
"{",
"logging",
".",
"WithError",
"(",
"err",
")",
".",
"Errorf",
"(",
"c",
",",
"\"",
"\"",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n\n",
"return",
"nil",
"\n",
"}"
] | // readProjectConfig grabs a list of jobs in a project from catalog, updates
// all changed jobs, adds new ones, disables old ones. | [
"readProjectConfig",
"grabs",
"a",
"list",
"of",
"jobs",
"in",
"a",
"project",
"from",
"catalog",
"updates",
"all",
"changed",
"jobs",
"adds",
"new",
"ones",
"disables",
"old",
"ones",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/scheduler/appengine/frontend/handler.go#L290-L308 |
7,697 | luci/luci-go | grpc/prpc/server.go | RegisterService | func (s *Server) RegisterService(desc *grpc.ServiceDesc, impl interface{}) {
serv := &service{
impl: impl,
methods: make(map[string]grpc.MethodDesc, len(desc.Methods)),
}
for _, m := range desc.Methods {
serv.methods[m.MethodName] = m
}
s.mu.Lock()
defer s.mu.Unlock()
if s.services == nil {
s.services = map[string]*service{}
} else if _, ok := s.services[desc.ServiceName]; ok {
panic(fmt.Errorf("service %q is already registered", desc.ServiceName))
}
s.services[desc.ServiceName] = serv
} | go | func (s *Server) RegisterService(desc *grpc.ServiceDesc, impl interface{}) {
serv := &service{
impl: impl,
methods: make(map[string]grpc.MethodDesc, len(desc.Methods)),
}
for _, m := range desc.Methods {
serv.methods[m.MethodName] = m
}
s.mu.Lock()
defer s.mu.Unlock()
if s.services == nil {
s.services = map[string]*service{}
} else if _, ok := s.services[desc.ServiceName]; ok {
panic(fmt.Errorf("service %q is already registered", desc.ServiceName))
}
s.services[desc.ServiceName] = serv
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"RegisterService",
"(",
"desc",
"*",
"grpc",
".",
"ServiceDesc",
",",
"impl",
"interface",
"{",
"}",
")",
"{",
"serv",
":=",
"&",
"service",
"{",
"impl",
":",
"impl",
",",
"methods",
":",
"make",
"(",
"map",
"[",
"string",
"]",
"grpc",
".",
"MethodDesc",
",",
"len",
"(",
"desc",
".",
"Methods",
")",
")",
",",
"}",
"\n",
"for",
"_",
",",
"m",
":=",
"range",
"desc",
".",
"Methods",
"{",
"serv",
".",
"methods",
"[",
"m",
".",
"MethodName",
"]",
"=",
"m",
"\n",
"}",
"\n\n",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"if",
"s",
".",
"services",
"==",
"nil",
"{",
"s",
".",
"services",
"=",
"map",
"[",
"string",
"]",
"*",
"service",
"{",
"}",
"\n",
"}",
"else",
"if",
"_",
",",
"ok",
":=",
"s",
".",
"services",
"[",
"desc",
".",
"ServiceName",
"]",
";",
"ok",
"{",
"panic",
"(",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"desc",
".",
"ServiceName",
")",
")",
"\n",
"}",
"\n\n",
"s",
".",
"services",
"[",
"desc",
".",
"ServiceName",
"]",
"=",
"serv",
"\n",
"}"
] | // RegisterService registers a service implementation.
// Called from the generated code.
//
// desc must contain description of the service, its message types
// and all transitive dependencies.
//
// Panics if a service of the same name is already registered. | [
"RegisterService",
"registers",
"a",
"service",
"implementation",
".",
"Called",
"from",
"the",
"generated",
"code",
".",
"desc",
"must",
"contain",
"description",
"of",
"the",
"service",
"its",
"message",
"types",
"and",
"all",
"transitive",
"dependencies",
".",
"Panics",
"if",
"a",
"service",
"of",
"the",
"same",
"name",
"is",
"already",
"registered",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/prpc/server.go#L101-L120 |
7,698 | luci/luci-go | grpc/prpc/server.go | authenticate | func (s *Server) authenticate() router.Middleware {
a := s.Authenticator
if a == nil {
a = GetDefaultAuth()
if a == nil {
panic("prpc: no custom Authenticator was provided and default authenticator was not registered.\n" +
"Either explicitly set `Server.Authenticator = NoAuthentication`, or use RegisterDefaultAuth()")
}
}
return func(c *router.Context, next router.Handler) {
switch ctx, err := a.Authenticate(c.Context, c.Request); {
case transient.Tag.In(err):
writeError(c.Context, c.Writer, withCode(err, codes.Internal))
case err != nil:
writeError(c.Context, c.Writer, withCode(err, codes.Unauthenticated))
default:
c.Context = ctx
next(c)
}
}
} | go | func (s *Server) authenticate() router.Middleware {
a := s.Authenticator
if a == nil {
a = GetDefaultAuth()
if a == nil {
panic("prpc: no custom Authenticator was provided and default authenticator was not registered.\n" +
"Either explicitly set `Server.Authenticator = NoAuthentication`, or use RegisterDefaultAuth()")
}
}
return func(c *router.Context, next router.Handler) {
switch ctx, err := a.Authenticate(c.Context, c.Request); {
case transient.Tag.In(err):
writeError(c.Context, c.Writer, withCode(err, codes.Internal))
case err != nil:
writeError(c.Context, c.Writer, withCode(err, codes.Unauthenticated))
default:
c.Context = ctx
next(c)
}
}
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"authenticate",
"(",
")",
"router",
".",
"Middleware",
"{",
"a",
":=",
"s",
".",
"Authenticator",
"\n",
"if",
"a",
"==",
"nil",
"{",
"a",
"=",
"GetDefaultAuth",
"(",
")",
"\n",
"if",
"a",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\\n",
"\"",
"+",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"func",
"(",
"c",
"*",
"router",
".",
"Context",
",",
"next",
"router",
".",
"Handler",
")",
"{",
"switch",
"ctx",
",",
"err",
":=",
"a",
".",
"Authenticate",
"(",
"c",
".",
"Context",
",",
"c",
".",
"Request",
")",
";",
"{",
"case",
"transient",
".",
"Tag",
".",
"In",
"(",
"err",
")",
":",
"writeError",
"(",
"c",
".",
"Context",
",",
"c",
".",
"Writer",
",",
"withCode",
"(",
"err",
",",
"codes",
".",
"Internal",
")",
")",
"\n",
"case",
"err",
"!=",
"nil",
":",
"writeError",
"(",
"c",
".",
"Context",
",",
"c",
".",
"Writer",
",",
"withCode",
"(",
"err",
",",
"codes",
".",
"Unauthenticated",
")",
")",
"\n",
"default",
":",
"c",
".",
"Context",
"=",
"ctx",
"\n",
"next",
"(",
"c",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // authenticate forces authentication set by RegisterDefaultAuth. | [
"authenticate",
"forces",
"authentication",
"set",
"by",
"RegisterDefaultAuth",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/prpc/server.go#L123-L144 |
7,699 | luci/luci-go | grpc/prpc/server.go | ServiceNames | func (s *Server) ServiceNames() []string {
s.mu.Lock()
defer s.mu.Unlock()
names := make([]string, 0, len(s.services))
for name := range s.services {
names = append(names, name)
}
sort.Strings(names)
return names
} | go | func (s *Server) ServiceNames() []string {
s.mu.Lock()
defer s.mu.Unlock()
names := make([]string, 0, len(s.services))
for name := range s.services {
names = append(names, name)
}
sort.Strings(names)
return names
} | [
"func",
"(",
"s",
"*",
"Server",
")",
"ServiceNames",
"(",
")",
"[",
"]",
"string",
"{",
"s",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n\n",
"names",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"s",
".",
"services",
")",
")",
"\n",
"for",
"name",
":=",
"range",
"s",
".",
"services",
"{",
"names",
"=",
"append",
"(",
"names",
",",
"name",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"names",
")",
"\n",
"return",
"names",
"\n",
"}"
] | // ServiceNames returns a sorted list of full names of all registered services. | [
"ServiceNames",
"returns",
"a",
"sorted",
"list",
"of",
"full",
"names",
"of",
"all",
"registered",
"services",
"."
] | f6cef429871eee3be7c6903af88d3ee884eaf683 | https://github.com/luci/luci-go/blob/f6cef429871eee3be7c6903af88d3ee884eaf683/grpc/prpc/server.go#L267-L277 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.