repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
tus/tusd | etcd3locker/lock.go | Acquire | func (lock *etcd3Lock) Acquire() error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// this is a blocking call; if we receive DeadlineExceeded
// the lock is most likely already taken
if err := lock.Mutex.Lock(ctx); err != nil {
if err == context.DeadlineExceeded {
return tusd.ErrFileLocked
} else {
return err
}
}
return nil
} | go | func (lock *etcd3Lock) Acquire() error {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// this is a blocking call; if we receive DeadlineExceeded
// the lock is most likely already taken
if err := lock.Mutex.Lock(ctx); err != nil {
if err == context.DeadlineExceeded {
return tusd.ErrFileLocked
} else {
return err
}
}
return nil
} | [
"func",
"(",
"lock",
"*",
"etcd3Lock",
")",
"Acquire",
"(",
")",
"error",
"{",
"ctx",
",",
"cancel",
":=",
"context",
".",
"WithTimeout",
"(",
"context",
".",
"Background",
"(",
")",
",",
"5",
"*",
"time",
".",
"Second",
")",
"\n",
"defer",
"cancel",
"(",
")",
"\n",
"if",
"err",
":=",
"lock",
".",
"Mutex",
".",
"Lock",
"(",
"ctx",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"context",
".",
"DeadlineExceeded",
"{",
"return",
"tusd",
".",
"ErrFileLocked",
"\n",
"}",
"else",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // Acquires a lock from etcd3 | [
"Acquires",
"a",
"lock",
"from",
"etcd3"
] | 12f102abf6cbd174b4dc9323672f59c6357b561c | https://github.com/tus/tusd/blob/12f102abf6cbd174b4dc9323672f59c6357b561c/etcd3locker/lock.go#L27-L41 | train |
mitchellh/mapstructure | decode_hooks.go | DecodeHookExec | func DecodeHookExec(
raw DecodeHookFunc,
from reflect.Type, to reflect.Type,
data interface{}) (interface{}, error) {
switch f := typedDecodeHook(raw).(type) {
case DecodeHookFuncType:
return f(from, to, data)
case DecodeHookFuncKind:
return f(from.Kind(), to.Kind(), data)
default:
return nil, errors.New("invalid decode hook signature")
}
} | go | func DecodeHookExec(
raw DecodeHookFunc,
from reflect.Type, to reflect.Type,
data interface{}) (interface{}, error) {
switch f := typedDecodeHook(raw).(type) {
case DecodeHookFuncType:
return f(from, to, data)
case DecodeHookFuncKind:
return f(from.Kind(), to.Kind(), data)
default:
return nil, errors.New("invalid decode hook signature")
}
} | [
"func",
"DecodeHookExec",
"(",
"raw",
"DecodeHookFunc",
",",
"from",
"reflect",
".",
"Type",
",",
"to",
"reflect",
".",
"Type",
",",
"data",
"interface",
"{",
"}",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"switch",
"f",
":=",
"typedDecodeHook",
"(",
"raw",
")",
".",
"(",
"type",
")",
"{",
"case",
"DecodeHookFuncType",
":",
"return",
"f",
"(",
"from",
",",
"to",
",",
"data",
")",
"\n",
"case",
"DecodeHookFuncKind",
":",
"return",
"f",
"(",
"from",
".",
"Kind",
"(",
")",
",",
"to",
".",
"Kind",
"(",
")",
",",
"data",
")",
"\n",
"default",
":",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"invalid decode hook signature\"",
")",
"\n",
"}",
"\n",
"}"
] | // DecodeHookExec executes the given decode hook. This should be used
// since it'll naturally degrade to the older backwards compatible DecodeHookFunc
// that took reflect.Kind instead of reflect.Type. | [
"DecodeHookExec",
"executes",
"the",
"given",
"decode",
"hook",
".",
"This",
"should",
"be",
"used",
"since",
"it",
"ll",
"naturally",
"degrade",
"to",
"the",
"older",
"backwards",
"compatible",
"DecodeHookFunc",
"that",
"took",
"reflect",
".",
"Kind",
"instead",
"of",
"reflect",
".",
"Type",
"."
] | 3536a929edddb9a5b34bd6861dc4a9647cb459fe | https://github.com/mitchellh/mapstructure/blob/3536a929edddb9a5b34bd6861dc4a9647cb459fe/decode_hooks.go#L39-L51 | train |
mitchellh/mapstructure | decode_hooks.go | ComposeDecodeHookFunc | func ComposeDecodeHookFunc(fs ...DecodeHookFunc) DecodeHookFunc {
return func(
f reflect.Type,
t reflect.Type,
data interface{}) (interface{}, error) {
var err error
for _, f1 := range fs {
data, err = DecodeHookExec(f1, f, t, data)
if err != nil {
return nil, err
}
// Modify the from kind to be correct with the new data
f = nil
if val := reflect.ValueOf(data); val.IsValid() {
f = val.Type()
}
}
return data, nil
}
} | go | func ComposeDecodeHookFunc(fs ...DecodeHookFunc) DecodeHookFunc {
return func(
f reflect.Type,
t reflect.Type,
data interface{}) (interface{}, error) {
var err error
for _, f1 := range fs {
data, err = DecodeHookExec(f1, f, t, data)
if err != nil {
return nil, err
}
// Modify the from kind to be correct with the new data
f = nil
if val := reflect.ValueOf(data); val.IsValid() {
f = val.Type()
}
}
return data, nil
}
} | [
"func",
"ComposeDecodeHookFunc",
"(",
"fs",
"...",
"DecodeHookFunc",
")",
"DecodeHookFunc",
"{",
"return",
"func",
"(",
"f",
"reflect",
".",
"Type",
",",
"t",
"reflect",
".",
"Type",
",",
"data",
"interface",
"{",
"}",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"var",
"err",
"error",
"\n",
"for",
"_",
",",
"f1",
":=",
"range",
"fs",
"{",
"data",
",",
"err",
"=",
"DecodeHookExec",
"(",
"f1",
",",
"f",
",",
"t",
",",
"data",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"f",
"=",
"nil",
"\n",
"if",
"val",
":=",
"reflect",
".",
"ValueOf",
"(",
"data",
")",
";",
"val",
".",
"IsValid",
"(",
")",
"{",
"f",
"=",
"val",
".",
"Type",
"(",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"data",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // ComposeDecodeHookFunc creates a single DecodeHookFunc that
// automatically composes multiple DecodeHookFuncs.
//
// The composed funcs are called in order, with the result of the
// previous transformation. | [
"ComposeDecodeHookFunc",
"creates",
"a",
"single",
"DecodeHookFunc",
"that",
"automatically",
"composes",
"multiple",
"DecodeHookFuncs",
".",
"The",
"composed",
"funcs",
"are",
"called",
"in",
"order",
"with",
"the",
"result",
"of",
"the",
"previous",
"transformation",
"."
] | 3536a929edddb9a5b34bd6861dc4a9647cb459fe | https://github.com/mitchellh/mapstructure/blob/3536a929edddb9a5b34bd6861dc4a9647cb459fe/decode_hooks.go#L58-L79 | train |
mitchellh/mapstructure | decode_hooks.go | StringToTimeDurationHookFunc | func StringToTimeDurationHookFunc() DecodeHookFunc {
return func(
f reflect.Type,
t reflect.Type,
data interface{}) (interface{}, error) {
if f.Kind() != reflect.String {
return data, nil
}
if t != reflect.TypeOf(time.Duration(5)) {
return data, nil
}
// Convert it by parsing
return time.ParseDuration(data.(string))
}
} | go | func StringToTimeDurationHookFunc() DecodeHookFunc {
return func(
f reflect.Type,
t reflect.Type,
data interface{}) (interface{}, error) {
if f.Kind() != reflect.String {
return data, nil
}
if t != reflect.TypeOf(time.Duration(5)) {
return data, nil
}
// Convert it by parsing
return time.ParseDuration(data.(string))
}
} | [
"func",
"StringToTimeDurationHookFunc",
"(",
")",
"DecodeHookFunc",
"{",
"return",
"func",
"(",
"f",
"reflect",
".",
"Type",
",",
"t",
"reflect",
".",
"Type",
",",
"data",
"interface",
"{",
"}",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"if",
"f",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"String",
"{",
"return",
"data",
",",
"nil",
"\n",
"}",
"\n",
"if",
"t",
"!=",
"reflect",
".",
"TypeOf",
"(",
"time",
".",
"Duration",
"(",
"5",
")",
")",
"{",
"return",
"data",
",",
"nil",
"\n",
"}",
"\n",
"return",
"time",
".",
"ParseDuration",
"(",
"data",
".",
"(",
"string",
")",
")",
"\n",
"}",
"\n",
"}"
] | // StringToTimeDurationHookFunc returns a DecodeHookFunc that converts
// strings to time.Duration. | [
"StringToTimeDurationHookFunc",
"returns",
"a",
"DecodeHookFunc",
"that",
"converts",
"strings",
"to",
"time",
".",
"Duration",
"."
] | 3536a929edddb9a5b34bd6861dc4a9647cb459fe | https://github.com/mitchellh/mapstructure/blob/3536a929edddb9a5b34bd6861dc4a9647cb459fe/decode_hooks.go#L103-L118 | train |
mitchellh/mapstructure | decode_hooks.go | StringToIPHookFunc | func StringToIPHookFunc() DecodeHookFunc {
return func(
f reflect.Type,
t reflect.Type,
data interface{}) (interface{}, error) {
if f.Kind() != reflect.String {
return data, nil
}
if t != reflect.TypeOf(net.IP{}) {
return data, nil
}
// Convert it by parsing
ip := net.ParseIP(data.(string))
if ip == nil {
return net.IP{}, fmt.Errorf("failed parsing ip %v", data)
}
return ip, nil
}
} | go | func StringToIPHookFunc() DecodeHookFunc {
return func(
f reflect.Type,
t reflect.Type,
data interface{}) (interface{}, error) {
if f.Kind() != reflect.String {
return data, nil
}
if t != reflect.TypeOf(net.IP{}) {
return data, nil
}
// Convert it by parsing
ip := net.ParseIP(data.(string))
if ip == nil {
return net.IP{}, fmt.Errorf("failed parsing ip %v", data)
}
return ip, nil
}
} | [
"func",
"StringToIPHookFunc",
"(",
")",
"DecodeHookFunc",
"{",
"return",
"func",
"(",
"f",
"reflect",
".",
"Type",
",",
"t",
"reflect",
".",
"Type",
",",
"data",
"interface",
"{",
"}",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"if",
"f",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"String",
"{",
"return",
"data",
",",
"nil",
"\n",
"}",
"\n",
"if",
"t",
"!=",
"reflect",
".",
"TypeOf",
"(",
"net",
".",
"IP",
"{",
"}",
")",
"{",
"return",
"data",
",",
"nil",
"\n",
"}",
"\n",
"ip",
":=",
"net",
".",
"ParseIP",
"(",
"data",
".",
"(",
"string",
")",
")",
"\n",
"if",
"ip",
"==",
"nil",
"{",
"return",
"net",
".",
"IP",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"failed parsing ip %v\"",
",",
"data",
")",
"\n",
"}",
"\n",
"return",
"ip",
",",
"nil",
"\n",
"}",
"\n",
"}"
] | // StringToIPHookFunc returns a DecodeHookFunc that converts
// strings to net.IP | [
"StringToIPHookFunc",
"returns",
"a",
"DecodeHookFunc",
"that",
"converts",
"strings",
"to",
"net",
".",
"IP"
] | 3536a929edddb9a5b34bd6861dc4a9647cb459fe | https://github.com/mitchellh/mapstructure/blob/3536a929edddb9a5b34bd6861dc4a9647cb459fe/decode_hooks.go#L122-L142 | train |
mitchellh/mapstructure | decode_hooks.go | StringToIPNetHookFunc | func StringToIPNetHookFunc() DecodeHookFunc {
return func(
f reflect.Type,
t reflect.Type,
data interface{}) (interface{}, error) {
if f.Kind() != reflect.String {
return data, nil
}
if t != reflect.TypeOf(net.IPNet{}) {
return data, nil
}
// Convert it by parsing
_, net, err := net.ParseCIDR(data.(string))
return net, err
}
} | go | func StringToIPNetHookFunc() DecodeHookFunc {
return func(
f reflect.Type,
t reflect.Type,
data interface{}) (interface{}, error) {
if f.Kind() != reflect.String {
return data, nil
}
if t != reflect.TypeOf(net.IPNet{}) {
return data, nil
}
// Convert it by parsing
_, net, err := net.ParseCIDR(data.(string))
return net, err
}
} | [
"func",
"StringToIPNetHookFunc",
"(",
")",
"DecodeHookFunc",
"{",
"return",
"func",
"(",
"f",
"reflect",
".",
"Type",
",",
"t",
"reflect",
".",
"Type",
",",
"data",
"interface",
"{",
"}",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"if",
"f",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"String",
"{",
"return",
"data",
",",
"nil",
"\n",
"}",
"\n",
"if",
"t",
"!=",
"reflect",
".",
"TypeOf",
"(",
"net",
".",
"IPNet",
"{",
"}",
")",
"{",
"return",
"data",
",",
"nil",
"\n",
"}",
"\n",
"_",
",",
"net",
",",
"err",
":=",
"net",
".",
"ParseCIDR",
"(",
"data",
".",
"(",
"string",
")",
")",
"\n",
"return",
"net",
",",
"err",
"\n",
"}",
"\n",
"}"
] | // StringToIPNetHookFunc returns a DecodeHookFunc that converts
// strings to net.IPNet | [
"StringToIPNetHookFunc",
"returns",
"a",
"DecodeHookFunc",
"that",
"converts",
"strings",
"to",
"net",
".",
"IPNet"
] | 3536a929edddb9a5b34bd6861dc4a9647cb459fe | https://github.com/mitchellh/mapstructure/blob/3536a929edddb9a5b34bd6861dc4a9647cb459fe/decode_hooks.go#L146-L162 | train |
mitchellh/mapstructure | decode_hooks.go | StringToTimeHookFunc | func StringToTimeHookFunc(layout string) DecodeHookFunc {
return func(
f reflect.Type,
t reflect.Type,
data interface{}) (interface{}, error) {
if f.Kind() != reflect.String {
return data, nil
}
if t != reflect.TypeOf(time.Time{}) {
return data, nil
}
// Convert it by parsing
return time.Parse(layout, data.(string))
}
} | go | func StringToTimeHookFunc(layout string) DecodeHookFunc {
return func(
f reflect.Type,
t reflect.Type,
data interface{}) (interface{}, error) {
if f.Kind() != reflect.String {
return data, nil
}
if t != reflect.TypeOf(time.Time{}) {
return data, nil
}
// Convert it by parsing
return time.Parse(layout, data.(string))
}
} | [
"func",
"StringToTimeHookFunc",
"(",
"layout",
"string",
")",
"DecodeHookFunc",
"{",
"return",
"func",
"(",
"f",
"reflect",
".",
"Type",
",",
"t",
"reflect",
".",
"Type",
",",
"data",
"interface",
"{",
"}",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"if",
"f",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"String",
"{",
"return",
"data",
",",
"nil",
"\n",
"}",
"\n",
"if",
"t",
"!=",
"reflect",
".",
"TypeOf",
"(",
"time",
".",
"Time",
"{",
"}",
")",
"{",
"return",
"data",
",",
"nil",
"\n",
"}",
"\n",
"return",
"time",
".",
"Parse",
"(",
"layout",
",",
"data",
".",
"(",
"string",
")",
")",
"\n",
"}",
"\n",
"}"
] | // StringToTimeHookFunc returns a DecodeHookFunc that converts
// strings to time.Time. | [
"StringToTimeHookFunc",
"returns",
"a",
"DecodeHookFunc",
"that",
"converts",
"strings",
"to",
"time",
".",
"Time",
"."
] | 3536a929edddb9a5b34bd6861dc4a9647cb459fe | https://github.com/mitchellh/mapstructure/blob/3536a929edddb9a5b34bd6861dc4a9647cb459fe/decode_hooks.go#L166-L181 | train |
mitchellh/mapstructure | decode_hooks.go | WeaklyTypedHook | func WeaklyTypedHook(
f reflect.Kind,
t reflect.Kind,
data interface{}) (interface{}, error) {
dataVal := reflect.ValueOf(data)
switch t {
case reflect.String:
switch f {
case reflect.Bool:
if dataVal.Bool() {
return "1", nil
}
return "0", nil
case reflect.Float32:
return strconv.FormatFloat(dataVal.Float(), 'f', -1, 64), nil
case reflect.Int:
return strconv.FormatInt(dataVal.Int(), 10), nil
case reflect.Slice:
dataType := dataVal.Type()
elemKind := dataType.Elem().Kind()
if elemKind == reflect.Uint8 {
return string(dataVal.Interface().([]uint8)), nil
}
case reflect.Uint:
return strconv.FormatUint(dataVal.Uint(), 10), nil
}
}
return data, nil
} | go | func WeaklyTypedHook(
f reflect.Kind,
t reflect.Kind,
data interface{}) (interface{}, error) {
dataVal := reflect.ValueOf(data)
switch t {
case reflect.String:
switch f {
case reflect.Bool:
if dataVal.Bool() {
return "1", nil
}
return "0", nil
case reflect.Float32:
return strconv.FormatFloat(dataVal.Float(), 'f', -1, 64), nil
case reflect.Int:
return strconv.FormatInt(dataVal.Int(), 10), nil
case reflect.Slice:
dataType := dataVal.Type()
elemKind := dataType.Elem().Kind()
if elemKind == reflect.Uint8 {
return string(dataVal.Interface().([]uint8)), nil
}
case reflect.Uint:
return strconv.FormatUint(dataVal.Uint(), 10), nil
}
}
return data, nil
} | [
"func",
"WeaklyTypedHook",
"(",
"f",
"reflect",
".",
"Kind",
",",
"t",
"reflect",
".",
"Kind",
",",
"data",
"interface",
"{",
"}",
")",
"(",
"interface",
"{",
"}",
",",
"error",
")",
"{",
"dataVal",
":=",
"reflect",
".",
"ValueOf",
"(",
"data",
")",
"\n",
"switch",
"t",
"{",
"case",
"reflect",
".",
"String",
":",
"switch",
"f",
"{",
"case",
"reflect",
".",
"Bool",
":",
"if",
"dataVal",
".",
"Bool",
"(",
")",
"{",
"return",
"\"1\"",
",",
"nil",
"\n",
"}",
"\n",
"return",
"\"0\"",
",",
"nil",
"\n",
"case",
"reflect",
".",
"Float32",
":",
"return",
"strconv",
".",
"FormatFloat",
"(",
"dataVal",
".",
"Float",
"(",
")",
",",
"'f'",
",",
"-",
"1",
",",
"64",
")",
",",
"nil",
"\n",
"case",
"reflect",
".",
"Int",
":",
"return",
"strconv",
".",
"FormatInt",
"(",
"dataVal",
".",
"Int",
"(",
")",
",",
"10",
")",
",",
"nil",
"\n",
"case",
"reflect",
".",
"Slice",
":",
"dataType",
":=",
"dataVal",
".",
"Type",
"(",
")",
"\n",
"elemKind",
":=",
"dataType",
".",
"Elem",
"(",
")",
".",
"Kind",
"(",
")",
"\n",
"if",
"elemKind",
"==",
"reflect",
".",
"Uint8",
"{",
"return",
"string",
"(",
"dataVal",
".",
"Interface",
"(",
")",
".",
"(",
"[",
"]",
"uint8",
")",
")",
",",
"nil",
"\n",
"}",
"\n",
"case",
"reflect",
".",
"Uint",
":",
"return",
"strconv",
".",
"FormatUint",
"(",
"dataVal",
".",
"Uint",
"(",
")",
",",
"10",
")",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"data",
",",
"nil",
"\n",
"}"
] | // WeaklyTypedHook is a DecodeHookFunc which adds support for weak typing to
// the decoder.
//
// Note that this is significantly different from the WeaklyTypedInput option
// of the DecoderConfig. | [
"WeaklyTypedHook",
"is",
"a",
"DecodeHookFunc",
"which",
"adds",
"support",
"for",
"weak",
"typing",
"to",
"the",
"decoder",
".",
"Note",
"that",
"this",
"is",
"significantly",
"different",
"from",
"the",
"WeaklyTypedInput",
"option",
"of",
"the",
"DecoderConfig",
"."
] | 3536a929edddb9a5b34bd6861dc4a9647cb459fe | https://github.com/mitchellh/mapstructure/blob/3536a929edddb9a5b34bd6861dc4a9647cb459fe/decode_hooks.go#L188-L217 | train |
mitchellh/mapstructure | mapstructure.go | Decode | func Decode(input interface{}, output interface{}) error {
config := &DecoderConfig{
Metadata: nil,
Result: output,
}
decoder, err := NewDecoder(config)
if err != nil {
return err
}
return decoder.Decode(input)
} | go | func Decode(input interface{}, output interface{}) error {
config := &DecoderConfig{
Metadata: nil,
Result: output,
}
decoder, err := NewDecoder(config)
if err != nil {
return err
}
return decoder.Decode(input)
} | [
"func",
"Decode",
"(",
"input",
"interface",
"{",
"}",
",",
"output",
"interface",
"{",
"}",
")",
"error",
"{",
"config",
":=",
"&",
"DecoderConfig",
"{",
"Metadata",
":",
"nil",
",",
"Result",
":",
"output",
",",
"}",
"\n",
"decoder",
",",
"err",
":=",
"NewDecoder",
"(",
"config",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"decoder",
".",
"Decode",
"(",
"input",
")",
"\n",
"}"
] | // Decode takes an input structure and uses reflection to translate it to
// the output structure. output must be a pointer to a map or struct. | [
"Decode",
"takes",
"an",
"input",
"structure",
"and",
"uses",
"reflection",
"to",
"translate",
"it",
"to",
"the",
"output",
"structure",
".",
"output",
"must",
"be",
"a",
"pointer",
"to",
"a",
"map",
"or",
"struct",
"."
] | 3536a929edddb9a5b34bd6861dc4a9647cb459fe | https://github.com/mitchellh/mapstructure/blob/3536a929edddb9a5b34bd6861dc4a9647cb459fe/mapstructure.go#L119-L131 | train |
mitchellh/mapstructure | mapstructure.go | NewDecoder | func NewDecoder(config *DecoderConfig) (*Decoder, error) {
val := reflect.ValueOf(config.Result)
if val.Kind() != reflect.Ptr {
return nil, errors.New("result must be a pointer")
}
val = val.Elem()
if !val.CanAddr() {
return nil, errors.New("result must be addressable (a pointer)")
}
if config.Metadata != nil {
if config.Metadata.Keys == nil {
config.Metadata.Keys = make([]string, 0)
}
if config.Metadata.Unused == nil {
config.Metadata.Unused = make([]string, 0)
}
}
if config.TagName == "" {
config.TagName = "mapstructure"
}
result := &Decoder{
config: config,
}
return result, nil
} | go | func NewDecoder(config *DecoderConfig) (*Decoder, error) {
val := reflect.ValueOf(config.Result)
if val.Kind() != reflect.Ptr {
return nil, errors.New("result must be a pointer")
}
val = val.Elem()
if !val.CanAddr() {
return nil, errors.New("result must be addressable (a pointer)")
}
if config.Metadata != nil {
if config.Metadata.Keys == nil {
config.Metadata.Keys = make([]string, 0)
}
if config.Metadata.Unused == nil {
config.Metadata.Unused = make([]string, 0)
}
}
if config.TagName == "" {
config.TagName = "mapstructure"
}
result := &Decoder{
config: config,
}
return result, nil
} | [
"func",
"NewDecoder",
"(",
"config",
"*",
"DecoderConfig",
")",
"(",
"*",
"Decoder",
",",
"error",
")",
"{",
"val",
":=",
"reflect",
".",
"ValueOf",
"(",
"config",
".",
"Result",
")",
"\n",
"if",
"val",
".",
"Kind",
"(",
")",
"!=",
"reflect",
".",
"Ptr",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"result must be a pointer\"",
")",
"\n",
"}",
"\n",
"val",
"=",
"val",
".",
"Elem",
"(",
")",
"\n",
"if",
"!",
"val",
".",
"CanAddr",
"(",
")",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"result must be addressable (a pointer)\"",
")",
"\n",
"}",
"\n",
"if",
"config",
".",
"Metadata",
"!=",
"nil",
"{",
"if",
"config",
".",
"Metadata",
".",
"Keys",
"==",
"nil",
"{",
"config",
".",
"Metadata",
".",
"Keys",
"=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
")",
"\n",
"}",
"\n",
"if",
"config",
".",
"Metadata",
".",
"Unused",
"==",
"nil",
"{",
"config",
".",
"Metadata",
".",
"Unused",
"=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"config",
".",
"TagName",
"==",
"\"\"",
"{",
"config",
".",
"TagName",
"=",
"\"mapstructure\"",
"\n",
"}",
"\n",
"result",
":=",
"&",
"Decoder",
"{",
"config",
":",
"config",
",",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] | // NewDecoder returns a new decoder for the given configuration. Once
// a decoder has been returned, the same configuration must not be used
// again. | [
"NewDecoder",
"returns",
"a",
"new",
"decoder",
"for",
"the",
"given",
"configuration",
".",
"Once",
"a",
"decoder",
"has",
"been",
"returned",
"the",
"same",
"configuration",
"must",
"not",
"be",
"used",
"again",
"."
] | 3536a929edddb9a5b34bd6861dc4a9647cb459fe | https://github.com/mitchellh/mapstructure/blob/3536a929edddb9a5b34bd6861dc4a9647cb459fe/mapstructure.go#L187-L217 | train |
mitchellh/mapstructure | error.go | WrappedErrors | func (e *Error) WrappedErrors() []error {
if e == nil {
return nil
}
result := make([]error, len(e.Errors))
for i, e := range e.Errors {
result[i] = errors.New(e)
}
return result
} | go | func (e *Error) WrappedErrors() []error {
if e == nil {
return nil
}
result := make([]error, len(e.Errors))
for i, e := range e.Errors {
result[i] = errors.New(e)
}
return result
} | [
"func",
"(",
"e",
"*",
"Error",
")",
"WrappedErrors",
"(",
")",
"[",
"]",
"error",
"{",
"if",
"e",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"result",
":=",
"make",
"(",
"[",
"]",
"error",
",",
"len",
"(",
"e",
".",
"Errors",
")",
")",
"\n",
"for",
"i",
",",
"e",
":=",
"range",
"e",
".",
"Errors",
"{",
"result",
"[",
"i",
"]",
"=",
"errors",
".",
"New",
"(",
"e",
")",
"\n",
"}",
"\n",
"return",
"result",
"\n",
"}"
] | // WrappedErrors implements the errwrap.Wrapper interface to make this
// return value more useful with the errwrap and go-multierror libraries. | [
"WrappedErrors",
"implements",
"the",
"errwrap",
".",
"Wrapper",
"interface",
"to",
"make",
"this",
"return",
"value",
"more",
"useful",
"with",
"the",
"errwrap",
"and",
"go",
"-",
"multierror",
"libraries",
"."
] | 3536a929edddb9a5b34bd6861dc4a9647cb459fe | https://github.com/mitchellh/mapstructure/blob/3536a929edddb9a5b34bd6861dc4a9647cb459fe/error.go#L30-L41 | train |
perkeep/perkeep | pkg/gpgchallenge/gpg.go | rateLimit | func (cs *Server) rateLimit(keyID, claimedIP string) (isSpammer bool) {
cs.whiteListMu.Lock()
if _, ok := cs.whiteList[keyID+"-"+claimedIP]; ok {
cs.whiteListMu.Unlock()
return false
}
cs.whiteListMu.Unlock()
// If they haven't successfully challenged us before, they look suspicious.
cs.keyIDSeenMu.Lock()
lastSeen, ok := cs.keyIDSeen[keyID]
// always keep track of the last time we saw them
cs.keyIDSeen[keyID] = time.Now()
cs.keyIDSeenMu.Unlock()
time.AfterFunc(forgetSeen, func() {
// but everyone get a clean slate after a minute of being quiet
cs.keyIDSeenMu.Lock()
delete(cs.keyIDSeen, keyID)
cs.keyIDSeenMu.Unlock()
})
if ok {
// if we've seen their keyID before, they look even more suspicious, so investigate.
if lastSeen.Add(spamDelay).After(time.Now()) {
// we kick them out if we saw them less than 5 seconds ago.
return true
}
}
cs.IPSeenMu.Lock()
lastSeen, ok = cs.IPSeen[claimedIP]
// always keep track of the last time we saw them
cs.IPSeen[claimedIP] = time.Now()
cs.IPSeenMu.Unlock()
time.AfterFunc(forgetSeen, func() {
// but everyone get a clean slate after a minute of being quiet
cs.IPSeenMu.Lock()
delete(cs.IPSeen, claimedIP)
cs.IPSeenMu.Unlock()
})
if ok {
// if we've seen their IP before, they look even more suspicious, so investigate.
if lastSeen.Add(spamDelay).After(time.Now()) {
// we kick them out if we saw them less than 5 seconds ago.
return true
}
}
// global rate limit that applies to all strangers at the same time
cs.limiter.Wait(context.Background())
return false
} | go | func (cs *Server) rateLimit(keyID, claimedIP string) (isSpammer bool) {
cs.whiteListMu.Lock()
if _, ok := cs.whiteList[keyID+"-"+claimedIP]; ok {
cs.whiteListMu.Unlock()
return false
}
cs.whiteListMu.Unlock()
// If they haven't successfully challenged us before, they look suspicious.
cs.keyIDSeenMu.Lock()
lastSeen, ok := cs.keyIDSeen[keyID]
// always keep track of the last time we saw them
cs.keyIDSeen[keyID] = time.Now()
cs.keyIDSeenMu.Unlock()
time.AfterFunc(forgetSeen, func() {
// but everyone get a clean slate after a minute of being quiet
cs.keyIDSeenMu.Lock()
delete(cs.keyIDSeen, keyID)
cs.keyIDSeenMu.Unlock()
})
if ok {
// if we've seen their keyID before, they look even more suspicious, so investigate.
if lastSeen.Add(spamDelay).After(time.Now()) {
// we kick them out if we saw them less than 5 seconds ago.
return true
}
}
cs.IPSeenMu.Lock()
lastSeen, ok = cs.IPSeen[claimedIP]
// always keep track of the last time we saw them
cs.IPSeen[claimedIP] = time.Now()
cs.IPSeenMu.Unlock()
time.AfterFunc(forgetSeen, func() {
// but everyone get a clean slate after a minute of being quiet
cs.IPSeenMu.Lock()
delete(cs.IPSeen, claimedIP)
cs.IPSeenMu.Unlock()
})
if ok {
// if we've seen their IP before, they look even more suspicious, so investigate.
if lastSeen.Add(spamDelay).After(time.Now()) {
// we kick them out if we saw them less than 5 seconds ago.
return true
}
}
// global rate limit that applies to all strangers at the same time
cs.limiter.Wait(context.Background())
return false
} | [
"func",
"(",
"cs",
"*",
"Server",
")",
"rateLimit",
"(",
"keyID",
",",
"claimedIP",
"string",
")",
"(",
"isSpammer",
"bool",
")",
"{",
"cs",
".",
"whiteListMu",
".",
"Lock",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"cs",
".",
"whiteList",
"[",
"keyID",
"+",
"\"-\"",
"+",
"claimedIP",
"]",
";",
"ok",
"{",
"cs",
".",
"whiteListMu",
".",
"Unlock",
"(",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"cs",
".",
"whiteListMu",
".",
"Unlock",
"(",
")",
"\n",
"cs",
".",
"keyIDSeenMu",
".",
"Lock",
"(",
")",
"\n",
"lastSeen",
",",
"ok",
":=",
"cs",
".",
"keyIDSeen",
"[",
"keyID",
"]",
"\n",
"cs",
".",
"keyIDSeen",
"[",
"keyID",
"]",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"cs",
".",
"keyIDSeenMu",
".",
"Unlock",
"(",
")",
"\n",
"time",
".",
"AfterFunc",
"(",
"forgetSeen",
",",
"func",
"(",
")",
"{",
"cs",
".",
"keyIDSeenMu",
".",
"Lock",
"(",
")",
"\n",
"delete",
"(",
"cs",
".",
"keyIDSeen",
",",
"keyID",
")",
"\n",
"cs",
".",
"keyIDSeenMu",
".",
"Unlock",
"(",
")",
"\n",
"}",
")",
"\n",
"if",
"ok",
"{",
"if",
"lastSeen",
".",
"Add",
"(",
"spamDelay",
")",
".",
"After",
"(",
"time",
".",
"Now",
"(",
")",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"cs",
".",
"IPSeenMu",
".",
"Lock",
"(",
")",
"\n",
"lastSeen",
",",
"ok",
"=",
"cs",
".",
"IPSeen",
"[",
"claimedIP",
"]",
"\n",
"cs",
".",
"IPSeen",
"[",
"claimedIP",
"]",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"cs",
".",
"IPSeenMu",
".",
"Unlock",
"(",
")",
"\n",
"time",
".",
"AfterFunc",
"(",
"forgetSeen",
",",
"func",
"(",
")",
"{",
"cs",
".",
"IPSeenMu",
".",
"Lock",
"(",
")",
"\n",
"delete",
"(",
"cs",
".",
"IPSeen",
",",
"claimedIP",
")",
"\n",
"cs",
".",
"IPSeenMu",
".",
"Unlock",
"(",
")",
"\n",
"}",
")",
"\n",
"if",
"ok",
"{",
"if",
"lastSeen",
".",
"Add",
"(",
"spamDelay",
")",
".",
"After",
"(",
"time",
".",
"Now",
"(",
")",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"cs",
".",
"limiter",
".",
"Wait",
"(",
"context",
".",
"Background",
"(",
")",
")",
"\n",
"return",
"false",
"\n",
"}"
] | // rateLimit uses the cs.limiter to make sure that any client that hasn't
// previously successfully challenged us is rate limited. It also keeps track of
// clients that haven't successfully challenged, and it returns true if such a
// client should be considered a spammer. | [
"rateLimit",
"uses",
"the",
"cs",
".",
"limiter",
"to",
"make",
"sure",
"that",
"any",
"client",
"that",
"hasn",
"t",
"previously",
"successfully",
"challenged",
"us",
"is",
"rate",
"limited",
".",
"It",
"also",
"keeps",
"track",
"of",
"clients",
"that",
"haven",
"t",
"successfully",
"challenged",
"and",
"it",
"returns",
"true",
"if",
"such",
"a",
"client",
"should",
"be",
"considered",
"a",
"spammer",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/gpgchallenge/gpg.go#L343-L390 | train |
perkeep/perkeep | pkg/gpgchallenge/gpg.go | NewClient | func NewClient(keyRing, keyId, challengeIP string) (*Client, error) {
signer, err := secretKeyEntity(keyRing, keyId)
if err != nil {
return nil, fmt.Errorf("could not get signer %v from keyRing %v: %v", keyId, keyRing, err)
}
cl := &Client{
keyRing: keyRing,
keyId: keyId,
signer: signer,
challengeIP: challengeIP,
errc: make(chan error, 1),
}
handler := &clientHandler{
cl: cl,
}
cl.handler = handler
return cl, nil
} | go | func NewClient(keyRing, keyId, challengeIP string) (*Client, error) {
signer, err := secretKeyEntity(keyRing, keyId)
if err != nil {
return nil, fmt.Errorf("could not get signer %v from keyRing %v: %v", keyId, keyRing, err)
}
cl := &Client{
keyRing: keyRing,
keyId: keyId,
signer: signer,
challengeIP: challengeIP,
errc: make(chan error, 1),
}
handler := &clientHandler{
cl: cl,
}
cl.handler = handler
return cl, nil
} | [
"func",
"NewClient",
"(",
"keyRing",
",",
"keyId",
",",
"challengeIP",
"string",
")",
"(",
"*",
"Client",
",",
"error",
")",
"{",
"signer",
",",
"err",
":=",
"secretKeyEntity",
"(",
"keyRing",
",",
"keyId",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"could not get signer %v from keyRing %v: %v\"",
",",
"keyId",
",",
"keyRing",
",",
"err",
")",
"\n",
"}",
"\n",
"cl",
":=",
"&",
"Client",
"{",
"keyRing",
":",
"keyRing",
",",
"keyId",
":",
"keyId",
",",
"signer",
":",
"signer",
",",
"challengeIP",
":",
"challengeIP",
",",
"errc",
":",
"make",
"(",
"chan",
"error",
",",
"1",
")",
",",
"}",
"\n",
"handler",
":=",
"&",
"clientHandler",
"{",
"cl",
":",
"cl",
",",
"}",
"\n",
"cl",
".",
"handler",
"=",
"handler",
"\n",
"return",
"cl",
",",
"nil",
"\n",
"}"
] | // NewClient returns a Client. keyRing and keyId are the GPG key ring and key ID
// used to fulfill the challenge. challengeIP is the address that client proves
// that it owns, by answering the challenge the server sends at this address. | [
"NewClient",
"returns",
"a",
"Client",
".",
"keyRing",
"and",
"keyId",
"are",
"the",
"GPG",
"key",
"ring",
"and",
"key",
"ID",
"used",
"to",
"fulfill",
"the",
"challenge",
".",
"challengeIP",
"is",
"the",
"address",
"that",
"client",
"proves",
"that",
"it",
"owns",
"by",
"answering",
"the",
"challenge",
"the",
"server",
"sends",
"at",
"this",
"address",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/gpgchallenge/gpg.go#L515-L532 | train |
perkeep/perkeep | pkg/gpgchallenge/gpg.go | Handler | func (cl *Client) Handler() (prefix string, h http.Handler) {
return clientHandlerPrefix, cl.handler
} | go | func (cl *Client) Handler() (prefix string, h http.Handler) {
return clientHandlerPrefix, cl.handler
} | [
"func",
"(",
"cl",
"*",
"Client",
")",
"Handler",
"(",
")",
"(",
"prefix",
"string",
",",
"h",
"http",
".",
"Handler",
")",
"{",
"return",
"clientHandlerPrefix",
",",
"cl",
".",
"handler",
"\n",
"}"
] | // Handler returns the client's handler, that should be registered with an HTTPS
// server for the returned prefix, for the client to be able to receive the
// challenge. | [
"Handler",
"returns",
"the",
"client",
"s",
"handler",
"that",
"should",
"be",
"registered",
"with",
"an",
"HTTPS",
"server",
"for",
"the",
"returned",
"prefix",
"for",
"the",
"client",
"to",
"be",
"able",
"to",
"receive",
"the",
"challenge",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/gpgchallenge/gpg.go#L537-L539 | train |
perkeep/perkeep | pkg/gpgchallenge/gpg.go | listenSelfCheck | func (cl *Client) listenSelfCheck(serverAddr string) error {
tr := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
ServerName: cl.challengeIP + SNISuffix,
},
}
httpClient := &http.Client{
Transport: tr,
}
errc := make(chan error, 1)
respc := make(chan *http.Response, 1)
var err error
var resp *http.Response
go func() {
resp, err := httpClient.PostForm(fmt.Sprintf("https://localhost:%d%s%s", ClientChallengedPort, clientHandlerPrefix, clientEndPointReady),
url.Values{"server": []string{serverAddr}})
errc <- err
respc <- resp
}()
timeout := time.NewTimer(time.Second)
defer timeout.Stop()
select {
case err = <-errc:
resp = <-respc
case <-timeout.C:
return errors.New("The client needs an HTTPS listener for its handler to answer the server's challenge. You need to call Handler and register the http.Handler with an HTTPS server, before calling Challenge.")
}
if err != nil {
return fmt.Errorf("error starting challenge: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusNoContent {
return fmt.Errorf("error starting challenge: %v", resp.Status)
}
return nil
} | go | func (cl *Client) listenSelfCheck(serverAddr string) error {
tr := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
ServerName: cl.challengeIP + SNISuffix,
},
}
httpClient := &http.Client{
Transport: tr,
}
errc := make(chan error, 1)
respc := make(chan *http.Response, 1)
var err error
var resp *http.Response
go func() {
resp, err := httpClient.PostForm(fmt.Sprintf("https://localhost:%d%s%s", ClientChallengedPort, clientHandlerPrefix, clientEndPointReady),
url.Values{"server": []string{serverAddr}})
errc <- err
respc <- resp
}()
timeout := time.NewTimer(time.Second)
defer timeout.Stop()
select {
case err = <-errc:
resp = <-respc
case <-timeout.C:
return errors.New("The client needs an HTTPS listener for its handler to answer the server's challenge. You need to call Handler and register the http.Handler with an HTTPS server, before calling Challenge.")
}
if err != nil {
return fmt.Errorf("error starting challenge: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusNoContent {
return fmt.Errorf("error starting challenge: %v", resp.Status)
}
return nil
} | [
"func",
"(",
"cl",
"*",
"Client",
")",
"listenSelfCheck",
"(",
"serverAddr",
"string",
")",
"error",
"{",
"tr",
":=",
"&",
"http",
".",
"Transport",
"{",
"TLSClientConfig",
":",
"&",
"tls",
".",
"Config",
"{",
"InsecureSkipVerify",
":",
"true",
",",
"ServerName",
":",
"cl",
".",
"challengeIP",
"+",
"SNISuffix",
",",
"}",
",",
"}",
"\n",
"httpClient",
":=",
"&",
"http",
".",
"Client",
"{",
"Transport",
":",
"tr",
",",
"}",
"\n",
"errc",
":=",
"make",
"(",
"chan",
"error",
",",
"1",
")",
"\n",
"respc",
":=",
"make",
"(",
"chan",
"*",
"http",
".",
"Response",
",",
"1",
")",
"\n",
"var",
"err",
"error",
"\n",
"var",
"resp",
"*",
"http",
".",
"Response",
"\n",
"go",
"func",
"(",
")",
"{",
"resp",
",",
"err",
":=",
"httpClient",
".",
"PostForm",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"https://localhost:%d%s%s\"",
",",
"ClientChallengedPort",
",",
"clientHandlerPrefix",
",",
"clientEndPointReady",
")",
",",
"url",
".",
"Values",
"{",
"\"server\"",
":",
"[",
"]",
"string",
"{",
"serverAddr",
"}",
"}",
")",
"\n",
"errc",
"<-",
"err",
"\n",
"respc",
"<-",
"resp",
"\n",
"}",
"(",
")",
"\n",
"timeout",
":=",
"time",
".",
"NewTimer",
"(",
"time",
".",
"Second",
")",
"\n",
"defer",
"timeout",
".",
"Stop",
"(",
")",
"\n",
"select",
"{",
"case",
"err",
"=",
"<-",
"errc",
":",
"resp",
"=",
"<-",
"respc",
"\n",
"case",
"<-",
"timeout",
".",
"C",
":",
"return",
"errors",
".",
"New",
"(",
"\"The client needs an HTTPS listener for its handler to answer the server's challenge. You need to call Handler and register the http.Handler with an HTTPS server, before calling Challenge.\"",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"error starting challenge: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"if",
"resp",
".",
"StatusCode",
"!=",
"http",
".",
"StatusNoContent",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"error starting challenge: %v\"",
",",
"resp",
".",
"Status",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // listenSelfCheck tests whether the client is ready to receive a challenge,
// i.e. that the caller has registered the client's handler with a server. | [
"listenSelfCheck",
"tests",
"whether",
"the",
"client",
"is",
"ready",
"to",
"receive",
"a",
"challenge",
"i",
".",
"e",
".",
"that",
"the",
"caller",
"has",
"registered",
"the",
"client",
"s",
"handler",
"with",
"a",
"server",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/gpgchallenge/gpg.go#L576-L612 | train |
perkeep/perkeep | pkg/blobserver/proxycache/proxycache.go | New | func New(maxBytes int64, cache, origin blobserver.Storage) *Storage {
sto := &Storage{
origin: origin,
cache: cache,
lru: lru.NewUnlocked(0),
maxCacheBytes: maxBytes,
}
return sto
} | go | func New(maxBytes int64, cache, origin blobserver.Storage) *Storage {
sto := &Storage{
origin: origin,
cache: cache,
lru: lru.NewUnlocked(0),
maxCacheBytes: maxBytes,
}
return sto
} | [
"func",
"New",
"(",
"maxBytes",
"int64",
",",
"cache",
",",
"origin",
"blobserver",
".",
"Storage",
")",
"*",
"Storage",
"{",
"sto",
":=",
"&",
"Storage",
"{",
"origin",
":",
"origin",
",",
"cache",
":",
"cache",
",",
"lru",
":",
"lru",
".",
"NewUnlocked",
"(",
"0",
")",
",",
"maxCacheBytes",
":",
"maxBytes",
",",
"}",
"\n",
"return",
"sto",
"\n",
"}"
] | // New returns a proxycache blob storage that reads from cache,
// then origin, populating cache as needed, up to a total of maxBytes. | [
"New",
"returns",
"a",
"proxycache",
"blob",
"storage",
"that",
"reads",
"from",
"cache",
"then",
"origin",
"populating",
"cache",
"as",
"needed",
"up",
"to",
"a",
"total",
"of",
"maxBytes",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/proxycache/proxycache.go#L77-L85 | train |
perkeep/perkeep | pkg/blobserver/proxycache/proxycache.go | removeOldest | func (sto *Storage) removeOldest() bool {
ctx := context.TODO()
k, v := sto.lru.RemoveOldest()
if v == nil {
return false
}
sb := v.(blob.SizedRef)
// TODO: run these without sto.mu held in background
// goroutine? at least pass a context?
err := sto.cache.RemoveBlobs(ctx, []blob.Ref{sb.Ref})
if err != nil {
log.Printf("proxycache: could not remove oldest blob %v (%d bytes): %v", sb.Ref, sb.Size, err)
sto.lru.Add(k, v)
return false
}
if sto.debug {
log.Printf("proxycache: removed blob %v (%d bytes)", sb.Ref, sb.Size)
}
sto.cacheBytes -= int64(sb.Size)
return true
} | go | func (sto *Storage) removeOldest() bool {
ctx := context.TODO()
k, v := sto.lru.RemoveOldest()
if v == nil {
return false
}
sb := v.(blob.SizedRef)
// TODO: run these without sto.mu held in background
// goroutine? at least pass a context?
err := sto.cache.RemoveBlobs(ctx, []blob.Ref{sb.Ref})
if err != nil {
log.Printf("proxycache: could not remove oldest blob %v (%d bytes): %v", sb.Ref, sb.Size, err)
sto.lru.Add(k, v)
return false
}
if sto.debug {
log.Printf("proxycache: removed blob %v (%d bytes)", sb.Ref, sb.Size)
}
sto.cacheBytes -= int64(sb.Size)
return true
} | [
"func",
"(",
"sto",
"*",
"Storage",
")",
"removeOldest",
"(",
")",
"bool",
"{",
"ctx",
":=",
"context",
".",
"TODO",
"(",
")",
"\n",
"k",
",",
"v",
":=",
"sto",
".",
"lru",
".",
"RemoveOldest",
"(",
")",
"\n",
"if",
"v",
"==",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"sb",
":=",
"v",
".",
"(",
"blob",
".",
"SizedRef",
")",
"\n",
"err",
":=",
"sto",
".",
"cache",
".",
"RemoveBlobs",
"(",
"ctx",
",",
"[",
"]",
"blob",
".",
"Ref",
"{",
"sb",
".",
"Ref",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"proxycache: could not remove oldest blob %v (%d bytes): %v\"",
",",
"sb",
".",
"Ref",
",",
"sb",
".",
"Size",
",",
"err",
")",
"\n",
"sto",
".",
"lru",
".",
"Add",
"(",
"k",
",",
"v",
")",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"if",
"sto",
".",
"debug",
"{",
"log",
".",
"Printf",
"(",
"\"proxycache: removed blob %v (%d bytes)\"",
",",
"sb",
".",
"Ref",
",",
"sb",
".",
"Size",
")",
"\n",
"}",
"\n",
"sto",
".",
"cacheBytes",
"-=",
"int64",
"(",
"sb",
".",
"Size",
")",
"\n",
"return",
"true",
"\n",
"}"
] | // must hold sto.mu.
// Reports whether an item was removed. | [
"must",
"hold",
"sto",
".",
"mu",
".",
"Reports",
"whether",
"an",
"item",
"was",
"removed",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/proxycache/proxycache.go#L113-L133 | train |
perkeep/perkeep | server/perkeepd/ui/goui/dirchildren/dirchildren.go | New | func New(authToken, parentDir string, limit int,
updadeSearchSession func(string), triggerRender func()) *js.Object {
parentDirbr, ok := blob.Parse(parentDir)
if !ok {
dom.GetWindow().Alert(fmt.Sprintf("invalid parentDir blobRef: %q", parentDir))
return nil
}
return js.MakeWrapper(&Query{
ParentDir: parentDirbr,
AuthToken: authToken,
UpdateSearchSession: updadeSearchSession,
TriggerRender: triggerRender,
Limit: limit,
})
} | go | func New(authToken, parentDir string, limit int,
updadeSearchSession func(string), triggerRender func()) *js.Object {
parentDirbr, ok := blob.Parse(parentDir)
if !ok {
dom.GetWindow().Alert(fmt.Sprintf("invalid parentDir blobRef: %q", parentDir))
return nil
}
return js.MakeWrapper(&Query{
ParentDir: parentDirbr,
AuthToken: authToken,
UpdateSearchSession: updadeSearchSession,
TriggerRender: triggerRender,
Limit: limit,
})
} | [
"func",
"New",
"(",
"authToken",
",",
"parentDir",
"string",
",",
"limit",
"int",
",",
"updadeSearchSession",
"func",
"(",
"string",
")",
",",
"triggerRender",
"func",
"(",
")",
")",
"*",
"js",
".",
"Object",
"{",
"parentDirbr",
",",
"ok",
":=",
"blob",
".",
"Parse",
"(",
"parentDir",
")",
"\n",
"if",
"!",
"ok",
"{",
"dom",
".",
"GetWindow",
"(",
")",
".",
"Alert",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"invalid parentDir blobRef: %q\"",
",",
"parentDir",
")",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"js",
".",
"MakeWrapper",
"(",
"&",
"Query",
"{",
"ParentDir",
":",
"parentDirbr",
",",
"AuthToken",
":",
"authToken",
",",
"UpdateSearchSession",
":",
"updadeSearchSession",
",",
"TriggerRender",
":",
"triggerRender",
",",
"Limit",
":",
"limit",
",",
"}",
")",
"\n",
"}"
] | // New returns a new Query as a javascript object, of nil if parentDir is not a
// valid blobRef. | [
"New",
"returns",
"a",
"new",
"Query",
"as",
"a",
"javascript",
"object",
"of",
"nil",
"if",
"parentDir",
"is",
"not",
"a",
"valid",
"blobRef",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/server/perkeepd/ui/goui/dirchildren/dirchildren.go#L72-L86 | train |
perkeep/perkeep | server/perkeepd/ui/goui/dirchildren/dirchildren.go | Get | func (q *Query) Get() {
if q.isComplete {
return
}
if q.pending {
return
}
q.pending = true
go func() {
if err := q.get(); err != nil {
dom.GetWindow().Alert(fmt.Sprintf("%v", err))
return
}
q.TriggerRender()
}()
} | go | func (q *Query) Get() {
if q.isComplete {
return
}
if q.pending {
return
}
q.pending = true
go func() {
if err := q.get(); err != nil {
dom.GetWindow().Alert(fmt.Sprintf("%v", err))
return
}
q.TriggerRender()
}()
} | [
"func",
"(",
"q",
"*",
"Query",
")",
"Get",
"(",
")",
"{",
"if",
"q",
".",
"isComplete",
"{",
"return",
"\n",
"}",
"\n",
"if",
"q",
".",
"pending",
"{",
"return",
"\n",
"}",
"\n",
"q",
".",
"pending",
"=",
"true",
"\n",
"go",
"func",
"(",
")",
"{",
"if",
"err",
":=",
"q",
".",
"get",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"dom",
".",
"GetWindow",
"(",
")",
".",
"Alert",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"%v\"",
",",
"err",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"q",
".",
"TriggerRender",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"}"
] | // Get asynchronously sends the query, if one is not already in flight, or being
// processed. It runs q.UpdateSearchSession once the results have been received and
// merged with q.Blobs and q.Meta. It runs q.TriggerRender to refresh the DOM with
// the new results in the search session. | [
"Get",
"asynchronously",
"sends",
"the",
"query",
"if",
"one",
"is",
"not",
"already",
"in",
"flight",
"or",
"being",
"processed",
".",
"It",
"runs",
"q",
".",
"UpdateSearchSession",
"once",
"the",
"results",
"have",
"been",
"received",
"and",
"merged",
"with",
"q",
".",
"Blobs",
"and",
"q",
".",
"Meta",
".",
"It",
"runs",
"q",
".",
"TriggerRender",
"to",
"refresh",
"the",
"DOM",
"with",
"the",
"new",
"results",
"in",
"the",
"search",
"session",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/server/perkeepd/ui/goui/dirchildren/dirchildren.go#L114-L129 | train |
perkeep/perkeep | pkg/sorted/mysql/mysqlkv.go | newKVDB | func newKVDB(cfg jsonconfig.Obj) (sorted.KeyValue, error) {
var (
user = cfg.RequiredString("user")
database = cfg.RequiredString("database")
host = cfg.OptionalString("host", "")
password = cfg.OptionalString("password", "")
)
if err := cfg.Validate(); err != nil {
return nil, err
}
if !validDatabaseName(database) {
return nil, fmt.Errorf("%q looks like an invalid database name", database)
}
var err error
if host != "" {
host, err = maybeRemapCloudSQL(host)
if err != nil {
return nil, err
}
if !strings.Contains(host, ":") {
host += ":3306"
}
host = "tcp(" + host + ")"
}
// The DSN does NOT have a database name in it so it's
// cacheable and can be shared between different queues & the
// index, all sharing the same database server, cutting down
// number of TCP connections required. We add the database
// name in queries instead.
dsn := fmt.Sprintf("%s:%s@%s/", user, password, host)
db, err := openOrCachedDB(dsn)
if err != nil {
return nil, err
}
if err := CreateDB(db, database); err != nil {
return nil, err
}
return &keyValue{
database: database,
dsn: dsn,
db: db,
KeyValue: &sqlkv.KeyValue{
DB: db,
TablePrefix: database + ".",
Gate: syncutil.NewGate(20), // arbitrary limit. TODO: configurable, automatically-learned?
},
}, nil
} | go | func newKVDB(cfg jsonconfig.Obj) (sorted.KeyValue, error) {
var (
user = cfg.RequiredString("user")
database = cfg.RequiredString("database")
host = cfg.OptionalString("host", "")
password = cfg.OptionalString("password", "")
)
if err := cfg.Validate(); err != nil {
return nil, err
}
if !validDatabaseName(database) {
return nil, fmt.Errorf("%q looks like an invalid database name", database)
}
var err error
if host != "" {
host, err = maybeRemapCloudSQL(host)
if err != nil {
return nil, err
}
if !strings.Contains(host, ":") {
host += ":3306"
}
host = "tcp(" + host + ")"
}
// The DSN does NOT have a database name in it so it's
// cacheable and can be shared between different queues & the
// index, all sharing the same database server, cutting down
// number of TCP connections required. We add the database
// name in queries instead.
dsn := fmt.Sprintf("%s:%s@%s/", user, password, host)
db, err := openOrCachedDB(dsn)
if err != nil {
return nil, err
}
if err := CreateDB(db, database); err != nil {
return nil, err
}
return &keyValue{
database: database,
dsn: dsn,
db: db,
KeyValue: &sqlkv.KeyValue{
DB: db,
TablePrefix: database + ".",
Gate: syncutil.NewGate(20), // arbitrary limit. TODO: configurable, automatically-learned?
},
}, nil
} | [
"func",
"newKVDB",
"(",
"cfg",
"jsonconfig",
".",
"Obj",
")",
"(",
"sorted",
".",
"KeyValue",
",",
"error",
")",
"{",
"var",
"(",
"user",
"=",
"cfg",
".",
"RequiredString",
"(",
"\"user\"",
")",
"\n",
"database",
"=",
"cfg",
".",
"RequiredString",
"(",
"\"database\"",
")",
"\n",
"host",
"=",
"cfg",
".",
"OptionalString",
"(",
"\"host\"",
",",
"\"\"",
")",
"\n",
"password",
"=",
"cfg",
".",
"OptionalString",
"(",
"\"password\"",
",",
"\"\"",
")",
"\n",
")",
"\n",
"if",
"err",
":=",
"cfg",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"!",
"validDatabaseName",
"(",
"database",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"%q looks like an invalid database name\"",
",",
"database",
")",
"\n",
"}",
"\n",
"var",
"err",
"error",
"\n",
"if",
"host",
"!=",
"\"\"",
"{",
"host",
",",
"err",
"=",
"maybeRemapCloudSQL",
"(",
"host",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"!",
"strings",
".",
"Contains",
"(",
"host",
",",
"\":\"",
")",
"{",
"host",
"+=",
"\":3306\"",
"\n",
"}",
"\n",
"host",
"=",
"\"tcp(\"",
"+",
"host",
"+",
"\")\"",
"\n",
"}",
"\n",
"dsn",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%s:%s@%s/\"",
",",
"user",
",",
"password",
",",
"host",
")",
"\n",
"db",
",",
"err",
":=",
"openOrCachedDB",
"(",
"dsn",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"CreateDB",
"(",
"db",
",",
"database",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"keyValue",
"{",
"database",
":",
"database",
",",
"dsn",
":",
"dsn",
",",
"db",
":",
"db",
",",
"KeyValue",
":",
"&",
"sqlkv",
".",
"KeyValue",
"{",
"DB",
":",
"db",
",",
"TablePrefix",
":",
"database",
"+",
"\".\"",
",",
"Gate",
":",
"syncutil",
".",
"NewGate",
"(",
"20",
")",
",",
"}",
",",
"}",
",",
"nil",
"\n",
"}"
] | // newKVDB returns an unusable KeyValue, with a database, but no tables yet. It
// should be followed by Wipe or finalize. | [
"newKVDB",
"returns",
"an",
"unusable",
"KeyValue",
"with",
"a",
"database",
"but",
"no",
"tables",
"yet",
".",
"It",
"should",
"be",
"followed",
"by",
"Wipe",
"or",
"finalize",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/sorted/mysql/mysqlkv.go#L45-L94 | train |
perkeep/perkeep | pkg/sorted/mysql/mysqlkv.go | Wipe | func (kv *keyValue) Wipe() error {
if _, err := kv.db.Exec("DROP TABLE IF EXISTS " + kv.database + ".rows"); err != nil {
return err
}
if _, err := kv.db.Exec("DROP TABLE IF EXISTS " + kv.database + ".meta"); err != nil {
return err
}
return kv.finalize()
} | go | func (kv *keyValue) Wipe() error {
if _, err := kv.db.Exec("DROP TABLE IF EXISTS " + kv.database + ".rows"); err != nil {
return err
}
if _, err := kv.db.Exec("DROP TABLE IF EXISTS " + kv.database + ".meta"); err != nil {
return err
}
return kv.finalize()
} | [
"func",
"(",
"kv",
"*",
"keyValue",
")",
"Wipe",
"(",
")",
"error",
"{",
"if",
"_",
",",
"err",
":=",
"kv",
".",
"db",
".",
"Exec",
"(",
"\"DROP TABLE IF EXISTS \"",
"+",
"kv",
".",
"database",
"+",
"\".rows\"",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"kv",
".",
"db",
".",
"Exec",
"(",
"\"DROP TABLE IF EXISTS \"",
"+",
"kv",
".",
"database",
"+",
"\".meta\"",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"kv",
".",
"finalize",
"(",
")",
"\n",
"}"
] | // Wipe resets the KeyValue by dropping and recreating the database tables. | [
"Wipe",
"resets",
"the",
"KeyValue",
"by",
"dropping",
"and",
"recreating",
"the",
"database",
"tables",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/sorted/mysql/mysqlkv.go#L97-L105 | train |
perkeep/perkeep | pkg/sorted/mysql/mysqlkv.go | finalize | func (kv *keyValue) finalize() error {
if err := createTables(kv.db, kv.database); err != nil {
return err
}
if err := kv.ping(); err != nil {
return fmt.Errorf("MySQL db unreachable: %v", err)
}
version, err := kv.SchemaVersion()
if err != nil {
return fmt.Errorf("error getting current database schema version: %v", err)
}
if version == 0 {
// Newly created table case
if _, err := kv.db.Exec(fmt.Sprintf(`REPLACE INTO %s.meta VALUES ('version', ?)`, kv.database), requiredSchemaVersion); err != nil {
return fmt.Errorf("error setting schema version: %v", err)
}
return nil
}
if version != requiredSchemaVersion {
if version == 20 && requiredSchemaVersion == 21 {
fmt.Fprintf(os.Stderr, fixSchema20to21)
}
if env.IsDev() {
// Good signal that we're using the devcam server, so help out
// the user with a more useful tip:
return sorted.NeedWipeError{
Msg: fmt.Sprintf("database schema version is %d; expect %d (run \"devcam server --wipe\" to wipe both your blobs and re-populate the database schema)", version, requiredSchemaVersion),
}
}
return sorted.NeedWipeError{
Msg: fmt.Sprintf("database schema version is %d; expect %d (need to re-init/upgrade database?)",
version, requiredSchemaVersion),
}
}
return nil
} | go | func (kv *keyValue) finalize() error {
if err := createTables(kv.db, kv.database); err != nil {
return err
}
if err := kv.ping(); err != nil {
return fmt.Errorf("MySQL db unreachable: %v", err)
}
version, err := kv.SchemaVersion()
if err != nil {
return fmt.Errorf("error getting current database schema version: %v", err)
}
if version == 0 {
// Newly created table case
if _, err := kv.db.Exec(fmt.Sprintf(`REPLACE INTO %s.meta VALUES ('version', ?)`, kv.database), requiredSchemaVersion); err != nil {
return fmt.Errorf("error setting schema version: %v", err)
}
return nil
}
if version != requiredSchemaVersion {
if version == 20 && requiredSchemaVersion == 21 {
fmt.Fprintf(os.Stderr, fixSchema20to21)
}
if env.IsDev() {
// Good signal that we're using the devcam server, so help out
// the user with a more useful tip:
return sorted.NeedWipeError{
Msg: fmt.Sprintf("database schema version is %d; expect %d (run \"devcam server --wipe\" to wipe both your blobs and re-populate the database schema)", version, requiredSchemaVersion),
}
}
return sorted.NeedWipeError{
Msg: fmt.Sprintf("database schema version is %d; expect %d (need to re-init/upgrade database?)",
version, requiredSchemaVersion),
}
}
return nil
} | [
"func",
"(",
"kv",
"*",
"keyValue",
")",
"finalize",
"(",
")",
"error",
"{",
"if",
"err",
":=",
"createTables",
"(",
"kv",
".",
"db",
",",
"kv",
".",
"database",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"kv",
".",
"ping",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"MySQL db unreachable: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"version",
",",
"err",
":=",
"kv",
".",
"SchemaVersion",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"error getting current database schema version: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"version",
"==",
"0",
"{",
"if",
"_",
",",
"err",
":=",
"kv",
".",
"db",
".",
"Exec",
"(",
"fmt",
".",
"Sprintf",
"(",
"`REPLACE INTO %s.meta VALUES ('version', ?)`",
",",
"kv",
".",
"database",
")",
",",
"requiredSchemaVersion",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"error setting schema version: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"version",
"!=",
"requiredSchemaVersion",
"{",
"if",
"version",
"==",
"20",
"&&",
"requiredSchemaVersion",
"==",
"21",
"{",
"fmt",
".",
"Fprintf",
"(",
"os",
".",
"Stderr",
",",
"fixSchema20to21",
")",
"\n",
"}",
"\n",
"if",
"env",
".",
"IsDev",
"(",
")",
"{",
"return",
"sorted",
".",
"NeedWipeError",
"{",
"Msg",
":",
"fmt",
".",
"Sprintf",
"(",
"\"database schema version is %d; expect %d (run \\\"devcam server --wipe\\\" to wipe both your blobs and re-populate the database schema)\"",
",",
"\\\"",
",",
"\\\"",
")",
",",
"}",
"\n",
"}",
"\n",
"version",
"\n",
"}",
"\n",
"requiredSchemaVersion",
"\n",
"}"
] | // finalize should be called on a keyValue initialized with newKVDB. | [
"finalize",
"should",
"be",
"called",
"on",
"a",
"keyValue",
"initialized",
"with",
"newKVDB",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/sorted/mysql/mysqlkv.go#L108-L146 | train |
perkeep/perkeep | pkg/sorted/mysql/mysqlkv.go | CreateDB | func CreateDB(db *sql.DB, dbname string) error {
if dbname == "" {
return errors.New("can not create database: database name is missing")
}
if _, err := db.Exec(fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s", dbname)); err != nil {
return fmt.Errorf("error creating database %v: %v", dbname, err)
}
return nil
} | go | func CreateDB(db *sql.DB, dbname string) error {
if dbname == "" {
return errors.New("can not create database: database name is missing")
}
if _, err := db.Exec(fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s", dbname)); err != nil {
return fmt.Errorf("error creating database %v: %v", dbname, err)
}
return nil
} | [
"func",
"CreateDB",
"(",
"db",
"*",
"sql",
".",
"DB",
",",
"dbname",
"string",
")",
"error",
"{",
"if",
"dbname",
"==",
"\"\"",
"{",
"return",
"errors",
".",
"New",
"(",
"\"can not create database: database name is missing\"",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"CREATE DATABASE IF NOT EXISTS %s\"",
",",
"dbname",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"error creating database %v: %v\"",
",",
"dbname",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // CreateDB creates the named database if it does not already exist. | [
"CreateDB",
"creates",
"the",
"named",
"database",
"if",
"it",
"does",
"not",
"already",
"exist",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/sorted/mysql/mysqlkv.go#L164-L172 | train |
perkeep/perkeep | pkg/sorted/mysql/mysqlkv.go | Close | func (kv *keyValue) Close() error {
dbsmu.Lock()
defer dbsmu.Unlock()
delete(dbs, kv.dsn)
return kv.DB.Close()
} | go | func (kv *keyValue) Close() error {
dbsmu.Lock()
defer dbsmu.Unlock()
delete(dbs, kv.dsn)
return kv.DB.Close()
} | [
"func",
"(",
"kv",
"*",
"keyValue",
")",
"Close",
"(",
")",
"error",
"{",
"dbsmu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"dbsmu",
".",
"Unlock",
"(",
")",
"\n",
"delete",
"(",
"dbs",
",",
"kv",
".",
"dsn",
")",
"\n",
"return",
"kv",
".",
"DB",
".",
"Close",
"(",
")",
"\n",
"}"
] | // Close overrides KeyValue.Close because we need to remove the DB from the pool
// when closing. | [
"Close",
"overrides",
"KeyValue",
".",
"Close",
"because",
"we",
"need",
"to",
"remove",
"the",
"DB",
"from",
"the",
"pool",
"when",
"closing",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/sorted/mysql/mysqlkv.go#L223-L228 | train |
perkeep/perkeep | website/pk-web/email.go | emailOnTimeout | func emailOnTimeout(fnName string, d time.Duration, fn func() error) error {
c := make(chan error, 1)
go func() {
c <- fn()
}()
select {
case <-time.After(d):
log.Printf("timeout for %s, sending e-mail about it", fnName)
m := mailGun.NewMessage(
"noreply@perkeep.org",
"timeout for docker on pk-web",
"Because "+fnName+" is stuck.",
"mathieu.lonjaret@gmail.com",
)
if _, _, err := mailGun.Send(m); err != nil {
return fmt.Errorf("failed to send docker restart e-mail: %v", err)
}
return nil
case err := <-c:
return err
}
} | go | func emailOnTimeout(fnName string, d time.Duration, fn func() error) error {
c := make(chan error, 1)
go func() {
c <- fn()
}()
select {
case <-time.After(d):
log.Printf("timeout for %s, sending e-mail about it", fnName)
m := mailGun.NewMessage(
"noreply@perkeep.org",
"timeout for docker on pk-web",
"Because "+fnName+" is stuck.",
"mathieu.lonjaret@gmail.com",
)
if _, _, err := mailGun.Send(m); err != nil {
return fmt.Errorf("failed to send docker restart e-mail: %v", err)
}
return nil
case err := <-c:
return err
}
} | [
"func",
"emailOnTimeout",
"(",
"fnName",
"string",
",",
"d",
"time",
".",
"Duration",
",",
"fn",
"func",
"(",
")",
"error",
")",
"error",
"{",
"c",
":=",
"make",
"(",
"chan",
"error",
",",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"c",
"<-",
"fn",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"select",
"{",
"case",
"<-",
"time",
".",
"After",
"(",
"d",
")",
":",
"log",
".",
"Printf",
"(",
"\"timeout for %s, sending e-mail about it\"",
",",
"fnName",
")",
"\n",
"m",
":=",
"mailGun",
".",
"NewMessage",
"(",
"\"noreply@perkeep.org\"",
",",
"\"timeout for docker on pk-web\"",
",",
"\"Because \"",
"+",
"fnName",
"+",
"\" is stuck.\"",
",",
"\"mathieu.lonjaret@gmail.com\"",
",",
")",
"\n",
"if",
"_",
",",
"_",
",",
"err",
":=",
"mailGun",
".",
"Send",
"(",
"m",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"failed to send docker restart e-mail: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"case",
"err",
":=",
"<-",
"c",
":",
"return",
"err",
"\n",
"}",
"\n",
"}"
] | // emailOnTimeout runs fn in a goroutine. If fn is not done after d,
// a message about fnName is logged, and an e-mail about it is sent. | [
"emailOnTimeout",
"runs",
"fn",
"in",
"a",
"goroutine",
".",
"If",
"fn",
"is",
"not",
"done",
"after",
"d",
"a",
"message",
"about",
"fnName",
"is",
"logged",
"and",
"an",
"e",
"-",
"mail",
"about",
"it",
"is",
"sent",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/website/pk-web/email.go#L207-L228 | train |
perkeep/perkeep | pkg/blobserver/files/files.go | u32 | func u32(n int64) uint32 {
if n < 0 || n > math.MaxUint32 {
panic("bad size " + fmt.Sprint(n))
}
return uint32(n)
} | go | func u32(n int64) uint32 {
if n < 0 || n > math.MaxUint32 {
panic("bad size " + fmt.Sprint(n))
}
return uint32(n)
} | [
"func",
"u32",
"(",
"n",
"int64",
")",
"uint32",
"{",
"if",
"n",
"<",
"0",
"||",
"n",
">",
"math",
".",
"MaxUint32",
"{",
"panic",
"(",
"\"bad size \"",
"+",
"fmt",
".",
"Sprint",
"(",
"n",
")",
")",
"\n",
"}",
"\n",
"return",
"uint32",
"(",
"n",
")",
"\n",
"}"
] | // u32 converts n to an uint32, or panics if n is out of range | [
"u32",
"converts",
"n",
"to",
"an",
"uint32",
"or",
"panics",
"if",
"n",
"is",
"out",
"of",
"range"
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/files/files.go#L131-L136 | train |
perkeep/perkeep | pkg/blobserver/files/files.go | fetch | func (ds *Storage) fetch(ctx context.Context, br blob.Ref, offset, length int64) (rc io.ReadCloser, size uint32, err error) {
// TODO: use ctx, if the os package ever supports that.
fileName := ds.blobPath(br)
stat, err := ds.fs.Stat(fileName)
if os.IsNotExist(err) {
return nil, 0, os.ErrNotExist
}
size = u32(stat.Size())
file, err := ds.fs.Open(fileName)
if err != nil {
if os.IsNotExist(err) {
err = os.ErrNotExist
}
return nil, 0, err
}
// normal Fetch
if length < 0 && offset == 0 {
return file, size, nil
}
// SubFetch:
if offset < 0 || offset > stat.Size() {
if offset < 0 {
return nil, 0, blob.ErrNegativeSubFetch
}
return nil, 0, blob.ErrOutOfRangeOffsetSubFetch
}
if offset != 0 {
if at, err := file.Seek(offset, io.SeekStart); err != nil || at != offset {
file.Close()
return nil, 0, fmt.Errorf("localdisk: error seeking to %d: got %v, %v", offset, at, err)
}
}
return struct {
io.Reader
io.Closer
}{
Reader: io.LimitReader(file, length),
Closer: file,
}, 0 /* unused */, nil
} | go | func (ds *Storage) fetch(ctx context.Context, br blob.Ref, offset, length int64) (rc io.ReadCloser, size uint32, err error) {
// TODO: use ctx, if the os package ever supports that.
fileName := ds.blobPath(br)
stat, err := ds.fs.Stat(fileName)
if os.IsNotExist(err) {
return nil, 0, os.ErrNotExist
}
size = u32(stat.Size())
file, err := ds.fs.Open(fileName)
if err != nil {
if os.IsNotExist(err) {
err = os.ErrNotExist
}
return nil, 0, err
}
// normal Fetch
if length < 0 && offset == 0 {
return file, size, nil
}
// SubFetch:
if offset < 0 || offset > stat.Size() {
if offset < 0 {
return nil, 0, blob.ErrNegativeSubFetch
}
return nil, 0, blob.ErrOutOfRangeOffsetSubFetch
}
if offset != 0 {
if at, err := file.Seek(offset, io.SeekStart); err != nil || at != offset {
file.Close()
return nil, 0, fmt.Errorf("localdisk: error seeking to %d: got %v, %v", offset, at, err)
}
}
return struct {
io.Reader
io.Closer
}{
Reader: io.LimitReader(file, length),
Closer: file,
}, 0 /* unused */, nil
} | [
"func",
"(",
"ds",
"*",
"Storage",
")",
"fetch",
"(",
"ctx",
"context",
".",
"Context",
",",
"br",
"blob",
".",
"Ref",
",",
"offset",
",",
"length",
"int64",
")",
"(",
"rc",
"io",
".",
"ReadCloser",
",",
"size",
"uint32",
",",
"err",
"error",
")",
"{",
"fileName",
":=",
"ds",
".",
"blobPath",
"(",
"br",
")",
"\n",
"stat",
",",
"err",
":=",
"ds",
".",
"fs",
".",
"Stat",
"(",
"fileName",
")",
"\n",
"if",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"nil",
",",
"0",
",",
"os",
".",
"ErrNotExist",
"\n",
"}",
"\n",
"size",
"=",
"u32",
"(",
"stat",
".",
"Size",
"(",
")",
")",
"\n",
"file",
",",
"err",
":=",
"ds",
".",
"fs",
".",
"Open",
"(",
"fileName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"err",
"=",
"os",
".",
"ErrNotExist",
"\n",
"}",
"\n",
"return",
"nil",
",",
"0",
",",
"err",
"\n",
"}",
"\n",
"if",
"length",
"<",
"0",
"&&",
"offset",
"==",
"0",
"{",
"return",
"file",
",",
"size",
",",
"nil",
"\n",
"}",
"\n",
"if",
"offset",
"<",
"0",
"||",
"offset",
">",
"stat",
".",
"Size",
"(",
")",
"{",
"if",
"offset",
"<",
"0",
"{",
"return",
"nil",
",",
"0",
",",
"blob",
".",
"ErrNegativeSubFetch",
"\n",
"}",
"\n",
"return",
"nil",
",",
"0",
",",
"blob",
".",
"ErrOutOfRangeOffsetSubFetch",
"\n",
"}",
"\n",
"if",
"offset",
"!=",
"0",
"{",
"if",
"at",
",",
"err",
":=",
"file",
".",
"Seek",
"(",
"offset",
",",
"io",
".",
"SeekStart",
")",
";",
"err",
"!=",
"nil",
"||",
"at",
"!=",
"offset",
"{",
"file",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"localdisk: error seeking to %d: got %v, %v\"",
",",
"offset",
",",
"at",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"struct",
"{",
"io",
".",
"Reader",
"\n",
"io",
".",
"Closer",
"\n",
"}",
"{",
"Reader",
":",
"io",
".",
"LimitReader",
"(",
"file",
",",
"length",
")",
",",
"Closer",
":",
"file",
",",
"}",
",",
"0",
",",
"nil",
"\n",
"}"
] | // length -1 means entire file | [
"length",
"-",
"1",
"means",
"entire",
"file"
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/files/files.go#L139-L178 | train |
perkeep/perkeep | pkg/client/config.go | AddFlags | func AddFlags() {
defaultPath := "/x/y/z/we're/in-a-test"
if !buildinfo.TestingLinked() {
defaultPath = osutil.UserClientConfigPath()
}
flag.StringVar(&flagServer, "server", "", "Perkeep server prefix. If blank, the default from the \"server\" field of "+defaultPath+" is used. Acceptable forms: https://you.example.com, example.com:1345 (https assumed), or http://you.example.com/alt-root")
osutil.AddSecretRingFlag()
} | go | func AddFlags() {
defaultPath := "/x/y/z/we're/in-a-test"
if !buildinfo.TestingLinked() {
defaultPath = osutil.UserClientConfigPath()
}
flag.StringVar(&flagServer, "server", "", "Perkeep server prefix. If blank, the default from the \"server\" field of "+defaultPath+" is used. Acceptable forms: https://you.example.com, example.com:1345 (https assumed), or http://you.example.com/alt-root")
osutil.AddSecretRingFlag()
} | [
"func",
"AddFlags",
"(",
")",
"{",
"defaultPath",
":=",
"\"/x/y/z/we're/in-a-test\"",
"\n",
"if",
"!",
"buildinfo",
".",
"TestingLinked",
"(",
")",
"{",
"defaultPath",
"=",
"osutil",
".",
"UserClientConfigPath",
"(",
")",
"\n",
"}",
"\n",
"flag",
".",
"StringVar",
"(",
"&",
"flagServer",
",",
"\"server\"",
",",
"\"\"",
",",
"\"Perkeep server prefix. If blank, the default from the \\\"server\\\" field of \"",
"+",
"\\\"",
"+",
"\\\"",
")",
"\n",
"defaultPath",
"\n",
"}"
] | // AddFlags registers the "server" and "secret-keyring" string flags. | [
"AddFlags",
"registers",
"the",
"server",
"and",
"secret",
"-",
"keyring",
"string",
"flags",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/config.go#L52-L59 | train |
perkeep/perkeep | pkg/client/config.go | parseConfig | func (c *Client) parseConfig() {
if android.OnAndroid() {
panic("parseConfig should never have been called on Android")
}
if configDisabled {
panic("parseConfig should never have been called with CAMLI_DISABLE_CLIENT_CONFIG_FILE set")
}
configPath := osutil.UserClientConfigPath()
if _, err := wkfs.Stat(configPath); os.IsNotExist(err) {
if c != nil && c.isSharePrefix {
return
}
errMsg := fmt.Sprintf("Client configuration file %v does not exist. See 'pk-put init' to generate it.", configPath)
if keyID := serverKeyId(); keyID != "" {
hint := fmt.Sprintf("\nThe key id %v was found in the server config %v, so you might want:\n'pk-put init -gpgkey %v'", keyID, osutil.UserServerConfigPath(), keyID)
errMsg += hint
}
log.Fatal(errMsg)
}
// TODO: instead of using jsonconfig, we could read the file,
// and unmarshal into the structs that we now have in
// pkg/types/clientconfig. But we'll have to add the old
// fields (before the name changes, and before the
// multi-servers change) to the structs as well for our
// graceful conversion/error messages to work.
conf, err := osutil.NewJSONConfigParser().ReadFile(configPath)
if err != nil {
log.Fatal(err.Error())
}
cfg := jsonconfig.Obj(conf)
if singleServerAuth := cfg.OptionalString("auth", ""); singleServerAuth != "" {
newConf, err := convertToMultiServers(cfg)
if err != nil {
log.Print(err)
} else {
cfg = newConf
}
}
config = &clientconfig.Config{
Identity: cfg.OptionalString("identity", ""),
IdentitySecretRing: cfg.OptionalString("identitySecretRing", ""),
IgnoredFiles: cfg.OptionalList("ignoredFiles"),
}
serversList := make(map[string]*clientconfig.Server)
servers := cfg.OptionalObject("servers")
for alias, vei := range servers {
// An alias should never be confused with a host name,
// so we forbid anything looking like one.
if isURLOrHostPort(alias) {
log.Fatalf("Server alias %q looks like a hostname; \".\" or \";\" are not allowed.", alias)
}
serverMap, ok := vei.(map[string]interface{})
if !ok {
log.Fatalf("entry %q in servers section is a %T, want an object", alias, vei)
}
serverConf := jsonconfig.Obj(serverMap)
serverStr, err := cleanServer(serverConf.OptionalString("server", ""))
if err != nil {
log.Fatalf("invalid server alias %q: %v", alias, err)
}
server := &clientconfig.Server{
Server: serverStr,
Auth: serverConf.OptionalString("auth", ""),
IsDefault: serverConf.OptionalBool("default", false),
TrustedCerts: serverConf.OptionalList("trustedCerts"),
}
if err := serverConf.Validate(); err != nil {
log.Fatalf("Error in servers section of config file for server %q: %v", alias, err)
}
serversList[alias] = server
}
config.Servers = serversList
if err := cfg.Validate(); err != nil {
printConfigChangeHelp(cfg)
log.Fatalf("Error in config file: %v", err)
}
} | go | func (c *Client) parseConfig() {
if android.OnAndroid() {
panic("parseConfig should never have been called on Android")
}
if configDisabled {
panic("parseConfig should never have been called with CAMLI_DISABLE_CLIENT_CONFIG_FILE set")
}
configPath := osutil.UserClientConfigPath()
if _, err := wkfs.Stat(configPath); os.IsNotExist(err) {
if c != nil && c.isSharePrefix {
return
}
errMsg := fmt.Sprintf("Client configuration file %v does not exist. See 'pk-put init' to generate it.", configPath)
if keyID := serverKeyId(); keyID != "" {
hint := fmt.Sprintf("\nThe key id %v was found in the server config %v, so you might want:\n'pk-put init -gpgkey %v'", keyID, osutil.UserServerConfigPath(), keyID)
errMsg += hint
}
log.Fatal(errMsg)
}
// TODO: instead of using jsonconfig, we could read the file,
// and unmarshal into the structs that we now have in
// pkg/types/clientconfig. But we'll have to add the old
// fields (before the name changes, and before the
// multi-servers change) to the structs as well for our
// graceful conversion/error messages to work.
conf, err := osutil.NewJSONConfigParser().ReadFile(configPath)
if err != nil {
log.Fatal(err.Error())
}
cfg := jsonconfig.Obj(conf)
if singleServerAuth := cfg.OptionalString("auth", ""); singleServerAuth != "" {
newConf, err := convertToMultiServers(cfg)
if err != nil {
log.Print(err)
} else {
cfg = newConf
}
}
config = &clientconfig.Config{
Identity: cfg.OptionalString("identity", ""),
IdentitySecretRing: cfg.OptionalString("identitySecretRing", ""),
IgnoredFiles: cfg.OptionalList("ignoredFiles"),
}
serversList := make(map[string]*clientconfig.Server)
servers := cfg.OptionalObject("servers")
for alias, vei := range servers {
// An alias should never be confused with a host name,
// so we forbid anything looking like one.
if isURLOrHostPort(alias) {
log.Fatalf("Server alias %q looks like a hostname; \".\" or \";\" are not allowed.", alias)
}
serverMap, ok := vei.(map[string]interface{})
if !ok {
log.Fatalf("entry %q in servers section is a %T, want an object", alias, vei)
}
serverConf := jsonconfig.Obj(serverMap)
serverStr, err := cleanServer(serverConf.OptionalString("server", ""))
if err != nil {
log.Fatalf("invalid server alias %q: %v", alias, err)
}
server := &clientconfig.Server{
Server: serverStr,
Auth: serverConf.OptionalString("auth", ""),
IsDefault: serverConf.OptionalBool("default", false),
TrustedCerts: serverConf.OptionalList("trustedCerts"),
}
if err := serverConf.Validate(); err != nil {
log.Fatalf("Error in servers section of config file for server %q: %v", alias, err)
}
serversList[alias] = server
}
config.Servers = serversList
if err := cfg.Validate(); err != nil {
printConfigChangeHelp(cfg)
log.Fatalf("Error in config file: %v", err)
}
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"parseConfig",
"(",
")",
"{",
"if",
"android",
".",
"OnAndroid",
"(",
")",
"{",
"panic",
"(",
"\"parseConfig should never have been called on Android\"",
")",
"\n",
"}",
"\n",
"if",
"configDisabled",
"{",
"panic",
"(",
"\"parseConfig should never have been called with CAMLI_DISABLE_CLIENT_CONFIG_FILE set\"",
")",
"\n",
"}",
"\n",
"configPath",
":=",
"osutil",
".",
"UserClientConfigPath",
"(",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"wkfs",
".",
"Stat",
"(",
"configPath",
")",
";",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"if",
"c",
"!=",
"nil",
"&&",
"c",
".",
"isSharePrefix",
"{",
"return",
"\n",
"}",
"\n",
"errMsg",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"Client configuration file %v does not exist. See 'pk-put init' to generate it.\"",
",",
"configPath",
")",
"\n",
"if",
"keyID",
":=",
"serverKeyId",
"(",
")",
";",
"keyID",
"!=",
"\"\"",
"{",
"hint",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"\\nThe key id %v was found in the server config %v, so you might want:\\n'pk-put init -gpgkey %v'\"",
",",
"\\n",
",",
"\\n",
",",
"keyID",
")",
"\n",
"osutil",
".",
"UserServerConfigPath",
"(",
")",
"\n",
"}",
"\n",
"keyID",
"\n",
"}",
"\n",
"errMsg",
"+=",
"hint",
"\n",
"log",
".",
"Fatal",
"(",
"errMsg",
")",
"\n",
"conf",
",",
"err",
":=",
"osutil",
".",
"NewJSONConfigParser",
"(",
")",
".",
"ReadFile",
"(",
"configPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatal",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"cfg",
":=",
"jsonconfig",
".",
"Obj",
"(",
"conf",
")",
"\n",
"if",
"singleServerAuth",
":=",
"cfg",
".",
"OptionalString",
"(",
"\"auth\"",
",",
"\"\"",
")",
";",
"singleServerAuth",
"!=",
"\"\"",
"{",
"newConf",
",",
"err",
":=",
"convertToMultiServers",
"(",
"cfg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Print",
"(",
"err",
")",
"\n",
"}",
"else",
"{",
"cfg",
"=",
"newConf",
"\n",
"}",
"\n",
"}",
"\n",
"config",
"=",
"&",
"clientconfig",
".",
"Config",
"{",
"Identity",
":",
"cfg",
".",
"OptionalString",
"(",
"\"identity\"",
",",
"\"\"",
")",
",",
"IdentitySecretRing",
":",
"cfg",
".",
"OptionalString",
"(",
"\"identitySecretRing\"",
",",
"\"\"",
")",
",",
"IgnoredFiles",
":",
"cfg",
".",
"OptionalList",
"(",
"\"ignoredFiles\"",
")",
",",
"}",
"\n",
"serversList",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"clientconfig",
".",
"Server",
")",
"\n",
"servers",
":=",
"cfg",
".",
"OptionalObject",
"(",
"\"servers\"",
")",
"\n",
"for",
"alias",
",",
"vei",
":=",
"range",
"servers",
"{",
"if",
"isURLOrHostPort",
"(",
"alias",
")",
"{",
"log",
".",
"Fatalf",
"(",
"\"Server alias %q looks like a hostname; \\\".\\\" or \\\";\\\" are not allowed.\"",
",",
"\\\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"alias",
"\n",
"serverMap",
",",
"ok",
":=",
"vei",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"if",
"!",
"ok",
"{",
"log",
".",
"Fatalf",
"(",
"\"entry %q in servers section is a %T, want an object\"",
",",
"alias",
",",
"vei",
")",
"\n",
"}",
"\n",
"serverConf",
":=",
"jsonconfig",
".",
"Obj",
"(",
"serverMap",
")",
"\n",
"serverStr",
",",
"err",
":=",
"cleanServer",
"(",
"serverConf",
".",
"OptionalString",
"(",
"\"server\"",
",",
"\"\"",
")",
")",
"\n",
"}",
"\n",
"}"
] | // lazy config parsing when there's a known client already.
// The client c may be nil. | [
"lazy",
"config",
"parsing",
"when",
"there",
"s",
"a",
"known",
"client",
"already",
".",
"The",
"client",
"c",
"may",
"be",
"nil",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/config.go#L84-L162 | train |
perkeep/perkeep | pkg/client/config.go | convertToMultiServers | func convertToMultiServers(conf jsonconfig.Obj) (jsonconfig.Obj, error) {
server := conf.OptionalString("server", "")
if server == "" {
return nil, errors.New("could not convert config to multi-servers style: no \"server\" key found")
}
newConf := jsonconfig.Obj{
"servers": map[string]interface{}{
"server": map[string]interface{}{
"auth": conf.OptionalString("auth", ""),
"default": true,
"server": server,
},
},
"identity": conf.OptionalString("identity", ""),
"identitySecretRing": conf.OptionalString("identitySecretRing", ""),
}
if ignoredFiles := conf.OptionalList("ignoredFiles"); ignoredFiles != nil {
var list []interface{}
for _, v := range ignoredFiles {
list = append(list, v)
}
newConf["ignoredFiles"] = list
}
return newConf, nil
} | go | func convertToMultiServers(conf jsonconfig.Obj) (jsonconfig.Obj, error) {
server := conf.OptionalString("server", "")
if server == "" {
return nil, errors.New("could not convert config to multi-servers style: no \"server\" key found")
}
newConf := jsonconfig.Obj{
"servers": map[string]interface{}{
"server": map[string]interface{}{
"auth": conf.OptionalString("auth", ""),
"default": true,
"server": server,
},
},
"identity": conf.OptionalString("identity", ""),
"identitySecretRing": conf.OptionalString("identitySecretRing", ""),
}
if ignoredFiles := conf.OptionalList("ignoredFiles"); ignoredFiles != nil {
var list []interface{}
for _, v := range ignoredFiles {
list = append(list, v)
}
newConf["ignoredFiles"] = list
}
return newConf, nil
} | [
"func",
"convertToMultiServers",
"(",
"conf",
"jsonconfig",
".",
"Obj",
")",
"(",
"jsonconfig",
".",
"Obj",
",",
"error",
")",
"{",
"server",
":=",
"conf",
".",
"OptionalString",
"(",
"\"server\"",
",",
"\"\"",
")",
"\n",
"if",
"server",
"==",
"\"\"",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"could not convert config to multi-servers style: no \\\"server\\\" key found\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"\\\"",
"\n",
"newConf",
":=",
"jsonconfig",
".",
"Obj",
"{",
"\"servers\"",
":",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"server\"",
":",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"auth\"",
":",
"conf",
".",
"OptionalString",
"(",
"\"auth\"",
",",
"\"\"",
")",
",",
"\"default\"",
":",
"true",
",",
"\"server\"",
":",
"server",
",",
"}",
",",
"}",
",",
"\"identity\"",
":",
"conf",
".",
"OptionalString",
"(",
"\"identity\"",
",",
"\"\"",
")",
",",
"\"identitySecretRing\"",
":",
"conf",
".",
"OptionalString",
"(",
"\"identitySecretRing\"",
",",
"\"\"",
")",
",",
"}",
"\n",
"}"
] | // convertToMultiServers takes an old style single-server client configuration and maps it to new a multi-servers configuration that is returned. | [
"convertToMultiServers",
"takes",
"an",
"old",
"style",
"single",
"-",
"server",
"client",
"configuration",
"and",
"maps",
"it",
"to",
"new",
"a",
"multi",
"-",
"servers",
"configuration",
"that",
"is",
"returned",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/config.go#L172-L196 | train |
perkeep/perkeep | pkg/client/config.go | printConfigChangeHelp | func printConfigChangeHelp(conf jsonconfig.Obj) {
// rename maps from old key names to the new ones.
// If there is no new one, the value is the empty string.
rename := map[string]string{
"keyId": "identity",
"publicKeyBlobref": "",
"selfPubKeyDir": "",
"secretRing": "identitySecretRing",
}
oldConfig := false
configChangedMsg := fmt.Sprintf("The client configuration file (%s) keys have changed.\n", osutil.UserClientConfigPath())
for _, unknown := range conf.UnknownKeys() {
v, ok := rename[unknown]
if ok {
if v != "" {
configChangedMsg += fmt.Sprintf("%q should be renamed %q.\n", unknown, v)
} else {
configChangedMsg += fmt.Sprintf("%q should be removed.\n", unknown)
}
oldConfig = true
}
}
if oldConfig {
configChangedMsg += "Please see https://perkeep.org/doc/client-config, or use pk-put init to recreate a default one."
log.Print(configChangedMsg)
}
} | go | func printConfigChangeHelp(conf jsonconfig.Obj) {
// rename maps from old key names to the new ones.
// If there is no new one, the value is the empty string.
rename := map[string]string{
"keyId": "identity",
"publicKeyBlobref": "",
"selfPubKeyDir": "",
"secretRing": "identitySecretRing",
}
oldConfig := false
configChangedMsg := fmt.Sprintf("The client configuration file (%s) keys have changed.\n", osutil.UserClientConfigPath())
for _, unknown := range conf.UnknownKeys() {
v, ok := rename[unknown]
if ok {
if v != "" {
configChangedMsg += fmt.Sprintf("%q should be renamed %q.\n", unknown, v)
} else {
configChangedMsg += fmt.Sprintf("%q should be removed.\n", unknown)
}
oldConfig = true
}
}
if oldConfig {
configChangedMsg += "Please see https://perkeep.org/doc/client-config, or use pk-put init to recreate a default one."
log.Print(configChangedMsg)
}
} | [
"func",
"printConfigChangeHelp",
"(",
"conf",
"jsonconfig",
".",
"Obj",
")",
"{",
"rename",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"\"keyId\"",
":",
"\"identity\"",
",",
"\"publicKeyBlobref\"",
":",
"\"\"",
",",
"\"selfPubKeyDir\"",
":",
"\"\"",
",",
"\"secretRing\"",
":",
"\"identitySecretRing\"",
",",
"}",
"\n",
"oldConfig",
":=",
"false",
"\n",
"configChangedMsg",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"The client configuration file (%s) keys have changed.\\n\"",
",",
"\\n",
")",
"\n",
"osutil",
".",
"UserClientConfigPath",
"(",
")",
"\n",
"for",
"_",
",",
"unknown",
":=",
"range",
"conf",
".",
"UnknownKeys",
"(",
")",
"{",
"v",
",",
"ok",
":=",
"rename",
"[",
"unknown",
"]",
"\n",
"if",
"ok",
"{",
"if",
"v",
"!=",
"\"\"",
"{",
"configChangedMsg",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\"%q should be renamed %q.\\n\"",
",",
"\\n",
",",
"unknown",
")",
"\n",
"}",
"else",
"v",
"\n",
"{",
"configChangedMsg",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\"%q should be removed.\\n\"",
",",
"\\n",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] | // printConfigChangeHelp checks if conf contains obsolete keys,
// and prints additional help in this case. | [
"printConfigChangeHelp",
"checks",
"if",
"conf",
"contains",
"obsolete",
"keys",
"and",
"prints",
"additional",
"help",
"in",
"this",
"case",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/config.go#L200-L226 | train |
perkeep/perkeep | pkg/client/config.go | getServer | func getServer() (string, error) {
if s := os.Getenv("CAMLI_SERVER"); s != "" {
return cleanServer(s)
}
if flagServer != "" {
if !isURLOrHostPort(flagServer) {
configOnce.Do(parseConfig)
serverConf, ok := config.Servers[flagServer]
if ok {
return serverConf.Server, nil
}
log.Printf("%q looks like a server alias, but no such alias found in config.", flagServer)
} else {
return cleanServer(flagServer)
}
}
server, err := defaultServer()
if err != nil {
return "", err
}
if server == "" {
return "", camtypes.ErrClientNoServer
}
return cleanServer(server)
} | go | func getServer() (string, error) {
if s := os.Getenv("CAMLI_SERVER"); s != "" {
return cleanServer(s)
}
if flagServer != "" {
if !isURLOrHostPort(flagServer) {
configOnce.Do(parseConfig)
serverConf, ok := config.Servers[flagServer]
if ok {
return serverConf.Server, nil
}
log.Printf("%q looks like a server alias, but no such alias found in config.", flagServer)
} else {
return cleanServer(flagServer)
}
}
server, err := defaultServer()
if err != nil {
return "", err
}
if server == "" {
return "", camtypes.ErrClientNoServer
}
return cleanServer(server)
} | [
"func",
"getServer",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"s",
":=",
"os",
".",
"Getenv",
"(",
"\"CAMLI_SERVER\"",
")",
";",
"s",
"!=",
"\"\"",
"{",
"return",
"cleanServer",
"(",
"s",
")",
"\n",
"}",
"\n",
"if",
"flagServer",
"!=",
"\"\"",
"{",
"if",
"!",
"isURLOrHostPort",
"(",
"flagServer",
")",
"{",
"configOnce",
".",
"Do",
"(",
"parseConfig",
")",
"\n",
"serverConf",
",",
"ok",
":=",
"config",
".",
"Servers",
"[",
"flagServer",
"]",
"\n",
"if",
"ok",
"{",
"return",
"serverConf",
".",
"Server",
",",
"nil",
"\n",
"}",
"\n",
"log",
".",
"Printf",
"(",
"\"%q looks like a server alias, but no such alias found in config.\"",
",",
"flagServer",
")",
"\n",
"}",
"else",
"{",
"return",
"cleanServer",
"(",
"flagServer",
")",
"\n",
"}",
"\n",
"}",
"\n",
"server",
",",
"err",
":=",
"defaultServer",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"if",
"server",
"==",
"\"\"",
"{",
"return",
"\"\"",
",",
"camtypes",
".",
"ErrClientNoServer",
"\n",
"}",
"\n",
"return",
"cleanServer",
"(",
"server",
")",
"\n",
"}"
] | // getServer returns the server's URL found either as a command-line flag,
// or as the default server in the config file. | [
"getServer",
"returns",
"the",
"server",
"s",
"URL",
"found",
"either",
"as",
"a",
"command",
"-",
"line",
"flag",
"or",
"as",
"the",
"default",
"server",
"in",
"the",
"config",
"file",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/config.go#L269-L293 | train |
perkeep/perkeep | pkg/client/config.go | SetupAuth | func (c *Client) SetupAuth() error {
if c.noExtConfig {
if c.authMode != nil {
if _, ok := c.authMode.(*auth.None); !ok {
return nil
}
}
return errors.New("client: noExtConfig set; auth should not be configured from config or env vars")
}
// env var takes precedence, but only if we're in dev mode or on android.
// Too risky otherwise.
if android.OnAndroid() ||
env.IsDev() ||
configDisabled {
authMode, err := auth.FromEnv()
if err == nil {
c.authMode = authMode
return nil
}
if err != auth.ErrNoAuth {
return fmt.Errorf("Could not set up auth from env var CAMLI_AUTH: %v", err)
}
}
if c.server == "" {
return fmt.Errorf("no server defined for this client: can not set up auth")
}
authConf := serverAuth(c.server)
if authConf == "" {
c.authErr = fmt.Errorf("could not find auth key for server %q in config, defaulting to no auth", c.server)
c.authMode = auth.None{}
return nil
}
var err error
c.authMode, err = auth.FromConfig(authConf)
return err
} | go | func (c *Client) SetupAuth() error {
if c.noExtConfig {
if c.authMode != nil {
if _, ok := c.authMode.(*auth.None); !ok {
return nil
}
}
return errors.New("client: noExtConfig set; auth should not be configured from config or env vars")
}
// env var takes precedence, but only if we're in dev mode or on android.
// Too risky otherwise.
if android.OnAndroid() ||
env.IsDev() ||
configDisabled {
authMode, err := auth.FromEnv()
if err == nil {
c.authMode = authMode
return nil
}
if err != auth.ErrNoAuth {
return fmt.Errorf("Could not set up auth from env var CAMLI_AUTH: %v", err)
}
}
if c.server == "" {
return fmt.Errorf("no server defined for this client: can not set up auth")
}
authConf := serverAuth(c.server)
if authConf == "" {
c.authErr = fmt.Errorf("could not find auth key for server %q in config, defaulting to no auth", c.server)
c.authMode = auth.None{}
return nil
}
var err error
c.authMode, err = auth.FromConfig(authConf)
return err
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"SetupAuth",
"(",
")",
"error",
"{",
"if",
"c",
".",
"noExtConfig",
"{",
"if",
"c",
".",
"authMode",
"!=",
"nil",
"{",
"if",
"_",
",",
"ok",
":=",
"c",
".",
"authMode",
".",
"(",
"*",
"auth",
".",
"None",
")",
";",
"!",
"ok",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"errors",
".",
"New",
"(",
"\"client: noExtConfig set; auth should not be configured from config or env vars\"",
")",
"\n",
"}",
"\n",
"if",
"android",
".",
"OnAndroid",
"(",
")",
"||",
"env",
".",
"IsDev",
"(",
")",
"||",
"configDisabled",
"{",
"authMode",
",",
"err",
":=",
"auth",
".",
"FromEnv",
"(",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"c",
".",
"authMode",
"=",
"authMode",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"auth",
".",
"ErrNoAuth",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Could not set up auth from env var CAMLI_AUTH: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"c",
".",
"server",
"==",
"\"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"no server defined for this client: can not set up auth\"",
")",
"\n",
"}",
"\n",
"authConf",
":=",
"serverAuth",
"(",
"c",
".",
"server",
")",
"\n",
"if",
"authConf",
"==",
"\"\"",
"{",
"c",
".",
"authErr",
"=",
"fmt",
".",
"Errorf",
"(",
"\"could not find auth key for server %q in config, defaulting to no auth\"",
",",
"c",
".",
"server",
")",
"\n",
"c",
".",
"authMode",
"=",
"auth",
".",
"None",
"{",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"var",
"err",
"error",
"\n",
"c",
".",
"authMode",
",",
"err",
"=",
"auth",
".",
"FromConfig",
"(",
"authConf",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // SetupAuth sets the client's authMode. It tries from the environment first if we're on android or in dev mode, and then from the client configuration. | [
"SetupAuth",
"sets",
"the",
"client",
"s",
"authMode",
".",
"It",
"tries",
"from",
"the",
"environment",
"first",
"if",
"we",
"re",
"on",
"android",
"or",
"in",
"dev",
"mode",
"and",
"then",
"from",
"the",
"client",
"configuration",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/config.go#L311-L346 | train |
perkeep/perkeep | pkg/client/config.go | serverAuth | func serverAuth(server string) string {
configOnce.Do(parseConfig)
alias := config.Alias(server)
if alias == "" {
return ""
}
return config.Servers[alias].Auth
} | go | func serverAuth(server string) string {
configOnce.Do(parseConfig)
alias := config.Alias(server)
if alias == "" {
return ""
}
return config.Servers[alias].Auth
} | [
"func",
"serverAuth",
"(",
"server",
"string",
")",
"string",
"{",
"configOnce",
".",
"Do",
"(",
"parseConfig",
")",
"\n",
"alias",
":=",
"config",
".",
"Alias",
"(",
"server",
")",
"\n",
"if",
"alias",
"==",
"\"\"",
"{",
"return",
"\"\"",
"\n",
"}",
"\n",
"return",
"config",
".",
"Servers",
"[",
"alias",
"]",
".",
"Auth",
"\n",
"}"
] | // serverAuth returns the auth scheme for server from the config, or the empty string if the server was not found in the config. | [
"serverAuth",
"returns",
"the",
"auth",
"scheme",
"for",
"server",
"from",
"the",
"config",
"or",
"the",
"empty",
"string",
"if",
"the",
"server",
"was",
"not",
"found",
"in",
"the",
"config",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/config.go#L349-L356 | train |
perkeep/perkeep | pkg/client/config.go | SetupAuthFromString | func (c *Client) SetupAuthFromString(a string) error {
// TODO(mpl): review the one using that (pkg/blobserver/remote/remote.go)
var err error
c.authMode, err = auth.FromConfig(a)
return err
} | go | func (c *Client) SetupAuthFromString(a string) error {
// TODO(mpl): review the one using that (pkg/blobserver/remote/remote.go)
var err error
c.authMode, err = auth.FromConfig(a)
return err
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"SetupAuthFromString",
"(",
"a",
"string",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"c",
".",
"authMode",
",",
"err",
"=",
"auth",
".",
"FromConfig",
"(",
"a",
")",
"\n",
"return",
"err",
"\n",
"}"
] | // SetupAuthFromString configures the clients authentication mode from
// an explicit auth string. | [
"SetupAuthFromString",
"configures",
"the",
"clients",
"authentication",
"mode",
"from",
"an",
"explicit",
"auth",
"string",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/config.go#L360-L365 | train |
perkeep/perkeep | pkg/client/config.go | serverTrustedCerts | func (c *Client) serverTrustedCerts(server string) []string {
configOnce.Do(c.parseConfig)
if config == nil {
return nil
}
alias := config.Alias(server)
if alias == "" {
return nil
}
return config.Servers[alias].TrustedCerts
} | go | func (c *Client) serverTrustedCerts(server string) []string {
configOnce.Do(c.parseConfig)
if config == nil {
return nil
}
alias := config.Alias(server)
if alias == "" {
return nil
}
return config.Servers[alias].TrustedCerts
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"serverTrustedCerts",
"(",
"server",
"string",
")",
"[",
"]",
"string",
"{",
"configOnce",
".",
"Do",
"(",
"c",
".",
"parseConfig",
")",
"\n",
"if",
"config",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"alias",
":=",
"config",
".",
"Alias",
"(",
"server",
")",
"\n",
"if",
"alias",
"==",
"\"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"config",
".",
"Servers",
"[",
"alias",
"]",
".",
"TrustedCerts",
"\n",
"}"
] | // serverTrustedCerts returns the trusted certs for server from the config. | [
"serverTrustedCerts",
"returns",
"the",
"trusted",
"certs",
"for",
"server",
"from",
"the",
"config",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/config.go#L463-L473 | train |
perkeep/perkeep | pkg/client/config.go | newIgnoreChecker | func newIgnoreChecker(ignoredFiles []string) func(path string) (shouldIgnore bool) {
var fns []func(string) bool
// copy of ignoredFiles for us to mutate
ignFiles := append([]string(nil), ignoredFiles...)
for k, v := range ignFiles {
if strings.HasPrefix(v, filepath.FromSlash("~/")) {
ignFiles[k] = filepath.Join(osutilHomeDir(), v[2:])
}
}
// We cache the ignoredFiles patterns in 3 categories (not necessarily exclusive):
// 1) shell patterns
// 3) absolute paths
// 4) paths components
for _, pattern := range ignFiles {
pattern := pattern
_, err := filepath.Match(pattern, "whatever")
if err == nil {
fns = append(fns, func(v string) bool { return isShellPatternMatch(pattern, v) })
}
}
for _, pattern := range ignFiles {
pattern := pattern
if filepath.IsAbs(pattern) {
fns = append(fns, func(v string) bool { return hasDirPrefix(filepath.Clean(pattern), v) })
} else {
fns = append(fns, func(v string) bool { return hasComponent(filepath.Clean(pattern), v) })
}
}
return func(path string) bool {
for _, fn := range fns {
if fn(path) {
return true
}
}
return false
}
} | go | func newIgnoreChecker(ignoredFiles []string) func(path string) (shouldIgnore bool) {
var fns []func(string) bool
// copy of ignoredFiles for us to mutate
ignFiles := append([]string(nil), ignoredFiles...)
for k, v := range ignFiles {
if strings.HasPrefix(v, filepath.FromSlash("~/")) {
ignFiles[k] = filepath.Join(osutilHomeDir(), v[2:])
}
}
// We cache the ignoredFiles patterns in 3 categories (not necessarily exclusive):
// 1) shell patterns
// 3) absolute paths
// 4) paths components
for _, pattern := range ignFiles {
pattern := pattern
_, err := filepath.Match(pattern, "whatever")
if err == nil {
fns = append(fns, func(v string) bool { return isShellPatternMatch(pattern, v) })
}
}
for _, pattern := range ignFiles {
pattern := pattern
if filepath.IsAbs(pattern) {
fns = append(fns, func(v string) bool { return hasDirPrefix(filepath.Clean(pattern), v) })
} else {
fns = append(fns, func(v string) bool { return hasComponent(filepath.Clean(pattern), v) })
}
}
return func(path string) bool {
for _, fn := range fns {
if fn(path) {
return true
}
}
return false
}
} | [
"func",
"newIgnoreChecker",
"(",
"ignoredFiles",
"[",
"]",
"string",
")",
"func",
"(",
"path",
"string",
")",
"(",
"shouldIgnore",
"bool",
")",
"{",
"var",
"fns",
"[",
"]",
"func",
"(",
"string",
")",
"bool",
"\n",
"ignFiles",
":=",
"append",
"(",
"[",
"]",
"string",
"(",
"nil",
")",
",",
"ignoredFiles",
"...",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"ignFiles",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"v",
",",
"filepath",
".",
"FromSlash",
"(",
"\"~/\"",
")",
")",
"{",
"ignFiles",
"[",
"k",
"]",
"=",
"filepath",
".",
"Join",
"(",
"osutilHomeDir",
"(",
")",
",",
"v",
"[",
"2",
":",
"]",
")",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"pattern",
":=",
"range",
"ignFiles",
"{",
"pattern",
":=",
"pattern",
"\n",
"_",
",",
"err",
":=",
"filepath",
".",
"Match",
"(",
"pattern",
",",
"\"whatever\"",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"fns",
"=",
"append",
"(",
"fns",
",",
"func",
"(",
"v",
"string",
")",
"bool",
"{",
"return",
"isShellPatternMatch",
"(",
"pattern",
",",
"v",
")",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"pattern",
":=",
"range",
"ignFiles",
"{",
"pattern",
":=",
"pattern",
"\n",
"if",
"filepath",
".",
"IsAbs",
"(",
"pattern",
")",
"{",
"fns",
"=",
"append",
"(",
"fns",
",",
"func",
"(",
"v",
"string",
")",
"bool",
"{",
"return",
"hasDirPrefix",
"(",
"filepath",
".",
"Clean",
"(",
"pattern",
")",
",",
"v",
")",
"}",
")",
"\n",
"}",
"else",
"{",
"fns",
"=",
"append",
"(",
"fns",
",",
"func",
"(",
"v",
"string",
")",
"bool",
"{",
"return",
"hasComponent",
"(",
"filepath",
".",
"Clean",
"(",
"pattern",
")",
",",
"v",
")",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"func",
"(",
"path",
"string",
")",
"bool",
"{",
"for",
"_",
",",
"fn",
":=",
"range",
"fns",
"{",
"if",
"fn",
"(",
"path",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"}"
] | // newIgnoreChecker uses ignoredFiles to build and return a func that returns whether the file path argument should be ignored. See IsIgnoredFile for the ignore rules. | [
"newIgnoreChecker",
"uses",
"ignoredFiles",
"to",
"build",
"and",
"return",
"a",
"func",
"that",
"returns",
"whether",
"the",
"file",
"path",
"argument",
"should",
"be",
"ignored",
".",
"See",
"IsIgnoredFile",
"for",
"the",
"ignore",
"rules",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/config.go#L502-L540 | train |
perkeep/perkeep | pkg/client/config.go | hasDirPrefix | func hasDirPrefix(dirPrefix, fullpath string) bool {
if !strings.HasPrefix(fullpath, dirPrefix) {
return false
}
if len(fullpath) == len(dirPrefix) {
return true
}
if fullpath[len(dirPrefix)] == filepath.Separator {
return true
}
return false
} | go | func hasDirPrefix(dirPrefix, fullpath string) bool {
if !strings.HasPrefix(fullpath, dirPrefix) {
return false
}
if len(fullpath) == len(dirPrefix) {
return true
}
if fullpath[len(dirPrefix)] == filepath.Separator {
return true
}
return false
} | [
"func",
"hasDirPrefix",
"(",
"dirPrefix",
",",
"fullpath",
"string",
")",
"bool",
"{",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"fullpath",
",",
"dirPrefix",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"len",
"(",
"fullpath",
")",
"==",
"len",
"(",
"dirPrefix",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"fullpath",
"[",
"len",
"(",
"dirPrefix",
")",
"]",
"==",
"filepath",
".",
"Separator",
"{",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] | // hasDirPrefix reports whether the path has the provided directory prefix.
// Both should be absolute paths. | [
"hasDirPrefix",
"reports",
"whether",
"the",
"path",
"has",
"the",
"provided",
"directory",
"prefix",
".",
"Both",
"should",
"be",
"absolute",
"paths",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/config.go#L561-L572 | train |
perkeep/perkeep | pkg/client/config.go | hasComponent | func hasComponent(component, fullpath string) bool {
// trim Windows volume name
fullpath = strings.TrimPrefix(fullpath, filepath.VolumeName(fullpath))
for {
i := strings.Index(fullpath, component)
if i == -1 {
return false
}
if i != 0 && fullpath[i-1] == filepath.Separator {
componentEnd := i + len(component)
if componentEnd == len(fullpath) {
return true
}
if fullpath[componentEnd] == filepath.Separator {
return true
}
}
fullpath = fullpath[i+1:]
}
panic("unreachable")
} | go | func hasComponent(component, fullpath string) bool {
// trim Windows volume name
fullpath = strings.TrimPrefix(fullpath, filepath.VolumeName(fullpath))
for {
i := strings.Index(fullpath, component)
if i == -1 {
return false
}
if i != 0 && fullpath[i-1] == filepath.Separator {
componentEnd := i + len(component)
if componentEnd == len(fullpath) {
return true
}
if fullpath[componentEnd] == filepath.Separator {
return true
}
}
fullpath = fullpath[i+1:]
}
panic("unreachable")
} | [
"func",
"hasComponent",
"(",
"component",
",",
"fullpath",
"string",
")",
"bool",
"{",
"fullpath",
"=",
"strings",
".",
"TrimPrefix",
"(",
"fullpath",
",",
"filepath",
".",
"VolumeName",
"(",
"fullpath",
")",
")",
"\n",
"for",
"{",
"i",
":=",
"strings",
".",
"Index",
"(",
"fullpath",
",",
"component",
")",
"\n",
"if",
"i",
"==",
"-",
"1",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"i",
"!=",
"0",
"&&",
"fullpath",
"[",
"i",
"-",
"1",
"]",
"==",
"filepath",
".",
"Separator",
"{",
"componentEnd",
":=",
"i",
"+",
"len",
"(",
"component",
")",
"\n",
"if",
"componentEnd",
"==",
"len",
"(",
"fullpath",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"fullpath",
"[",
"componentEnd",
"]",
"==",
"filepath",
".",
"Separator",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"fullpath",
"=",
"fullpath",
"[",
"i",
"+",
"1",
":",
"]",
"\n",
"}",
"\n",
"panic",
"(",
"\"unreachable\"",
")",
"\n",
"}"
] | // hasComponent returns whether the pathComponent is a path component of
// fullpath. i.e it is a part of fullpath that fits exactly between two path
// separators. | [
"hasComponent",
"returns",
"whether",
"the",
"pathComponent",
"is",
"a",
"path",
"component",
"of",
"fullpath",
".",
"i",
".",
"e",
"it",
"is",
"a",
"part",
"of",
"fullpath",
"that",
"fits",
"exactly",
"between",
"two",
"path",
"separators",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/config.go#L577-L597 | train |
perkeep/perkeep | misc/release/make-release.go | genAll | func genAll() ([]string, error) {
zipSource()
for _, platform := range []string{"linux", "darwin", "windows"} {
genBinaries(platform)
packBinaries(platform)
}
getVersions()
return []string{
"perkeep-darwin.tar.gz",
"perkeep-linux.tar.gz",
"perkeep-src.zip",
"perkeep-windows.zip",
}, nil
} | go | func genAll() ([]string, error) {
zipSource()
for _, platform := range []string{"linux", "darwin", "windows"} {
genBinaries(platform)
packBinaries(platform)
}
getVersions()
return []string{
"perkeep-darwin.tar.gz",
"perkeep-linux.tar.gz",
"perkeep-src.zip",
"perkeep-windows.zip",
}, nil
} | [
"func",
"genAll",
"(",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"zipSource",
"(",
")",
"\n",
"for",
"_",
",",
"platform",
":=",
"range",
"[",
"]",
"string",
"{",
"\"linux\"",
",",
"\"darwin\"",
",",
"\"windows\"",
"}",
"{",
"genBinaries",
"(",
"platform",
")",
"\n",
"packBinaries",
"(",
"platform",
")",
"\n",
"}",
"\n",
"getVersions",
"(",
")",
"\n",
"return",
"[",
"]",
"string",
"{",
"\"perkeep-darwin.tar.gz\"",
",",
"\"perkeep-linux.tar.gz\"",
",",
"\"perkeep-src.zip\"",
",",
"\"perkeep-windows.zip\"",
",",
"}",
",",
"nil",
"\n",
"}"
] | // genAll creates all the zips and tarballs, and returns their filenames. | [
"genAll",
"creates",
"all",
"the",
"zips",
"and",
"tarballs",
"and",
"returns",
"their",
"filenames",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/misc/release/make-release.go#L196-L209 | train |
perkeep/perkeep | misc/release/make-release.go | getVersions | func getVersions() {
pkBin := filepath.Join(workDir, runtime.GOOS, "bin", "perkeepd")
cmd := exec.Command(pkBin, "-version")
var buf bytes.Buffer
cmd.Stderr = &buf
if err := cmd.Run(); err != nil {
log.Fatalf("Error getting version from perkeepd: %v, %v", err, buf.String())
}
sc := bufio.NewScanner(&buf)
for sc.Scan() {
l := sc.Text()
fields := strings.Fields(l)
if pkVersion == "" {
if len(fields) != 4 || fields[0] != "perkeepd" {
log.Fatalf("Unexpected perkeepd -version output: %q", l)
}
pkVersion = fields[3]
continue
}
if len(fields) != 4 || fields[0] != "Go" {
log.Fatalf("Unexpected perkeepd -version output: %q", l)
}
goVersion = fields[2]
break
}
if err := sc.Err(); err != nil {
log.Fatal(err)
}
} | go | func getVersions() {
pkBin := filepath.Join(workDir, runtime.GOOS, "bin", "perkeepd")
cmd := exec.Command(pkBin, "-version")
var buf bytes.Buffer
cmd.Stderr = &buf
if err := cmd.Run(); err != nil {
log.Fatalf("Error getting version from perkeepd: %v, %v", err, buf.String())
}
sc := bufio.NewScanner(&buf)
for sc.Scan() {
l := sc.Text()
fields := strings.Fields(l)
if pkVersion == "" {
if len(fields) != 4 || fields[0] != "perkeepd" {
log.Fatalf("Unexpected perkeepd -version output: %q", l)
}
pkVersion = fields[3]
continue
}
if len(fields) != 4 || fields[0] != "Go" {
log.Fatalf("Unexpected perkeepd -version output: %q", l)
}
goVersion = fields[2]
break
}
if err := sc.Err(); err != nil {
log.Fatal(err)
}
} | [
"func",
"getVersions",
"(",
")",
"{",
"pkBin",
":=",
"filepath",
".",
"Join",
"(",
"workDir",
",",
"runtime",
".",
"GOOS",
",",
"\"bin\"",
",",
"\"perkeepd\"",
")",
"\n",
"cmd",
":=",
"exec",
".",
"Command",
"(",
"pkBin",
",",
"\"-version\"",
")",
"\n",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"cmd",
".",
"Stderr",
"=",
"&",
"buf",
"\n",
"if",
"err",
":=",
"cmd",
".",
"Run",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"Error getting version from perkeepd: %v, %v\"",
",",
"err",
",",
"buf",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"sc",
":=",
"bufio",
".",
"NewScanner",
"(",
"&",
"buf",
")",
"\n",
"for",
"sc",
".",
"Scan",
"(",
")",
"{",
"l",
":=",
"sc",
".",
"Text",
"(",
")",
"\n",
"fields",
":=",
"strings",
".",
"Fields",
"(",
"l",
")",
"\n",
"if",
"pkVersion",
"==",
"\"\"",
"{",
"if",
"len",
"(",
"fields",
")",
"!=",
"4",
"||",
"fields",
"[",
"0",
"]",
"!=",
"\"perkeepd\"",
"{",
"log",
".",
"Fatalf",
"(",
"\"Unexpected perkeepd -version output: %q\"",
",",
"l",
")",
"\n",
"}",
"\n",
"pkVersion",
"=",
"fields",
"[",
"3",
"]",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"len",
"(",
"fields",
")",
"!=",
"4",
"||",
"fields",
"[",
"0",
"]",
"!=",
"\"Go\"",
"{",
"log",
".",
"Fatalf",
"(",
"\"Unexpected perkeepd -version output: %q\"",
",",
"l",
")",
"\n",
"}",
"\n",
"goVersion",
"=",
"fields",
"[",
"2",
"]",
"\n",
"break",
"\n",
"}",
"\n",
"if",
"err",
":=",
"sc",
".",
"Err",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatal",
"(",
"err",
")",
"\n",
"}",
"\n",
"}"
] | // getVersions uses the freshly built perkeepd binary to get the Perkeep and Go
// versions used to build the release. | [
"getVersions",
"uses",
"the",
"freshly",
"built",
"perkeepd",
"binary",
"to",
"get",
"the",
"Perkeep",
"and",
"Go",
"versions",
"used",
"to",
"build",
"the",
"release",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/misc/release/make-release.go#L213-L241 | train |
perkeep/perkeep | misc/release/make-release.go | zipSource | func zipSource() string {
cwd := filepath.Join(workDir, "src")
check(os.MkdirAll(cwd, 0755))
image := goDockerImage
args := []string{
"run",
"--rm",
"--volume=" + cwd + ":/OUT",
"--volume=" + path.Join(releaseDir, "zip-source.go") + ":" + zipSourceProgram + ":ro",
}
if isWIP() {
args = append(args, "--volume="+localCamliSource()+":/IN:ro",
image, goCmd, "run", zipSourceProgram, "--rev=WIP:/IN")
} else {
args = append(args, image, goCmd, "run", zipSourceProgram, "--rev="+rev())
}
cmd := exec.Command("docker", args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Fatalf("Error zipping Perkeep source in go container: %v", err)
}
archiveName := "perkeep-src.zip"
// can't use os.Rename because invalid cross-device link error likely
cmd = exec.Command("mv", filepath.Join(cwd, archiveName), releaseDir)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Fatalf("Error moving source zip from %v to %v: %v", filepath.Join(cwd, archiveName), releaseDir, err)
}
fmt.Printf("Perkeep source successfully zipped in %v\n", releaseDir)
return archiveName
} | go | func zipSource() string {
cwd := filepath.Join(workDir, "src")
check(os.MkdirAll(cwd, 0755))
image := goDockerImage
args := []string{
"run",
"--rm",
"--volume=" + cwd + ":/OUT",
"--volume=" + path.Join(releaseDir, "zip-source.go") + ":" + zipSourceProgram + ":ro",
}
if isWIP() {
args = append(args, "--volume="+localCamliSource()+":/IN:ro",
image, goCmd, "run", zipSourceProgram, "--rev=WIP:/IN")
} else {
args = append(args, image, goCmd, "run", zipSourceProgram, "--rev="+rev())
}
cmd := exec.Command("docker", args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Fatalf("Error zipping Perkeep source in go container: %v", err)
}
archiveName := "perkeep-src.zip"
// can't use os.Rename because invalid cross-device link error likely
cmd = exec.Command("mv", filepath.Join(cwd, archiveName), releaseDir)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Fatalf("Error moving source zip from %v to %v: %v", filepath.Join(cwd, archiveName), releaseDir, err)
}
fmt.Printf("Perkeep source successfully zipped in %v\n", releaseDir)
return archiveName
} | [
"func",
"zipSource",
"(",
")",
"string",
"{",
"cwd",
":=",
"filepath",
".",
"Join",
"(",
"workDir",
",",
"\"src\"",
")",
"\n",
"check",
"(",
"os",
".",
"MkdirAll",
"(",
"cwd",
",",
"0755",
")",
")",
"\n",
"image",
":=",
"goDockerImage",
"\n",
"args",
":=",
"[",
"]",
"string",
"{",
"\"run\"",
",",
"\"--rm\"",
",",
"\"--volume=\"",
"+",
"cwd",
"+",
"\":/OUT\"",
",",
"\"--volume=\"",
"+",
"path",
".",
"Join",
"(",
"releaseDir",
",",
"\"zip-source.go\"",
")",
"+",
"\":\"",
"+",
"zipSourceProgram",
"+",
"\":ro\"",
",",
"}",
"\n",
"if",
"isWIP",
"(",
")",
"{",
"args",
"=",
"append",
"(",
"args",
",",
"\"--volume=\"",
"+",
"localCamliSource",
"(",
")",
"+",
"\":/IN:ro\"",
",",
"image",
",",
"goCmd",
",",
"\"run\"",
",",
"zipSourceProgram",
",",
"\"--rev=WIP:/IN\"",
")",
"\n",
"}",
"else",
"{",
"args",
"=",
"append",
"(",
"args",
",",
"image",
",",
"goCmd",
",",
"\"run\"",
",",
"zipSourceProgram",
",",
"\"--rev=\"",
"+",
"rev",
"(",
")",
")",
"\n",
"}",
"\n",
"cmd",
":=",
"exec",
".",
"Command",
"(",
"\"docker\"",
",",
"args",
"...",
")",
"\n",
"cmd",
".",
"Stdout",
"=",
"os",
".",
"Stdout",
"\n",
"cmd",
".",
"Stderr",
"=",
"os",
".",
"Stderr",
"\n",
"if",
"err",
":=",
"cmd",
".",
"Run",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"Error zipping Perkeep source in go container: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"archiveName",
":=",
"\"perkeep-src.zip\"",
"\n",
"cmd",
"=",
"exec",
".",
"Command",
"(",
"\"mv\"",
",",
"filepath",
".",
"Join",
"(",
"cwd",
",",
"archiveName",
")",
",",
"releaseDir",
")",
"\n",
"cmd",
".",
"Stdout",
"=",
"os",
".",
"Stdout",
"\n",
"cmd",
".",
"Stderr",
"=",
"os",
".",
"Stderr",
"\n",
"if",
"err",
":=",
"cmd",
".",
"Run",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"Error moving source zip from %v to %v: %v\"",
",",
"filepath",
".",
"Join",
"(",
"cwd",
",",
"archiveName",
")",
",",
"releaseDir",
",",
"err",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Printf",
"(",
"\"Perkeep source successfully zipped in %v\\n\"",
",",
"\\n",
")",
"\n",
"releaseDir",
"\n",
"}"
] | // zipSource builds the zip archive that contains the source code of Perkeep. | [
"zipSource",
"builds",
"the",
"zip",
"archive",
"that",
"contains",
"the",
"source",
"code",
"of",
"Perkeep",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/misc/release/make-release.go#L378-L410 | train |
perkeep/perkeep | misc/release/make-release.go | committers | func committers() (map[string]string, error) {
cmd := exec.Command("git", "shortlog", "-n", "-e", "-s", *flagStatsFrom+".."+revOrHEAD())
out, err := cmd.CombinedOutput()
if err != nil {
return nil, fmt.Errorf("%v; %v", err, string(out))
}
rxp := regexp.MustCompile(`^\s+(\d+)\s+(.*)<(.*)>.*$`)
sc := bufio.NewScanner(bytes.NewReader(out))
// maps email to name
committers := make(map[string]string)
// remember the count, to keep the committer that has the most count, when same name.
commitCountByEmail := make(map[string]int)
for sc.Scan() {
m := rxp.FindStringSubmatch(sc.Text())
if len(m) != 4 {
return nil, fmt.Errorf("commit line regexp didn't match properly")
}
count, err := strconv.Atoi(m[1])
if err != nil {
return nil, fmt.Errorf("couldn't convert %q as a number of commits: %v", m[1], err)
}
name := strings.TrimSpace(m[2])
email := m[3]
// uniq by e-mail. first one encountered wins as it has more commits.
if _, ok := committers[email]; !ok {
committers[email] = name
}
commitCountByEmail[email] += count
}
if err := sc.Err(); err != nil {
return nil, err
}
// uniq by name
committerByName := make(map[string]string)
for email, name := range committers {
firstEmail, ok := committerByName[name]
if !ok {
committerByName[name] = email
continue
}
c1, _ := commitCountByEmail[firstEmail]
c2, _ := commitCountByEmail[email]
if c1 < c2 {
delete(committers, firstEmail)
} else {
delete(committers, email)
}
}
return committers, nil
} | go | func committers() (map[string]string, error) {
cmd := exec.Command("git", "shortlog", "-n", "-e", "-s", *flagStatsFrom+".."+revOrHEAD())
out, err := cmd.CombinedOutput()
if err != nil {
return nil, fmt.Errorf("%v; %v", err, string(out))
}
rxp := regexp.MustCompile(`^\s+(\d+)\s+(.*)<(.*)>.*$`)
sc := bufio.NewScanner(bytes.NewReader(out))
// maps email to name
committers := make(map[string]string)
// remember the count, to keep the committer that has the most count, when same name.
commitCountByEmail := make(map[string]int)
for sc.Scan() {
m := rxp.FindStringSubmatch(sc.Text())
if len(m) != 4 {
return nil, fmt.Errorf("commit line regexp didn't match properly")
}
count, err := strconv.Atoi(m[1])
if err != nil {
return nil, fmt.Errorf("couldn't convert %q as a number of commits: %v", m[1], err)
}
name := strings.TrimSpace(m[2])
email := m[3]
// uniq by e-mail. first one encountered wins as it has more commits.
if _, ok := committers[email]; !ok {
committers[email] = name
}
commitCountByEmail[email] += count
}
if err := sc.Err(); err != nil {
return nil, err
}
// uniq by name
committerByName := make(map[string]string)
for email, name := range committers {
firstEmail, ok := committerByName[name]
if !ok {
committerByName[name] = email
continue
}
c1, _ := commitCountByEmail[firstEmail]
c2, _ := commitCountByEmail[email]
if c1 < c2 {
delete(committers, firstEmail)
} else {
delete(committers, email)
}
}
return committers, nil
} | [
"func",
"committers",
"(",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"cmd",
":=",
"exec",
".",
"Command",
"(",
"\"git\"",
",",
"\"shortlog\"",
",",
"\"-n\"",
",",
"\"-e\"",
",",
"\"-s\"",
",",
"*",
"flagStatsFrom",
"+",
"\"..\"",
"+",
"revOrHEAD",
"(",
")",
")",
"\n",
"out",
",",
"err",
":=",
"cmd",
".",
"CombinedOutput",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"%v; %v\"",
",",
"err",
",",
"string",
"(",
"out",
")",
")",
"\n",
"}",
"\n",
"rxp",
":=",
"regexp",
".",
"MustCompile",
"(",
"`^\\s+(\\d+)\\s+(.*)<(.*)>.*$`",
")",
"\n",
"sc",
":=",
"bufio",
".",
"NewScanner",
"(",
"bytes",
".",
"NewReader",
"(",
"out",
")",
")",
"\n",
"committers",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"commitCountByEmail",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"int",
")",
"\n",
"for",
"sc",
".",
"Scan",
"(",
")",
"{",
"m",
":=",
"rxp",
".",
"FindStringSubmatch",
"(",
"sc",
".",
"Text",
"(",
")",
")",
"\n",
"if",
"len",
"(",
"m",
")",
"!=",
"4",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"commit line regexp didn't match properly\"",
")",
"\n",
"}",
"\n",
"count",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"m",
"[",
"1",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"couldn't convert %q as a number of commits: %v\"",
",",
"m",
"[",
"1",
"]",
",",
"err",
")",
"\n",
"}",
"\n",
"name",
":=",
"strings",
".",
"TrimSpace",
"(",
"m",
"[",
"2",
"]",
")",
"\n",
"email",
":=",
"m",
"[",
"3",
"]",
"\n",
"if",
"_",
",",
"ok",
":=",
"committers",
"[",
"email",
"]",
";",
"!",
"ok",
"{",
"committers",
"[",
"email",
"]",
"=",
"name",
"\n",
"}",
"\n",
"commitCountByEmail",
"[",
"email",
"]",
"+=",
"count",
"\n",
"}",
"\n",
"if",
"err",
":=",
"sc",
".",
"Err",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"committerByName",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"for",
"email",
",",
"name",
":=",
"range",
"committers",
"{",
"firstEmail",
",",
"ok",
":=",
"committerByName",
"[",
"name",
"]",
"\n",
"if",
"!",
"ok",
"{",
"committerByName",
"[",
"name",
"]",
"=",
"email",
"\n",
"continue",
"\n",
"}",
"\n",
"c1",
",",
"_",
":=",
"commitCountByEmail",
"[",
"firstEmail",
"]",
"\n",
"c2",
",",
"_",
":=",
"commitCountByEmail",
"[",
"email",
"]",
"\n",
"if",
"c1",
"<",
"c2",
"{",
"delete",
"(",
"committers",
",",
"firstEmail",
")",
"\n",
"}",
"else",
"{",
"delete",
"(",
"committers",
",",
"email",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"committers",
",",
"nil",
"\n",
"}"
] | // returns commiters names mapped by e-mail, uniqued first by e-mail, then by name.
// When uniquing, higher count of commits wins. | [
"returns",
"commiters",
"names",
"mapped",
"by",
"e",
"-",
"mail",
"uniqued",
"first",
"by",
"e",
"-",
"mail",
"then",
"by",
"name",
".",
"When",
"uniquing",
"higher",
"count",
"of",
"commits",
"wins",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/misc/release/make-release.go#L690-L739 | train |
perkeep/perkeep | misc/release/make-release.go | ProjectTokenSource | func ProjectTokenSource(proj string, scopes ...string) (oauth2.TokenSource, error) {
// TODO(bradfitz): try different strategies too, like
// three-legged flow if the service account doesn't exist, and
// then cache the token file on disk somewhere. Or maybe that should be an
// option, for environments without stdin/stdout available to the user.
// We'll figure it out as needed.
fileName := filepath.Join(homedir(), "keys", proj+".key.json")
jsonConf, err := ioutil.ReadFile(fileName)
if err != nil {
if os.IsNotExist(err) {
return nil, fmt.Errorf("Missing JSON key configuration. Download the Service Account JSON key from https://console.developers.google.com/project/%s/apiui/credential and place it at %s", proj, fileName)
}
return nil, err
}
conf, err := google.JWTConfigFromJSON(jsonConf, scopes...)
if err != nil {
return nil, fmt.Errorf("reading JSON config from %s: %v", fileName, err)
}
return conf.TokenSource(oauth2.NoContext), nil
} | go | func ProjectTokenSource(proj string, scopes ...string) (oauth2.TokenSource, error) {
// TODO(bradfitz): try different strategies too, like
// three-legged flow if the service account doesn't exist, and
// then cache the token file on disk somewhere. Or maybe that should be an
// option, for environments without stdin/stdout available to the user.
// We'll figure it out as needed.
fileName := filepath.Join(homedir(), "keys", proj+".key.json")
jsonConf, err := ioutil.ReadFile(fileName)
if err != nil {
if os.IsNotExist(err) {
return nil, fmt.Errorf("Missing JSON key configuration. Download the Service Account JSON key from https://console.developers.google.com/project/%s/apiui/credential and place it at %s", proj, fileName)
}
return nil, err
}
conf, err := google.JWTConfigFromJSON(jsonConf, scopes...)
if err != nil {
return nil, fmt.Errorf("reading JSON config from %s: %v", fileName, err)
}
return conf.TokenSource(oauth2.NoContext), nil
} | [
"func",
"ProjectTokenSource",
"(",
"proj",
"string",
",",
"scopes",
"...",
"string",
")",
"(",
"oauth2",
".",
"TokenSource",
",",
"error",
")",
"{",
"fileName",
":=",
"filepath",
".",
"Join",
"(",
"homedir",
"(",
")",
",",
"\"keys\"",
",",
"proj",
"+",
"\".key.json\"",
")",
"\n",
"jsonConf",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"fileName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Missing JSON key configuration. Download the Service Account JSON key from https://console.developers.google.com/project/%s/apiui/credential and place it at %s\"",
",",
"proj",
",",
"fileName",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"conf",
",",
"err",
":=",
"google",
".",
"JWTConfigFromJSON",
"(",
"jsonConf",
",",
"scopes",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"reading JSON config from %s: %v\"",
",",
"fileName",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"conf",
".",
"TokenSource",
"(",
"oauth2",
".",
"NoContext",
")",
",",
"nil",
"\n",
"}"
] | // ProjectTokenSource returns an OAuth2 TokenSource for the given Google Project ID. | [
"ProjectTokenSource",
"returns",
"an",
"OAuth2",
"TokenSource",
"for",
"the",
"given",
"Google",
"Project",
"ID",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/misc/release/make-release.go#L907-L926 | train |
perkeep/perkeep | internal/hashutil/hashutil.go | SHA256Prefix | func SHA256Prefix(data []byte) string {
h := sha256.New()
h.Write(data)
return fmt.Sprintf("%x", h.Sum(nil))[:20]
} | go | func SHA256Prefix(data []byte) string {
h := sha256.New()
h.Write(data)
return fmt.Sprintf("%x", h.Sum(nil))[:20]
} | [
"func",
"SHA256Prefix",
"(",
"data",
"[",
"]",
"byte",
")",
"string",
"{",
"h",
":=",
"sha256",
".",
"New",
"(",
")",
"\n",
"h",
".",
"Write",
"(",
"data",
")",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%x\"",
",",
"h",
".",
"Sum",
"(",
"nil",
")",
")",
"[",
":",
"20",
"]",
"\n",
"}"
] | // SHA256Prefix computes the SHA-256 digest of data and returns
// its first twenty lowercase hex digits. | [
"SHA256Prefix",
"computes",
"the",
"SHA",
"-",
"256",
"digest",
"of",
"data",
"and",
"returns",
"its",
"first",
"twenty",
"lowercase",
"hex",
"digits",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/hashutil/hashutil.go#L32-L36 | train |
perkeep/perkeep | internal/hashutil/hashutil.go | SHA1Prefix | func SHA1Prefix(data []byte) string {
h := sha1.New()
h.Write(data)
return fmt.Sprintf("%x", h.Sum(nil))[:20]
} | go | func SHA1Prefix(data []byte) string {
h := sha1.New()
h.Write(data)
return fmt.Sprintf("%x", h.Sum(nil))[:20]
} | [
"func",
"SHA1Prefix",
"(",
"data",
"[",
"]",
"byte",
")",
"string",
"{",
"h",
":=",
"sha1",
".",
"New",
"(",
")",
"\n",
"h",
".",
"Write",
"(",
"data",
")",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%x\"",
",",
"h",
".",
"Sum",
"(",
"nil",
")",
")",
"[",
":",
"20",
"]",
"\n",
"}"
] | // SHA1Prefix computes the SHA-1 digest of data and returns
// its first twenty lowercase hex digits. | [
"SHA1Prefix",
"computes",
"the",
"SHA",
"-",
"1",
"digest",
"of",
"data",
"and",
"returns",
"its",
"first",
"twenty",
"lowercase",
"hex",
"digits",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/hashutil/hashutil.go#L40-L44 | train |
perkeep/perkeep | internal/osutil/paths.go | HomeDir | func HomeDir() string {
failInTests()
if runtime.GOOS == "windows" {
return os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
}
return os.Getenv("HOME")
} | go | func HomeDir() string {
failInTests()
if runtime.GOOS == "windows" {
return os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
}
return os.Getenv("HOME")
} | [
"func",
"HomeDir",
"(",
")",
"string",
"{",
"failInTests",
"(",
")",
"\n",
"if",
"runtime",
".",
"GOOS",
"==",
"\"windows\"",
"{",
"return",
"os",
".",
"Getenv",
"(",
"\"HOMEDRIVE\"",
")",
"+",
"os",
".",
"Getenv",
"(",
"\"HOMEPATH\"",
")",
"\n",
"}",
"\n",
"return",
"os",
".",
"Getenv",
"(",
"\"HOME\"",
")",
"\n",
"}"
] | // HomeDir returns the path to the user's home directory.
// It returns the empty string if the value isn't known. | [
"HomeDir",
"returns",
"the",
"path",
"to",
"the",
"user",
"s",
"home",
"directory",
".",
"It",
"returns",
"the",
"empty",
"string",
"if",
"the",
"value",
"isn",
"t",
"known",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/osutil/paths.go#L37-L43 | train |
perkeep/perkeep | internal/osutil/paths.go | NewJSONConfigParser | func NewJSONConfigParser() *jsonconfig.ConfigParser {
var cp jsonconfig.ConfigParser
dir, err := PerkeepConfigDir()
if err != nil {
log.Fatalf("NewJSONConfigParser error: %v", err)
}
cp.IncludeDirs = append([]string{dir}, filepath.SplitList(os.Getenv("CAMLI_INCLUDE_PATH"))...)
return &cp
} | go | func NewJSONConfigParser() *jsonconfig.ConfigParser {
var cp jsonconfig.ConfigParser
dir, err := PerkeepConfigDir()
if err != nil {
log.Fatalf("NewJSONConfigParser error: %v", err)
}
cp.IncludeDirs = append([]string{dir}, filepath.SplitList(os.Getenv("CAMLI_INCLUDE_PATH"))...)
return &cp
} | [
"func",
"NewJSONConfigParser",
"(",
")",
"*",
"jsonconfig",
".",
"ConfigParser",
"{",
"var",
"cp",
"jsonconfig",
".",
"ConfigParser",
"\n",
"dir",
",",
"err",
":=",
"PerkeepConfigDir",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"NewJSONConfigParser error: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"cp",
".",
"IncludeDirs",
"=",
"append",
"(",
"[",
"]",
"string",
"{",
"dir",
"}",
",",
"filepath",
".",
"SplitList",
"(",
"os",
".",
"Getenv",
"(",
"\"CAMLI_INCLUDE_PATH\"",
")",
")",
"...",
")",
"\n",
"return",
"&",
"cp",
"\n",
"}"
] | // NewJSONConfigParser returns a jsonconfig.ConfigParser with its IncludeDirs
// set with PerkeepConfigDir and the contents of CAMLI_INCLUDE_PATH. | [
"NewJSONConfigParser",
"returns",
"a",
"jsonconfig",
".",
"ConfigParser",
"with",
"its",
"IncludeDirs",
"set",
"with",
"PerkeepConfigDir",
"and",
"the",
"contents",
"of",
"CAMLI_INCLUDE_PATH",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/osutil/paths.go#L332-L340 | train |
perkeep/perkeep | pkg/sorted/mem.go | NewMemoryKeyValue | func NewMemoryKeyValue() KeyValue {
db := memdb.New(comparer.DefaultComparer, 128)
return &memKeys{db: db}
} | go | func NewMemoryKeyValue() KeyValue {
db := memdb.New(comparer.DefaultComparer, 128)
return &memKeys{db: db}
} | [
"func",
"NewMemoryKeyValue",
"(",
")",
"KeyValue",
"{",
"db",
":=",
"memdb",
".",
"New",
"(",
"comparer",
".",
"DefaultComparer",
",",
"128",
")",
"\n",
"return",
"&",
"memKeys",
"{",
"db",
":",
"db",
"}",
"\n",
"}"
] | // NewMemoryKeyValue returns a KeyValue implementation that's backed only
// by memory. It's mostly useful for tests and development. | [
"NewMemoryKeyValue",
"returns",
"a",
"KeyValue",
"implementation",
"that",
"s",
"backed",
"only",
"by",
"memory",
".",
"It",
"s",
"mostly",
"useful",
"for",
"tests",
"and",
"development",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/sorted/mem.go#L33-L36 | train |
perkeep/perkeep | app/publisher/zip.go | blobsFromDir | func (zh *zipHandler) blobsFromDir(dirPath string, dirBlob blob.Ref) ([]*blobFile, error) {
var list []*blobFile
dr, err := schema.NewDirReader(context.TODO(), zh.fetcher, dirBlob)
if err != nil {
return nil, fmt.Errorf("Could not read dir blob %v: %v", dirBlob, err)
}
ent, err := dr.Readdir(context.TODO(), -1)
if err != nil {
return nil, fmt.Errorf("Could not read dir entries: %v", err)
}
for _, v := range ent {
fullpath := path.Join(dirPath, v.FileName())
switch v.CamliType() {
case "file":
list = append(list, &blobFile{v.BlobRef(), fullpath})
case "directory":
children, err := zh.blobsFromDir(fullpath, v.BlobRef())
if err != nil {
return nil, fmt.Errorf("Could not get list of blobs from %v: %v", v.BlobRef(), err)
}
list = append(list, children...)
}
}
return list, nil
} | go | func (zh *zipHandler) blobsFromDir(dirPath string, dirBlob blob.Ref) ([]*blobFile, error) {
var list []*blobFile
dr, err := schema.NewDirReader(context.TODO(), zh.fetcher, dirBlob)
if err != nil {
return nil, fmt.Errorf("Could not read dir blob %v: %v", dirBlob, err)
}
ent, err := dr.Readdir(context.TODO(), -1)
if err != nil {
return nil, fmt.Errorf("Could not read dir entries: %v", err)
}
for _, v := range ent {
fullpath := path.Join(dirPath, v.FileName())
switch v.CamliType() {
case "file":
list = append(list, &blobFile{v.BlobRef(), fullpath})
case "directory":
children, err := zh.blobsFromDir(fullpath, v.BlobRef())
if err != nil {
return nil, fmt.Errorf("Could not get list of blobs from %v: %v", v.BlobRef(), err)
}
list = append(list, children...)
}
}
return list, nil
} | [
"func",
"(",
"zh",
"*",
"zipHandler",
")",
"blobsFromDir",
"(",
"dirPath",
"string",
",",
"dirBlob",
"blob",
".",
"Ref",
")",
"(",
"[",
"]",
"*",
"blobFile",
",",
"error",
")",
"{",
"var",
"list",
"[",
"]",
"*",
"blobFile",
"\n",
"dr",
",",
"err",
":=",
"schema",
".",
"NewDirReader",
"(",
"context",
".",
"TODO",
"(",
")",
",",
"zh",
".",
"fetcher",
",",
"dirBlob",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Could not read dir blob %v: %v\"",
",",
"dirBlob",
",",
"err",
")",
"\n",
"}",
"\n",
"ent",
",",
"err",
":=",
"dr",
".",
"Readdir",
"(",
"context",
".",
"TODO",
"(",
")",
",",
"-",
"1",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Could not read dir entries: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"ent",
"{",
"fullpath",
":=",
"path",
".",
"Join",
"(",
"dirPath",
",",
"v",
".",
"FileName",
"(",
")",
")",
"\n",
"switch",
"v",
".",
"CamliType",
"(",
")",
"{",
"case",
"\"file\"",
":",
"list",
"=",
"append",
"(",
"list",
",",
"&",
"blobFile",
"{",
"v",
".",
"BlobRef",
"(",
")",
",",
"fullpath",
"}",
")",
"\n",
"case",
"\"directory\"",
":",
"children",
",",
"err",
":=",
"zh",
".",
"blobsFromDir",
"(",
"fullpath",
",",
"v",
".",
"BlobRef",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Could not get list of blobs from %v: %v\"",
",",
"v",
".",
"BlobRef",
"(",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"list",
"=",
"append",
"(",
"list",
",",
"children",
"...",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"list",
",",
"nil",
"\n",
"}"
] | // blobsFromDir returns the list of file blobs in directory dirBlob.
// It only traverses permanode directories. | [
"blobsFromDir",
"returns",
"the",
"list",
"of",
"file",
"blobs",
"in",
"directory",
"dirBlob",
".",
"It",
"only",
"traverses",
"permanode",
"directories",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/publisher/zip.go#L159-L183 | train |
perkeep/perkeep | app/publisher/zip.go | renameDuplicates | func renameDuplicates(bf []*blobFile) sortedFiles {
noDup := make(map[string]blob.Ref)
// use a map to detect duplicates and rename them
for _, file := range bf {
if _, ok := noDup[file.path]; ok {
// path already exists, so rename
suffix := 0
var newname string
for {
suffix++
ext := path.Ext(file.path)
newname = fmt.Sprintf("%s(%d)%s",
file.path[:len(file.path)-len(ext)], suffix, ext)
if _, ok := noDup[newname]; !ok {
break
}
}
noDup[newname] = file.blobRef
} else {
noDup[file.path] = file.blobRef
}
}
// reinsert in a slice and sort it
var sorted sortedFiles
for p, b := range noDup {
sorted = append(sorted, &blobFile{path: p, blobRef: b})
}
sort.Sort(sorted)
return sorted
} | go | func renameDuplicates(bf []*blobFile) sortedFiles {
noDup := make(map[string]blob.Ref)
// use a map to detect duplicates and rename them
for _, file := range bf {
if _, ok := noDup[file.path]; ok {
// path already exists, so rename
suffix := 0
var newname string
for {
suffix++
ext := path.Ext(file.path)
newname = fmt.Sprintf("%s(%d)%s",
file.path[:len(file.path)-len(ext)], suffix, ext)
if _, ok := noDup[newname]; !ok {
break
}
}
noDup[newname] = file.blobRef
} else {
noDup[file.path] = file.blobRef
}
}
// reinsert in a slice and sort it
var sorted sortedFiles
for p, b := range noDup {
sorted = append(sorted, &blobFile{path: p, blobRef: b})
}
sort.Sort(sorted)
return sorted
} | [
"func",
"renameDuplicates",
"(",
"bf",
"[",
"]",
"*",
"blobFile",
")",
"sortedFiles",
"{",
"noDup",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"blob",
".",
"Ref",
")",
"\n",
"for",
"_",
",",
"file",
":=",
"range",
"bf",
"{",
"if",
"_",
",",
"ok",
":=",
"noDup",
"[",
"file",
".",
"path",
"]",
";",
"ok",
"{",
"suffix",
":=",
"0",
"\n",
"var",
"newname",
"string",
"\n",
"for",
"{",
"suffix",
"++",
"\n",
"ext",
":=",
"path",
".",
"Ext",
"(",
"file",
".",
"path",
")",
"\n",
"newname",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"%s(%d)%s\"",
",",
"file",
".",
"path",
"[",
":",
"len",
"(",
"file",
".",
"path",
")",
"-",
"len",
"(",
"ext",
")",
"]",
",",
"suffix",
",",
"ext",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"noDup",
"[",
"newname",
"]",
";",
"!",
"ok",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"noDup",
"[",
"newname",
"]",
"=",
"file",
".",
"blobRef",
"\n",
"}",
"else",
"{",
"noDup",
"[",
"file",
".",
"path",
"]",
"=",
"file",
".",
"blobRef",
"\n",
"}",
"\n",
"}",
"\n",
"var",
"sorted",
"sortedFiles",
"\n",
"for",
"p",
",",
"b",
":=",
"range",
"noDup",
"{",
"sorted",
"=",
"append",
"(",
"sorted",
",",
"&",
"blobFile",
"{",
"path",
":",
"p",
",",
"blobRef",
":",
"b",
"}",
")",
"\n",
"}",
"\n",
"sort",
".",
"Sort",
"(",
"sorted",
")",
"\n",
"return",
"sorted",
"\n",
"}"
] | // renameDuplicates goes through bf to check for duplicate filepaths.
// It renames duplicate filepaths and returns a new slice, sorted by
// file path. | [
"renameDuplicates",
"goes",
"through",
"bf",
"to",
"check",
"for",
"duplicate",
"filepaths",
".",
"It",
"renames",
"duplicate",
"filepaths",
"and",
"returns",
"a",
"new",
"slice",
"sorted",
"by",
"file",
"path",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/publisher/zip.go#L188-L218 | train |
perkeep/perkeep | app/publisher/zip.go | ServeHTTP | func (zh *zipHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
// TODO: use http.ServeContent, so Range requests work and downloads can be resumed.
// Will require calculating the zip length once first (ideally as cheaply as possible,
// with dummy counting writer and dummy all-zero-byte-files of a fixed size),
// and then making a dummy ReadSeeker for ServeContent that can seek to the end,
// and then seek back to the beginning, but then seeks forward make it remember
// to skip that many bytes from the archive/zip writer when answering Reads.
if !httputil.IsGet(req) {
http.Error(rw, "Invalid method", http.StatusMethodNotAllowed)
return
}
bf, err := zh.blobList("", zh.root)
if err != nil {
log.Printf("Could not serve zip for %v: %v", zh.root, err)
http.Error(rw, "Server error", http.StatusInternalServerError)
return
}
blobFiles := renameDuplicates(bf)
// TODO(mpl): streaming directly won't work on appengine if the size goes
// over 32 MB. Deal with that.
h := rw.Header()
h.Set("Content-Type", "application/zip")
filename := zh.filename
if filename == "" {
filename = "download.zip"
}
h.Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": filename}))
zw := zip.NewWriter(rw)
etag := sha1.New()
for _, file := range blobFiles {
etag.Write([]byte(file.blobRef.String()))
}
h.Set("Etag", fmt.Sprintf(`"%x"`, etag.Sum(nil)))
for _, file := range blobFiles {
fr, err := schema.NewFileReader(context.TODO(), zh.fetcher, file.blobRef)
if err != nil {
log.Printf("Can not add %v in zip, not a file: %v", file.blobRef, err)
http.Error(rw, "Server error", http.StatusInternalServerError)
return
}
zh := zip.FileHeader{
Name: file.path,
Method: zip.Store,
}
zh.SetModTime(fr.ModTime())
f, err := zw.CreateHeader(&zh)
if err != nil {
log.Printf("Could not create %q in zip: %v", file.path, err)
http.Error(rw, "Server error", http.StatusInternalServerError)
return
}
_, err = io.Copy(f, fr)
fr.Close()
if err != nil {
log.Printf("Could not zip %q: %v", file.path, err)
return
}
}
err = zw.Close()
if err != nil {
log.Printf("Could not close zipwriter: %v", err)
return
}
} | go | func (zh *zipHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
// TODO: use http.ServeContent, so Range requests work and downloads can be resumed.
// Will require calculating the zip length once first (ideally as cheaply as possible,
// with dummy counting writer and dummy all-zero-byte-files of a fixed size),
// and then making a dummy ReadSeeker for ServeContent that can seek to the end,
// and then seek back to the beginning, but then seeks forward make it remember
// to skip that many bytes from the archive/zip writer when answering Reads.
if !httputil.IsGet(req) {
http.Error(rw, "Invalid method", http.StatusMethodNotAllowed)
return
}
bf, err := zh.blobList("", zh.root)
if err != nil {
log.Printf("Could not serve zip for %v: %v", zh.root, err)
http.Error(rw, "Server error", http.StatusInternalServerError)
return
}
blobFiles := renameDuplicates(bf)
// TODO(mpl): streaming directly won't work on appengine if the size goes
// over 32 MB. Deal with that.
h := rw.Header()
h.Set("Content-Type", "application/zip")
filename := zh.filename
if filename == "" {
filename = "download.zip"
}
h.Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": filename}))
zw := zip.NewWriter(rw)
etag := sha1.New()
for _, file := range blobFiles {
etag.Write([]byte(file.blobRef.String()))
}
h.Set("Etag", fmt.Sprintf(`"%x"`, etag.Sum(nil)))
for _, file := range blobFiles {
fr, err := schema.NewFileReader(context.TODO(), zh.fetcher, file.blobRef)
if err != nil {
log.Printf("Can not add %v in zip, not a file: %v", file.blobRef, err)
http.Error(rw, "Server error", http.StatusInternalServerError)
return
}
zh := zip.FileHeader{
Name: file.path,
Method: zip.Store,
}
zh.SetModTime(fr.ModTime())
f, err := zw.CreateHeader(&zh)
if err != nil {
log.Printf("Could not create %q in zip: %v", file.path, err)
http.Error(rw, "Server error", http.StatusInternalServerError)
return
}
_, err = io.Copy(f, fr)
fr.Close()
if err != nil {
log.Printf("Could not zip %q: %v", file.path, err)
return
}
}
err = zw.Close()
if err != nil {
log.Printf("Could not close zipwriter: %v", err)
return
}
} | [
"func",
"(",
"zh",
"*",
"zipHandler",
")",
"ServeHTTP",
"(",
"rw",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"!",
"httputil",
".",
"IsGet",
"(",
"req",
")",
"{",
"http",
".",
"Error",
"(",
"rw",
",",
"\"Invalid method\"",
",",
"http",
".",
"StatusMethodNotAllowed",
")",
"\n",
"return",
"\n",
"}",
"\n",
"bf",
",",
"err",
":=",
"zh",
".",
"blobList",
"(",
"\"\"",
",",
"zh",
".",
"root",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"Could not serve zip for %v: %v\"",
",",
"zh",
".",
"root",
",",
"err",
")",
"\n",
"http",
".",
"Error",
"(",
"rw",
",",
"\"Server error\"",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"blobFiles",
":=",
"renameDuplicates",
"(",
"bf",
")",
"\n",
"h",
":=",
"rw",
".",
"Header",
"(",
")",
"\n",
"h",
".",
"Set",
"(",
"\"Content-Type\"",
",",
"\"application/zip\"",
")",
"\n",
"filename",
":=",
"zh",
".",
"filename",
"\n",
"if",
"filename",
"==",
"\"\"",
"{",
"filename",
"=",
"\"download.zip\"",
"\n",
"}",
"\n",
"h",
".",
"Set",
"(",
"\"Content-Disposition\"",
",",
"mime",
".",
"FormatMediaType",
"(",
"\"attachment\"",
",",
"map",
"[",
"string",
"]",
"string",
"{",
"\"filename\"",
":",
"filename",
"}",
")",
")",
"\n",
"zw",
":=",
"zip",
".",
"NewWriter",
"(",
"rw",
")",
"\n",
"etag",
":=",
"sha1",
".",
"New",
"(",
")",
"\n",
"for",
"_",
",",
"file",
":=",
"range",
"blobFiles",
"{",
"etag",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"file",
".",
"blobRef",
".",
"String",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"h",
".",
"Set",
"(",
"\"Etag\"",
",",
"fmt",
".",
"Sprintf",
"(",
"`\"%x\"`",
",",
"etag",
".",
"Sum",
"(",
"nil",
")",
")",
")",
"\n",
"for",
"_",
",",
"file",
":=",
"range",
"blobFiles",
"{",
"fr",
",",
"err",
":=",
"schema",
".",
"NewFileReader",
"(",
"context",
".",
"TODO",
"(",
")",
",",
"zh",
".",
"fetcher",
",",
"file",
".",
"blobRef",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"Can not add %v in zip, not a file: %v\"",
",",
"file",
".",
"blobRef",
",",
"err",
")",
"\n",
"http",
".",
"Error",
"(",
"rw",
",",
"\"Server error\"",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"zh",
":=",
"zip",
".",
"FileHeader",
"{",
"Name",
":",
"file",
".",
"path",
",",
"Method",
":",
"zip",
".",
"Store",
",",
"}",
"\n",
"zh",
".",
"SetModTime",
"(",
"fr",
".",
"ModTime",
"(",
")",
")",
"\n",
"f",
",",
"err",
":=",
"zw",
".",
"CreateHeader",
"(",
"&",
"zh",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"Could not create %q in zip: %v\"",
",",
"file",
".",
"path",
",",
"err",
")",
"\n",
"http",
".",
"Error",
"(",
"rw",
",",
"\"Server error\"",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"io",
".",
"Copy",
"(",
"f",
",",
"fr",
")",
"\n",
"fr",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"Could not zip %q: %v\"",
",",
"file",
".",
"path",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"err",
"=",
"zw",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"Could not close zipwriter: %v\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}"
] | // ServeHTTP streams a zip archive of all the files "under"
// zh.root. That is, all the files pointed by file permanodes,
// which are directly members of zh.root or recursively down
// directory permanodes and permanodes members.
// To build the fullpath of a file in a collection, it uses
// the collection title if present, its blobRef otherwise, as
// a directory name. | [
"ServeHTTP",
"streams",
"a",
"zip",
"archive",
"of",
"all",
"the",
"files",
"under",
"zh",
".",
"root",
".",
"That",
"is",
"all",
"the",
"files",
"pointed",
"by",
"file",
"permanodes",
"which",
"are",
"directly",
"members",
"of",
"zh",
".",
"root",
"or",
"recursively",
"down",
"directory",
"permanodes",
"and",
"permanodes",
"members",
".",
"To",
"build",
"the",
"fullpath",
"of",
"a",
"file",
"in",
"a",
"collection",
"it",
"uses",
"the",
"collection",
"title",
"if",
"present",
"its",
"blobRef",
"otherwise",
"as",
"a",
"directory",
"name",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/publisher/zip.go#L227-L292 | train |
perkeep/perkeep | server/perkeepd/ui/goui/sharebutton/gen_ShareItemsBtn_reactGen.go | Props | func (s ShareItemsBtnDef) Props() ShareItemsBtnProps {
uprops := s.ComponentDef.Props()
return uprops.(ShareItemsBtnProps)
} | go | func (s ShareItemsBtnDef) Props() ShareItemsBtnProps {
uprops := s.ComponentDef.Props()
return uprops.(ShareItemsBtnProps)
} | [
"func",
"(",
"s",
"ShareItemsBtnDef",
")",
"Props",
"(",
")",
"ShareItemsBtnProps",
"{",
"uprops",
":=",
"s",
".",
"ComponentDef",
".",
"Props",
"(",
")",
"\n",
"return",
"uprops",
".",
"(",
"ShareItemsBtnProps",
")",
"\n",
"}"
] | // Props is an auto-generated proxy to the current props of ShareItemsBtn | [
"Props",
"is",
"an",
"auto",
"-",
"generated",
"proxy",
"to",
"the",
"current",
"props",
"of",
"ShareItemsBtn"
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/server/perkeepd/ui/goui/sharebutton/gen_ShareItemsBtn_reactGen.go#L30-L33 | train |
perkeep/perkeep | app/publisher/main.go | appConfig | func appConfig() (*config, error) {
configURL := os.Getenv("CAMLI_APP_CONFIG_URL")
if configURL == "" {
return nil, fmt.Errorf("Publisher application needs a CAMLI_APP_CONFIG_URL env var")
}
cl, err := app.Client()
if err != nil {
return nil, fmt.Errorf("could not get a client to fetch extra config: %v", err)
}
conf := &config{}
pause := time.Second
giveupTime := time.Now().Add(time.Hour)
for {
err := cl.GetJSON(context.TODO(), configURL, conf)
if err == nil {
break
}
if time.Now().After(giveupTime) {
logger.Fatalf("Giving up on starting: could not get app config at %v: %v", configURL, err)
}
logger.Printf("could not get app config at %v: %v. Will retry in a while.", configURL, err)
time.Sleep(pause)
pause *= 2
}
return conf, nil
} | go | func appConfig() (*config, error) {
configURL := os.Getenv("CAMLI_APP_CONFIG_URL")
if configURL == "" {
return nil, fmt.Errorf("Publisher application needs a CAMLI_APP_CONFIG_URL env var")
}
cl, err := app.Client()
if err != nil {
return nil, fmt.Errorf("could not get a client to fetch extra config: %v", err)
}
conf := &config{}
pause := time.Second
giveupTime := time.Now().Add(time.Hour)
for {
err := cl.GetJSON(context.TODO(), configURL, conf)
if err == nil {
break
}
if time.Now().After(giveupTime) {
logger.Fatalf("Giving up on starting: could not get app config at %v: %v", configURL, err)
}
logger.Printf("could not get app config at %v: %v. Will retry in a while.", configURL, err)
time.Sleep(pause)
pause *= 2
}
return conf, nil
} | [
"func",
"appConfig",
"(",
")",
"(",
"*",
"config",
",",
"error",
")",
"{",
"configURL",
":=",
"os",
".",
"Getenv",
"(",
"\"CAMLI_APP_CONFIG_URL\"",
")",
"\n",
"if",
"configURL",
"==",
"\"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"Publisher application needs a CAMLI_APP_CONFIG_URL env var\"",
")",
"\n",
"}",
"\n",
"cl",
",",
"err",
":=",
"app",
".",
"Client",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"could not get a client to fetch extra config: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"conf",
":=",
"&",
"config",
"{",
"}",
"\n",
"pause",
":=",
"time",
".",
"Second",
"\n",
"giveupTime",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"time",
".",
"Hour",
")",
"\n",
"for",
"{",
"err",
":=",
"cl",
".",
"GetJSON",
"(",
"context",
".",
"TODO",
"(",
")",
",",
"configURL",
",",
"conf",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"if",
"time",
".",
"Now",
"(",
")",
".",
"After",
"(",
"giveupTime",
")",
"{",
"logger",
".",
"Fatalf",
"(",
"\"Giving up on starting: could not get app config at %v: %v\"",
",",
"configURL",
",",
"err",
")",
"\n",
"}",
"\n",
"logger",
".",
"Printf",
"(",
"\"could not get app config at %v: %v. Will retry in a while.\"",
",",
"configURL",
",",
"err",
")",
"\n",
"time",
".",
"Sleep",
"(",
"pause",
")",
"\n",
"pause",
"*=",
"2",
"\n",
"}",
"\n",
"return",
"conf",
",",
"nil",
"\n",
"}"
] | // appConfig keeps on trying to fetch the extra config from the app handler. If
// it doesn't succed after an hour has passed, the program exits. | [
"appConfig",
"keeps",
"on",
"trying",
"to",
"fetch",
"the",
"extra",
"config",
"from",
"the",
"app",
"handler",
".",
"If",
"it",
"doesn",
"t",
"succed",
"after",
"an",
"hour",
"has",
"passed",
"the",
"program",
"exits",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/publisher/main.go#L93-L118 | train |
perkeep/perkeep | app/publisher/main.go | setMasterQuery | func (ph *publishHandler) setMasterQuery(topNode blob.Ref) error {
query := &search.SearchQuery{
Sort: search.CreatedDesc,
Limit: -1,
Constraint: &search.Constraint{
Permanode: &search.PermanodeConstraint{
Relation: &search.RelationConstraint{
Relation: "parent",
Any: &search.Constraint{
BlobRefPrefix: topNode.String(),
},
},
},
},
Describe: &search.DescribeRequest{
Depth: 1,
Rules: []*search.DescribeRule{
{Attrs: []string{"camliContent", "camliContentImage", "camliMember", "camliPath:*"}},
},
},
}
data, err := json.Marshal(query)
if err != nil {
return err
}
// TODO(mpl): we should use app.Client instead, but a *client.Client
// Post method doesn't let us get the body.
req, err := http.NewRequest("POST", ph.masterQueryURL, bytes.NewReader(data))
if err != nil {
return err
}
if err := addAuth(req); err != nil {
return err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if string(body) != "OK" {
return fmt.Errorf("error setting master query on app handler: %v", string(body))
}
return nil
} | go | func (ph *publishHandler) setMasterQuery(topNode blob.Ref) error {
query := &search.SearchQuery{
Sort: search.CreatedDesc,
Limit: -1,
Constraint: &search.Constraint{
Permanode: &search.PermanodeConstraint{
Relation: &search.RelationConstraint{
Relation: "parent",
Any: &search.Constraint{
BlobRefPrefix: topNode.String(),
},
},
},
},
Describe: &search.DescribeRequest{
Depth: 1,
Rules: []*search.DescribeRule{
{Attrs: []string{"camliContent", "camliContentImage", "camliMember", "camliPath:*"}},
},
},
}
data, err := json.Marshal(query)
if err != nil {
return err
}
// TODO(mpl): we should use app.Client instead, but a *client.Client
// Post method doesn't let us get the body.
req, err := http.NewRequest("POST", ph.masterQueryURL, bytes.NewReader(data))
if err != nil {
return err
}
if err := addAuth(req); err != nil {
return err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if string(body) != "OK" {
return fmt.Errorf("error setting master query on app handler: %v", string(body))
}
return nil
} | [
"func",
"(",
"ph",
"*",
"publishHandler",
")",
"setMasterQuery",
"(",
"topNode",
"blob",
".",
"Ref",
")",
"error",
"{",
"query",
":=",
"&",
"search",
".",
"SearchQuery",
"{",
"Sort",
":",
"search",
".",
"CreatedDesc",
",",
"Limit",
":",
"-",
"1",
",",
"Constraint",
":",
"&",
"search",
".",
"Constraint",
"{",
"Permanode",
":",
"&",
"search",
".",
"PermanodeConstraint",
"{",
"Relation",
":",
"&",
"search",
".",
"RelationConstraint",
"{",
"Relation",
":",
"\"parent\"",
",",
"Any",
":",
"&",
"search",
".",
"Constraint",
"{",
"BlobRefPrefix",
":",
"topNode",
".",
"String",
"(",
")",
",",
"}",
",",
"}",
",",
"}",
",",
"}",
",",
"Describe",
":",
"&",
"search",
".",
"DescribeRequest",
"{",
"Depth",
":",
"1",
",",
"Rules",
":",
"[",
"]",
"*",
"search",
".",
"DescribeRule",
"{",
"{",
"Attrs",
":",
"[",
"]",
"string",
"{",
"\"camliContent\"",
",",
"\"camliContentImage\"",
",",
"\"camliMember\"",
",",
"\"camliPath:*\"",
"}",
"}",
",",
"}",
",",
"}",
",",
"}",
"\n",
"data",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"query",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"\"POST\"",
",",
"ph",
".",
"masterQueryURL",
",",
"bytes",
".",
"NewReader",
"(",
"data",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"addAuth",
"(",
"req",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"resp",
",",
"err",
":=",
"http",
".",
"DefaultClient",
".",
"Do",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"body",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"resp",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"string",
"(",
"body",
")",
"!=",
"\"OK\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"error setting master query on app handler: %v\"",
",",
"string",
"(",
"body",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] | // setMasterQuery registers with the app handler a master query that includes
// topNode and all its descendants as the search response. | [
"setMasterQuery",
"registers",
"with",
"the",
"app",
"handler",
"a",
"master",
"query",
"that",
"includes",
"topNode",
"and",
"all",
"its",
"descendants",
"as",
"the",
"search",
"response",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/publisher/main.go#L122-L169 | train |
perkeep/perkeep | app/publisher/main.go | resolvePrefixHop | func (ph *publishHandler) resolvePrefixHop(parent blob.Ref, prefix string) (child blob.Ref, err error) {
// TODO: this is a linear scan right now. this should be
// optimized to use a new database table of members so this is
// a quick lookup. in the meantime it should be in memcached
// at least.
if len(prefix) < 8 {
return blob.Ref{}, fmt.Errorf("Member prefix %q too small", prefix)
}
des, err := ph.describe(parent)
if err != nil {
return blob.Ref{}, fmt.Errorf("Failed to describe member %q in parent %q", prefix, parent)
}
if des.Permanode != nil {
cr, ok := des.ContentRef()
if ok && strings.HasPrefix(cr.Digest(), prefix) {
return cr, nil
}
for _, member := range des.Members() {
if strings.HasPrefix(member.BlobRef.Digest(), prefix) {
return member.BlobRef, nil
}
}
crdes, err := ph.describe(cr)
if err != nil {
return blob.Ref{}, fmt.Errorf("Failed to describe content %q of parent %q", cr, parent)
}
if crdes.Dir != nil {
return ph.resolvePrefixHop(cr, prefix)
}
} else if des.Dir != nil {
for _, child := range des.DirChildren {
if strings.HasPrefix(child.Digest(), prefix) {
return child, nil
}
}
}
return blob.Ref{}, fmt.Errorf("Member prefix %q not found in %q", prefix, parent)
} | go | func (ph *publishHandler) resolvePrefixHop(parent blob.Ref, prefix string) (child blob.Ref, err error) {
// TODO: this is a linear scan right now. this should be
// optimized to use a new database table of members so this is
// a quick lookup. in the meantime it should be in memcached
// at least.
if len(prefix) < 8 {
return blob.Ref{}, fmt.Errorf("Member prefix %q too small", prefix)
}
des, err := ph.describe(parent)
if err != nil {
return blob.Ref{}, fmt.Errorf("Failed to describe member %q in parent %q", prefix, parent)
}
if des.Permanode != nil {
cr, ok := des.ContentRef()
if ok && strings.HasPrefix(cr.Digest(), prefix) {
return cr, nil
}
for _, member := range des.Members() {
if strings.HasPrefix(member.BlobRef.Digest(), prefix) {
return member.BlobRef, nil
}
}
crdes, err := ph.describe(cr)
if err != nil {
return blob.Ref{}, fmt.Errorf("Failed to describe content %q of parent %q", cr, parent)
}
if crdes.Dir != nil {
return ph.resolvePrefixHop(cr, prefix)
}
} else if des.Dir != nil {
for _, child := range des.DirChildren {
if strings.HasPrefix(child.Digest(), prefix) {
return child, nil
}
}
}
return blob.Ref{}, fmt.Errorf("Member prefix %q not found in %q", prefix, parent)
} | [
"func",
"(",
"ph",
"*",
"publishHandler",
")",
"resolvePrefixHop",
"(",
"parent",
"blob",
".",
"Ref",
",",
"prefix",
"string",
")",
"(",
"child",
"blob",
".",
"Ref",
",",
"err",
"error",
")",
"{",
"if",
"len",
"(",
"prefix",
")",
"<",
"8",
"{",
"return",
"blob",
".",
"Ref",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"Member prefix %q too small\"",
",",
"prefix",
")",
"\n",
"}",
"\n",
"des",
",",
"err",
":=",
"ph",
".",
"describe",
"(",
"parent",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"blob",
".",
"Ref",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"Failed to describe member %q in parent %q\"",
",",
"prefix",
",",
"parent",
")",
"\n",
"}",
"\n",
"if",
"des",
".",
"Permanode",
"!=",
"nil",
"{",
"cr",
",",
"ok",
":=",
"des",
".",
"ContentRef",
"(",
")",
"\n",
"if",
"ok",
"&&",
"strings",
".",
"HasPrefix",
"(",
"cr",
".",
"Digest",
"(",
")",
",",
"prefix",
")",
"{",
"return",
"cr",
",",
"nil",
"\n",
"}",
"\n",
"for",
"_",
",",
"member",
":=",
"range",
"des",
".",
"Members",
"(",
")",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"member",
".",
"BlobRef",
".",
"Digest",
"(",
")",
",",
"prefix",
")",
"{",
"return",
"member",
".",
"BlobRef",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"crdes",
",",
"err",
":=",
"ph",
".",
"describe",
"(",
"cr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"blob",
".",
"Ref",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"Failed to describe content %q of parent %q\"",
",",
"cr",
",",
"parent",
")",
"\n",
"}",
"\n",
"if",
"crdes",
".",
"Dir",
"!=",
"nil",
"{",
"return",
"ph",
".",
"resolvePrefixHop",
"(",
"cr",
",",
"prefix",
")",
"\n",
"}",
"\n",
"}",
"else",
"if",
"des",
".",
"Dir",
"!=",
"nil",
"{",
"for",
"_",
",",
"child",
":=",
"range",
"des",
".",
"DirChildren",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"child",
".",
"Digest",
"(",
")",
",",
"prefix",
")",
"{",
"return",
"child",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"blob",
".",
"Ref",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"Member prefix %q not found in %q\"",
",",
"prefix",
",",
"parent",
")",
"\n",
"}"
] | // Given a blobref and a few hex characters of the digest of the next hop, return the complete
// blobref of the prefix, if that's a valid next hop. | [
"Given",
"a",
"blobref",
"and",
"a",
"few",
"hex",
"characters",
"of",
"the",
"digest",
"of",
"the",
"next",
"hop",
"return",
"the",
"complete",
"blobref",
"of",
"the",
"prefix",
"if",
"that",
"s",
"a",
"valid",
"next",
"hop",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/publisher/main.go#L565-L602 | train |
perkeep/perkeep | app/publisher/main.go | serveSubjectTemplate | func (pr *publishRequest) serveSubjectTemplate() {
res, err := pr.ph.deepDescribe(pr.subject)
if err != nil {
httputil.ServeError(pr.rw, pr.req, err)
return
}
pr.ph.cacheDescribed(res.Meta)
subdes := res.Meta[pr.subject.String()]
if subdes.CamliType == "file" {
pr.serveFileDownload(subdes)
return
}
headerFunc := func() *publish.PageHeader {
return pr.subjectHeader(res.Meta)
}
fileFunc := func() *publish.PageFile {
file, err := pr.subjectFile(res.Meta)
if err != nil {
logf("%v", err)
return nil
}
return file
}
membersFunc := func() *publish.PageMembers {
members, err := pr.subjectMembers(res.Meta)
if err != nil {
logf("%v", err)
return nil
}
return members
}
page := &publish.SubjectPage{
Header: headerFunc,
File: fileFunc,
Members: membersFunc,
}
err = pr.ph.goTemplate.Execute(pr.rw, page)
if err != nil {
logf("Error serving subject template: %v", err)
http.Error(pr.rw, "Error serving template", http.StatusInternalServerError)
return
}
} | go | func (pr *publishRequest) serveSubjectTemplate() {
res, err := pr.ph.deepDescribe(pr.subject)
if err != nil {
httputil.ServeError(pr.rw, pr.req, err)
return
}
pr.ph.cacheDescribed(res.Meta)
subdes := res.Meta[pr.subject.String()]
if subdes.CamliType == "file" {
pr.serveFileDownload(subdes)
return
}
headerFunc := func() *publish.PageHeader {
return pr.subjectHeader(res.Meta)
}
fileFunc := func() *publish.PageFile {
file, err := pr.subjectFile(res.Meta)
if err != nil {
logf("%v", err)
return nil
}
return file
}
membersFunc := func() *publish.PageMembers {
members, err := pr.subjectMembers(res.Meta)
if err != nil {
logf("%v", err)
return nil
}
return members
}
page := &publish.SubjectPage{
Header: headerFunc,
File: fileFunc,
Members: membersFunc,
}
err = pr.ph.goTemplate.Execute(pr.rw, page)
if err != nil {
logf("Error serving subject template: %v", err)
http.Error(pr.rw, "Error serving template", http.StatusInternalServerError)
return
}
} | [
"func",
"(",
"pr",
"*",
"publishRequest",
")",
"serveSubjectTemplate",
"(",
")",
"{",
"res",
",",
"err",
":=",
"pr",
".",
"ph",
".",
"deepDescribe",
"(",
"pr",
".",
"subject",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"httputil",
".",
"ServeError",
"(",
"pr",
".",
"rw",
",",
"pr",
".",
"req",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"pr",
".",
"ph",
".",
"cacheDescribed",
"(",
"res",
".",
"Meta",
")",
"\n",
"subdes",
":=",
"res",
".",
"Meta",
"[",
"pr",
".",
"subject",
".",
"String",
"(",
")",
"]",
"\n",
"if",
"subdes",
".",
"CamliType",
"==",
"\"file\"",
"{",
"pr",
".",
"serveFileDownload",
"(",
"subdes",
")",
"\n",
"return",
"\n",
"}",
"\n",
"headerFunc",
":=",
"func",
"(",
")",
"*",
"publish",
".",
"PageHeader",
"{",
"return",
"pr",
".",
"subjectHeader",
"(",
"res",
".",
"Meta",
")",
"\n",
"}",
"\n",
"fileFunc",
":=",
"func",
"(",
")",
"*",
"publish",
".",
"PageFile",
"{",
"file",
",",
"err",
":=",
"pr",
".",
"subjectFile",
"(",
"res",
".",
"Meta",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logf",
"(",
"\"%v\"",
",",
"err",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"file",
"\n",
"}",
"\n",
"membersFunc",
":=",
"func",
"(",
")",
"*",
"publish",
".",
"PageMembers",
"{",
"members",
",",
"err",
":=",
"pr",
".",
"subjectMembers",
"(",
"res",
".",
"Meta",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logf",
"(",
"\"%v\"",
",",
"err",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"members",
"\n",
"}",
"\n",
"page",
":=",
"&",
"publish",
".",
"SubjectPage",
"{",
"Header",
":",
"headerFunc",
",",
"File",
":",
"fileFunc",
",",
"Members",
":",
"membersFunc",
",",
"}",
"\n",
"err",
"=",
"pr",
".",
"ph",
".",
"goTemplate",
".",
"Execute",
"(",
"pr",
".",
"rw",
",",
"page",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logf",
"(",
"\"Error serving subject template: %v\"",
",",
"err",
")",
"\n",
"http",
".",
"Error",
"(",
"pr",
".",
"rw",
",",
"\"Error serving template\"",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}"
] | // serveSubjectTemplate creates the funcs to generate the PageHeader, PageFile,
// and pageMembers that can be used by the subject template, and serves the template. | [
"serveSubjectTemplate",
"creates",
"the",
"funcs",
"to",
"generate",
"the",
"PageHeader",
"PageFile",
"and",
"pageMembers",
"that",
"can",
"be",
"used",
"by",
"the",
"subject",
"template",
"and",
"serves",
"the",
"template",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/publisher/main.go#L863-L908 | train |
perkeep/perkeep | app/publisher/main.go | subjectHeader | func (pr *publishRequest) subjectHeader(described map[string]*search.DescribedBlob) *publish.PageHeader {
subdes := described[pr.subject.String()]
header := &publish.PageHeader{
Title: html.EscapeString(getTitle(subdes.BlobRef, described)),
CSSFiles: pr.cssFiles(),
JSDeps: pr.jsDeps(),
Subject: pr.subject,
Host: pr.req.Host,
SubjectBasePath: pr.subjectBasePath,
PathPrefix: pr.base,
PublishedRoot: pr.publishedRoot,
}
return header
} | go | func (pr *publishRequest) subjectHeader(described map[string]*search.DescribedBlob) *publish.PageHeader {
subdes := described[pr.subject.String()]
header := &publish.PageHeader{
Title: html.EscapeString(getTitle(subdes.BlobRef, described)),
CSSFiles: pr.cssFiles(),
JSDeps: pr.jsDeps(),
Subject: pr.subject,
Host: pr.req.Host,
SubjectBasePath: pr.subjectBasePath,
PathPrefix: pr.base,
PublishedRoot: pr.publishedRoot,
}
return header
} | [
"func",
"(",
"pr",
"*",
"publishRequest",
")",
"subjectHeader",
"(",
"described",
"map",
"[",
"string",
"]",
"*",
"search",
".",
"DescribedBlob",
")",
"*",
"publish",
".",
"PageHeader",
"{",
"subdes",
":=",
"described",
"[",
"pr",
".",
"subject",
".",
"String",
"(",
")",
"]",
"\n",
"header",
":=",
"&",
"publish",
".",
"PageHeader",
"{",
"Title",
":",
"html",
".",
"EscapeString",
"(",
"getTitle",
"(",
"subdes",
".",
"BlobRef",
",",
"described",
")",
")",
",",
"CSSFiles",
":",
"pr",
".",
"cssFiles",
"(",
")",
",",
"JSDeps",
":",
"pr",
".",
"jsDeps",
"(",
")",
",",
"Subject",
":",
"pr",
".",
"subject",
",",
"Host",
":",
"pr",
".",
"req",
".",
"Host",
",",
"SubjectBasePath",
":",
"pr",
".",
"subjectBasePath",
",",
"PathPrefix",
":",
"pr",
".",
"base",
",",
"PublishedRoot",
":",
"pr",
".",
"publishedRoot",
",",
"}",
"\n",
"return",
"header",
"\n",
"}"
] | // subjectHeader returns the PageHeader corresponding to the described subject. | [
"subjectHeader",
"returns",
"the",
"PageHeader",
"corresponding",
"to",
"the",
"described",
"subject",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/publisher/main.go#L977-L990 | train |
perkeep/perkeep | app/publisher/main.go | subjectFile | func (pr *publishRequest) subjectFile(described map[string]*search.DescribedBlob) (*publish.PageFile, error) {
subdes := described[pr.subject.String()]
contentRef, ok := subdes.ContentRef()
if !ok {
return nil, nil
}
fileDes, err := pr.ph.describe(contentRef)
if err != nil {
return nil, err
}
if fileDes.File == nil {
// most likely a dir
return nil, nil
}
path := []blob.Ref{pr.subject, contentRef}
downloadURL := pr.SubresFileURL(path, fileDes.File.FileName)
thumbnailURL := ""
if fileDes.File.IsImage() {
thumbnailURL = pr.SubresThumbnailURL(path, fileDes.File.FileName, 600)
}
fileName := html.EscapeString(fileDes.File.FileName)
return &publish.PageFile{
FileName: fileName,
Size: fileDes.File.Size,
MIMEType: fileDes.File.MIMEType,
IsImage: fileDes.File.IsImage(),
DownloadURL: downloadURL,
ThumbnailURL: thumbnailURL,
DomID: contentRef.DomID(),
Nav: func() *publish.Nav {
return nil
},
}, nil
} | go | func (pr *publishRequest) subjectFile(described map[string]*search.DescribedBlob) (*publish.PageFile, error) {
subdes := described[pr.subject.String()]
contentRef, ok := subdes.ContentRef()
if !ok {
return nil, nil
}
fileDes, err := pr.ph.describe(contentRef)
if err != nil {
return nil, err
}
if fileDes.File == nil {
// most likely a dir
return nil, nil
}
path := []blob.Ref{pr.subject, contentRef}
downloadURL := pr.SubresFileURL(path, fileDes.File.FileName)
thumbnailURL := ""
if fileDes.File.IsImage() {
thumbnailURL = pr.SubresThumbnailURL(path, fileDes.File.FileName, 600)
}
fileName := html.EscapeString(fileDes.File.FileName)
return &publish.PageFile{
FileName: fileName,
Size: fileDes.File.Size,
MIMEType: fileDes.File.MIMEType,
IsImage: fileDes.File.IsImage(),
DownloadURL: downloadURL,
ThumbnailURL: thumbnailURL,
DomID: contentRef.DomID(),
Nav: func() *publish.Nav {
return nil
},
}, nil
} | [
"func",
"(",
"pr",
"*",
"publishRequest",
")",
"subjectFile",
"(",
"described",
"map",
"[",
"string",
"]",
"*",
"search",
".",
"DescribedBlob",
")",
"(",
"*",
"publish",
".",
"PageFile",
",",
"error",
")",
"{",
"subdes",
":=",
"described",
"[",
"pr",
".",
"subject",
".",
"String",
"(",
")",
"]",
"\n",
"contentRef",
",",
"ok",
":=",
"subdes",
".",
"ContentRef",
"(",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"fileDes",
",",
"err",
":=",
"pr",
".",
"ph",
".",
"describe",
"(",
"contentRef",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"fileDes",
".",
"File",
"==",
"nil",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"path",
":=",
"[",
"]",
"blob",
".",
"Ref",
"{",
"pr",
".",
"subject",
",",
"contentRef",
"}",
"\n",
"downloadURL",
":=",
"pr",
".",
"SubresFileURL",
"(",
"path",
",",
"fileDes",
".",
"File",
".",
"FileName",
")",
"\n",
"thumbnailURL",
":=",
"\"\"",
"\n",
"if",
"fileDes",
".",
"File",
".",
"IsImage",
"(",
")",
"{",
"thumbnailURL",
"=",
"pr",
".",
"SubresThumbnailURL",
"(",
"path",
",",
"fileDes",
".",
"File",
".",
"FileName",
",",
"600",
")",
"\n",
"}",
"\n",
"fileName",
":=",
"html",
".",
"EscapeString",
"(",
"fileDes",
".",
"File",
".",
"FileName",
")",
"\n",
"return",
"&",
"publish",
".",
"PageFile",
"{",
"FileName",
":",
"fileName",
",",
"Size",
":",
"fileDes",
".",
"File",
".",
"Size",
",",
"MIMEType",
":",
"fileDes",
".",
"File",
".",
"MIMEType",
",",
"IsImage",
":",
"fileDes",
".",
"File",
".",
"IsImage",
"(",
")",
",",
"DownloadURL",
":",
"downloadURL",
",",
"ThumbnailURL",
":",
"thumbnailURL",
",",
"DomID",
":",
"contentRef",
".",
"DomID",
"(",
")",
",",
"Nav",
":",
"func",
"(",
")",
"*",
"publish",
".",
"Nav",
"{",
"return",
"nil",
"\n",
"}",
",",
"}",
",",
"nil",
"\n",
"}"
] | // subjectFile returns the relevant PageFile if the described subject is a file permanode. | [
"subjectFile",
"returns",
"the",
"relevant",
"PageFile",
"if",
"the",
"described",
"subject",
"is",
"a",
"file",
"permanode",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/publisher/main.go#L1037-L1071 | train |
perkeep/perkeep | app/publisher/main.go | subjectMembers | func (pr *publishRequest) subjectMembers(resMap map[string]*search.DescribedBlob) (*publish.PageMembers, error) {
subdes := resMap[pr.subject.String()]
res, err := pr.ph.describeMembers(pr.subject)
if err != nil {
return nil, err
}
members := []*search.DescribedBlob{}
for _, v := range res.Blobs {
members = append(members, res.Describe.Meta[v.Blob.String()])
}
if len(members) == 0 {
return nil, nil
}
zipName := ""
if title := getTitle(subdes.BlobRef, resMap); title == "" {
zipName = "download.zip"
} else {
zipName = title + ".zip"
}
subjectPath := pr.subjectBasePath
if !strings.Contains(subjectPath, "/-/") {
subjectPath += "/-"
}
return &publish.PageMembers{
SubjectPath: subjectPath,
ZipName: zipName,
Members: members,
Description: func(member *search.DescribedBlob) string {
des := member.Description()
if des != "" {
des = " - " + des
}
return des
},
Title: func(member *search.DescribedBlob) string {
memberTitle := getTitle(member.BlobRef, resMap)
if memberTitle == "" {
memberTitle = member.BlobRef.DigestPrefix(10)
}
return html.EscapeString(memberTitle)
},
Path: func(member *search.DescribedBlob) string {
return pr.memberPath(member.BlobRef)
},
DomID: func(member *search.DescribedBlob) string {
return member.DomID()
},
FileInfo: func(member *search.DescribedBlob) *publish.MemberFileInfo {
if path, fileInfo, ok := getFileInfo(member.BlobRef, resMap); ok {
info := &publish.MemberFileInfo{
FileName: fileInfo.FileName,
FileDomID: path[len(path)-1].DomID(),
FilePath: html.EscapeString(pr.SubresFileURL(path, fileInfo.FileName)),
}
if fileInfo.IsImage() {
info.FileThumbnailURL = pr.SubresThumbnailURL(path, fileInfo.FileName, 200)
}
return info
}
return nil
},
}, nil
} | go | func (pr *publishRequest) subjectMembers(resMap map[string]*search.DescribedBlob) (*publish.PageMembers, error) {
subdes := resMap[pr.subject.String()]
res, err := pr.ph.describeMembers(pr.subject)
if err != nil {
return nil, err
}
members := []*search.DescribedBlob{}
for _, v := range res.Blobs {
members = append(members, res.Describe.Meta[v.Blob.String()])
}
if len(members) == 0 {
return nil, nil
}
zipName := ""
if title := getTitle(subdes.BlobRef, resMap); title == "" {
zipName = "download.zip"
} else {
zipName = title + ".zip"
}
subjectPath := pr.subjectBasePath
if !strings.Contains(subjectPath, "/-/") {
subjectPath += "/-"
}
return &publish.PageMembers{
SubjectPath: subjectPath,
ZipName: zipName,
Members: members,
Description: func(member *search.DescribedBlob) string {
des := member.Description()
if des != "" {
des = " - " + des
}
return des
},
Title: func(member *search.DescribedBlob) string {
memberTitle := getTitle(member.BlobRef, resMap)
if memberTitle == "" {
memberTitle = member.BlobRef.DigestPrefix(10)
}
return html.EscapeString(memberTitle)
},
Path: func(member *search.DescribedBlob) string {
return pr.memberPath(member.BlobRef)
},
DomID: func(member *search.DescribedBlob) string {
return member.DomID()
},
FileInfo: func(member *search.DescribedBlob) *publish.MemberFileInfo {
if path, fileInfo, ok := getFileInfo(member.BlobRef, resMap); ok {
info := &publish.MemberFileInfo{
FileName: fileInfo.FileName,
FileDomID: path[len(path)-1].DomID(),
FilePath: html.EscapeString(pr.SubresFileURL(path, fileInfo.FileName)),
}
if fileInfo.IsImage() {
info.FileThumbnailURL = pr.SubresThumbnailURL(path, fileInfo.FileName, 200)
}
return info
}
return nil
},
}, nil
} | [
"func",
"(",
"pr",
"*",
"publishRequest",
")",
"subjectMembers",
"(",
"resMap",
"map",
"[",
"string",
"]",
"*",
"search",
".",
"DescribedBlob",
")",
"(",
"*",
"publish",
".",
"PageMembers",
",",
"error",
")",
"{",
"subdes",
":=",
"resMap",
"[",
"pr",
".",
"subject",
".",
"String",
"(",
")",
"]",
"\n",
"res",
",",
"err",
":=",
"pr",
".",
"ph",
".",
"describeMembers",
"(",
"pr",
".",
"subject",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"members",
":=",
"[",
"]",
"*",
"search",
".",
"DescribedBlob",
"{",
"}",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"res",
".",
"Blobs",
"{",
"members",
"=",
"append",
"(",
"members",
",",
"res",
".",
"Describe",
".",
"Meta",
"[",
"v",
".",
"Blob",
".",
"String",
"(",
")",
"]",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"members",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"zipName",
":=",
"\"\"",
"\n",
"if",
"title",
":=",
"getTitle",
"(",
"subdes",
".",
"BlobRef",
",",
"resMap",
")",
";",
"title",
"==",
"\"\"",
"{",
"zipName",
"=",
"\"download.zip\"",
"\n",
"}",
"else",
"{",
"zipName",
"=",
"title",
"+",
"\".zip\"",
"\n",
"}",
"\n",
"subjectPath",
":=",
"pr",
".",
"subjectBasePath",
"\n",
"if",
"!",
"strings",
".",
"Contains",
"(",
"subjectPath",
",",
"\"/-/\"",
")",
"{",
"subjectPath",
"+=",
"\"/-\"",
"\n",
"}",
"\n",
"return",
"&",
"publish",
".",
"PageMembers",
"{",
"SubjectPath",
":",
"subjectPath",
",",
"ZipName",
":",
"zipName",
",",
"Members",
":",
"members",
",",
"Description",
":",
"func",
"(",
"member",
"*",
"search",
".",
"DescribedBlob",
")",
"string",
"{",
"des",
":=",
"member",
".",
"Description",
"(",
")",
"\n",
"if",
"des",
"!=",
"\"\"",
"{",
"des",
"=",
"\" - \"",
"+",
"des",
"\n",
"}",
"\n",
"return",
"des",
"\n",
"}",
",",
"Title",
":",
"func",
"(",
"member",
"*",
"search",
".",
"DescribedBlob",
")",
"string",
"{",
"memberTitle",
":=",
"getTitle",
"(",
"member",
".",
"BlobRef",
",",
"resMap",
")",
"\n",
"if",
"memberTitle",
"==",
"\"\"",
"{",
"memberTitle",
"=",
"member",
".",
"BlobRef",
".",
"DigestPrefix",
"(",
"10",
")",
"\n",
"}",
"\n",
"return",
"html",
".",
"EscapeString",
"(",
"memberTitle",
")",
"\n",
"}",
",",
"Path",
":",
"func",
"(",
"member",
"*",
"search",
".",
"DescribedBlob",
")",
"string",
"{",
"return",
"pr",
".",
"memberPath",
"(",
"member",
".",
"BlobRef",
")",
"\n",
"}",
",",
"DomID",
":",
"func",
"(",
"member",
"*",
"search",
".",
"DescribedBlob",
")",
"string",
"{",
"return",
"member",
".",
"DomID",
"(",
")",
"\n",
"}",
",",
"FileInfo",
":",
"func",
"(",
"member",
"*",
"search",
".",
"DescribedBlob",
")",
"*",
"publish",
".",
"MemberFileInfo",
"{",
"if",
"path",
",",
"fileInfo",
",",
"ok",
":=",
"getFileInfo",
"(",
"member",
".",
"BlobRef",
",",
"resMap",
")",
";",
"ok",
"{",
"info",
":=",
"&",
"publish",
".",
"MemberFileInfo",
"{",
"FileName",
":",
"fileInfo",
".",
"FileName",
",",
"FileDomID",
":",
"path",
"[",
"len",
"(",
"path",
")",
"-",
"1",
"]",
".",
"DomID",
"(",
")",
",",
"FilePath",
":",
"html",
".",
"EscapeString",
"(",
"pr",
".",
"SubresFileURL",
"(",
"path",
",",
"fileInfo",
".",
"FileName",
")",
")",
",",
"}",
"\n",
"if",
"fileInfo",
".",
"IsImage",
"(",
")",
"{",
"info",
".",
"FileThumbnailURL",
"=",
"pr",
".",
"SubresThumbnailURL",
"(",
"path",
",",
"fileInfo",
".",
"FileName",
",",
"200",
")",
"\n",
"}",
"\n",
"return",
"info",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
",",
"}",
",",
"nil",
"\n",
"}"
] | // subjectMembers returns the relevant PageMembers if the described subject is a permanode with members. | [
"subjectMembers",
"returns",
"the",
"relevant",
"PageMembers",
"if",
"the",
"described",
"subject",
"is",
"a",
"permanode",
"with",
"members",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/publisher/main.go#L1102-L1166 | train |
perkeep/perkeep | app/publisher/main.go | serveZip | func (pr *publishRequest) serveZip() {
filename := ""
if len(pr.subres) > len("/=z/") {
filename = pr.subres[4:]
}
zh := &zipHandler{
fetcher: pr.ph.cl,
cl: pr.ph.cl,
root: pr.subject,
filename: filename,
}
zh.ServeHTTP(pr.rw, pr.req)
} | go | func (pr *publishRequest) serveZip() {
filename := ""
if len(pr.subres) > len("/=z/") {
filename = pr.subres[4:]
}
zh := &zipHandler{
fetcher: pr.ph.cl,
cl: pr.ph.cl,
root: pr.subject,
filename: filename,
}
zh.ServeHTTP(pr.rw, pr.req)
} | [
"func",
"(",
"pr",
"*",
"publishRequest",
")",
"serveZip",
"(",
")",
"{",
"filename",
":=",
"\"\"",
"\n",
"if",
"len",
"(",
"pr",
".",
"subres",
")",
">",
"len",
"(",
"\"/=z/\"",
")",
"{",
"filename",
"=",
"pr",
".",
"subres",
"[",
"4",
":",
"]",
"\n",
"}",
"\n",
"zh",
":=",
"&",
"zipHandler",
"{",
"fetcher",
":",
"pr",
".",
"ph",
".",
"cl",
",",
"cl",
":",
"pr",
".",
"ph",
".",
"cl",
",",
"root",
":",
"pr",
".",
"subject",
",",
"filename",
":",
"filename",
",",
"}",
"\n",
"zh",
".",
"ServeHTTP",
"(",
"pr",
".",
"rw",
",",
"pr",
".",
"req",
")",
"\n",
"}"
] | // serveZip streams a zip archive of all the files "under"
// pr.subject. That is, all the files pointed by file permanodes,
// which are directly members of pr.subject or recursively down
// directory permanodes and permanodes members. | [
"serveZip",
"streams",
"a",
"zip",
"archive",
"of",
"all",
"the",
"files",
"under",
"pr",
".",
"subject",
".",
"That",
"is",
"all",
"the",
"files",
"pointed",
"by",
"file",
"permanodes",
"which",
"are",
"directly",
"members",
"of",
"pr",
".",
"subject",
"or",
"recursively",
"down",
"directory",
"permanodes",
"and",
"permanodes",
"members",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/publisher/main.go#L1244-L1256 | train |
perkeep/perkeep | pkg/blobserver/blobpacked/subfetch.go | SubFetch | func (s *storage) SubFetch(ctx context.Context, ref blob.Ref, offset, length int64) (io.ReadCloser, error) {
// TODO: pass ctx to more calls within this method.
m, err := s.getMetaRow(ref)
if err != nil {
return nil, err
}
if m.isPacked() {
length, err = capOffsetLength(m.size, offset, length)
if err != nil {
return nil, err
}
// get the blob from the large subfetcher
return s.large.SubFetch(ctx, m.largeRef, int64(m.largeOff)+offset, length)
}
if sf, ok := s.small.(blob.SubFetcher); ok {
rc, err := sf.SubFetch(ctx, ref, offset, length)
if err != blob.ErrUnimplemented {
return rc, err
}
}
rc, size, err := s.small.Fetch(ctx, ref)
if err != nil {
return rc, err
}
length, err = capOffsetLength(size, offset, length)
if err != nil {
rc.Close()
return nil, err
}
if offset != 0 {
if _, err = io.CopyN(ioutil.Discard, rc, offset); err != nil {
rc.Close()
return nil, err
}
}
return struct {
io.Reader
io.Closer
}{io.LimitReader(rc, length), rc}, nil
} | go | func (s *storage) SubFetch(ctx context.Context, ref blob.Ref, offset, length int64) (io.ReadCloser, error) {
// TODO: pass ctx to more calls within this method.
m, err := s.getMetaRow(ref)
if err != nil {
return nil, err
}
if m.isPacked() {
length, err = capOffsetLength(m.size, offset, length)
if err != nil {
return nil, err
}
// get the blob from the large subfetcher
return s.large.SubFetch(ctx, m.largeRef, int64(m.largeOff)+offset, length)
}
if sf, ok := s.small.(blob.SubFetcher); ok {
rc, err := sf.SubFetch(ctx, ref, offset, length)
if err != blob.ErrUnimplemented {
return rc, err
}
}
rc, size, err := s.small.Fetch(ctx, ref)
if err != nil {
return rc, err
}
length, err = capOffsetLength(size, offset, length)
if err != nil {
rc.Close()
return nil, err
}
if offset != 0 {
if _, err = io.CopyN(ioutil.Discard, rc, offset); err != nil {
rc.Close()
return nil, err
}
}
return struct {
io.Reader
io.Closer
}{io.LimitReader(rc, length), rc}, nil
} | [
"func",
"(",
"s",
"*",
"storage",
")",
"SubFetch",
"(",
"ctx",
"context",
".",
"Context",
",",
"ref",
"blob",
".",
"Ref",
",",
"offset",
",",
"length",
"int64",
")",
"(",
"io",
".",
"ReadCloser",
",",
"error",
")",
"{",
"m",
",",
"err",
":=",
"s",
".",
"getMetaRow",
"(",
"ref",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"m",
".",
"isPacked",
"(",
")",
"{",
"length",
",",
"err",
"=",
"capOffsetLength",
"(",
"m",
".",
"size",
",",
"offset",
",",
"length",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"s",
".",
"large",
".",
"SubFetch",
"(",
"ctx",
",",
"m",
".",
"largeRef",
",",
"int64",
"(",
"m",
".",
"largeOff",
")",
"+",
"offset",
",",
"length",
")",
"\n",
"}",
"\n",
"if",
"sf",
",",
"ok",
":=",
"s",
".",
"small",
".",
"(",
"blob",
".",
"SubFetcher",
")",
";",
"ok",
"{",
"rc",
",",
"err",
":=",
"sf",
".",
"SubFetch",
"(",
"ctx",
",",
"ref",
",",
"offset",
",",
"length",
")",
"\n",
"if",
"err",
"!=",
"blob",
".",
"ErrUnimplemented",
"{",
"return",
"rc",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"rc",
",",
"size",
",",
"err",
":=",
"s",
".",
"small",
".",
"Fetch",
"(",
"ctx",
",",
"ref",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"rc",
",",
"err",
"\n",
"}",
"\n",
"length",
",",
"err",
"=",
"capOffsetLength",
"(",
"size",
",",
"offset",
",",
"length",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"rc",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"offset",
"!=",
"0",
"{",
"if",
"_",
",",
"err",
"=",
"io",
".",
"CopyN",
"(",
"ioutil",
".",
"Discard",
",",
"rc",
",",
"offset",
")",
";",
"err",
"!=",
"nil",
"{",
"rc",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"struct",
"{",
"io",
".",
"Reader",
"\n",
"io",
".",
"Closer",
"\n",
"}",
"{",
"io",
".",
"LimitReader",
"(",
"rc",
",",
"length",
")",
",",
"rc",
"}",
",",
"nil",
"\n",
"}"
] | // SubFetch returns part of a blob.
// The caller must close the returned io.ReadCloser.
// The Reader may return fewer than 'length' bytes. Callers should
// check. The returned error should be os.ErrNotExist if the blob
// doesn't exist. | [
"SubFetch",
"returns",
"part",
"of",
"a",
"blob",
".",
"The",
"caller",
"must",
"close",
"the",
"returned",
"io",
".",
"ReadCloser",
".",
"The",
"Reader",
"may",
"return",
"fewer",
"than",
"length",
"bytes",
".",
"Callers",
"should",
"check",
".",
"The",
"returned",
"error",
"should",
"be",
"os",
".",
"ErrNotExist",
"if",
"the",
"blob",
"doesn",
"t",
"exist",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/blobpacked/subfetch.go#L35-L74 | train |
perkeep/perkeep | pkg/deploy/gce/handler.go | NewDeployHandlerFromConfig | func NewDeployHandlerFromConfig(host, prefix string, cfg *Config) (*DeployHandler, error) {
if cfg == nil {
panic("NewDeployHandlerFromConfig: nil config")
}
if cfg.ClientID == "" {
return nil, errors.New("oauth2 clientID required in config")
}
if cfg.ClientSecret == "" {
return nil, errors.New("oauth2 clientSecret required in config")
}
os.Setenv("CAMLI_GCE_CLIENTID", cfg.ClientID)
os.Setenv("CAMLI_GCE_CLIENTSECRET", cfg.ClientSecret)
os.Setenv("CAMLI_GCE_PROJECT", cfg.Project)
os.Setenv("CAMLI_GCE_SERVICE_ACCOUNT", cfg.ServiceAccount)
os.Setenv("CAMLI_GCE_DATA", cfg.DataDir)
return NewDeployHandler(host, prefix)
} | go | func NewDeployHandlerFromConfig(host, prefix string, cfg *Config) (*DeployHandler, error) {
if cfg == nil {
panic("NewDeployHandlerFromConfig: nil config")
}
if cfg.ClientID == "" {
return nil, errors.New("oauth2 clientID required in config")
}
if cfg.ClientSecret == "" {
return nil, errors.New("oauth2 clientSecret required in config")
}
os.Setenv("CAMLI_GCE_CLIENTID", cfg.ClientID)
os.Setenv("CAMLI_GCE_CLIENTSECRET", cfg.ClientSecret)
os.Setenv("CAMLI_GCE_PROJECT", cfg.Project)
os.Setenv("CAMLI_GCE_SERVICE_ACCOUNT", cfg.ServiceAccount)
os.Setenv("CAMLI_GCE_DATA", cfg.DataDir)
return NewDeployHandler(host, prefix)
} | [
"func",
"NewDeployHandlerFromConfig",
"(",
"host",
",",
"prefix",
"string",
",",
"cfg",
"*",
"Config",
")",
"(",
"*",
"DeployHandler",
",",
"error",
")",
"{",
"if",
"cfg",
"==",
"nil",
"{",
"panic",
"(",
"\"NewDeployHandlerFromConfig: nil config\"",
")",
"\n",
"}",
"\n",
"if",
"cfg",
".",
"ClientID",
"==",
"\"\"",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"oauth2 clientID required in config\"",
")",
"\n",
"}",
"\n",
"if",
"cfg",
".",
"ClientSecret",
"==",
"\"\"",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"oauth2 clientSecret required in config\"",
")",
"\n",
"}",
"\n",
"os",
".",
"Setenv",
"(",
"\"CAMLI_GCE_CLIENTID\"",
",",
"cfg",
".",
"ClientID",
")",
"\n",
"os",
".",
"Setenv",
"(",
"\"CAMLI_GCE_CLIENTSECRET\"",
",",
"cfg",
".",
"ClientSecret",
")",
"\n",
"os",
".",
"Setenv",
"(",
"\"CAMLI_GCE_PROJECT\"",
",",
"cfg",
".",
"Project",
")",
"\n",
"os",
".",
"Setenv",
"(",
"\"CAMLI_GCE_SERVICE_ACCOUNT\"",
",",
"cfg",
".",
"ServiceAccount",
")",
"\n",
"os",
".",
"Setenv",
"(",
"\"CAMLI_GCE_DATA\"",
",",
"cfg",
".",
"DataDir",
")",
"\n",
"return",
"NewDeployHandler",
"(",
"host",
",",
"prefix",
")",
"\n",
"}"
] | // NewDeployHandlerFromConfig initializes a DeployHandler from cfg.
// Host and prefix have the same meaning as for NewDeployHandler. cfg should not be nil. | [
"NewDeployHandlerFromConfig",
"initializes",
"a",
"DeployHandler",
"from",
"cfg",
".",
"Host",
"and",
"prefix",
"have",
"the",
"same",
"meaning",
"as",
"for",
"NewDeployHandler",
".",
"cfg",
"should",
"not",
"be",
"nil",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/deploy/gce/handler.go#L128-L144 | train |
perkeep/perkeep | pkg/deploy/gce/handler.go | serveRoot | func (h *DeployHandler) serveRoot(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
h.serveSetup(w, r)
return
}
_, err := r.Cookie("user")
if err != nil {
http.SetCookie(w, newCookie())
}
camliRev := h.camliRev()
if r.FormValue("WIP") == "1" {
camliRev = "WORKINPROGRESS"
}
h.tplMu.RLock()
defer h.tplMu.RUnlock()
if err := h.tpl.ExecuteTemplate(w, "withform", &TemplateData{
ProjectID: r.FormValue("project"),
Prefix: h.prefix,
Help: h.help,
ZoneValues: h.zoneValues(),
MachineValues: machineValues,
CamliVersion: camliRev,
}); err != nil {
h.logger.Print(err)
}
} | go | func (h *DeployHandler) serveRoot(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
h.serveSetup(w, r)
return
}
_, err := r.Cookie("user")
if err != nil {
http.SetCookie(w, newCookie())
}
camliRev := h.camliRev()
if r.FormValue("WIP") == "1" {
camliRev = "WORKINPROGRESS"
}
h.tplMu.RLock()
defer h.tplMu.RUnlock()
if err := h.tpl.ExecuteTemplate(w, "withform", &TemplateData{
ProjectID: r.FormValue("project"),
Prefix: h.prefix,
Help: h.help,
ZoneValues: h.zoneValues(),
MachineValues: machineValues,
CamliVersion: camliRev,
}); err != nil {
h.logger.Print(err)
}
} | [
"func",
"(",
"h",
"*",
"DeployHandler",
")",
"serveRoot",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"r",
".",
"Method",
"==",
"\"POST\"",
"{",
"h",
".",
"serveSetup",
"(",
"w",
",",
"r",
")",
"\n",
"return",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"r",
".",
"Cookie",
"(",
"\"user\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"SetCookie",
"(",
"w",
",",
"newCookie",
"(",
")",
")",
"\n",
"}",
"\n",
"camliRev",
":=",
"h",
".",
"camliRev",
"(",
")",
"\n",
"if",
"r",
".",
"FormValue",
"(",
"\"WIP\"",
")",
"==",
"\"1\"",
"{",
"camliRev",
"=",
"\"WORKINPROGRESS\"",
"\n",
"}",
"\n",
"h",
".",
"tplMu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"h",
".",
"tplMu",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"err",
":=",
"h",
".",
"tpl",
".",
"ExecuteTemplate",
"(",
"w",
",",
"\"withform\"",
",",
"&",
"TemplateData",
"{",
"ProjectID",
":",
"r",
".",
"FormValue",
"(",
"\"project\"",
")",
",",
"Prefix",
":",
"h",
".",
"prefix",
",",
"Help",
":",
"h",
".",
"help",
",",
"ZoneValues",
":",
"h",
".",
"zoneValues",
"(",
")",
",",
"MachineValues",
":",
"machineValues",
",",
"CamliVersion",
":",
"camliRev",
",",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"h",
".",
"logger",
".",
"Print",
"(",
"err",
")",
"\n",
"}",
"\n",
"}"
] | // if there's project as a query parameter, it means we've just created a
// project for them and we're redirecting them to the form, but with the projectID
// field pre-filled for them this time. | [
"if",
"there",
"s",
"project",
"as",
"a",
"query",
"parameter",
"it",
"means",
"we",
"ve",
"just",
"created",
"a",
"project",
"for",
"them",
"and",
"we",
"re",
"redirecting",
"them",
"to",
"the",
"form",
"but",
"with",
"the",
"projectID",
"field",
"pre",
"-",
"filled",
"for",
"them",
"this",
"time",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/deploy/gce/handler.go#L351-L377 | train |
perkeep/perkeep | pkg/deploy/gce/handler.go | serveOldInstance | func (h *DeployHandler) serveOldInstance(w http.ResponseWriter, br blob.Ref, depl *Deployer) (found bool) {
inst, err := depl.Get()
if err != nil {
// TODO(mpl,bradfitz): log or do something more
// drastic if the error is something other than
// instance not found.
return false
}
h.logger.Printf("Reusing existing instance for (%v, %v, %v)", depl.Conf.Project, depl.Conf.Name, depl.Conf.Zone)
if err := h.recordState(br, &creationState{
InstConf: br,
InstAddr: addr(inst),
Exists: true,
}); err != nil {
h.logger.Printf("Could not record creation state for %v: %v", br, err)
h.serveErrorPage(w, fmt.Errorf("An error occurred while recording the state of your instance. %v", fileIssue(br.String())))
return true
}
h.serveProgress(w, br)
return true
} | go | func (h *DeployHandler) serveOldInstance(w http.ResponseWriter, br blob.Ref, depl *Deployer) (found bool) {
inst, err := depl.Get()
if err != nil {
// TODO(mpl,bradfitz): log or do something more
// drastic if the error is something other than
// instance not found.
return false
}
h.logger.Printf("Reusing existing instance for (%v, %v, %v)", depl.Conf.Project, depl.Conf.Name, depl.Conf.Zone)
if err := h.recordState(br, &creationState{
InstConf: br,
InstAddr: addr(inst),
Exists: true,
}); err != nil {
h.logger.Printf("Could not record creation state for %v: %v", br, err)
h.serveErrorPage(w, fmt.Errorf("An error occurred while recording the state of your instance. %v", fileIssue(br.String())))
return true
}
h.serveProgress(w, br)
return true
} | [
"func",
"(",
"h",
"*",
"DeployHandler",
")",
"serveOldInstance",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"br",
"blob",
".",
"Ref",
",",
"depl",
"*",
"Deployer",
")",
"(",
"found",
"bool",
")",
"{",
"inst",
",",
"err",
":=",
"depl",
".",
"Get",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"h",
".",
"logger",
".",
"Printf",
"(",
"\"Reusing existing instance for (%v, %v, %v)\"",
",",
"depl",
".",
"Conf",
".",
"Project",
",",
"depl",
".",
"Conf",
".",
"Name",
",",
"depl",
".",
"Conf",
".",
"Zone",
")",
"\n",
"if",
"err",
":=",
"h",
".",
"recordState",
"(",
"br",
",",
"&",
"creationState",
"{",
"InstConf",
":",
"br",
",",
"InstAddr",
":",
"addr",
"(",
"inst",
")",
",",
"Exists",
":",
"true",
",",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"h",
".",
"logger",
".",
"Printf",
"(",
"\"Could not record creation state for %v: %v\"",
",",
"br",
",",
"err",
")",
"\n",
"h",
".",
"serveErrorPage",
"(",
"w",
",",
"fmt",
".",
"Errorf",
"(",
"\"An error occurred while recording the state of your instance. %v\"",
",",
"fileIssue",
"(",
"br",
".",
"String",
"(",
")",
")",
")",
")",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"h",
".",
"serveProgress",
"(",
"w",
",",
"br",
")",
"\n",
"return",
"true",
"\n",
"}"
] | // serveOldInstance looks on GCE for an instance such as defined in depl.Conf, and if
// found, serves the appropriate page depending on whether the instance is usable. It does
// not serve anything if the instance is not found. | [
"serveOldInstance",
"looks",
"on",
"GCE",
"for",
"an",
"instance",
"such",
"as",
"defined",
"in",
"depl",
".",
"Conf",
"and",
"if",
"found",
"serves",
"the",
"appropriate",
"page",
"depending",
"on",
"whether",
"the",
"instance",
"is",
"usable",
".",
"It",
"does",
"not",
"serve",
"anything",
"if",
"the",
"instance",
"is",
"not",
"found",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/deploy/gce/handler.go#L564-L585 | train |
perkeep/perkeep | pkg/deploy/gce/handler.go | serveInstanceState | func (h *DeployHandler) serveInstanceState(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if r.Method != "GET" {
h.serveError(w, r, fmt.Errorf("Wrong method: %v", r.Method))
return
}
br := r.URL.Query().Get("instancekey")
stateValue, err := h.instState.Get(br)
if err != nil {
http.Error(w, "unknown instance", http.StatusNotFound)
return
}
var state creationState
if err := json.Unmarshal([]byte(stateValue), &state); err != nil {
h.serveError(w, r, fmt.Errorf("could not json decode instance state: %v", err))
return
}
if state.Err != "" {
// No need to log that error here since we're already doing it in serveCallback
h.serveErrorPage(w, fmt.Errorf("an error occurred while creating your instance: %v", state.Err))
return
}
if state.Success || state.Exists {
conf, err := h.instanceConf(ctx, state.InstConf)
if err != nil {
h.logger.Printf("Could not get parameters for success message: %v", err)
h.serveErrorPage(w, fmt.Errorf("your instance was created and should soon be up at https://%s but there might have been a problem in the creation process. %v", state.Err, fileIssue(br)))
return
}
h.serveSuccess(w, &TemplateData{
Prefix: h.prefix,
Help: h.help,
InstanceIP: state.InstAddr,
InstanceHostname: state.InstHostname,
ProjectConsoleURL: fmt.Sprintf("%s/project/%s/compute", ConsoleURL, conf.Project),
Conf: conf,
ZoneValues: h.zoneValues(),
MachineValues: machineValues,
})
return
}
h.recordStateErrMu.RLock()
defer h.recordStateErrMu.RUnlock()
if _, ok := h.recordStateErr[br]; ok {
// No need to log that error here since we're already doing it in serveCallback
h.serveErrorPage(w, fmt.Errorf("An error occurred while recording the state of your instance. %v", fileIssue(br)))
return
}
fmt.Fprintf(w, "running")
} | go | func (h *DeployHandler) serveInstanceState(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if r.Method != "GET" {
h.serveError(w, r, fmt.Errorf("Wrong method: %v", r.Method))
return
}
br := r.URL.Query().Get("instancekey")
stateValue, err := h.instState.Get(br)
if err != nil {
http.Error(w, "unknown instance", http.StatusNotFound)
return
}
var state creationState
if err := json.Unmarshal([]byte(stateValue), &state); err != nil {
h.serveError(w, r, fmt.Errorf("could not json decode instance state: %v", err))
return
}
if state.Err != "" {
// No need to log that error here since we're already doing it in serveCallback
h.serveErrorPage(w, fmt.Errorf("an error occurred while creating your instance: %v", state.Err))
return
}
if state.Success || state.Exists {
conf, err := h.instanceConf(ctx, state.InstConf)
if err != nil {
h.logger.Printf("Could not get parameters for success message: %v", err)
h.serveErrorPage(w, fmt.Errorf("your instance was created and should soon be up at https://%s but there might have been a problem in the creation process. %v", state.Err, fileIssue(br)))
return
}
h.serveSuccess(w, &TemplateData{
Prefix: h.prefix,
Help: h.help,
InstanceIP: state.InstAddr,
InstanceHostname: state.InstHostname,
ProjectConsoleURL: fmt.Sprintf("%s/project/%s/compute", ConsoleURL, conf.Project),
Conf: conf,
ZoneValues: h.zoneValues(),
MachineValues: machineValues,
})
return
}
h.recordStateErrMu.RLock()
defer h.recordStateErrMu.RUnlock()
if _, ok := h.recordStateErr[br]; ok {
// No need to log that error here since we're already doing it in serveCallback
h.serveErrorPage(w, fmt.Errorf("An error occurred while recording the state of your instance. %v", fileIssue(br)))
return
}
fmt.Fprintf(w, "running")
} | [
"func",
"(",
"h",
"*",
"DeployHandler",
")",
"serveInstanceState",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"ctx",
":=",
"r",
".",
"Context",
"(",
")",
"\n",
"if",
"r",
".",
"Method",
"!=",
"\"GET\"",
"{",
"h",
".",
"serveError",
"(",
"w",
",",
"r",
",",
"fmt",
".",
"Errorf",
"(",
"\"Wrong method: %v\"",
",",
"r",
".",
"Method",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"br",
":=",
"r",
".",
"URL",
".",
"Query",
"(",
")",
".",
"Get",
"(",
"\"instancekey\"",
")",
"\n",
"stateValue",
",",
"err",
":=",
"h",
".",
"instState",
".",
"Get",
"(",
"br",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"unknown instance\"",
",",
"http",
".",
"StatusNotFound",
")",
"\n",
"return",
"\n",
"}",
"\n",
"var",
"state",
"creationState",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"[",
"]",
"byte",
"(",
"stateValue",
")",
",",
"&",
"state",
")",
";",
"err",
"!=",
"nil",
"{",
"h",
".",
"serveError",
"(",
"w",
",",
"r",
",",
"fmt",
".",
"Errorf",
"(",
"\"could not json decode instance state: %v\"",
",",
"err",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"state",
".",
"Err",
"!=",
"\"\"",
"{",
"h",
".",
"serveErrorPage",
"(",
"w",
",",
"fmt",
".",
"Errorf",
"(",
"\"an error occurred while creating your instance: %v\"",
",",
"state",
".",
"Err",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"state",
".",
"Success",
"||",
"state",
".",
"Exists",
"{",
"conf",
",",
"err",
":=",
"h",
".",
"instanceConf",
"(",
"ctx",
",",
"state",
".",
"InstConf",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"h",
".",
"logger",
".",
"Printf",
"(",
"\"Could not get parameters for success message: %v\"",
",",
"err",
")",
"\n",
"h",
".",
"serveErrorPage",
"(",
"w",
",",
"fmt",
".",
"Errorf",
"(",
"\"your instance was created and should soon be up at https://%s but there might have been a problem in the creation process. %v\"",
",",
"state",
".",
"Err",
",",
"fileIssue",
"(",
"br",
")",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"h",
".",
"serveSuccess",
"(",
"w",
",",
"&",
"TemplateData",
"{",
"Prefix",
":",
"h",
".",
"prefix",
",",
"Help",
":",
"h",
".",
"help",
",",
"InstanceIP",
":",
"state",
".",
"InstAddr",
",",
"InstanceHostname",
":",
"state",
".",
"InstHostname",
",",
"ProjectConsoleURL",
":",
"fmt",
".",
"Sprintf",
"(",
"\"%s/project/%s/compute\"",
",",
"ConsoleURL",
",",
"conf",
".",
"Project",
")",
",",
"Conf",
":",
"conf",
",",
"ZoneValues",
":",
"h",
".",
"zoneValues",
"(",
")",
",",
"MachineValues",
":",
"machineValues",
",",
"}",
")",
"\n",
"return",
"\n",
"}",
"\n",
"h",
".",
"recordStateErrMu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"h",
".",
"recordStateErrMu",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"h",
".",
"recordStateErr",
"[",
"br",
"]",
";",
"ok",
"{",
"h",
".",
"serveErrorPage",
"(",
"w",
",",
"fmt",
".",
"Errorf",
"(",
"\"An error occurred while recording the state of your instance. %v\"",
",",
"fileIssue",
"(",
"br",
")",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"running\"",
")",
"\n",
"}"
] | // serveInstanceState serves the state of the requested Google Cloud Engine VM creation
// process. If the operation was successful, it serves a success page. If it failed, it
// serves an error page. If it isn't finished yet, it replies with "running". | [
"serveInstanceState",
"serves",
"the",
"state",
"of",
"the",
"requested",
"Google",
"Cloud",
"Engine",
"VM",
"creation",
"process",
".",
"If",
"the",
"operation",
"was",
"successful",
"it",
"serves",
"a",
"success",
"page",
".",
"If",
"it",
"failed",
"it",
"serves",
"an",
"error",
"page",
".",
"If",
"it",
"isn",
"t",
"finished",
"yet",
"it",
"replies",
"with",
"running",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/deploy/gce/handler.go#L612-L661 | train |
perkeep/perkeep | pkg/deploy/gce/handler.go | serveProgress | func (h *DeployHandler) serveProgress(w http.ResponseWriter, instanceKey blob.Ref) {
h.tplMu.RLock()
defer h.tplMu.RUnlock()
if err := h.tpl.ExecuteTemplate(w, "withform", &TemplateData{
Prefix: h.prefix,
InstanceKey: instanceKey.String(),
PiggyGIF: h.piggyGIF,
}); err != nil {
h.logger.Printf("Could not serve progress: %v", err)
}
} | go | func (h *DeployHandler) serveProgress(w http.ResponseWriter, instanceKey blob.Ref) {
h.tplMu.RLock()
defer h.tplMu.RUnlock()
if err := h.tpl.ExecuteTemplate(w, "withform", &TemplateData{
Prefix: h.prefix,
InstanceKey: instanceKey.String(),
PiggyGIF: h.piggyGIF,
}); err != nil {
h.logger.Printf("Could not serve progress: %v", err)
}
} | [
"func",
"(",
"h",
"*",
"DeployHandler",
")",
"serveProgress",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"instanceKey",
"blob",
".",
"Ref",
")",
"{",
"h",
".",
"tplMu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"h",
".",
"tplMu",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"err",
":=",
"h",
".",
"tpl",
".",
"ExecuteTemplate",
"(",
"w",
",",
"\"withform\"",
",",
"&",
"TemplateData",
"{",
"Prefix",
":",
"h",
".",
"prefix",
",",
"InstanceKey",
":",
"instanceKey",
".",
"String",
"(",
")",
",",
"PiggyGIF",
":",
"h",
".",
"piggyGIF",
",",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"h",
".",
"logger",
".",
"Printf",
"(",
"\"Could not serve progress: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}"
] | // serveProgress serves a page with some javascript code that regularly queries
// the server about the progress of the requested Google Cloud Engine VM creation.
// The server replies through serveInstanceState. | [
"serveProgress",
"serves",
"a",
"page",
"with",
"some",
"javascript",
"code",
"that",
"regularly",
"queries",
"the",
"server",
"about",
"the",
"progress",
"of",
"the",
"requested",
"Google",
"Cloud",
"Engine",
"VM",
"creation",
".",
"The",
"server",
"replies",
"through",
"serveInstanceState",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/deploy/gce/handler.go#L666-L676 | train |
perkeep/perkeep | pkg/deploy/gce/handler.go | randomZone | func (h *DeployHandler) randomZone(region string) string {
h.zonesMu.RLock()
defer h.zonesMu.RUnlock()
zones, ok := h.zones[region]
if !ok {
return fallbackZone
}
return region + zones[rand.Intn(len(zones))]
} | go | func (h *DeployHandler) randomZone(region string) string {
h.zonesMu.RLock()
defer h.zonesMu.RUnlock()
zones, ok := h.zones[region]
if !ok {
return fallbackZone
}
return region + zones[rand.Intn(len(zones))]
} | [
"func",
"(",
"h",
"*",
"DeployHandler",
")",
"randomZone",
"(",
"region",
"string",
")",
"string",
"{",
"h",
".",
"zonesMu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"h",
".",
"zonesMu",
".",
"RUnlock",
"(",
")",
"\n",
"zones",
",",
"ok",
":=",
"h",
".",
"zones",
"[",
"region",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"fallbackZone",
"\n",
"}",
"\n",
"return",
"region",
"+",
"zones",
"[",
"rand",
".",
"Intn",
"(",
"len",
"(",
"zones",
")",
")",
"]",
"\n",
"}"
] | // randomZone picks one of the zone suffixes for region and returns it
// appended to region, as a fully-qualified zone name.
// If the given region is invalid, the default Zone is returned instead. | [
"randomZone",
"picks",
"one",
"of",
"the",
"zone",
"suffixes",
"for",
"region",
"and",
"returns",
"it",
"appended",
"to",
"region",
"as",
"a",
"fully",
"-",
"qualified",
"zone",
"name",
".",
"If",
"the",
"given",
"region",
"is",
"invalid",
"the",
"default",
"Zone",
"is",
"returned",
"instead",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/deploy/gce/handler.go#L770-L778 | train |
perkeep/perkeep | pkg/deploy/gce/handler.go | fromState | func fromState(r *http.Request) (br blob.Ref, xsrfToken string, err error) {
params := strings.Split(r.FormValue("state"), ":")
if len(params) != 2 {
return br, "", fmt.Errorf("Invalid format for state parameter: %q, wanted blobRef:xsrfToken", r.FormValue("state"))
}
br, ok := blob.Parse(params[0])
if !ok {
return br, "", fmt.Errorf("Invalid blobRef in state parameter: %q", params[0])
}
token, err := hex.DecodeString(params[1])
if err != nil {
return br, "", fmt.Errorf("can't decode hex xsrftoken %q: %v", params[1], err)
}
return br, string(token), nil
} | go | func fromState(r *http.Request) (br blob.Ref, xsrfToken string, err error) {
params := strings.Split(r.FormValue("state"), ":")
if len(params) != 2 {
return br, "", fmt.Errorf("Invalid format for state parameter: %q, wanted blobRef:xsrfToken", r.FormValue("state"))
}
br, ok := blob.Parse(params[0])
if !ok {
return br, "", fmt.Errorf("Invalid blobRef in state parameter: %q", params[0])
}
token, err := hex.DecodeString(params[1])
if err != nil {
return br, "", fmt.Errorf("can't decode hex xsrftoken %q: %v", params[1], err)
}
return br, string(token), nil
} | [
"func",
"fromState",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"br",
"blob",
".",
"Ref",
",",
"xsrfToken",
"string",
",",
"err",
"error",
")",
"{",
"params",
":=",
"strings",
".",
"Split",
"(",
"r",
".",
"FormValue",
"(",
"\"state\"",
")",
",",
"\":\"",
")",
"\n",
"if",
"len",
"(",
"params",
")",
"!=",
"2",
"{",
"return",
"br",
",",
"\"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"Invalid format for state parameter: %q, wanted blobRef:xsrfToken\"",
",",
"r",
".",
"FormValue",
"(",
"\"state\"",
")",
")",
"\n",
"}",
"\n",
"br",
",",
"ok",
":=",
"blob",
".",
"Parse",
"(",
"params",
"[",
"0",
"]",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"br",
",",
"\"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"Invalid blobRef in state parameter: %q\"",
",",
"params",
"[",
"0",
"]",
")",
"\n",
"}",
"\n",
"token",
",",
"err",
":=",
"hex",
".",
"DecodeString",
"(",
"params",
"[",
"1",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"br",
",",
"\"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"can't decode hex xsrftoken %q: %v\"",
",",
"params",
"[",
"1",
"]",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"br",
",",
"string",
"(",
"token",
")",
",",
"nil",
"\n",
"}"
] | // fromState parses the oauth state parameter from r to extract the blobRef of the
// instance configuration and the xsrftoken that were stored during serveSetup. | [
"fromState",
"parses",
"the",
"oauth",
"state",
"parameter",
"from",
"r",
"to",
"extract",
"the",
"blobRef",
"of",
"the",
"instance",
"configuration",
"and",
"the",
"xsrftoken",
"that",
"were",
"stored",
"during",
"serveSetup",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/deploy/gce/handler.go#L799-L813 | train |
perkeep/perkeep | pkg/deploy/gce/handler.go | dataStores | func dataStores() (blobserver.Storage, sorted.KeyValue, error) {
dataDir := os.Getenv("CAMLI_GCE_DATA")
if dataDir == "" {
var err error
dataDir, err = ioutil.TempDir("", "camli-gcedeployer-data")
if err != nil {
return nil, nil, err
}
log.Printf("data dir not provided as env var CAMLI_GCE_DATA, so defaulting to %v", dataDir)
}
blobsDir := filepath.Join(dataDir, "instance-conf")
if err := os.MkdirAll(blobsDir, 0700); err != nil {
return nil, nil, err
}
instConf, err := localdisk.New(blobsDir)
if err != nil {
return nil, nil, err
}
instState, err := leveldb.NewStorage(filepath.Join(dataDir, "instance-state"))
if err != nil {
return nil, nil, err
}
return instConf, instState, nil
} | go | func dataStores() (blobserver.Storage, sorted.KeyValue, error) {
dataDir := os.Getenv("CAMLI_GCE_DATA")
if dataDir == "" {
var err error
dataDir, err = ioutil.TempDir("", "camli-gcedeployer-data")
if err != nil {
return nil, nil, err
}
log.Printf("data dir not provided as env var CAMLI_GCE_DATA, so defaulting to %v", dataDir)
}
blobsDir := filepath.Join(dataDir, "instance-conf")
if err := os.MkdirAll(blobsDir, 0700); err != nil {
return nil, nil, err
}
instConf, err := localdisk.New(blobsDir)
if err != nil {
return nil, nil, err
}
instState, err := leveldb.NewStorage(filepath.Join(dataDir, "instance-state"))
if err != nil {
return nil, nil, err
}
return instConf, instState, nil
} | [
"func",
"dataStores",
"(",
")",
"(",
"blobserver",
".",
"Storage",
",",
"sorted",
".",
"KeyValue",
",",
"error",
")",
"{",
"dataDir",
":=",
"os",
".",
"Getenv",
"(",
"\"CAMLI_GCE_DATA\"",
")",
"\n",
"if",
"dataDir",
"==",
"\"\"",
"{",
"var",
"err",
"error",
"\n",
"dataDir",
",",
"err",
"=",
"ioutil",
".",
"TempDir",
"(",
"\"\"",
",",
"\"camli-gcedeployer-data\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"log",
".",
"Printf",
"(",
"\"data dir not provided as env var CAMLI_GCE_DATA, so defaulting to %v\"",
",",
"dataDir",
")",
"\n",
"}",
"\n",
"blobsDir",
":=",
"filepath",
".",
"Join",
"(",
"dataDir",
",",
"\"instance-conf\"",
")",
"\n",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"blobsDir",
",",
"0700",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"instConf",
",",
"err",
":=",
"localdisk",
".",
"New",
"(",
"blobsDir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"instState",
",",
"err",
":=",
"leveldb",
".",
"NewStorage",
"(",
"filepath",
".",
"Join",
"(",
"dataDir",
",",
"\"instance-state\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"instConf",
",",
"instState",
",",
"nil",
"\n",
"}"
] | // dataStores returns the blobserver that stores the instances configurations, and the kv
// store for the instances states. | [
"dataStores",
"returns",
"the",
"blobserver",
"that",
"stores",
"the",
"instances",
"configurations",
"and",
"the",
"kv",
"store",
"for",
"the",
"instances",
"states",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/deploy/gce/handler.go#L886-L909 | train |
perkeep/perkeep | pkg/server/app/app.go | handleMasterQuery | func (a *Handler) handleMasterQuery(w http.ResponseWriter, r *http.Request) {
if !(a.auth.AllowedAccess(r)&auth.OpAll == auth.OpAll) {
auth.SendUnauthorized(w, r)
return
}
if r.Method != http.MethodPost {
http.Error(w, "not a POST", http.StatusMethodNotAllowed)
return
}
if a.sh == nil {
http.Error(w, "app proxy has no search handler", 500)
return
}
if refresh, _ := strconv.ParseBool(r.FormValue("refresh")); refresh {
if err := a.refreshDomainBlobs(); err != nil {
if err == errRefreshSuppress {
http.Error(w, "too many refresh requests", http.StatusTooManyRequests)
} else {
http.Error(w, fmt.Sprintf("%v", err), 500)
}
return
}
w.Write([]byte("OK"))
return
}
sq := new(search.SearchQuery)
if err := sq.FromHTTP(r); err != nil {
http.Error(w, fmt.Sprintf("error reading master query: %v", err), 500)
return
}
var masterQuery search.SearchQuery = *(sq)
des := *(masterQuery.Describe)
masterQuery.Describe = &des
sr, err := a.sh.Query(r.Context(), sq)
if err != nil {
http.Error(w, fmt.Sprintf("error running master query: %v", err), 500)
return
}
a.masterQueryMu.Lock()
defer a.masterQueryMu.Unlock()
a.masterQuery = &masterQuery
a.domainBlobs = make(map[blob.Ref]bool, len(sr.Describe.Meta))
for _, v := range sr.Describe.Meta {
a.domainBlobs[v.BlobRef] = true
}
a.domainBlobsRefresh = time.Now()
w.Write([]byte("OK"))
} | go | func (a *Handler) handleMasterQuery(w http.ResponseWriter, r *http.Request) {
if !(a.auth.AllowedAccess(r)&auth.OpAll == auth.OpAll) {
auth.SendUnauthorized(w, r)
return
}
if r.Method != http.MethodPost {
http.Error(w, "not a POST", http.StatusMethodNotAllowed)
return
}
if a.sh == nil {
http.Error(w, "app proxy has no search handler", 500)
return
}
if refresh, _ := strconv.ParseBool(r.FormValue("refresh")); refresh {
if err := a.refreshDomainBlobs(); err != nil {
if err == errRefreshSuppress {
http.Error(w, "too many refresh requests", http.StatusTooManyRequests)
} else {
http.Error(w, fmt.Sprintf("%v", err), 500)
}
return
}
w.Write([]byte("OK"))
return
}
sq := new(search.SearchQuery)
if err := sq.FromHTTP(r); err != nil {
http.Error(w, fmt.Sprintf("error reading master query: %v", err), 500)
return
}
var masterQuery search.SearchQuery = *(sq)
des := *(masterQuery.Describe)
masterQuery.Describe = &des
sr, err := a.sh.Query(r.Context(), sq)
if err != nil {
http.Error(w, fmt.Sprintf("error running master query: %v", err), 500)
return
}
a.masterQueryMu.Lock()
defer a.masterQueryMu.Unlock()
a.masterQuery = &masterQuery
a.domainBlobs = make(map[blob.Ref]bool, len(sr.Describe.Meta))
for _, v := range sr.Describe.Meta {
a.domainBlobs[v.BlobRef] = true
}
a.domainBlobsRefresh = time.Now()
w.Write([]byte("OK"))
} | [
"func",
"(",
"a",
"*",
"Handler",
")",
"handleMasterQuery",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"!",
"(",
"a",
".",
"auth",
".",
"AllowedAccess",
"(",
"r",
")",
"&",
"auth",
".",
"OpAll",
"==",
"auth",
".",
"OpAll",
")",
"{",
"auth",
".",
"SendUnauthorized",
"(",
"w",
",",
"r",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"r",
".",
"Method",
"!=",
"http",
".",
"MethodPost",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"not a POST\"",
",",
"http",
".",
"StatusMethodNotAllowed",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"a",
".",
"sh",
"==",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"app proxy has no search handler\"",
",",
"500",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"refresh",
",",
"_",
":=",
"strconv",
".",
"ParseBool",
"(",
"r",
".",
"FormValue",
"(",
"\"refresh\"",
")",
")",
";",
"refresh",
"{",
"if",
"err",
":=",
"a",
".",
"refreshDomainBlobs",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"errRefreshSuppress",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"too many refresh requests\"",
",",
"http",
".",
"StatusTooManyRequests",
")",
"\n",
"}",
"else",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"%v\"",
",",
"err",
")",
",",
"500",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"\"OK\"",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"sq",
":=",
"new",
"(",
"search",
".",
"SearchQuery",
")",
"\n",
"if",
"err",
":=",
"sq",
".",
"FromHTTP",
"(",
"r",
")",
";",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"error reading master query: %v\"",
",",
"err",
")",
",",
"500",
")",
"\n",
"return",
"\n",
"}",
"\n",
"var",
"masterQuery",
"search",
".",
"SearchQuery",
"=",
"*",
"(",
"sq",
")",
"\n",
"des",
":=",
"*",
"(",
"masterQuery",
".",
"Describe",
")",
"\n",
"masterQuery",
".",
"Describe",
"=",
"&",
"des",
"\n",
"sr",
",",
"err",
":=",
"a",
".",
"sh",
".",
"Query",
"(",
"r",
".",
"Context",
"(",
")",
",",
"sq",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"error running master query: %v\"",
",",
"err",
")",
",",
"500",
")",
"\n",
"return",
"\n",
"}",
"\n",
"a",
".",
"masterQueryMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"a",
".",
"masterQueryMu",
".",
"Unlock",
"(",
")",
"\n",
"a",
".",
"masterQuery",
"=",
"&",
"masterQuery",
"\n",
"a",
".",
"domainBlobs",
"=",
"make",
"(",
"map",
"[",
"blob",
".",
"Ref",
"]",
"bool",
",",
"len",
"(",
"sr",
".",
"Describe",
".",
"Meta",
")",
")",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"sr",
".",
"Describe",
".",
"Meta",
"{",
"a",
".",
"domainBlobs",
"[",
"v",
".",
"BlobRef",
"]",
"=",
"true",
"\n",
"}",
"\n",
"a",
".",
"domainBlobsRefresh",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"\"OK\"",
")",
")",
"\n",
"}"
] | // handleMasterQuery allows an app to register the master query that defines the
// domain limiting all subsequent search queries. | [
"handleMasterQuery",
"allows",
"an",
"app",
"to",
"register",
"the",
"master",
"query",
"that",
"defines",
"the",
"domain",
"limiting",
"all",
"subsequent",
"search",
"queries",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/server/app/app.go#L111-L158 | train |
perkeep/perkeep | pkg/server/app/app.go | handleSearch | func (a *Handler) handleSearch(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
camhttputil.BadRequestError(w, camhttputil.InvalidMethodError{}.Error())
return
}
if a.sh == nil {
http.Error(w, "app proxy has no search handler", 500)
return
}
a.masterQueryMu.RLock()
if a.masterQuery == nil {
http.Error(w, "search is not allowed", http.StatusForbidden)
a.masterQueryMu.RUnlock()
return
}
a.masterQueryMu.RUnlock()
var sq search.SearchQuery
if err := sq.FromHTTP(r); err != nil {
camhttputil.ServeJSONError(w, err)
return
}
sr, err := a.sh.Query(r.Context(), &sq)
if err != nil {
camhttputil.ServeJSONError(w, err)
return
}
// check this search is in the allowed domain
if !a.allowProxySearchResponse(sr) {
// there's a chance our domainBlobs cache is expired so let's
// refresh it and retry, but no more than once per minute.
if err := a.refreshDomainBlobs(); err != nil {
http.Error(w, "search scope is forbidden", http.StatusForbidden)
return
}
if !a.allowProxySearchResponse(sr) {
http.Error(w, "search scope is forbidden", http.StatusForbidden)
return
}
}
camhttputil.ReturnJSON(w, sr)
} | go | func (a *Handler) handleSearch(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
camhttputil.BadRequestError(w, camhttputil.InvalidMethodError{}.Error())
return
}
if a.sh == nil {
http.Error(w, "app proxy has no search handler", 500)
return
}
a.masterQueryMu.RLock()
if a.masterQuery == nil {
http.Error(w, "search is not allowed", http.StatusForbidden)
a.masterQueryMu.RUnlock()
return
}
a.masterQueryMu.RUnlock()
var sq search.SearchQuery
if err := sq.FromHTTP(r); err != nil {
camhttputil.ServeJSONError(w, err)
return
}
sr, err := a.sh.Query(r.Context(), &sq)
if err != nil {
camhttputil.ServeJSONError(w, err)
return
}
// check this search is in the allowed domain
if !a.allowProxySearchResponse(sr) {
// there's a chance our domainBlobs cache is expired so let's
// refresh it and retry, but no more than once per minute.
if err := a.refreshDomainBlobs(); err != nil {
http.Error(w, "search scope is forbidden", http.StatusForbidden)
return
}
if !a.allowProxySearchResponse(sr) {
http.Error(w, "search scope is forbidden", http.StatusForbidden)
return
}
}
camhttputil.ReturnJSON(w, sr)
} | [
"func",
"(",
"a",
"*",
"Handler",
")",
"handleSearch",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"r",
".",
"Method",
"!=",
"http",
".",
"MethodPost",
"{",
"camhttputil",
".",
"BadRequestError",
"(",
"w",
",",
"camhttputil",
".",
"InvalidMethodError",
"{",
"}",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"a",
".",
"sh",
"==",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"app proxy has no search handler\"",
",",
"500",
")",
"\n",
"return",
"\n",
"}",
"\n",
"a",
".",
"masterQueryMu",
".",
"RLock",
"(",
")",
"\n",
"if",
"a",
".",
"masterQuery",
"==",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"search is not allowed\"",
",",
"http",
".",
"StatusForbidden",
")",
"\n",
"a",
".",
"masterQueryMu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"a",
".",
"masterQueryMu",
".",
"RUnlock",
"(",
")",
"\n",
"var",
"sq",
"search",
".",
"SearchQuery",
"\n",
"if",
"err",
":=",
"sq",
".",
"FromHTTP",
"(",
"r",
")",
";",
"err",
"!=",
"nil",
"{",
"camhttputil",
".",
"ServeJSONError",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"sr",
",",
"err",
":=",
"a",
".",
"sh",
".",
"Query",
"(",
"r",
".",
"Context",
"(",
")",
",",
"&",
"sq",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"camhttputil",
".",
"ServeJSONError",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"!",
"a",
".",
"allowProxySearchResponse",
"(",
"sr",
")",
"{",
"if",
"err",
":=",
"a",
".",
"refreshDomainBlobs",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"search scope is forbidden\"",
",",
"http",
".",
"StatusForbidden",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"!",
"a",
".",
"allowProxySearchResponse",
"(",
"sr",
")",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"search scope is forbidden\"",
",",
"http",
".",
"StatusForbidden",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"camhttputil",
".",
"ReturnJSON",
"(",
"w",
",",
"sr",
")",
"\n",
"}"
] | // handleSearch runs the requested search query against the search handler, and
// if the results are within the domain allowed by the master query, forwards them
// back to the client. | [
"handleSearch",
"runs",
"the",
"requested",
"search",
"query",
"against",
"the",
"search",
"handler",
"and",
"if",
"the",
"results",
"are",
"within",
"the",
"domain",
"allowed",
"by",
"the",
"master",
"query",
"forwards",
"them",
"back",
"to",
"the",
"client",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/server/app/app.go#L190-L230 | train |
perkeep/perkeep | pkg/server/app/app.go | allowProxySearchResponse | func (a *Handler) allowProxySearchResponse(sr *search.SearchResult) bool {
a.masterQueryMu.RLock()
defer a.masterQueryMu.RUnlock()
for _, v := range sr.Blobs {
if _, ok := a.domainBlobs[v.Blob]; !ok {
return false
}
}
return true
} | go | func (a *Handler) allowProxySearchResponse(sr *search.SearchResult) bool {
a.masterQueryMu.RLock()
defer a.masterQueryMu.RUnlock()
for _, v := range sr.Blobs {
if _, ok := a.domainBlobs[v.Blob]; !ok {
return false
}
}
return true
} | [
"func",
"(",
"a",
"*",
"Handler",
")",
"allowProxySearchResponse",
"(",
"sr",
"*",
"search",
".",
"SearchResult",
")",
"bool",
"{",
"a",
".",
"masterQueryMu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"a",
".",
"masterQueryMu",
".",
"RUnlock",
"(",
")",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"sr",
".",
"Blobs",
"{",
"if",
"_",
",",
"ok",
":=",
"a",
".",
"domainBlobs",
"[",
"v",
".",
"Blob",
"]",
";",
"!",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] | // allowProxySearchResponse checks whether the blobs in sr are within the domain
// defined by the masterQuery, and hence if the client is allowed to get that
// response. | [
"allowProxySearchResponse",
"checks",
"whether",
"the",
"blobs",
"in",
"sr",
"are",
"within",
"the",
"domain",
"defined",
"by",
"the",
"masterQuery",
"and",
"hence",
"if",
"the",
"client",
"is",
"allowed",
"to",
"get",
"that",
"response",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/server/app/app.go#L235-L244 | train |
perkeep/perkeep | pkg/server/app/app.go | randListenFn | func randListenFn(listenAddr string, randPortFn func() (int, error)) (string, error) {
portIdx := strings.LastIndex(listenAddr, ":") + 1
if portIdx <= 0 || portIdx >= len(listenAddr) {
return "", errors.New("invalid listen addr, no port found")
}
port, err := randPortFn()
if err != nil {
return "", err
}
return fmt.Sprintf("%s%d", listenAddr[:portIdx], port), nil
} | go | func randListenFn(listenAddr string, randPortFn func() (int, error)) (string, error) {
portIdx := strings.LastIndex(listenAddr, ":") + 1
if portIdx <= 0 || portIdx >= len(listenAddr) {
return "", errors.New("invalid listen addr, no port found")
}
port, err := randPortFn()
if err != nil {
return "", err
}
return fmt.Sprintf("%s%d", listenAddr[:portIdx], port), nil
} | [
"func",
"randListenFn",
"(",
"listenAddr",
"string",
",",
"randPortFn",
"func",
"(",
")",
"(",
"int",
",",
"error",
")",
")",
"(",
"string",
",",
"error",
")",
"{",
"portIdx",
":=",
"strings",
".",
"LastIndex",
"(",
"listenAddr",
",",
"\":\"",
")",
"+",
"1",
"\n",
"if",
"portIdx",
"<=",
"0",
"||",
"portIdx",
">=",
"len",
"(",
"listenAddr",
")",
"{",
"return",
"\"\"",
",",
"errors",
".",
"New",
"(",
"\"invalid listen addr, no port found\"",
")",
"\n",
"}",
"\n",
"port",
",",
"err",
":=",
"randPortFn",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%s%d\"",
",",
"listenAddr",
"[",
":",
"portIdx",
"]",
",",
"port",
")",
",",
"nil",
"\n",
"}"
] | // randListenFn only exists to allow testing of randListen, by letting the caller
// replace randPort with a func that actually has a predictable result. | [
"randListenFn",
"only",
"exists",
"to",
"allow",
"testing",
"of",
"randListen",
"by",
"letting",
"the",
"caller",
"replace",
"randPort",
"with",
"a",
"func",
"that",
"actually",
"has",
"a",
"predictable",
"result",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/server/app/app.go#L253-L263 | train |
perkeep/perkeep | pkg/server/app/app.go | baseURL | func baseURL(serverBaseURL, listenAddr string) (string, error) {
backendURL, err := url.Parse(serverBaseURL)
if err != nil {
return "", fmt.Errorf("invalid baseURL %q: %v", serverBaseURL, err)
}
scheme := backendURL.Scheme
host := backendURL.Host
if netutil.HasPort(host) {
host = host[:strings.LastIndex(host, ":")]
}
port := portMap[scheme]
if netutil.HasPort(listenAddr) {
port = listenAddr[strings.LastIndex(listenAddr, ":")+1:]
}
return fmt.Sprintf("%s://%s:%s/", scheme, host, port), nil
} | go | func baseURL(serverBaseURL, listenAddr string) (string, error) {
backendURL, err := url.Parse(serverBaseURL)
if err != nil {
return "", fmt.Errorf("invalid baseURL %q: %v", serverBaseURL, err)
}
scheme := backendURL.Scheme
host := backendURL.Host
if netutil.HasPort(host) {
host = host[:strings.LastIndex(host, ":")]
}
port := portMap[scheme]
if netutil.HasPort(listenAddr) {
port = listenAddr[strings.LastIndex(listenAddr, ":")+1:]
}
return fmt.Sprintf("%s://%s:%s/", scheme, host, port), nil
} | [
"func",
"baseURL",
"(",
"serverBaseURL",
",",
"listenAddr",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"backendURL",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"serverBaseURL",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"invalid baseURL %q: %v\"",
",",
"serverBaseURL",
",",
"err",
")",
"\n",
"}",
"\n",
"scheme",
":=",
"backendURL",
".",
"Scheme",
"\n",
"host",
":=",
"backendURL",
".",
"Host",
"\n",
"if",
"netutil",
".",
"HasPort",
"(",
"host",
")",
"{",
"host",
"=",
"host",
"[",
":",
"strings",
".",
"LastIndex",
"(",
"host",
",",
"\":\"",
")",
"]",
"\n",
"}",
"\n",
"port",
":=",
"portMap",
"[",
"scheme",
"]",
"\n",
"if",
"netutil",
".",
"HasPort",
"(",
"listenAddr",
")",
"{",
"port",
"=",
"listenAddr",
"[",
"strings",
".",
"LastIndex",
"(",
"listenAddr",
",",
"\":\"",
")",
"+",
"1",
":",
"]",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%s://%s:%s/\"",
",",
"scheme",
",",
"host",
",",
"port",
")",
",",
"nil",
"\n",
"}"
] | // baseURL returns the concatenation of the scheme and host parts of
// serverBaseURL with the port of listenAddr. | [
"baseURL",
"returns",
"the",
"concatenation",
"of",
"the",
"scheme",
"and",
"host",
"parts",
"of",
"serverBaseURL",
"with",
"the",
"port",
"of",
"listenAddr",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/server/app/app.go#L272-L287 | train |
perkeep/perkeep | pkg/server/app/app.go | FromJSONConfig | func FromJSONConfig(config jsonconfig.Obj, prefix, serverBaseURL string) (HandlerConfig, error) {
hc := HandlerConfig{
Program: config.RequiredString("program"),
Prefix: config.OptionalString("prefix", prefix),
BackendURL: config.OptionalString("backendURL", ""),
Listen: config.OptionalString("listen", ""),
APIHost: config.OptionalString("apiHost", ""),
ServerListen: config.OptionalString("serverListen", ""),
ServerBaseURL: config.OptionalString("serverBaseURL", serverBaseURL),
AppConfig: config.OptionalObject("appConfig"),
}
if err := config.Validate(); err != nil {
return HandlerConfig{}, err
}
return hc, nil
} | go | func FromJSONConfig(config jsonconfig.Obj, prefix, serverBaseURL string) (HandlerConfig, error) {
hc := HandlerConfig{
Program: config.RequiredString("program"),
Prefix: config.OptionalString("prefix", prefix),
BackendURL: config.OptionalString("backendURL", ""),
Listen: config.OptionalString("listen", ""),
APIHost: config.OptionalString("apiHost", ""),
ServerListen: config.OptionalString("serverListen", ""),
ServerBaseURL: config.OptionalString("serverBaseURL", serverBaseURL),
AppConfig: config.OptionalObject("appConfig"),
}
if err := config.Validate(); err != nil {
return HandlerConfig{}, err
}
return hc, nil
} | [
"func",
"FromJSONConfig",
"(",
"config",
"jsonconfig",
".",
"Obj",
",",
"prefix",
",",
"serverBaseURL",
"string",
")",
"(",
"HandlerConfig",
",",
"error",
")",
"{",
"hc",
":=",
"HandlerConfig",
"{",
"Program",
":",
"config",
".",
"RequiredString",
"(",
"\"program\"",
")",
",",
"Prefix",
":",
"config",
".",
"OptionalString",
"(",
"\"prefix\"",
",",
"prefix",
")",
",",
"BackendURL",
":",
"config",
".",
"OptionalString",
"(",
"\"backendURL\"",
",",
"\"\"",
")",
",",
"Listen",
":",
"config",
".",
"OptionalString",
"(",
"\"listen\"",
",",
"\"\"",
")",
",",
"APIHost",
":",
"config",
".",
"OptionalString",
"(",
"\"apiHost\"",
",",
"\"\"",
")",
",",
"ServerListen",
":",
"config",
".",
"OptionalString",
"(",
"\"serverListen\"",
",",
"\"\"",
")",
",",
"ServerBaseURL",
":",
"config",
".",
"OptionalString",
"(",
"\"serverBaseURL\"",
",",
"serverBaseURL",
")",
",",
"AppConfig",
":",
"config",
".",
"OptionalObject",
"(",
"\"appConfig\"",
")",
",",
"}",
"\n",
"if",
"err",
":=",
"config",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"HandlerConfig",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"return",
"hc",
",",
"nil",
"\n",
"}"
] | // FromJSONConfig creates an HandlerConfig from the contents of config.
// prefix and serverBaseURL are used if not found in config. | [
"FromJSONConfig",
"creates",
"an",
"HandlerConfig",
"from",
"the",
"contents",
"of",
"config",
".",
"prefix",
"and",
"serverBaseURL",
"are",
"used",
"if",
"not",
"found",
"in",
"config",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/server/app/app.go#L340-L355 | train |
perkeep/perkeep | pkg/server/app/app.go | InitHandler | func (a *Handler) InitHandler(hl blobserver.FindHandlerByTyper) error {
apName := a.ProgramName()
searchPrefix, _, err := hl.FindHandlerByType("search")
if err != nil {
return fmt.Errorf("No search handler configured, which is necessary for the %v app handler", apName)
}
var sh *search.Handler
_, hi := hl.AllHandlers()
h, ok := hi[searchPrefix]
if !ok {
return fmt.Errorf("failed to find the \"search\" handler for %v", apName)
}
sh = h.(*search.Handler)
a.sh = sh
return nil
} | go | func (a *Handler) InitHandler(hl blobserver.FindHandlerByTyper) error {
apName := a.ProgramName()
searchPrefix, _, err := hl.FindHandlerByType("search")
if err != nil {
return fmt.Errorf("No search handler configured, which is necessary for the %v app handler", apName)
}
var sh *search.Handler
_, hi := hl.AllHandlers()
h, ok := hi[searchPrefix]
if !ok {
return fmt.Errorf("failed to find the \"search\" handler for %v", apName)
}
sh = h.(*search.Handler)
a.sh = sh
return nil
} | [
"func",
"(",
"a",
"*",
"Handler",
")",
"InitHandler",
"(",
"hl",
"blobserver",
".",
"FindHandlerByTyper",
")",
"error",
"{",
"apName",
":=",
"a",
".",
"ProgramName",
"(",
")",
"\n",
"searchPrefix",
",",
"_",
",",
"err",
":=",
"hl",
".",
"FindHandlerByType",
"(",
"\"search\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"No search handler configured, which is necessary for the %v app handler\"",
",",
"apName",
")",
"\n",
"}",
"\n",
"var",
"sh",
"*",
"search",
".",
"Handler",
"\n",
"_",
",",
"hi",
":=",
"hl",
".",
"AllHandlers",
"(",
")",
"\n",
"h",
",",
"ok",
":=",
"hi",
"[",
"searchPrefix",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"failed to find the \\\"search\\\" handler for %v\"",
",",
"\\\"",
")",
"\n",
"}",
"\n",
"\\\"",
"\n",
"apName",
"\n",
"sh",
"=",
"h",
".",
"(",
"*",
"search",
".",
"Handler",
")",
"\n",
"}"
] | // InitHandler sets the app handler's search handler, if the app handler was configured
// to have one with HasSearch. | [
"InitHandler",
"sets",
"the",
"app",
"handler",
"s",
"search",
"handler",
"if",
"the",
"app",
"handler",
"was",
"configured",
"to",
"have",
"one",
"with",
"HasSearch",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/server/app/app.go#L442-L457 | train |
perkeep/perkeep | pkg/server/app/app.go | Quit | func (a *Handler) Quit() error {
err := a.process.Signal(os.Interrupt)
if err != nil {
return err
}
c := make(chan error)
go func() {
_, err := a.process.Wait()
c <- err
}()
select {
case err = <-c:
case <-time.After(5 * time.Second):
// TODO Do we want to SIGKILL here or just leave the app alone?
err = errProcessTookTooLong
}
return err
} | go | func (a *Handler) Quit() error {
err := a.process.Signal(os.Interrupt)
if err != nil {
return err
}
c := make(chan error)
go func() {
_, err := a.process.Wait()
c <- err
}()
select {
case err = <-c:
case <-time.After(5 * time.Second):
// TODO Do we want to SIGKILL here or just leave the app alone?
err = errProcessTookTooLong
}
return err
} | [
"func",
"(",
"a",
"*",
"Handler",
")",
"Quit",
"(",
")",
"error",
"{",
"err",
":=",
"a",
".",
"process",
".",
"Signal",
"(",
"os",
".",
"Interrupt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"c",
":=",
"make",
"(",
"chan",
"error",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"_",
",",
"err",
":=",
"a",
".",
"process",
".",
"Wait",
"(",
")",
"\n",
"c",
"<-",
"err",
"\n",
"}",
"(",
")",
"\n",
"select",
"{",
"case",
"err",
"=",
"<-",
"c",
":",
"case",
"<-",
"time",
".",
"After",
"(",
"5",
"*",
"time",
".",
"Second",
")",
":",
"err",
"=",
"errProcessTookTooLong",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] | // Quit sends the app's process a SIGINT, and waits up to 5 seconds for it
// to exit, returning an error if it doesn't. | [
"Quit",
"sends",
"the",
"app",
"s",
"process",
"a",
"SIGINT",
"and",
"waits",
"up",
"to",
"5",
"seconds",
"for",
"it",
"to",
"exit",
"returning",
"an",
"error",
"if",
"it",
"doesn",
"t",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/server/app/app.go#L536-L554 | train |
perkeep/perkeep | pkg/cacher/cacher.go | NewCachingFetcher | func NewCachingFetcher(cache blobserver.Cache, fetcher blob.Fetcher) *CachingFetcher {
return &CachingFetcher{c: cache, sf: fetcher}
} | go | func NewCachingFetcher(cache blobserver.Cache, fetcher blob.Fetcher) *CachingFetcher {
return &CachingFetcher{c: cache, sf: fetcher}
} | [
"func",
"NewCachingFetcher",
"(",
"cache",
"blobserver",
".",
"Cache",
",",
"fetcher",
"blob",
".",
"Fetcher",
")",
"*",
"CachingFetcher",
"{",
"return",
"&",
"CachingFetcher",
"{",
"c",
":",
"cache",
",",
"sf",
":",
"fetcher",
"}",
"\n",
"}"
] | // NewCachingFetcher returns a CachingFetcher that fetches from
// fetcher and writes to and serves from cache. | [
"NewCachingFetcher",
"returns",
"a",
"CachingFetcher",
"that",
"fetches",
"from",
"fetcher",
"and",
"writes",
"to",
"and",
"serves",
"from",
"cache",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/cacher/cacher.go#L38-L40 | train |
perkeep/perkeep | pkg/cacher/cacher.go | SetCacheHitHook | func (cf *CachingFetcher) SetCacheHitHook(fn func(br blob.Ref, rc io.ReadCloser) (io.ReadCloser, error)) {
cf.cacheHitHook = fn
} | go | func (cf *CachingFetcher) SetCacheHitHook(fn func(br blob.Ref, rc io.ReadCloser) (io.ReadCloser, error)) {
cf.cacheHitHook = fn
} | [
"func",
"(",
"cf",
"*",
"CachingFetcher",
")",
"SetCacheHitHook",
"(",
"fn",
"func",
"(",
"br",
"blob",
".",
"Ref",
",",
"rc",
"io",
".",
"ReadCloser",
")",
"(",
"io",
".",
"ReadCloser",
",",
"error",
")",
")",
"{",
"cf",
".",
"cacheHitHook",
"=",
"fn",
"\n",
"}"
] | // SetCacheHitHook sets a function that will modify the return values from Fetch
// in the case of a cache hit.
// Its purpose is to add potential side-effects from calling the Fetcher that would
// have happened if we had had a cache miss. It is the responsibility of fn to
// return a ReadCloser equivalent to the state that rc was given in. | [
"SetCacheHitHook",
"sets",
"a",
"function",
"that",
"will",
"modify",
"the",
"return",
"values",
"from",
"Fetch",
"in",
"the",
"case",
"of",
"a",
"cache",
"hit",
".",
"Its",
"purpose",
"is",
"to",
"add",
"potential",
"side",
"-",
"effects",
"from",
"calling",
"the",
"Fetcher",
"that",
"would",
"have",
"happened",
"if",
"we",
"had",
"had",
"a",
"cache",
"miss",
".",
"It",
"is",
"the",
"responsibility",
"of",
"fn",
"to",
"return",
"a",
"ReadCloser",
"equivalent",
"to",
"the",
"state",
"that",
"rc",
"was",
"given",
"in",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/cacher/cacher.go#L60-L62 | train |
perkeep/perkeep | pkg/fs/mut.go | maybeAddChild | func (n *mutDir) maybeAddChild(name string, permanode *search.DescribedPermanode,
child mutFileOrDir) {
if current, ok := n.children[name]; !ok ||
current.permanodeString() != child.permanodeString() {
child.xattr().load(permanode)
n.children[name] = child
}
} | go | func (n *mutDir) maybeAddChild(name string, permanode *search.DescribedPermanode,
child mutFileOrDir) {
if current, ok := n.children[name]; !ok ||
current.permanodeString() != child.permanodeString() {
child.xattr().load(permanode)
n.children[name] = child
}
} | [
"func",
"(",
"n",
"*",
"mutDir",
")",
"maybeAddChild",
"(",
"name",
"string",
",",
"permanode",
"*",
"search",
".",
"DescribedPermanode",
",",
"child",
"mutFileOrDir",
")",
"{",
"if",
"current",
",",
"ok",
":=",
"n",
".",
"children",
"[",
"name",
"]",
";",
"!",
"ok",
"||",
"current",
".",
"permanodeString",
"(",
")",
"!=",
"child",
".",
"permanodeString",
"(",
")",
"{",
"child",
".",
"xattr",
"(",
")",
".",
"load",
"(",
"permanode",
")",
"\n",
"n",
".",
"children",
"[",
"name",
"]",
"=",
"child",
"\n",
"}",
"\n",
"}"
] | // maybeAddChild adds a child directory to this mutable directory
// unless it already has one with this name and permanode. | [
"maybeAddChild",
"adds",
"a",
"child",
"directory",
"to",
"this",
"mutable",
"directory",
"unless",
"it",
"already",
"has",
"one",
"with",
"this",
"name",
"and",
"permanode",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/fs/mut.go#L233-L241 | train |
perkeep/perkeep | pkg/fs/mut.go | Release | func (h *mutFileHandle) Release(ctx context.Context, req *fuse.ReleaseRequest) error {
h.tmp.Close()
os.Remove(h.tmp.Name())
h.tmp = nil
return nil
} | go | func (h *mutFileHandle) Release(ctx context.Context, req *fuse.ReleaseRequest) error {
h.tmp.Close()
os.Remove(h.tmp.Name())
h.tmp = nil
return nil
} | [
"func",
"(",
"h",
"*",
"mutFileHandle",
")",
"Release",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"*",
"fuse",
".",
"ReleaseRequest",
")",
"error",
"{",
"h",
".",
"tmp",
".",
"Close",
"(",
")",
"\n",
"os",
".",
"Remove",
"(",
"h",
".",
"tmp",
".",
"Name",
"(",
")",
")",
"\n",
"h",
".",
"tmp",
"=",
"nil",
"\n",
"return",
"nil",
"\n",
"}"
] | // Release is called when a file handle is no longer needed. This is
// called asynchronously after the last handle to a file is closed. | [
"Release",
"is",
"called",
"when",
"a",
"file",
"handle",
"is",
"no",
"longer",
"needed",
".",
"This",
"is",
"called",
"asynchronously",
"after",
"the",
"last",
"handle",
"to",
"a",
"file",
"is",
"closed",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/fs/mut.go#L871-L877 | train |
perkeep/perkeep | pkg/fs/time.go | parseCanonicalTime | func parseCanonicalTime(in string) (time.Time, error) {
if len(in) < 20 || in[len(in)-1] != 'Z' {
return time.Time{}, errUnparseableTimestamp
}
if !(in[4] == '-' && in[7] == '-' && in[10] == 'T' &&
in[13] == ':' && in[16] == ':' && (in[19] == '.' || in[19] == 'Z')) {
return time.Time{}, fmt.Errorf("positionally incorrect: %v", in)
}
// 2012-08-28T21:24:35.37465188Z
// 4 7 10 13 16 19
// -----------------------------
// 0-4 5 8 11 14 17 20
year, err := strconv.Atoi(in[0:4])
if err != nil {
return time.Time{}, fmt.Errorf("error parsing year: %v", err)
}
month, err := strconv.Atoi(in[5:7])
if err != nil {
return time.Time{}, fmt.Errorf("error parsing month: %v", err)
}
day, err := strconv.Atoi(in[8:10])
if err != nil {
return time.Time{}, fmt.Errorf("error parsing day: %v", err)
}
hour, err := strconv.Atoi(in[11:13])
if err != nil {
return time.Time{}, fmt.Errorf("error parsing hour: %v", err)
}
minute, err := strconv.Atoi(in[14:16])
if err != nil {
return time.Time{}, fmt.Errorf("error parsing minute: %v", err)
}
second, err := strconv.Atoi(in[17:19])
if err != nil {
return time.Time{}, fmt.Errorf("error parsing second: %v", err)
}
var nsecstr string
if in[19] != 'Z' {
nsecstr = in[20 : len(in)-1]
}
var nsec int
if nsecstr != "" {
nsec, err = strconv.Atoi(nsecstr)
if err != nil {
return time.Time{}, fmt.Errorf("error parsing nanoseconds: %v", err)
}
}
nsec *= powTable[len(nsecstr)]
return time.Date(year, time.Month(month), day,
hour, minute, second, nsec, time.UTC), nil
} | go | func parseCanonicalTime(in string) (time.Time, error) {
if len(in) < 20 || in[len(in)-1] != 'Z' {
return time.Time{}, errUnparseableTimestamp
}
if !(in[4] == '-' && in[7] == '-' && in[10] == 'T' &&
in[13] == ':' && in[16] == ':' && (in[19] == '.' || in[19] == 'Z')) {
return time.Time{}, fmt.Errorf("positionally incorrect: %v", in)
}
// 2012-08-28T21:24:35.37465188Z
// 4 7 10 13 16 19
// -----------------------------
// 0-4 5 8 11 14 17 20
year, err := strconv.Atoi(in[0:4])
if err != nil {
return time.Time{}, fmt.Errorf("error parsing year: %v", err)
}
month, err := strconv.Atoi(in[5:7])
if err != nil {
return time.Time{}, fmt.Errorf("error parsing month: %v", err)
}
day, err := strconv.Atoi(in[8:10])
if err != nil {
return time.Time{}, fmt.Errorf("error parsing day: %v", err)
}
hour, err := strconv.Atoi(in[11:13])
if err != nil {
return time.Time{}, fmt.Errorf("error parsing hour: %v", err)
}
minute, err := strconv.Atoi(in[14:16])
if err != nil {
return time.Time{}, fmt.Errorf("error parsing minute: %v", err)
}
second, err := strconv.Atoi(in[17:19])
if err != nil {
return time.Time{}, fmt.Errorf("error parsing second: %v", err)
}
var nsecstr string
if in[19] != 'Z' {
nsecstr = in[20 : len(in)-1]
}
var nsec int
if nsecstr != "" {
nsec, err = strconv.Atoi(nsecstr)
if err != nil {
return time.Time{}, fmt.Errorf("error parsing nanoseconds: %v", err)
}
}
nsec *= powTable[len(nsecstr)]
return time.Date(year, time.Month(month), day,
hour, minute, second, nsec, time.UTC), nil
} | [
"func",
"parseCanonicalTime",
"(",
"in",
"string",
")",
"(",
"time",
".",
"Time",
",",
"error",
")",
"{",
"if",
"len",
"(",
"in",
")",
"<",
"20",
"||",
"in",
"[",
"len",
"(",
"in",
")",
"-",
"1",
"]",
"!=",
"'Z'",
"{",
"return",
"time",
".",
"Time",
"{",
"}",
",",
"errUnparseableTimestamp",
"\n",
"}",
"\n",
"if",
"!",
"(",
"in",
"[",
"4",
"]",
"==",
"'-'",
"&&",
"in",
"[",
"7",
"]",
"==",
"'-'",
"&&",
"in",
"[",
"10",
"]",
"==",
"'T'",
"&&",
"in",
"[",
"13",
"]",
"==",
"':'",
"&&",
"in",
"[",
"16",
"]",
"==",
"':'",
"&&",
"(",
"in",
"[",
"19",
"]",
"==",
"'.'",
"||",
"in",
"[",
"19",
"]",
"==",
"'Z'",
")",
")",
"{",
"return",
"time",
".",
"Time",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"positionally incorrect: %v\"",
",",
"in",
")",
"\n",
"}",
"\n",
"year",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"in",
"[",
"0",
":",
"4",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"time",
".",
"Time",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"error parsing year: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"month",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"in",
"[",
"5",
":",
"7",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"time",
".",
"Time",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"error parsing month: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"day",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"in",
"[",
"8",
":",
"10",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"time",
".",
"Time",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"error parsing day: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"hour",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"in",
"[",
"11",
":",
"13",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"time",
".",
"Time",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"error parsing hour: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"minute",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"in",
"[",
"14",
":",
"16",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"time",
".",
"Time",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"error parsing minute: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"second",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"in",
"[",
"17",
":",
"19",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"time",
".",
"Time",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"error parsing second: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"var",
"nsecstr",
"string",
"\n",
"if",
"in",
"[",
"19",
"]",
"!=",
"'Z'",
"{",
"nsecstr",
"=",
"in",
"[",
"20",
":",
"len",
"(",
"in",
")",
"-",
"1",
"]",
"\n",
"}",
"\n",
"var",
"nsec",
"int",
"\n",
"if",
"nsecstr",
"!=",
"\"\"",
"{",
"nsec",
",",
"err",
"=",
"strconv",
".",
"Atoi",
"(",
"nsecstr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"time",
".",
"Time",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"error parsing nanoseconds: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"nsec",
"*=",
"powTable",
"[",
"len",
"(",
"nsecstr",
")",
"]",
"\n",
"return",
"time",
".",
"Date",
"(",
"year",
",",
"time",
".",
"Month",
"(",
"month",
")",
",",
"day",
",",
"hour",
",",
"minute",
",",
"second",
",",
"nsec",
",",
"time",
".",
"UTC",
")",
",",
"nil",
"\n",
"}"
] | // Hand crafted this parser since it's a really common path. | [
"Hand",
"crafted",
"this",
"parser",
"since",
"it",
"s",
"a",
"really",
"common",
"path",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/fs/time.go#L60-L122 | train |
perkeep/perkeep | pkg/index/memindex.go | NewMemoryIndex | func NewMemoryIndex() *Index {
ix, err := New(sorted.NewMemoryKeyValue())
if err != nil {
// Nothing to fail in memory, so worth panicing about
// if we ever see something.
panic(err)
}
return ix
} | go | func NewMemoryIndex() *Index {
ix, err := New(sorted.NewMemoryKeyValue())
if err != nil {
// Nothing to fail in memory, so worth panicing about
// if we ever see something.
panic(err)
}
return ix
} | [
"func",
"NewMemoryIndex",
"(",
")",
"*",
"Index",
"{",
"ix",
",",
"err",
":=",
"New",
"(",
"sorted",
".",
"NewMemoryKeyValue",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"ix",
"\n",
"}"
] | // NewMemoryIndex returns an Index backed only by memory, for use in tests. | [
"NewMemoryIndex",
"returns",
"an",
"Index",
"backed",
"only",
"by",
"memory",
"for",
"use",
"in",
"tests",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/memindex.go#L31-L39 | train |
perkeep/perkeep | app/scanningcabinet/scancab/pdf.go | pageCountPoppler | func pageCountPoppler(filename string) (cnt int, err error) {
cmd := exec.Command("pdfinfo", filename)
out, err := cmd.CombinedOutput()
if err != nil {
return cnt, fmt.Errorf("could not get page count with pdfinfo: %v, %v", err, string(out))
}
sc := bufio.NewScanner(bytes.NewReader(out))
for sc.Scan() {
l := sc.Text()
if !strings.HasPrefix(l, "Pages: ") {
continue
}
return strconv.Atoi(strings.TrimSpace(strings.TrimPrefix(l, "Pages:")))
}
if err := sc.Err(); err != nil {
return 0, err
}
return 0, errors.New("page count not found in pdfinfo output")
} | go | func pageCountPoppler(filename string) (cnt int, err error) {
cmd := exec.Command("pdfinfo", filename)
out, err := cmd.CombinedOutput()
if err != nil {
return cnt, fmt.Errorf("could not get page count with pdfinfo: %v, %v", err, string(out))
}
sc := bufio.NewScanner(bytes.NewReader(out))
for sc.Scan() {
l := sc.Text()
if !strings.HasPrefix(l, "Pages: ") {
continue
}
return strconv.Atoi(strings.TrimSpace(strings.TrimPrefix(l, "Pages:")))
}
if err := sc.Err(); err != nil {
return 0, err
}
return 0, errors.New("page count not found in pdfinfo output")
} | [
"func",
"pageCountPoppler",
"(",
"filename",
"string",
")",
"(",
"cnt",
"int",
",",
"err",
"error",
")",
"{",
"cmd",
":=",
"exec",
".",
"Command",
"(",
"\"pdfinfo\"",
",",
"filename",
")",
"\n",
"out",
",",
"err",
":=",
"cmd",
".",
"CombinedOutput",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"cnt",
",",
"fmt",
".",
"Errorf",
"(",
"\"could not get page count with pdfinfo: %v, %v\"",
",",
"err",
",",
"string",
"(",
"out",
")",
")",
"\n",
"}",
"\n",
"sc",
":=",
"bufio",
".",
"NewScanner",
"(",
"bytes",
".",
"NewReader",
"(",
"out",
")",
")",
"\n",
"for",
"sc",
".",
"Scan",
"(",
")",
"{",
"l",
":=",
"sc",
".",
"Text",
"(",
")",
"\n",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"l",
",",
"\"Pages: \"",
")",
"{",
"continue",
"\n",
"}",
"\n",
"return",
"strconv",
".",
"Atoi",
"(",
"strings",
".",
"TrimSpace",
"(",
"strings",
".",
"TrimPrefix",
"(",
"l",
",",
"\"Pages:\"",
")",
")",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"sc",
".",
"Err",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"page count not found in pdfinfo output\"",
")",
"\n",
"}"
] | // pageCountPoppler calls the tool pdfinfo from the Poppler project for
// filename and parses the output for the page count which is then returned. If
// any error occurs or the pages count information is not found, an error is
// returned. | [
"pageCountPoppler",
"calls",
"the",
"tool",
"pdfinfo",
"from",
"the",
"Poppler",
"project",
"for",
"filename",
"and",
"parses",
"the",
"output",
"for",
"the",
"page",
"count",
"which",
"is",
"then",
"returned",
".",
"If",
"any",
"error",
"occurs",
"or",
"the",
"pages",
"count",
"information",
"is",
"not",
"found",
"an",
"error",
"is",
"returned",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/scanningcabinet/scancab/pdf.go#L37-L55 | train |
perkeep/perkeep | app/scanningcabinet/scancab/pdf.go | pageCountNative | func pageCountNative(filename string) (int, error) {
f, err := os.Open(filename)
if err != nil {
return 0, err
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return 0, err
}
p, err := pdf.NewReader(f, fi.Size())
if err != nil {
return 0, err
}
c := p.NumPage()
if c < 1 {
return 0, errors.New("encountered PDF without any pages")
}
return p.NumPage(), nil
} | go | func pageCountNative(filename string) (int, error) {
f, err := os.Open(filename)
if err != nil {
return 0, err
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return 0, err
}
p, err := pdf.NewReader(f, fi.Size())
if err != nil {
return 0, err
}
c := p.NumPage()
if c < 1 {
return 0, errors.New("encountered PDF without any pages")
}
return p.NumPage(), nil
} | [
"func",
"pageCountNative",
"(",
"filename",
"string",
")",
"(",
"int",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n",
"fi",
",",
"err",
":=",
"f",
".",
"Stat",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"p",
",",
"err",
":=",
"pdf",
".",
"NewReader",
"(",
"f",
",",
"fi",
".",
"Size",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"c",
":=",
"p",
".",
"NumPage",
"(",
")",
"\n",
"if",
"c",
"<",
"1",
"{",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"encountered PDF without any pages\"",
")",
"\n",
"}",
"\n",
"return",
"p",
".",
"NumPage",
"(",
")",
",",
"nil",
"\n",
"}"
] | // pageCountNative uses a native Go library to extract and return the number of
// pages in the PDF document. It returns an error if the filename is not of a
// PDF file, or if it failed to decode the PDF. | [
"pageCountNative",
"uses",
"a",
"native",
"Go",
"library",
"to",
"extract",
"and",
"return",
"the",
"number",
"of",
"pages",
"in",
"the",
"PDF",
"document",
".",
"It",
"returns",
"an",
"error",
"if",
"the",
"filename",
"is",
"not",
"of",
"a",
"PDF",
"file",
"or",
"if",
"it",
"failed",
"to",
"decode",
"the",
"PDF",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/scanningcabinet/scancab/pdf.go#L60-L79 | train |
perkeep/perkeep | app/scanningcabinet/scancab/pdf.go | pageCount | func pageCount(filename string) (int, error) {
n, err := pageCountNative(filename)
if err != nil {
// fallback to using pdfinfo when internal count failed
n, err = pageCountPoppler(filename)
}
return n, err
} | go | func pageCount(filename string) (int, error) {
n, err := pageCountNative(filename)
if err != nil {
// fallback to using pdfinfo when internal count failed
n, err = pageCountPoppler(filename)
}
return n, err
} | [
"func",
"pageCount",
"(",
"filename",
"string",
")",
"(",
"int",
",",
"error",
")",
"{",
"n",
",",
"err",
":=",
"pageCountNative",
"(",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"n",
",",
"err",
"=",
"pageCountPoppler",
"(",
"filename",
")",
"\n",
"}",
"\n",
"return",
"n",
",",
"err",
"\n",
"}"
] | // pageCount returns the number of pages in the given PDF file, or an error if
// it could not be determined. The function may trigger calls to external tools
// to achieve a valid count after native counting has been tried without
// success. | [
"pageCount",
"returns",
"the",
"number",
"of",
"pages",
"in",
"the",
"given",
"PDF",
"file",
"or",
"an",
"error",
"if",
"it",
"could",
"not",
"be",
"determined",
".",
"The",
"function",
"may",
"trigger",
"calls",
"to",
"external",
"tools",
"to",
"achieve",
"a",
"valid",
"count",
"after",
"native",
"counting",
"has",
"been",
"tried",
"without",
"success",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/scanningcabinet/scancab/pdf.go#L85-L92 | train |
perkeep/perkeep | pkg/search/predicate.go | SearchHelp | func SearchHelp() string {
type help struct{ Name, Description string }
h := []help{}
for _, p := range keywords {
h = append(h, help{p.Name(), p.Description()})
}
b, err := json.MarshalIndent(h, "", " ")
if err != nil {
return "Error marshalling"
}
return string(b)
} | go | func SearchHelp() string {
type help struct{ Name, Description string }
h := []help{}
for _, p := range keywords {
h = append(h, help{p.Name(), p.Description()})
}
b, err := json.MarshalIndent(h, "", " ")
if err != nil {
return "Error marshalling"
}
return string(b)
} | [
"func",
"SearchHelp",
"(",
")",
"string",
"{",
"type",
"help",
"struct",
"{",
"Name",
",",
"Description",
"string",
"}",
"\n",
"h",
":=",
"[",
"]",
"help",
"{",
"}",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"keywords",
"{",
"h",
"=",
"append",
"(",
"h",
",",
"help",
"{",
"p",
".",
"Name",
"(",
")",
",",
"p",
".",
"Description",
"(",
")",
"}",
")",
"\n",
"}",
"\n",
"b",
",",
"err",
":=",
"json",
".",
"MarshalIndent",
"(",
"h",
",",
"\"\"",
",",
"\" \"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"Error marshalling\"",
"\n",
"}",
"\n",
"return",
"string",
"(",
"b",
")",
"\n",
"}"
] | // SearchHelp returns JSON of an array of predicate names and descriptions. | [
"SearchHelp",
"returns",
"JSON",
"of",
"an",
"array",
"of",
"predicate",
"names",
"and",
"descriptions",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/search/predicate.go#L91-L102 | train |
perkeep/perkeep | pkg/blobserver/receive.go | ReceiveString | func ReceiveString(ctx context.Context, dst BlobReceiver, s string) (blob.SizedRef, error) {
return Receive(ctx, dst, blob.RefFromString(s), strings.NewReader(s))
} | go | func ReceiveString(ctx context.Context, dst BlobReceiver, s string) (blob.SizedRef, error) {
return Receive(ctx, dst, blob.RefFromString(s), strings.NewReader(s))
} | [
"func",
"ReceiveString",
"(",
"ctx",
"context",
".",
"Context",
",",
"dst",
"BlobReceiver",
",",
"s",
"string",
")",
"(",
"blob",
".",
"SizedRef",
",",
"error",
")",
"{",
"return",
"Receive",
"(",
"ctx",
",",
"dst",
",",
"blob",
".",
"RefFromString",
"(",
"s",
")",
",",
"strings",
".",
"NewReader",
"(",
"s",
")",
")",
"\n",
"}"
] | // ReceiveString uploads the blob given by the string s to dst
// and returns its blobref and size. | [
"ReceiveString",
"uploads",
"the",
"blob",
"given",
"by",
"the",
"string",
"s",
"to",
"dst",
"and",
"returns",
"its",
"blobref",
"and",
"size",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/receive.go#L35-L37 | train |
perkeep/perkeep | pkg/blobserver/receive.go | Receive | func Receive(ctx context.Context, dst BlobReceiver, br blob.Ref, src io.Reader) (blob.SizedRef, error) {
return receive(ctx, dst, br, src, true)
} | go | func Receive(ctx context.Context, dst BlobReceiver, br blob.Ref, src io.Reader) (blob.SizedRef, error) {
return receive(ctx, dst, br, src, true)
} | [
"func",
"Receive",
"(",
"ctx",
"context",
".",
"Context",
",",
"dst",
"BlobReceiver",
",",
"br",
"blob",
".",
"Ref",
",",
"src",
"io",
".",
"Reader",
")",
"(",
"blob",
".",
"SizedRef",
",",
"error",
")",
"{",
"return",
"receive",
"(",
"ctx",
",",
"dst",
",",
"br",
",",
"src",
",",
"true",
")",
"\n",
"}"
] | // Receive wraps calling a BlobReceiver's ReceiveBlob method,
// additionally providing verification of the src digest, and also
// notifying the blob hub on success.
// The error will be ErrCorruptBlob if the blobref didn't match. | [
"Receive",
"wraps",
"calling",
"a",
"BlobReceiver",
"s",
"ReceiveBlob",
"method",
"additionally",
"providing",
"verification",
"of",
"the",
"src",
"digest",
"and",
"also",
"notifying",
"the",
"blob",
"hub",
"on",
"success",
".",
"The",
"error",
"will",
"be",
"ErrCorruptBlob",
"if",
"the",
"blobref",
"didn",
"t",
"match",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/receive.go#L43-L45 | train |
perkeep/perkeep | pkg/importer/importer.go | Register | func Register(name string, im Importer) {
if _, dup := importers[name]; dup {
panic("Dup registration of importer " + name)
}
if _, dup := reservedImporterKey[name]; dup {
panic("Dup registration of importer " + name)
}
if pt := im.Properties().PermanodeImporterType; pt != "" {
if _, dup := importers[pt]; dup {
panic("Dup registration of importer " + pt)
}
if _, dup := reservedImporterKey[pt]; dup {
panic("Dup registration of importer " + pt)
}
reservedImporterKey[pt] = true
}
importers[name] = im
} | go | func Register(name string, im Importer) {
if _, dup := importers[name]; dup {
panic("Dup registration of importer " + name)
}
if _, dup := reservedImporterKey[name]; dup {
panic("Dup registration of importer " + name)
}
if pt := im.Properties().PermanodeImporterType; pt != "" {
if _, dup := importers[pt]; dup {
panic("Dup registration of importer " + pt)
}
if _, dup := reservedImporterKey[pt]; dup {
panic("Dup registration of importer " + pt)
}
reservedImporterKey[pt] = true
}
importers[name] = im
} | [
"func",
"Register",
"(",
"name",
"string",
",",
"im",
"Importer",
")",
"{",
"if",
"_",
",",
"dup",
":=",
"importers",
"[",
"name",
"]",
";",
"dup",
"{",
"panic",
"(",
"\"Dup registration of importer \"",
"+",
"name",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"dup",
":=",
"reservedImporterKey",
"[",
"name",
"]",
";",
"dup",
"{",
"panic",
"(",
"\"Dup registration of importer \"",
"+",
"name",
")",
"\n",
"}",
"\n",
"if",
"pt",
":=",
"im",
".",
"Properties",
"(",
")",
".",
"PermanodeImporterType",
";",
"pt",
"!=",
"\"\"",
"{",
"if",
"_",
",",
"dup",
":=",
"importers",
"[",
"pt",
"]",
";",
"dup",
"{",
"panic",
"(",
"\"Dup registration of importer \"",
"+",
"pt",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"dup",
":=",
"reservedImporterKey",
"[",
"pt",
"]",
";",
"dup",
"{",
"panic",
"(",
"\"Dup registration of importer \"",
"+",
"pt",
")",
"\n",
"}",
"\n",
"reservedImporterKey",
"[",
"pt",
"]",
"=",
"true",
"\n",
"}",
"\n",
"importers",
"[",
"name",
"]",
"=",
"im",
"\n",
"}"
] | // Register registers a site-specific importer. It should only be called from init,
// and not from concurrent goroutines. | [
"Register",
"registers",
"a",
"site",
"-",
"specific",
"importer",
".",
"It",
"should",
"only",
"be",
"called",
"from",
"init",
"and",
"not",
"from",
"concurrent",
"goroutines",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/importer.go#L171-L188 | train |
perkeep/perkeep | pkg/importer/importer.go | Context | func (rc *RunContext) Context() context.Context {
if rc.ctx != nil {
return rc.ctx
}
return context.Background()
} | go | func (rc *RunContext) Context() context.Context {
if rc.ctx != nil {
return rc.ctx
}
return context.Background()
} | [
"func",
"(",
"rc",
"*",
"RunContext",
")",
"Context",
"(",
")",
"context",
".",
"Context",
"{",
"if",
"rc",
".",
"ctx",
"!=",
"nil",
"{",
"return",
"rc",
".",
"ctx",
"\n",
"}",
"\n",
"return",
"context",
".",
"Background",
"(",
")",
"\n",
"}"
] | // Context returns the run's context. It is always non-nil. | [
"Context",
"returns",
"the",
"run",
"s",
"context",
".",
"It",
"is",
"always",
"non",
"-",
"nil",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/importer.go#L345-L350 | train |
perkeep/perkeep | pkg/importer/importer.go | CreateAccount | func CreateAccount(h *Host, impl string) (*RunContext, error) {
imp, ok := h.imp[impl]
if !ok {
return nil, fmt.Errorf("host does not have a %v importer", impl)
}
ia, err := imp.newAccount()
if err != nil {
return nil, fmt.Errorf("could not create new account for importer %v: %v", impl, err)
}
rc := &RunContext{
Host: ia.im.host,
ia: ia,
}
rc.ctx, rc.cancel = context.WithCancel(context.WithValue(context.Background(), ctxutil.HTTPClient, ia.im.host.HTTPClient()))
return rc, nil
} | go | func CreateAccount(h *Host, impl string) (*RunContext, error) {
imp, ok := h.imp[impl]
if !ok {
return nil, fmt.Errorf("host does not have a %v importer", impl)
}
ia, err := imp.newAccount()
if err != nil {
return nil, fmt.Errorf("could not create new account for importer %v: %v", impl, err)
}
rc := &RunContext{
Host: ia.im.host,
ia: ia,
}
rc.ctx, rc.cancel = context.WithCancel(context.WithValue(context.Background(), ctxutil.HTTPClient, ia.im.host.HTTPClient()))
return rc, nil
} | [
"func",
"CreateAccount",
"(",
"h",
"*",
"Host",
",",
"impl",
"string",
")",
"(",
"*",
"RunContext",
",",
"error",
")",
"{",
"imp",
",",
"ok",
":=",
"h",
".",
"imp",
"[",
"impl",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"host does not have a %v importer\"",
",",
"impl",
")",
"\n",
"}",
"\n",
"ia",
",",
"err",
":=",
"imp",
".",
"newAccount",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"could not create new account for importer %v: %v\"",
",",
"impl",
",",
"err",
")",
"\n",
"}",
"\n",
"rc",
":=",
"&",
"RunContext",
"{",
"Host",
":",
"ia",
".",
"im",
".",
"host",
",",
"ia",
":",
"ia",
",",
"}",
"\n",
"rc",
".",
"ctx",
",",
"rc",
".",
"cancel",
"=",
"context",
".",
"WithCancel",
"(",
"context",
".",
"WithValue",
"(",
"context",
".",
"Background",
"(",
")",
",",
"ctxutil",
".",
"HTTPClient",
",",
"ia",
".",
"im",
".",
"host",
".",
"HTTPClient",
"(",
")",
")",
")",
"\n",
"return",
"rc",
",",
"nil",
"\n",
"}"
] | // CreateAccount creates a new importer account for the Host h, and the importer
// implementation named impl. It returns a RunContext setup with that account. | [
"CreateAccount",
"creates",
"a",
"new",
"importer",
"account",
"for",
"the",
"Host",
"h",
"and",
"the",
"importer",
"implementation",
"named",
"impl",
".",
"It",
"returns",
"a",
"RunContext",
"setup",
"with",
"that",
"account",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/importer.go#L354-L370 | train |
perkeep/perkeep | pkg/importer/importer.go | AccountsStatus | func (h *Host) AccountsStatus() (interface{}, []camtypes.StatusError) {
h.didInit.Wait()
var s []accountStatus
var errs []camtypes.StatusError
for _, impName := range h.importers {
imp := h.imp[impName]
accts, _ := imp.Accounts()
for _, ia := range accts {
as := accountStatus{
Type: impName,
Href: ia.AccountURL(),
Name: ia.AccountLinkSummary(),
}
ia.mu.Lock()
if ia.current != nil {
as.StartedUnixSec = ia.lastRunStart.Unix()
}
if !ia.lastRunDone.IsZero() {
as.LastFinishedUnixSec = ia.lastRunDone.Unix()
}
if ia.lastRunErr != nil {
as.LastError = ia.lastRunErr.Error()
errs = append(errs, camtypes.StatusError{
Error: ia.lastRunErr.Error(),
URL: ia.AccountURL(),
})
}
ia.mu.Unlock()
s = append(s, as)
}
}
return s, errs
} | go | func (h *Host) AccountsStatus() (interface{}, []camtypes.StatusError) {
h.didInit.Wait()
var s []accountStatus
var errs []camtypes.StatusError
for _, impName := range h.importers {
imp := h.imp[impName]
accts, _ := imp.Accounts()
for _, ia := range accts {
as := accountStatus{
Type: impName,
Href: ia.AccountURL(),
Name: ia.AccountLinkSummary(),
}
ia.mu.Lock()
if ia.current != nil {
as.StartedUnixSec = ia.lastRunStart.Unix()
}
if !ia.lastRunDone.IsZero() {
as.LastFinishedUnixSec = ia.lastRunDone.Unix()
}
if ia.lastRunErr != nil {
as.LastError = ia.lastRunErr.Error()
errs = append(errs, camtypes.StatusError{
Error: ia.lastRunErr.Error(),
URL: ia.AccountURL(),
})
}
ia.mu.Unlock()
s = append(s, as)
}
}
return s, errs
} | [
"func",
"(",
"h",
"*",
"Host",
")",
"AccountsStatus",
"(",
")",
"(",
"interface",
"{",
"}",
",",
"[",
"]",
"camtypes",
".",
"StatusError",
")",
"{",
"h",
".",
"didInit",
".",
"Wait",
"(",
")",
"\n",
"var",
"s",
"[",
"]",
"accountStatus",
"\n",
"var",
"errs",
"[",
"]",
"camtypes",
".",
"StatusError",
"\n",
"for",
"_",
",",
"impName",
":=",
"range",
"h",
".",
"importers",
"{",
"imp",
":=",
"h",
".",
"imp",
"[",
"impName",
"]",
"\n",
"accts",
",",
"_",
":=",
"imp",
".",
"Accounts",
"(",
")",
"\n",
"for",
"_",
",",
"ia",
":=",
"range",
"accts",
"{",
"as",
":=",
"accountStatus",
"{",
"Type",
":",
"impName",
",",
"Href",
":",
"ia",
".",
"AccountURL",
"(",
")",
",",
"Name",
":",
"ia",
".",
"AccountLinkSummary",
"(",
")",
",",
"}",
"\n",
"ia",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"ia",
".",
"current",
"!=",
"nil",
"{",
"as",
".",
"StartedUnixSec",
"=",
"ia",
".",
"lastRunStart",
".",
"Unix",
"(",
")",
"\n",
"}",
"\n",
"if",
"!",
"ia",
".",
"lastRunDone",
".",
"IsZero",
"(",
")",
"{",
"as",
".",
"LastFinishedUnixSec",
"=",
"ia",
".",
"lastRunDone",
".",
"Unix",
"(",
")",
"\n",
"}",
"\n",
"if",
"ia",
".",
"lastRunErr",
"!=",
"nil",
"{",
"as",
".",
"LastError",
"=",
"ia",
".",
"lastRunErr",
".",
"Error",
"(",
")",
"\n",
"errs",
"=",
"append",
"(",
"errs",
",",
"camtypes",
".",
"StatusError",
"{",
"Error",
":",
"ia",
".",
"lastRunErr",
".",
"Error",
"(",
")",
",",
"URL",
":",
"ia",
".",
"AccountURL",
"(",
")",
",",
"}",
")",
"\n",
"}",
"\n",
"ia",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"s",
"=",
"append",
"(",
"s",
",",
"as",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"s",
",",
"errs",
"\n",
"}"
] | // AccountsStatus returns the currently configured accounts and their status for
// inclusion in the status.json document, as rendered by the web UI. | [
"AccountsStatus",
"returns",
"the",
"currently",
"configured",
"accounts",
"and",
"their",
"status",
"for",
"inclusion",
"in",
"the",
"status",
".",
"json",
"document",
"as",
"rendered",
"by",
"the",
"web",
"UI",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/importer.go#L439-L471 | train |
perkeep/perkeep | pkg/importer/importer.go | RunImporterAccount | func (h *Host) RunImporterAccount(importerType string, accountNode blob.Ref) error {
h.didInit.Wait()
imp, ok := h.imp[importerType]
if !ok {
return fmt.Errorf("no %q importer for this account", importerType)
}
accounts, err := imp.Accounts()
if err != nil {
return err
}
for _, ia := range accounts {
if ia.acct.pn != accountNode {
continue
}
return ia.run()
}
return fmt.Errorf("no %v account matching account in node %v", importerType, accountNode)
} | go | func (h *Host) RunImporterAccount(importerType string, accountNode blob.Ref) error {
h.didInit.Wait()
imp, ok := h.imp[importerType]
if !ok {
return fmt.Errorf("no %q importer for this account", importerType)
}
accounts, err := imp.Accounts()
if err != nil {
return err
}
for _, ia := range accounts {
if ia.acct.pn != accountNode {
continue
}
return ia.run()
}
return fmt.Errorf("no %v account matching account in node %v", importerType, accountNode)
} | [
"func",
"(",
"h",
"*",
"Host",
")",
"RunImporterAccount",
"(",
"importerType",
"string",
",",
"accountNode",
"blob",
".",
"Ref",
")",
"error",
"{",
"h",
".",
"didInit",
".",
"Wait",
"(",
")",
"\n",
"imp",
",",
"ok",
":=",
"h",
".",
"imp",
"[",
"importerType",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"no %q importer for this account\"",
",",
"importerType",
")",
"\n",
"}",
"\n",
"accounts",
",",
"err",
":=",
"imp",
".",
"Accounts",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"ia",
":=",
"range",
"accounts",
"{",
"if",
"ia",
".",
"acct",
".",
"pn",
"!=",
"accountNode",
"{",
"continue",
"\n",
"}",
"\n",
"return",
"ia",
".",
"run",
"(",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"no %v account matching account in node %v\"",
",",
"importerType",
",",
"accountNode",
")",
"\n",
"}"
] | // RunImporterAccount runs the importerType importer on the account described in
// accountNode. | [
"RunImporterAccount",
"runs",
"the",
"importerType",
"importer",
"on",
"the",
"account",
"described",
"in",
"accountNode",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/importer.go#L475-L492 | train |
perkeep/perkeep | pkg/importer/importer.go | HTTPClient | func (h *Host) HTTPClient() *http.Client {
if h.client == nil {
return http.DefaultClient
}
return h.client
} | go | func (h *Host) HTTPClient() *http.Client {
if h.client == nil {
return http.DefaultClient
}
return h.client
} | [
"func",
"(",
"h",
"*",
"Host",
")",
"HTTPClient",
"(",
")",
"*",
"http",
".",
"Client",
"{",
"if",
"h",
".",
"client",
"==",
"nil",
"{",
"return",
"http",
".",
"DefaultClient",
"\n",
"}",
"\n",
"return",
"h",
".",
"client",
"\n",
"}"
] | // HTTPClient returns the HTTP client to use. | [
"HTTPClient",
"returns",
"the",
"HTTP",
"client",
"to",
"use",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/importer.go#L1333-L1338 | train |
perkeep/perkeep | pkg/importer/importer.go | HTTPTransport | func (h *Host) HTTPTransport() http.RoundTripper {
if h.transport == nil {
return http.DefaultTransport
}
return h.transport
} | go | func (h *Host) HTTPTransport() http.RoundTripper {
if h.transport == nil {
return http.DefaultTransport
}
return h.transport
} | [
"func",
"(",
"h",
"*",
"Host",
")",
"HTTPTransport",
"(",
")",
"http",
".",
"RoundTripper",
"{",
"if",
"h",
".",
"transport",
"==",
"nil",
"{",
"return",
"http",
".",
"DefaultTransport",
"\n",
"}",
"\n",
"return",
"h",
".",
"transport",
"\n",
"}"
] | // HTTPTransport returns the HTTP transport to use. | [
"HTTPTransport",
"returns",
"the",
"HTTP",
"transport",
"to",
"use",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/importer.go#L1341-L1346 | train |
perkeep/perkeep | pkg/importer/importer.go | NewObject | func (h *Host) NewObject() (*Object, error) {
ctx := context.TODO() // TODO: move the NewObject method to some "ImportRun" type with a context field?
pn, err := h.upload(ctx, schema.NewUnsignedPermanode())
if err != nil {
return nil, err
}
// No need to do a describe query against it: we know it's
// empty (has no claims against it yet).
return &Object{h: h, pn: pn}, nil
} | go | func (h *Host) NewObject() (*Object, error) {
ctx := context.TODO() // TODO: move the NewObject method to some "ImportRun" type with a context field?
pn, err := h.upload(ctx, schema.NewUnsignedPermanode())
if err != nil {
return nil, err
}
// No need to do a describe query against it: we know it's
// empty (has no claims against it yet).
return &Object{h: h, pn: pn}, nil
} | [
"func",
"(",
"h",
"*",
"Host",
")",
"NewObject",
"(",
")",
"(",
"*",
"Object",
",",
"error",
")",
"{",
"ctx",
":=",
"context",
".",
"TODO",
"(",
")",
"\n",
"pn",
",",
"err",
":=",
"h",
".",
"upload",
"(",
"ctx",
",",
"schema",
".",
"NewUnsignedPermanode",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"Object",
"{",
"h",
":",
"h",
",",
"pn",
":",
"pn",
"}",
",",
"nil",
"\n",
"}"
] | // NewObject creates a new permanode and returns its Object wrapper. | [
"NewObject",
"creates",
"a",
"new",
"permanode",
"and",
"returns",
"its",
"Object",
"wrapper",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/importer.go#L1366-L1375 | train |
perkeep/perkeep | pkg/importer/importer.go | Attr | func (o *Object) Attr(attr string) string {
o.mu.RLock()
defer o.mu.RUnlock()
if v := o.attr[attr]; len(v) > 0 {
return v[0]
}
return ""
} | go | func (o *Object) Attr(attr string) string {
o.mu.RLock()
defer o.mu.RUnlock()
if v := o.attr[attr]; len(v) > 0 {
return v[0]
}
return ""
} | [
"func",
"(",
"o",
"*",
"Object",
")",
"Attr",
"(",
"attr",
"string",
")",
"string",
"{",
"o",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"o",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"v",
":=",
"o",
".",
"attr",
"[",
"attr",
"]",
";",
"len",
"(",
"v",
")",
">",
"0",
"{",
"return",
"v",
"[",
"0",
"]",
"\n",
"}",
"\n",
"return",
"\"\"",
"\n",
"}"
] | // Attr returns the object's attribute value for the provided attr,
// or the empty string if unset. To distinguish between unset,
// an empty string, or multiple attribute values, use Attrs. | [
"Attr",
"returns",
"the",
"object",
"s",
"attribute",
"value",
"for",
"the",
"provided",
"attr",
"or",
"the",
"empty",
"string",
"if",
"unset",
".",
"To",
"distinguish",
"between",
"unset",
"an",
"empty",
"string",
"or",
"multiple",
"attribute",
"values",
"use",
"Attrs",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/importer.go#L1396-L1403 | train |
perkeep/perkeep | pkg/importer/importer.go | Attrs | func (o *Object) Attrs(attr string) []string {
o.mu.RLock()
defer o.mu.RUnlock()
return o.attr[attr]
} | go | func (o *Object) Attrs(attr string) []string {
o.mu.RLock()
defer o.mu.RUnlock()
return o.attr[attr]
} | [
"func",
"(",
"o",
"*",
"Object",
")",
"Attrs",
"(",
"attr",
"string",
")",
"[",
"]",
"string",
"{",
"o",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"o",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"o",
".",
"attr",
"[",
"attr",
"]",
"\n",
"}"
] | // Attrs returns the attribute values for the provided attr. | [
"Attrs",
"returns",
"the",
"attribute",
"values",
"for",
"the",
"provided",
"attr",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/importer.go#L1406-L1410 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.