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
golang/appengine
delay/delay.go
Func
func Func(key string, i interface{}) *Function { f := &Function{fv: reflect.ValueOf(i)} // Derive unique, somewhat stable key for this func. _, file, _, _ := runtime.Caller(1) fk, err := fileKey(file) if err != nil { // Not fatal, but log the error stdlog.Printf("delay: %v", err) } f.key = fk + ":" + key t := f.fv.Type() if t.Kind() != reflect.Func { f.err = errors.New("not a function") return f } if t.NumIn() == 0 || !isContext(t.In(0)) { f.err = errFirstArg return f } // Register the function's arguments with the gob package. // This is required because they are marshaled inside a []interface{}. // gob.Register only expects to be called during initialization; // that's fine because this function expects the same. for i := 0; i < t.NumIn(); i++ { // Only concrete types may be registered. If the argument has // interface type, the client is resposible for registering the // concrete types it will hold. if t.In(i).Kind() == reflect.Interface { continue } gob.Register(reflect.Zero(t.In(i)).Interface()) } if old := funcs[f.key]; old != nil { old.err = fmt.Errorf("multiple functions registered for %s in %s", key, file) } funcs[f.key] = f return f }
go
func Func(key string, i interface{}) *Function { f := &Function{fv: reflect.ValueOf(i)} // Derive unique, somewhat stable key for this func. _, file, _, _ := runtime.Caller(1) fk, err := fileKey(file) if err != nil { // Not fatal, but log the error stdlog.Printf("delay: %v", err) } f.key = fk + ":" + key t := f.fv.Type() if t.Kind() != reflect.Func { f.err = errors.New("not a function") return f } if t.NumIn() == 0 || !isContext(t.In(0)) { f.err = errFirstArg return f } // Register the function's arguments with the gob package. // This is required because they are marshaled inside a []interface{}. // gob.Register only expects to be called during initialization; // that's fine because this function expects the same. for i := 0; i < t.NumIn(); i++ { // Only concrete types may be registered. If the argument has // interface type, the client is resposible for registering the // concrete types it will hold. if t.In(i).Kind() == reflect.Interface { continue } gob.Register(reflect.Zero(t.In(i)).Interface()) } if old := funcs[f.key]; old != nil { old.err = fmt.Errorf("multiple functions registered for %s in %s", key, file) } funcs[f.key] = f return f }
[ "func", "Func", "(", "key", "string", ",", "i", "interface", "{", "}", ")", "*", "Function", "{", "f", ":=", "&", "Function", "{", "fv", ":", "reflect", ".", "ValueOf", "(", "i", ")", "}", "\n", "_", ",", "file", ",", "_", ",", "_", ":=", "runtime", ".", "Caller", "(", "1", ")", "\n", "fk", ",", "err", ":=", "fileKey", "(", "file", ")", "\n", "if", "err", "!=", "nil", "{", "stdlog", ".", "Printf", "(", "\"delay: %v\"", ",", "err", ")", "\n", "}", "\n", "f", ".", "key", "=", "fk", "+", "\":\"", "+", "key", "\n", "t", ":=", "f", ".", "fv", ".", "Type", "(", ")", "\n", "if", "t", ".", "Kind", "(", ")", "!=", "reflect", ".", "Func", "{", "f", ".", "err", "=", "errors", ".", "New", "(", "\"not a function\"", ")", "\n", "return", "f", "\n", "}", "\n", "if", "t", ".", "NumIn", "(", ")", "==", "0", "||", "!", "isContext", "(", "t", ".", "In", "(", "0", ")", ")", "{", "f", ".", "err", "=", "errFirstArg", "\n", "return", "f", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "t", ".", "NumIn", "(", ")", ";", "i", "++", "{", "if", "t", ".", "In", "(", "i", ")", ".", "Kind", "(", ")", "==", "reflect", ".", "Interface", "{", "continue", "\n", "}", "\n", "gob", ".", "Register", "(", "reflect", ".", "Zero", "(", "t", ".", "In", "(", "i", ")", ")", ".", "Interface", "(", ")", ")", "\n", "}", "\n", "if", "old", ":=", "funcs", "[", "f", ".", "key", "]", ";", "old", "!=", "nil", "{", "old", ".", "err", "=", "fmt", ".", "Errorf", "(", "\"multiple functions registered for %s in %s\"", ",", "key", ",", "file", ")", "\n", "}", "\n", "funcs", "[", "f", ".", "key", "]", "=", "f", "\n", "return", "f", "\n", "}" ]
// Func declares a new Function. The second argument must be a function with a // first argument of type context.Context. // This function must be called at program initialization time. That means it // must be called in a global variable declaration or from an init function. // This restriction is necessary because the instance that delays a function // call may not be the one that executes it. Only the code executed at program // initialization time is guaranteed to have been run by an instance before it // receives a request.
[ "Func", "declares", "a", "new", "Function", ".", "The", "second", "argument", "must", "be", "a", "function", "with", "a", "first", "argument", "of", "type", "context", ".", "Context", ".", "This", "function", "must", "be", "called", "at", "program", "initialization", "time", ".", "That", "means", "it", "must", "be", "called", "in", "a", "global", "variable", "declaration", "or", "from", "an", "init", "function", ".", "This", "restriction", "is", "necessary", "because", "the", "instance", "that", "delays", "a", "function", "call", "may", "not", "be", "the", "one", "that", "executes", "it", ".", "Only", "the", "code", "executed", "at", "program", "initialization", "time", "is", "guaranteed", "to", "have", "been", "run", "by", "an", "instance", "before", "it", "receives", "a", "request", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/delay/delay.go#L162-L203
test
golang/appengine
delay/delay.go
Task
func (f *Function) Task(args ...interface{}) (*taskqueue.Task, error) { if f.err != nil { return nil, fmt.Errorf("delay: func is invalid: %v", f.err) } nArgs := len(args) + 1 // +1 for the context.Context ft := f.fv.Type() minArgs := ft.NumIn() if ft.IsVariadic() { minArgs-- } if nArgs < minArgs { return nil, fmt.Errorf("delay: too few arguments to func: %d < %d", nArgs, minArgs) } if !ft.IsVariadic() && nArgs > minArgs { return nil, fmt.Errorf("delay: too many arguments to func: %d > %d", nArgs, minArgs) } // Check arg types. for i := 1; i < nArgs; i++ { at := reflect.TypeOf(args[i-1]) var dt reflect.Type if i < minArgs { // not a variadic arg dt = ft.In(i) } else { // a variadic arg dt = ft.In(minArgs).Elem() } // nil arguments won't have a type, so they need special handling. if at == nil { // nil interface switch dt.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: continue // may be nil } return nil, fmt.Errorf("delay: argument %d has wrong type: %v is not nilable", i, dt) } switch at.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: av := reflect.ValueOf(args[i-1]) if av.IsNil() { // nil value in interface; not supported by gob, so we replace it // with a nil interface value args[i-1] = nil } } if !at.AssignableTo(dt) { return nil, fmt.Errorf("delay: argument %d has wrong type: %v is not assignable to %v", i, at, dt) } } inv := invocation{ Key: f.key, Args: args, } buf := new(bytes.Buffer) if err := gob.NewEncoder(buf).Encode(inv); err != nil { return nil, fmt.Errorf("delay: gob encoding failed: %v", err) } return &taskqueue.Task{ Path: path, Payload: buf.Bytes(), }, nil }
go
func (f *Function) Task(args ...interface{}) (*taskqueue.Task, error) { if f.err != nil { return nil, fmt.Errorf("delay: func is invalid: %v", f.err) } nArgs := len(args) + 1 // +1 for the context.Context ft := f.fv.Type() minArgs := ft.NumIn() if ft.IsVariadic() { minArgs-- } if nArgs < minArgs { return nil, fmt.Errorf("delay: too few arguments to func: %d < %d", nArgs, minArgs) } if !ft.IsVariadic() && nArgs > minArgs { return nil, fmt.Errorf("delay: too many arguments to func: %d > %d", nArgs, minArgs) } // Check arg types. for i := 1; i < nArgs; i++ { at := reflect.TypeOf(args[i-1]) var dt reflect.Type if i < minArgs { // not a variadic arg dt = ft.In(i) } else { // a variadic arg dt = ft.In(minArgs).Elem() } // nil arguments won't have a type, so they need special handling. if at == nil { // nil interface switch dt.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: continue // may be nil } return nil, fmt.Errorf("delay: argument %d has wrong type: %v is not nilable", i, dt) } switch at.Kind() { case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: av := reflect.ValueOf(args[i-1]) if av.IsNil() { // nil value in interface; not supported by gob, so we replace it // with a nil interface value args[i-1] = nil } } if !at.AssignableTo(dt) { return nil, fmt.Errorf("delay: argument %d has wrong type: %v is not assignable to %v", i, at, dt) } } inv := invocation{ Key: f.key, Args: args, } buf := new(bytes.Buffer) if err := gob.NewEncoder(buf).Encode(inv); err != nil { return nil, fmt.Errorf("delay: gob encoding failed: %v", err) } return &taskqueue.Task{ Path: path, Payload: buf.Bytes(), }, nil }
[ "func", "(", "f", "*", "Function", ")", "Task", "(", "args", "...", "interface", "{", "}", ")", "(", "*", "taskqueue", ".", "Task", ",", "error", ")", "{", "if", "f", ".", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"delay: func is invalid: %v\"", ",", "f", ".", "err", ")", "\n", "}", "\n", "nArgs", ":=", "len", "(", "args", ")", "+", "1", "\n", "ft", ":=", "f", ".", "fv", ".", "Type", "(", ")", "\n", "minArgs", ":=", "ft", ".", "NumIn", "(", ")", "\n", "if", "ft", ".", "IsVariadic", "(", ")", "{", "minArgs", "--", "\n", "}", "\n", "if", "nArgs", "<", "minArgs", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"delay: too few arguments to func: %d < %d\"", ",", "nArgs", ",", "minArgs", ")", "\n", "}", "\n", "if", "!", "ft", ".", "IsVariadic", "(", ")", "&&", "nArgs", ">", "minArgs", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"delay: too many arguments to func: %d > %d\"", ",", "nArgs", ",", "minArgs", ")", "\n", "}", "\n", "for", "i", ":=", "1", ";", "i", "<", "nArgs", ";", "i", "++", "{", "at", ":=", "reflect", ".", "TypeOf", "(", "args", "[", "i", "-", "1", "]", ")", "\n", "var", "dt", "reflect", ".", "Type", "\n", "if", "i", "<", "minArgs", "{", "dt", "=", "ft", ".", "In", "(", "i", ")", "\n", "}", "else", "{", "dt", "=", "ft", ".", "In", "(", "minArgs", ")", ".", "Elem", "(", ")", "\n", "}", "\n", "if", "at", "==", "nil", "{", "switch", "dt", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Chan", ",", "reflect", ".", "Func", ",", "reflect", ".", "Interface", ",", "reflect", ".", "Map", ",", "reflect", ".", "Ptr", ",", "reflect", ".", "Slice", ":", "continue", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"delay: argument %d has wrong type: %v is not nilable\"", ",", "i", ",", "dt", ")", "\n", "}", "\n", "switch", "at", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Chan", ",", "reflect", ".", "Func", ",", "reflect", ".", "Interface", ",", "reflect", ".", "Map", ",", "reflect", ".", "Ptr", ",", "reflect", ".", "Slice", ":", "av", ":=", "reflect", ".", "ValueOf", "(", "args", "[", "i", "-", "1", "]", ")", "\n", "if", "av", ".", "IsNil", "(", ")", "{", "args", "[", "i", "-", "1", "]", "=", "nil", "\n", "}", "\n", "}", "\n", "if", "!", "at", ".", "AssignableTo", "(", "dt", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"delay: argument %d has wrong type: %v is not assignable to %v\"", ",", "i", ",", "at", ",", "dt", ")", "\n", "}", "\n", "}", "\n", "inv", ":=", "invocation", "{", "Key", ":", "f", ".", "key", ",", "Args", ":", "args", ",", "}", "\n", "buf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "if", "err", ":=", "gob", ".", "NewEncoder", "(", "buf", ")", ".", "Encode", "(", "inv", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"delay: gob encoding failed: %v\"", ",", "err", ")", "\n", "}", "\n", "return", "&", "taskqueue", ".", "Task", "{", "Path", ":", "path", ",", "Payload", ":", "buf", ".", "Bytes", "(", ")", ",", "}", ",", "nil", "\n", "}" ]
// Task creates a Task that will invoke the function. // Its parameters may be tweaked before adding it to a queue. // Users should not modify the Path or Payload fields of the returned Task.
[ "Task", "creates", "a", "Task", "that", "will", "invoke", "the", "function", ".", "Its", "parameters", "may", "be", "tweaked", "before", "adding", "it", "to", "a", "queue", ".", "Users", "should", "not", "modify", "the", "Path", "or", "Payload", "fields", "of", "the", "returned", "Task", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/delay/delay.go#L227-L293
test
golang/appengine
delay/delay.go
RequestHeaders
func RequestHeaders(c context.Context) (*taskqueue.RequestHeaders, error) { if ret, ok := c.Value(headersContextKey).(*taskqueue.RequestHeaders); ok { return ret, nil } return nil, errOutsideDelayFunc }
go
func RequestHeaders(c context.Context) (*taskqueue.RequestHeaders, error) { if ret, ok := c.Value(headersContextKey).(*taskqueue.RequestHeaders); ok { return ret, nil } return nil, errOutsideDelayFunc }
[ "func", "RequestHeaders", "(", "c", "context", ".", "Context", ")", "(", "*", "taskqueue", ".", "RequestHeaders", ",", "error", ")", "{", "if", "ret", ",", "ok", ":=", "c", ".", "Value", "(", "headersContextKey", ")", ".", "(", "*", "taskqueue", ".", "RequestHeaders", ")", ";", "ok", "{", "return", "ret", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "errOutsideDelayFunc", "\n", "}" ]
// Request returns the special task-queue HTTP request headers for the current // task queue handler. Returns an error if called from outside a delay.Func.
[ "Request", "returns", "the", "special", "task", "-", "queue", "HTTP", "request", "headers", "for", "the", "current", "task", "queue", "handler", ".", "Returns", "an", "error", "if", "called", "from", "outside", "a", "delay", ".", "Func", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/delay/delay.go#L297-L302
test
golang/appengine
appengine.go
WithContext
func WithContext(parent context.Context, req *http.Request) context.Context { return internal.WithContext(parent, req) }
go
func WithContext(parent context.Context, req *http.Request) context.Context { return internal.WithContext(parent, req) }
[ "func", "WithContext", "(", "parent", "context", ".", "Context", ",", "req", "*", "http", ".", "Request", ")", "context", ".", "Context", "{", "return", "internal", ".", "WithContext", "(", "parent", ",", "req", ")", "\n", "}" ]
// WithContext returns a copy of the parent context // and associates it with an in-flight HTTP request. // This function is cheap.
[ "WithContext", "returns", "a", "copy", "of", "the", "parent", "context", "and", "associates", "it", "with", "an", "in", "-", "flight", "HTTP", "request", ".", "This", "function", "is", "cheap", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/appengine.go#L96-L98
test
golang/appengine
appengine.go
WithAPICallFunc
func WithAPICallFunc(ctx context.Context, f APICallFunc) context.Context { return internal.WithCallOverride(ctx, internal.CallOverrideFunc(f)) }
go
func WithAPICallFunc(ctx context.Context, f APICallFunc) context.Context { return internal.WithCallOverride(ctx, internal.CallOverrideFunc(f)) }
[ "func", "WithAPICallFunc", "(", "ctx", "context", ".", "Context", ",", "f", "APICallFunc", ")", "context", ".", "Context", "{", "return", "internal", ".", "WithCallOverride", "(", "ctx", ",", "internal", ".", "CallOverrideFunc", "(", "f", ")", ")", "\n", "}" ]
// WithAPICallFunc returns a copy of the parent context // that will cause API calls to invoke f instead of their normal operation. // // This is intended for advanced users only.
[ "WithAPICallFunc", "returns", "a", "copy", "of", "the", "parent", "context", "that", "will", "cause", "API", "calls", "to", "invoke", "f", "instead", "of", "their", "normal", "operation", ".", "This", "is", "intended", "for", "advanced", "users", "only", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/appengine.go#L125-L127
test
golang/appengine
appengine.go
APICall
func APICall(ctx context.Context, service, method string, in, out proto.Message) error { return internal.Call(ctx, service, method, in, out) }
go
func APICall(ctx context.Context, service, method string, in, out proto.Message) error { return internal.Call(ctx, service, method, in, out) }
[ "func", "APICall", "(", "ctx", "context", ".", "Context", ",", "service", ",", "method", "string", ",", "in", ",", "out", "proto", ".", "Message", ")", "error", "{", "return", "internal", ".", "Call", "(", "ctx", ",", "service", ",", "method", ",", "in", ",", "out", ")", "\n", "}" ]
// APICall performs an API call. // // This is not intended for general use; it is exported for use in conjunction // with WithAPICallFunc.
[ "APICall", "performs", "an", "API", "call", ".", "This", "is", "not", "intended", "for", "general", "use", ";", "it", "is", "exported", "for", "use", "in", "conjunction", "with", "WithAPICallFunc", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/appengine.go#L133-L135
test
golang/appengine
identity.go
ModuleHostname
func ModuleHostname(c context.Context, module, version, instance string) (string, error) { req := &modpb.GetHostnameRequest{} if module != "" { req.Module = &module } if version != "" { req.Version = &version } if instance != "" { req.Instance = &instance } res := &modpb.GetHostnameResponse{} if err := internal.Call(c, "modules", "GetHostname", req, res); err != nil { return "", err } return *res.Hostname, nil }
go
func ModuleHostname(c context.Context, module, version, instance string) (string, error) { req := &modpb.GetHostnameRequest{} if module != "" { req.Module = &module } if version != "" { req.Version = &version } if instance != "" { req.Instance = &instance } res := &modpb.GetHostnameResponse{} if err := internal.Call(c, "modules", "GetHostname", req, res); err != nil { return "", err } return *res.Hostname, nil }
[ "func", "ModuleHostname", "(", "c", "context", ".", "Context", ",", "module", ",", "version", ",", "instance", "string", ")", "(", "string", ",", "error", ")", "{", "req", ":=", "&", "modpb", ".", "GetHostnameRequest", "{", "}", "\n", "if", "module", "!=", "\"\"", "{", "req", ".", "Module", "=", "&", "module", "\n", "}", "\n", "if", "version", "!=", "\"\"", "{", "req", ".", "Version", "=", "&", "version", "\n", "}", "\n", "if", "instance", "!=", "\"\"", "{", "req", ".", "Instance", "=", "&", "instance", "\n", "}", "\n", "res", ":=", "&", "modpb", ".", "GetHostnameResponse", "{", "}", "\n", "if", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"modules\"", ",", "\"GetHostname\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "return", "*", "res", ".", "Hostname", ",", "nil", "\n", "}" ]
// ModuleHostname returns a hostname of a module instance. // If module is the empty string, it refers to the module of the current instance. // If version is empty, it refers to the version of the current instance if valid, // or the default version of the module of the current instance. // If instance is empty, ModuleHostname returns the load-balancing hostname.
[ "ModuleHostname", "returns", "a", "hostname", "of", "a", "module", "instance", ".", "If", "module", "is", "the", "empty", "string", "it", "refers", "to", "the", "module", "of", "the", "current", "instance", ".", "If", "version", "is", "empty", "it", "refers", "to", "the", "version", "of", "the", "current", "instance", "if", "valid", "or", "the", "default", "version", "of", "the", "module", "of", "the", "current", "instance", ".", "If", "instance", "is", "empty", "ModuleHostname", "returns", "the", "load", "-", "balancing", "hostname", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/identity.go#L39-L55
test
golang/appengine
identity.go
AccessToken
func AccessToken(c context.Context, scopes ...string) (token string, expiry time.Time, err error) { req := &pb.GetAccessTokenRequest{Scope: scopes} res := &pb.GetAccessTokenResponse{} err = internal.Call(c, "app_identity_service", "GetAccessToken", req, res) if err != nil { return "", time.Time{}, err } return res.GetAccessToken(), time.Unix(res.GetExpirationTime(), 0), nil }
go
func AccessToken(c context.Context, scopes ...string) (token string, expiry time.Time, err error) { req := &pb.GetAccessTokenRequest{Scope: scopes} res := &pb.GetAccessTokenResponse{} err = internal.Call(c, "app_identity_service", "GetAccessToken", req, res) if err != nil { return "", time.Time{}, err } return res.GetAccessToken(), time.Unix(res.GetExpirationTime(), 0), nil }
[ "func", "AccessToken", "(", "c", "context", ".", "Context", ",", "scopes", "...", "string", ")", "(", "token", "string", ",", "expiry", "time", ".", "Time", ",", "err", "error", ")", "{", "req", ":=", "&", "pb", ".", "GetAccessTokenRequest", "{", "Scope", ":", "scopes", "}", "\n", "res", ":=", "&", "pb", ".", "GetAccessTokenResponse", "{", "}", "\n", "err", "=", "internal", ".", "Call", "(", "c", ",", "\"app_identity_service\"", ",", "\"GetAccessToken\"", ",", "req", ",", "res", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "time", ".", "Time", "{", "}", ",", "err", "\n", "}", "\n", "return", "res", ".", "GetAccessToken", "(", ")", ",", "time", ".", "Unix", "(", "res", ".", "GetExpirationTime", "(", ")", ",", "0", ")", ",", "nil", "\n", "}" ]
// AccessToken generates an OAuth2 access token for the specified scopes on // behalf of service account of this application. This token will expire after // the returned time.
[ "AccessToken", "generates", "an", "OAuth2", "access", "token", "for", "the", "specified", "scopes", "on", "behalf", "of", "service", "account", "of", "this", "application", ".", "This", "token", "will", "expire", "after", "the", "returned", "time", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/identity.go#L80-L89
test
golang/appengine
identity.go
PublicCertificates
func PublicCertificates(c context.Context) ([]Certificate, error) { req := &pb.GetPublicCertificateForAppRequest{} res := &pb.GetPublicCertificateForAppResponse{} if err := internal.Call(c, "app_identity_service", "GetPublicCertificatesForApp", req, res); err != nil { return nil, err } var cs []Certificate for _, pc := range res.PublicCertificateList { cs = append(cs, Certificate{ KeyName: pc.GetKeyName(), Data: []byte(pc.GetX509CertificatePem()), }) } return cs, nil }
go
func PublicCertificates(c context.Context) ([]Certificate, error) { req := &pb.GetPublicCertificateForAppRequest{} res := &pb.GetPublicCertificateForAppResponse{} if err := internal.Call(c, "app_identity_service", "GetPublicCertificatesForApp", req, res); err != nil { return nil, err } var cs []Certificate for _, pc := range res.PublicCertificateList { cs = append(cs, Certificate{ KeyName: pc.GetKeyName(), Data: []byte(pc.GetX509CertificatePem()), }) } return cs, nil }
[ "func", "PublicCertificates", "(", "c", "context", ".", "Context", ")", "(", "[", "]", "Certificate", ",", "error", ")", "{", "req", ":=", "&", "pb", ".", "GetPublicCertificateForAppRequest", "{", "}", "\n", "res", ":=", "&", "pb", ".", "GetPublicCertificateForAppResponse", "{", "}", "\n", "if", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"app_identity_service\"", ",", "\"GetPublicCertificatesForApp\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "var", "cs", "[", "]", "Certificate", "\n", "for", "_", ",", "pc", ":=", "range", "res", ".", "PublicCertificateList", "{", "cs", "=", "append", "(", "cs", ",", "Certificate", "{", "KeyName", ":", "pc", ".", "GetKeyName", "(", ")", ",", "Data", ":", "[", "]", "byte", "(", "pc", ".", "GetX509CertificatePem", "(", ")", ")", ",", "}", ")", "\n", "}", "\n", "return", "cs", ",", "nil", "\n", "}" ]
// PublicCertificates retrieves the public certificates for the app. // They can be used to verify a signature returned by SignBytes.
[ "PublicCertificates", "retrieves", "the", "public", "certificates", "for", "the", "app", ".", "They", "can", "be", "used", "to", "verify", "a", "signature", "returned", "by", "SignBytes", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/identity.go#L99-L113
test
golang/appengine
identity.go
ServiceAccount
func ServiceAccount(c context.Context) (string, error) { req := &pb.GetServiceAccountNameRequest{} res := &pb.GetServiceAccountNameResponse{} err := internal.Call(c, "app_identity_service", "GetServiceAccountName", req, res) if err != nil { return "", err } return res.GetServiceAccountName(), err }
go
func ServiceAccount(c context.Context) (string, error) { req := &pb.GetServiceAccountNameRequest{} res := &pb.GetServiceAccountNameResponse{} err := internal.Call(c, "app_identity_service", "GetServiceAccountName", req, res) if err != nil { return "", err } return res.GetServiceAccountName(), err }
[ "func", "ServiceAccount", "(", "c", "context", ".", "Context", ")", "(", "string", ",", "error", ")", "{", "req", ":=", "&", "pb", ".", "GetServiceAccountNameRequest", "{", "}", "\n", "res", ":=", "&", "pb", ".", "GetServiceAccountNameResponse", "{", "}", "\n", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"app_identity_service\"", ",", "\"GetServiceAccountName\"", ",", "req", ",", "res", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "return", "res", ".", "GetServiceAccountName", "(", ")", ",", "err", "\n", "}" ]
// ServiceAccount returns a string representing the service account name, in // the form of an email address (typically app_id@appspot.gserviceaccount.com).
[ "ServiceAccount", "returns", "a", "string", "representing", "the", "service", "account", "name", "in", "the", "form", "of", "an", "email", "address", "(", "typically", "app_id" ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/identity.go#L117-L126
test
golang/appengine
identity.go
SignBytes
func SignBytes(c context.Context, bytes []byte) (keyName string, signature []byte, err error) { req := &pb.SignForAppRequest{BytesToSign: bytes} res := &pb.SignForAppResponse{} if err := internal.Call(c, "app_identity_service", "SignForApp", req, res); err != nil { return "", nil, err } return res.GetKeyName(), res.GetSignatureBytes(), nil }
go
func SignBytes(c context.Context, bytes []byte) (keyName string, signature []byte, err error) { req := &pb.SignForAppRequest{BytesToSign: bytes} res := &pb.SignForAppResponse{} if err := internal.Call(c, "app_identity_service", "SignForApp", req, res); err != nil { return "", nil, err } return res.GetKeyName(), res.GetSignatureBytes(), nil }
[ "func", "SignBytes", "(", "c", "context", ".", "Context", ",", "bytes", "[", "]", "byte", ")", "(", "keyName", "string", ",", "signature", "[", "]", "byte", ",", "err", "error", ")", "{", "req", ":=", "&", "pb", ".", "SignForAppRequest", "{", "BytesToSign", ":", "bytes", "}", "\n", "res", ":=", "&", "pb", ".", "SignForAppResponse", "{", "}", "\n", "if", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"app_identity_service\"", ",", "\"SignForApp\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "\"\"", ",", "nil", ",", "err", "\n", "}", "\n", "return", "res", ".", "GetKeyName", "(", ")", ",", "res", ".", "GetSignatureBytes", "(", ")", ",", "nil", "\n", "}" ]
// SignBytes signs bytes using a private key unique to your application.
[ "SignBytes", "signs", "bytes", "using", "a", "private", "key", "unique", "to", "your", "application", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/identity.go#L129-L137
test
golang/appengine
blobstore/read.go
fetch
func (r *reader) fetch(off int64) error { req := &blobpb.FetchDataRequest{ BlobKey: proto.String(string(r.blobKey)), StartIndex: proto.Int64(off), EndIndex: proto.Int64(off + readBufferSize - 1), // EndIndex is inclusive. } res := &blobpb.FetchDataResponse{} if err := internal.Call(r.c, "blobstore", "FetchData", req, res); err != nil { return err } if len(res.Data) == 0 { return io.EOF } r.buf, r.r, r.off = res.Data, 0, off return nil }
go
func (r *reader) fetch(off int64) error { req := &blobpb.FetchDataRequest{ BlobKey: proto.String(string(r.blobKey)), StartIndex: proto.Int64(off), EndIndex: proto.Int64(off + readBufferSize - 1), // EndIndex is inclusive. } res := &blobpb.FetchDataResponse{} if err := internal.Call(r.c, "blobstore", "FetchData", req, res); err != nil { return err } if len(res.Data) == 0 { return io.EOF } r.buf, r.r, r.off = res.Data, 0, off return nil }
[ "func", "(", "r", "*", "reader", ")", "fetch", "(", "off", "int64", ")", "error", "{", "req", ":=", "&", "blobpb", ".", "FetchDataRequest", "{", "BlobKey", ":", "proto", ".", "String", "(", "string", "(", "r", ".", "blobKey", ")", ")", ",", "StartIndex", ":", "proto", ".", "Int64", "(", "off", ")", ",", "EndIndex", ":", "proto", ".", "Int64", "(", "off", "+", "readBufferSize", "-", "1", ")", ",", "}", "\n", "res", ":=", "&", "blobpb", ".", "FetchDataResponse", "{", "}", "\n", "if", "err", ":=", "internal", ".", "Call", "(", "r", ".", "c", ",", "\"blobstore\"", ",", "\"FetchData\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "len", "(", "res", ".", "Data", ")", "==", "0", "{", "return", "io", ".", "EOF", "\n", "}", "\n", "r", ".", "buf", ",", "r", ".", "r", ",", "r", ".", "off", "=", "res", ".", "Data", ",", "0", ",", "off", "\n", "return", "nil", "\n", "}" ]
// fetch fetches readBufferSize bytes starting at the given offset. On success, // the data is saved as r.buf.
[ "fetch", "fetches", "readBufferSize", "bytes", "starting", "at", "the", "given", "offset", ".", "On", "success", "the", "data", "is", "saved", "as", "r", ".", "buf", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/blobstore/read.go#L133-L148
test
golang/appengine
blobstore/read.go
seek
func (r *reader) seek(off int64) (int64, error) { delta := off - r.off if delta >= 0 && delta < int64(len(r.buf)) { r.r = int(delta) return off, nil } r.buf, r.r, r.off = nil, 0, off return off, nil }
go
func (r *reader) seek(off int64) (int64, error) { delta := off - r.off if delta >= 0 && delta < int64(len(r.buf)) { r.r = int(delta) return off, nil } r.buf, r.r, r.off = nil, 0, off return off, nil }
[ "func", "(", "r", "*", "reader", ")", "seek", "(", "off", "int64", ")", "(", "int64", ",", "error", ")", "{", "delta", ":=", "off", "-", "r", ".", "off", "\n", "if", "delta", ">=", "0", "&&", "delta", "<", "int64", "(", "len", "(", "r", ".", "buf", ")", ")", "{", "r", ".", "r", "=", "int", "(", "delta", ")", "\n", "return", "off", ",", "nil", "\n", "}", "\n", "r", ".", "buf", ",", "r", ".", "r", ",", "r", ".", "off", "=", "nil", ",", "0", ",", "off", "\n", "return", "off", ",", "nil", "\n", "}" ]
// seek seeks to the given offset with an effective whence equal to SEEK_SET. // It discards the read buffer if the invariant cannot be maintained.
[ "seek", "seeks", "to", "the", "given", "offset", "with", "an", "effective", "whence", "equal", "to", "SEEK_SET", ".", "It", "discards", "the", "read", "buffer", "if", "the", "invariant", "cannot", "be", "maintained", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/blobstore/read.go#L152-L160
test
golang/appengine
datastore/datastore.go
multiKeyToProto
func multiKeyToProto(appID string, key []*Key) []*pb.Reference { ret := make([]*pb.Reference, len(key)) for i, k := range key { ret[i] = keyToProto(appID, k) } return ret }
go
func multiKeyToProto(appID string, key []*Key) []*pb.Reference { ret := make([]*pb.Reference, len(key)) for i, k := range key { ret[i] = keyToProto(appID, k) } return ret }
[ "func", "multiKeyToProto", "(", "appID", "string", ",", "key", "[", "]", "*", "Key", ")", "[", "]", "*", "pb", ".", "Reference", "{", "ret", ":=", "make", "(", "[", "]", "*", "pb", ".", "Reference", ",", "len", "(", "key", ")", ")", "\n", "for", "i", ",", "k", ":=", "range", "key", "{", "ret", "[", "i", "]", "=", "keyToProto", "(", "appID", ",", "k", ")", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// multiKeyToProto is a batch version of keyToProto.
[ "multiKeyToProto", "is", "a", "batch", "version", "of", "keyToProto", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/datastore.go#L105-L111
test
golang/appengine
datastore/datastore.go
referenceValueToKey
func referenceValueToKey(r *pb.PropertyValue_ReferenceValue) (k *Key, err error) { appID := r.GetApp() namespace := r.GetNameSpace() for _, e := range r.Pathelement { k = &Key{ kind: e.GetType(), stringID: e.GetName(), intID: e.GetId(), parent: k, appID: appID, namespace: namespace, } if !k.valid() { return nil, ErrInvalidKey } } return }
go
func referenceValueToKey(r *pb.PropertyValue_ReferenceValue) (k *Key, err error) { appID := r.GetApp() namespace := r.GetNameSpace() for _, e := range r.Pathelement { k = &Key{ kind: e.GetType(), stringID: e.GetName(), intID: e.GetId(), parent: k, appID: appID, namespace: namespace, } if !k.valid() { return nil, ErrInvalidKey } } return }
[ "func", "referenceValueToKey", "(", "r", "*", "pb", ".", "PropertyValue_ReferenceValue", ")", "(", "k", "*", "Key", ",", "err", "error", ")", "{", "appID", ":=", "r", ".", "GetApp", "(", ")", "\n", "namespace", ":=", "r", ".", "GetNameSpace", "(", ")", "\n", "for", "_", ",", "e", ":=", "range", "r", ".", "Pathelement", "{", "k", "=", "&", "Key", "{", "kind", ":", "e", ".", "GetType", "(", ")", ",", "stringID", ":", "e", ".", "GetName", "(", ")", ",", "intID", ":", "e", ".", "GetId", "(", ")", ",", "parent", ":", "k", ",", "appID", ":", "appID", ",", "namespace", ":", "namespace", ",", "}", "\n", "if", "!", "k", ".", "valid", "(", ")", "{", "return", "nil", ",", "ErrInvalidKey", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// It's unfortunate that the two semantically equivalent concepts pb.Reference // and pb.PropertyValue_ReferenceValue aren't the same type. For example, the // two have different protobuf field numbers. // referenceValueToKey is the same as protoToKey except the input is a // PropertyValue_ReferenceValue instead of a Reference.
[ "It", "s", "unfortunate", "that", "the", "two", "semantically", "equivalent", "concepts", "pb", ".", "Reference", "and", "pb", ".", "PropertyValue_ReferenceValue", "aren", "t", "the", "same", "type", ".", "For", "example", "the", "two", "have", "different", "protobuf", "field", "numbers", ".", "referenceValueToKey", "is", "the", "same", "as", "protoToKey", "except", "the", "input", "is", "a", "PropertyValue_ReferenceValue", "instead", "of", "a", "Reference", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/datastore.go#L141-L158
test
golang/appengine
datastore/datastore.go
keyToReferenceValue
func keyToReferenceValue(defaultAppID string, k *Key) *pb.PropertyValue_ReferenceValue { ref := keyToProto(defaultAppID, k) pe := make([]*pb.PropertyValue_ReferenceValue_PathElement, len(ref.Path.Element)) for i, e := range ref.Path.Element { pe[i] = &pb.PropertyValue_ReferenceValue_PathElement{ Type: e.Type, Id: e.Id, Name: e.Name, } } return &pb.PropertyValue_ReferenceValue{ App: ref.App, NameSpace: ref.NameSpace, Pathelement: pe, } }
go
func keyToReferenceValue(defaultAppID string, k *Key) *pb.PropertyValue_ReferenceValue { ref := keyToProto(defaultAppID, k) pe := make([]*pb.PropertyValue_ReferenceValue_PathElement, len(ref.Path.Element)) for i, e := range ref.Path.Element { pe[i] = &pb.PropertyValue_ReferenceValue_PathElement{ Type: e.Type, Id: e.Id, Name: e.Name, } } return &pb.PropertyValue_ReferenceValue{ App: ref.App, NameSpace: ref.NameSpace, Pathelement: pe, } }
[ "func", "keyToReferenceValue", "(", "defaultAppID", "string", ",", "k", "*", "Key", ")", "*", "pb", ".", "PropertyValue_ReferenceValue", "{", "ref", ":=", "keyToProto", "(", "defaultAppID", ",", "k", ")", "\n", "pe", ":=", "make", "(", "[", "]", "*", "pb", ".", "PropertyValue_ReferenceValue_PathElement", ",", "len", "(", "ref", ".", "Path", ".", "Element", ")", ")", "\n", "for", "i", ",", "e", ":=", "range", "ref", ".", "Path", ".", "Element", "{", "pe", "[", "i", "]", "=", "&", "pb", ".", "PropertyValue_ReferenceValue_PathElement", "{", "Type", ":", "e", ".", "Type", ",", "Id", ":", "e", ".", "Id", ",", "Name", ":", "e", ".", "Name", ",", "}", "\n", "}", "\n", "return", "&", "pb", ".", "PropertyValue_ReferenceValue", "{", "App", ":", "ref", ".", "App", ",", "NameSpace", ":", "ref", ".", "NameSpace", ",", "Pathelement", ":", "pe", ",", "}", "\n", "}" ]
// keyToReferenceValue is the same as keyToProto except the output is a // PropertyValue_ReferenceValue instead of a Reference.
[ "keyToReferenceValue", "is", "the", "same", "as", "keyToProto", "except", "the", "output", "is", "a", "PropertyValue_ReferenceValue", "instead", "of", "a", "Reference", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/datastore.go#L162-L177
test
golang/appengine
datastore/datastore.go
Put
func Put(c context.Context, key *Key, src interface{}) (*Key, error) { k, err := PutMulti(c, []*Key{key}, []interface{}{src}) if err != nil { if me, ok := err.(appengine.MultiError); ok { return nil, me[0] } return nil, err } return k[0], nil }
go
func Put(c context.Context, key *Key, src interface{}) (*Key, error) { k, err := PutMulti(c, []*Key{key}, []interface{}{src}) if err != nil { if me, ok := err.(appengine.MultiError); ok { return nil, me[0] } return nil, err } return k[0], nil }
[ "func", "Put", "(", "c", "context", ".", "Context", ",", "key", "*", "Key", ",", "src", "interface", "{", "}", ")", "(", "*", "Key", ",", "error", ")", "{", "k", ",", "err", ":=", "PutMulti", "(", "c", ",", "[", "]", "*", "Key", "{", "key", "}", ",", "[", "]", "interface", "{", "}", "{", "src", "}", ")", "\n", "if", "err", "!=", "nil", "{", "if", "me", ",", "ok", ":=", "err", ".", "(", "appengine", ".", "MultiError", ")", ";", "ok", "{", "return", "nil", ",", "me", "[", "0", "]", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "return", "k", "[", "0", "]", ",", "nil", "\n", "}" ]
// Put saves the entity src into the datastore with key k. src must be a struct // pointer or implement PropertyLoadSaver; if a struct pointer then any // unexported fields of that struct will be skipped. If k is an incomplete key, // the returned key will be a unique key generated by the datastore.
[ "Put", "saves", "the", "entity", "src", "into", "the", "datastore", "with", "key", "k", ".", "src", "must", "be", "a", "struct", "pointer", "or", "implement", "PropertyLoadSaver", ";", "if", "a", "struct", "pointer", "then", "any", "unexported", "fields", "of", "that", "struct", "will", "be", "skipped", ".", "If", "k", "is", "an", "incomplete", "key", "the", "returned", "key", "will", "be", "a", "unique", "key", "generated", "by", "the", "datastore", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/datastore.go#L308-L317
test
golang/appengine
datastore/datastore.go
PutMulti
func PutMulti(c context.Context, key []*Key, src interface{}) ([]*Key, error) { v := reflect.ValueOf(src) multiArgType, _ := checkMultiArg(v) if multiArgType == multiArgTypeInvalid { return nil, errors.New("datastore: src has invalid type") } if len(key) != v.Len() { return nil, errors.New("datastore: key and src slices have different length") } if len(key) == 0 { return nil, nil } appID := internal.FullyQualifiedAppID(c) if err := multiValid(key); err != nil { return nil, err } req := &pb.PutRequest{} for i := range key { elem := v.Index(i) if multiArgType == multiArgTypePropertyLoadSaver || multiArgType == multiArgTypeStruct { elem = elem.Addr() } sProto, err := saveEntity(appID, key[i], elem.Interface()) if err != nil { return nil, err } req.Entity = append(req.Entity, sProto) } res := &pb.PutResponse{} if err := internal.Call(c, "datastore_v3", "Put", req, res); err != nil { return nil, err } if len(key) != len(res.Key) { return nil, errors.New("datastore: internal error: server returned the wrong number of keys") } ret := make([]*Key, len(key)) for i := range ret { var err error ret[i], err = protoToKey(res.Key[i]) if err != nil || ret[i].Incomplete() { return nil, errors.New("datastore: internal error: server returned an invalid key") } } return ret, nil }
go
func PutMulti(c context.Context, key []*Key, src interface{}) ([]*Key, error) { v := reflect.ValueOf(src) multiArgType, _ := checkMultiArg(v) if multiArgType == multiArgTypeInvalid { return nil, errors.New("datastore: src has invalid type") } if len(key) != v.Len() { return nil, errors.New("datastore: key and src slices have different length") } if len(key) == 0 { return nil, nil } appID := internal.FullyQualifiedAppID(c) if err := multiValid(key); err != nil { return nil, err } req := &pb.PutRequest{} for i := range key { elem := v.Index(i) if multiArgType == multiArgTypePropertyLoadSaver || multiArgType == multiArgTypeStruct { elem = elem.Addr() } sProto, err := saveEntity(appID, key[i], elem.Interface()) if err != nil { return nil, err } req.Entity = append(req.Entity, sProto) } res := &pb.PutResponse{} if err := internal.Call(c, "datastore_v3", "Put", req, res); err != nil { return nil, err } if len(key) != len(res.Key) { return nil, errors.New("datastore: internal error: server returned the wrong number of keys") } ret := make([]*Key, len(key)) for i := range ret { var err error ret[i], err = protoToKey(res.Key[i]) if err != nil || ret[i].Incomplete() { return nil, errors.New("datastore: internal error: server returned an invalid key") } } return ret, nil }
[ "func", "PutMulti", "(", "c", "context", ".", "Context", ",", "key", "[", "]", "*", "Key", ",", "src", "interface", "{", "}", ")", "(", "[", "]", "*", "Key", ",", "error", ")", "{", "v", ":=", "reflect", ".", "ValueOf", "(", "src", ")", "\n", "multiArgType", ",", "_", ":=", "checkMultiArg", "(", "v", ")", "\n", "if", "multiArgType", "==", "multiArgTypeInvalid", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"datastore: src has invalid type\"", ")", "\n", "}", "\n", "if", "len", "(", "key", ")", "!=", "v", ".", "Len", "(", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"datastore: key and src slices have different length\"", ")", "\n", "}", "\n", "if", "len", "(", "key", ")", "==", "0", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "appID", ":=", "internal", ".", "FullyQualifiedAppID", "(", "c", ")", "\n", "if", "err", ":=", "multiValid", "(", "key", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "req", ":=", "&", "pb", ".", "PutRequest", "{", "}", "\n", "for", "i", ":=", "range", "key", "{", "elem", ":=", "v", ".", "Index", "(", "i", ")", "\n", "if", "multiArgType", "==", "multiArgTypePropertyLoadSaver", "||", "multiArgType", "==", "multiArgTypeStruct", "{", "elem", "=", "elem", ".", "Addr", "(", ")", "\n", "}", "\n", "sProto", ",", "err", ":=", "saveEntity", "(", "appID", ",", "key", "[", "i", "]", ",", "elem", ".", "Interface", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "req", ".", "Entity", "=", "append", "(", "req", ".", "Entity", ",", "sProto", ")", "\n", "}", "\n", "res", ":=", "&", "pb", ".", "PutResponse", "{", "}", "\n", "if", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"datastore_v3\"", ",", "\"Put\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "key", ")", "!=", "len", "(", "res", ".", "Key", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"datastore: internal error: server returned the wrong number of keys\"", ")", "\n", "}", "\n", "ret", ":=", "make", "(", "[", "]", "*", "Key", ",", "len", "(", "key", ")", ")", "\n", "for", "i", ":=", "range", "ret", "{", "var", "err", "error", "\n", "ret", "[", "i", "]", ",", "err", "=", "protoToKey", "(", "res", ".", "Key", "[", "i", "]", ")", "\n", "if", "err", "!=", "nil", "||", "ret", "[", "i", "]", ".", "Incomplete", "(", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"datastore: internal error: server returned an invalid key\"", ")", "\n", "}", "\n", "}", "\n", "return", "ret", ",", "nil", "\n", "}" ]
// PutMulti is a batch version of Put. // // src must satisfy the same conditions as the dst argument to GetMulti.
[ "PutMulti", "is", "a", "batch", "version", "of", "Put", ".", "src", "must", "satisfy", "the", "same", "conditions", "as", "the", "dst", "argument", "to", "GetMulti", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/datastore.go#L322-L366
test
golang/appengine
datastore/datastore.go
Delete
func Delete(c context.Context, key *Key) error { err := DeleteMulti(c, []*Key{key}) if me, ok := err.(appengine.MultiError); ok { return me[0] } return err }
go
func Delete(c context.Context, key *Key) error { err := DeleteMulti(c, []*Key{key}) if me, ok := err.(appengine.MultiError); ok { return me[0] } return err }
[ "func", "Delete", "(", "c", "context", ".", "Context", ",", "key", "*", "Key", ")", "error", "{", "err", ":=", "DeleteMulti", "(", "c", ",", "[", "]", "*", "Key", "{", "key", "}", ")", "\n", "if", "me", ",", "ok", ":=", "err", ".", "(", "appengine", ".", "MultiError", ")", ";", "ok", "{", "return", "me", "[", "0", "]", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Delete deletes the entity for the given key.
[ "Delete", "deletes", "the", "entity", "for", "the", "given", "key", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/datastore.go#L369-L375
test
golang/appengine
datastore/datastore.go
DeleteMulti
func DeleteMulti(c context.Context, key []*Key) error { if len(key) == 0 { return nil } if err := multiValid(key); err != nil { return err } req := &pb.DeleteRequest{ Key: multiKeyToProto(internal.FullyQualifiedAppID(c), key), } res := &pb.DeleteResponse{} return internal.Call(c, "datastore_v3", "Delete", req, res) }
go
func DeleteMulti(c context.Context, key []*Key) error { if len(key) == 0 { return nil } if err := multiValid(key); err != nil { return err } req := &pb.DeleteRequest{ Key: multiKeyToProto(internal.FullyQualifiedAppID(c), key), } res := &pb.DeleteResponse{} return internal.Call(c, "datastore_v3", "Delete", req, res) }
[ "func", "DeleteMulti", "(", "c", "context", ".", "Context", ",", "key", "[", "]", "*", "Key", ")", "error", "{", "if", "len", "(", "key", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "if", "err", ":=", "multiValid", "(", "key", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "req", ":=", "&", "pb", ".", "DeleteRequest", "{", "Key", ":", "multiKeyToProto", "(", "internal", ".", "FullyQualifiedAppID", "(", "c", ")", ",", "key", ")", ",", "}", "\n", "res", ":=", "&", "pb", ".", "DeleteResponse", "{", "}", "\n", "return", "internal", ".", "Call", "(", "c", ",", "\"datastore_v3\"", ",", "\"Delete\"", ",", "req", ",", "res", ")", "\n", "}" ]
// DeleteMulti is a batch version of Delete.
[ "DeleteMulti", "is", "a", "batch", "version", "of", "Delete", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/datastore.go#L378-L390
test
golang/appengine
cmd/aedeploy/aedeploy.go
deploy
func deploy() error { vlogf("Running command %v", flag.Args()) cmd := exec.Command(flag.Arg(0), flag.Args()[1:]...) cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr if err := cmd.Run(); err != nil { return fmt.Errorf("unable to run %q: %v", strings.Join(flag.Args(), " "), err) } return nil }
go
func deploy() error { vlogf("Running command %v", flag.Args()) cmd := exec.Command(flag.Arg(0), flag.Args()[1:]...) cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr if err := cmd.Run(); err != nil { return fmt.Errorf("unable to run %q: %v", strings.Join(flag.Args(), " "), err) } return nil }
[ "func", "deploy", "(", ")", "error", "{", "vlogf", "(", "\"Running command %v\"", ",", "flag", ".", "Args", "(", ")", ")", "\n", "cmd", ":=", "exec", ".", "Command", "(", "flag", ".", "Arg", "(", "0", ")", ",", "flag", ".", "Args", "(", ")", "[", "1", ":", "]", "...", ")", "\n", "cmd", ".", "Stdin", ",", "cmd", ".", "Stdout", ",", "cmd", ".", "Stderr", "=", "os", ".", "Stdin", ",", "os", ".", "Stdout", ",", "os", ".", "Stderr", "\n", "if", "err", ":=", "cmd", ".", "Run", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"unable to run %q: %v\"", ",", "strings", ".", "Join", "(", "flag", ".", "Args", "(", ")", ",", "\" \"", ")", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// deploy calls the provided command to deploy the app from the temporary directory.
[ "deploy", "calls", "the", "provided", "command", "to", "deploy", "the", "app", "from", "the", "temporary", "directory", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aedeploy/aedeploy.go#L64-L72
test
golang/appengine
log/log.go
Next
func (qr *Result) Next() (*Record, error) { if qr.err != nil { return nil, qr.err } if len(qr.logs) > 0 { lr := qr.logs[0] qr.logs = qr.logs[1:] return lr, nil } if qr.request.Offset == nil && qr.resultsSeen { return nil, Done } if err := qr.run(); err != nil { // Errors here may be retried, so don't store the error. return nil, err } return qr.Next() }
go
func (qr *Result) Next() (*Record, error) { if qr.err != nil { return nil, qr.err } if len(qr.logs) > 0 { lr := qr.logs[0] qr.logs = qr.logs[1:] return lr, nil } if qr.request.Offset == nil && qr.resultsSeen { return nil, Done } if err := qr.run(); err != nil { // Errors here may be retried, so don't store the error. return nil, err } return qr.Next() }
[ "func", "(", "qr", "*", "Result", ")", "Next", "(", ")", "(", "*", "Record", ",", "error", ")", "{", "if", "qr", ".", "err", "!=", "nil", "{", "return", "nil", ",", "qr", ".", "err", "\n", "}", "\n", "if", "len", "(", "qr", ".", "logs", ")", ">", "0", "{", "lr", ":=", "qr", ".", "logs", "[", "0", "]", "\n", "qr", ".", "logs", "=", "qr", ".", "logs", "[", "1", ":", "]", "\n", "return", "lr", ",", "nil", "\n", "}", "\n", "if", "qr", ".", "request", ".", "Offset", "==", "nil", "&&", "qr", ".", "resultsSeen", "{", "return", "nil", ",", "Done", "\n", "}", "\n", "if", "err", ":=", "qr", ".", "run", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "qr", ".", "Next", "(", ")", "\n", "}" ]
// Next returns the next log record,
[ "Next", "returns", "the", "next", "log", "record" ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/log/log.go#L147-L167
test
golang/appengine
log/log.go
protoToAppLogs
func protoToAppLogs(logLines []*pb.LogLine) []AppLog { appLogs := make([]AppLog, len(logLines)) for i, line := range logLines { appLogs[i] = AppLog{ Time: time.Unix(0, *line.Time*1e3), Level: int(*line.Level), Message: *line.LogMessage, } } return appLogs }
go
func protoToAppLogs(logLines []*pb.LogLine) []AppLog { appLogs := make([]AppLog, len(logLines)) for i, line := range logLines { appLogs[i] = AppLog{ Time: time.Unix(0, *line.Time*1e3), Level: int(*line.Level), Message: *line.LogMessage, } } return appLogs }
[ "func", "protoToAppLogs", "(", "logLines", "[", "]", "*", "pb", ".", "LogLine", ")", "[", "]", "AppLog", "{", "appLogs", ":=", "make", "(", "[", "]", "AppLog", ",", "len", "(", "logLines", ")", ")", "\n", "for", "i", ",", "line", ":=", "range", "logLines", "{", "appLogs", "[", "i", "]", "=", "AppLog", "{", "Time", ":", "time", ".", "Unix", "(", "0", ",", "*", "line", ".", "Time", "*", "1e3", ")", ",", "Level", ":", "int", "(", "*", "line", ".", "Level", ")", ",", "Message", ":", "*", "line", ".", "LogMessage", ",", "}", "\n", "}", "\n", "return", "appLogs", "\n", "}" ]
// protoToAppLogs takes as input an array of pointers to LogLines, the internal // Protocol Buffer representation of a single application-level log, // and converts it to an array of AppLogs, the external representation // of an application-level log.
[ "protoToAppLogs", "takes", "as", "input", "an", "array", "of", "pointers", "to", "LogLines", "the", "internal", "Protocol", "Buffer", "representation", "of", "a", "single", "application", "-", "level", "log", "and", "converts", "it", "to", "an", "array", "of", "AppLogs", "the", "external", "representation", "of", "an", "application", "-", "level", "log", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/log/log.go#L176-L188
test
golang/appengine
log/log.go
protoToRecord
func protoToRecord(rl *pb.RequestLog) *Record { offset, err := proto.Marshal(rl.Offset) if err != nil { offset = nil } return &Record{ AppID: *rl.AppId, ModuleID: rl.GetModuleId(), VersionID: *rl.VersionId, RequestID: rl.RequestId, Offset: offset, IP: *rl.Ip, Nickname: rl.GetNickname(), AppEngineRelease: string(rl.GetAppEngineRelease()), StartTime: time.Unix(0, *rl.StartTime*1e3), EndTime: time.Unix(0, *rl.EndTime*1e3), Latency: time.Duration(*rl.Latency) * time.Microsecond, MCycles: *rl.Mcycles, Method: *rl.Method, Resource: *rl.Resource, HTTPVersion: *rl.HttpVersion, Status: *rl.Status, ResponseSize: *rl.ResponseSize, Referrer: rl.GetReferrer(), UserAgent: rl.GetUserAgent(), URLMapEntry: *rl.UrlMapEntry, Combined: *rl.Combined, Host: rl.GetHost(), Cost: rl.GetCost(), TaskQueueName: rl.GetTaskQueueName(), TaskName: rl.GetTaskName(), WasLoadingRequest: rl.GetWasLoadingRequest(), PendingTime: time.Duration(rl.GetPendingTime()) * time.Microsecond, Finished: rl.GetFinished(), AppLogs: protoToAppLogs(rl.Line), InstanceID: string(rl.GetCloneKey()), } }
go
func protoToRecord(rl *pb.RequestLog) *Record { offset, err := proto.Marshal(rl.Offset) if err != nil { offset = nil } return &Record{ AppID: *rl.AppId, ModuleID: rl.GetModuleId(), VersionID: *rl.VersionId, RequestID: rl.RequestId, Offset: offset, IP: *rl.Ip, Nickname: rl.GetNickname(), AppEngineRelease: string(rl.GetAppEngineRelease()), StartTime: time.Unix(0, *rl.StartTime*1e3), EndTime: time.Unix(0, *rl.EndTime*1e3), Latency: time.Duration(*rl.Latency) * time.Microsecond, MCycles: *rl.Mcycles, Method: *rl.Method, Resource: *rl.Resource, HTTPVersion: *rl.HttpVersion, Status: *rl.Status, ResponseSize: *rl.ResponseSize, Referrer: rl.GetReferrer(), UserAgent: rl.GetUserAgent(), URLMapEntry: *rl.UrlMapEntry, Combined: *rl.Combined, Host: rl.GetHost(), Cost: rl.GetCost(), TaskQueueName: rl.GetTaskQueueName(), TaskName: rl.GetTaskName(), WasLoadingRequest: rl.GetWasLoadingRequest(), PendingTime: time.Duration(rl.GetPendingTime()) * time.Microsecond, Finished: rl.GetFinished(), AppLogs: protoToAppLogs(rl.Line), InstanceID: string(rl.GetCloneKey()), } }
[ "func", "protoToRecord", "(", "rl", "*", "pb", ".", "RequestLog", ")", "*", "Record", "{", "offset", ",", "err", ":=", "proto", ".", "Marshal", "(", "rl", ".", "Offset", ")", "\n", "if", "err", "!=", "nil", "{", "offset", "=", "nil", "\n", "}", "\n", "return", "&", "Record", "{", "AppID", ":", "*", "rl", ".", "AppId", ",", "ModuleID", ":", "rl", ".", "GetModuleId", "(", ")", ",", "VersionID", ":", "*", "rl", ".", "VersionId", ",", "RequestID", ":", "rl", ".", "RequestId", ",", "Offset", ":", "offset", ",", "IP", ":", "*", "rl", ".", "Ip", ",", "Nickname", ":", "rl", ".", "GetNickname", "(", ")", ",", "AppEngineRelease", ":", "string", "(", "rl", ".", "GetAppEngineRelease", "(", ")", ")", ",", "StartTime", ":", "time", ".", "Unix", "(", "0", ",", "*", "rl", ".", "StartTime", "*", "1e3", ")", ",", "EndTime", ":", "time", ".", "Unix", "(", "0", ",", "*", "rl", ".", "EndTime", "*", "1e3", ")", ",", "Latency", ":", "time", ".", "Duration", "(", "*", "rl", ".", "Latency", ")", "*", "time", ".", "Microsecond", ",", "MCycles", ":", "*", "rl", ".", "Mcycles", ",", "Method", ":", "*", "rl", ".", "Method", ",", "Resource", ":", "*", "rl", ".", "Resource", ",", "HTTPVersion", ":", "*", "rl", ".", "HttpVersion", ",", "Status", ":", "*", "rl", ".", "Status", ",", "ResponseSize", ":", "*", "rl", ".", "ResponseSize", ",", "Referrer", ":", "rl", ".", "GetReferrer", "(", ")", ",", "UserAgent", ":", "rl", ".", "GetUserAgent", "(", ")", ",", "URLMapEntry", ":", "*", "rl", ".", "UrlMapEntry", ",", "Combined", ":", "*", "rl", ".", "Combined", ",", "Host", ":", "rl", ".", "GetHost", "(", ")", ",", "Cost", ":", "rl", ".", "GetCost", "(", ")", ",", "TaskQueueName", ":", "rl", ".", "GetTaskQueueName", "(", ")", ",", "TaskName", ":", "rl", ".", "GetTaskName", "(", ")", ",", "WasLoadingRequest", ":", "rl", ".", "GetWasLoadingRequest", "(", ")", ",", "PendingTime", ":", "time", ".", "Duration", "(", "rl", ".", "GetPendingTime", "(", ")", ")", "*", "time", ".", "Microsecond", ",", "Finished", ":", "rl", ".", "GetFinished", "(", ")", ",", "AppLogs", ":", "protoToAppLogs", "(", "rl", ".", "Line", ")", ",", "InstanceID", ":", "string", "(", "rl", ".", "GetCloneKey", "(", ")", ")", ",", "}", "\n", "}" ]
// protoToRecord converts a RequestLog, the internal Protocol Buffer // representation of a single request-level log, to a Record, its // corresponding external representation.
[ "protoToRecord", "converts", "a", "RequestLog", "the", "internal", "Protocol", "Buffer", "representation", "of", "a", "single", "request", "-", "level", "log", "to", "a", "Record", "its", "corresponding", "external", "representation", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/log/log.go#L193-L230
test
golang/appengine
log/log.go
Run
func (params *Query) Run(c context.Context) *Result { req, err := makeRequest(params, internal.FullyQualifiedAppID(c), appengine.VersionID(c)) return &Result{ context: c, request: req, err: err, } }
go
func (params *Query) Run(c context.Context) *Result { req, err := makeRequest(params, internal.FullyQualifiedAppID(c), appengine.VersionID(c)) return &Result{ context: c, request: req, err: err, } }
[ "func", "(", "params", "*", "Query", ")", "Run", "(", "c", "context", ".", "Context", ")", "*", "Result", "{", "req", ",", "err", ":=", "makeRequest", "(", "params", ",", "internal", ".", "FullyQualifiedAppID", "(", "c", ")", ",", "appengine", ".", "VersionID", "(", "c", ")", ")", "\n", "return", "&", "Result", "{", "context", ":", "c", ",", "request", ":", "req", ",", "err", ":", "err", ",", "}", "\n", "}" ]
// Run starts a query for log records, which contain request and application // level log information.
[ "Run", "starts", "a", "query", "for", "log", "records", "which", "contain", "request", "and", "application", "level", "log", "information", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/log/log.go#L234-L241
test
golang/appengine
log/log.go
run
func (r *Result) run() error { res := &pb.LogReadResponse{} if err := internal.Call(r.context, "logservice", "Read", r.request, res); err != nil { return err } r.logs = make([]*Record, len(res.Log)) r.request.Offset = res.Offset r.resultsSeen = true for i, log := range res.Log { r.logs[i] = protoToRecord(log) } return nil }
go
func (r *Result) run() error { res := &pb.LogReadResponse{} if err := internal.Call(r.context, "logservice", "Read", r.request, res); err != nil { return err } r.logs = make([]*Record, len(res.Log)) r.request.Offset = res.Offset r.resultsSeen = true for i, log := range res.Log { r.logs[i] = protoToRecord(log) } return nil }
[ "func", "(", "r", "*", "Result", ")", "run", "(", ")", "error", "{", "res", ":=", "&", "pb", ".", "LogReadResponse", "{", "}", "\n", "if", "err", ":=", "internal", ".", "Call", "(", "r", ".", "context", ",", "\"logservice\"", ",", "\"Read\"", ",", "r", ".", "request", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "r", ".", "logs", "=", "make", "(", "[", "]", "*", "Record", ",", "len", "(", "res", ".", "Log", ")", ")", "\n", "r", ".", "request", ".", "Offset", "=", "res", ".", "Offset", "\n", "r", ".", "resultsSeen", "=", "true", "\n", "for", "i", ",", "log", ":=", "range", "res", ".", "Log", "{", "r", ".", "logs", "[", "i", "]", "=", "protoToRecord", "(", "log", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// run takes the query Result produced by a call to Run and updates it with // more Records. The updated Result contains a new set of logs as well as an // offset to where more logs can be found. We also convert the items in the // response from their internal representations to external versions of the // same structs.
[ "run", "takes", "the", "query", "Result", "produced", "by", "a", "call", "to", "Run", "and", "updates", "it", "with", "more", "Records", ".", "The", "updated", "Result", "contains", "a", "new", "set", "of", "logs", "as", "well", "as", "an", "offset", "to", "where", "more", "logs", "can", "be", "found", ".", "We", "also", "convert", "the", "items", "in", "the", "response", "from", "their", "internal", "representations", "to", "external", "versions", "of", "the", "same", "structs", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/log/log.go#L304-L319
test
golang/appengine
user/user_vm.go
Current
func Current(c context.Context) *User { h := internal.IncomingHeaders(c) u := &User{ Email: h.Get("X-AppEngine-User-Email"), AuthDomain: h.Get("X-AppEngine-Auth-Domain"), ID: h.Get("X-AppEngine-User-Id"), Admin: h.Get("X-AppEngine-User-Is-Admin") == "1", FederatedIdentity: h.Get("X-AppEngine-Federated-Identity"), FederatedProvider: h.Get("X-AppEngine-Federated-Provider"), } if u.Email == "" && u.FederatedIdentity == "" { return nil } return u }
go
func Current(c context.Context) *User { h := internal.IncomingHeaders(c) u := &User{ Email: h.Get("X-AppEngine-User-Email"), AuthDomain: h.Get("X-AppEngine-Auth-Domain"), ID: h.Get("X-AppEngine-User-Id"), Admin: h.Get("X-AppEngine-User-Is-Admin") == "1", FederatedIdentity: h.Get("X-AppEngine-Federated-Identity"), FederatedProvider: h.Get("X-AppEngine-Federated-Provider"), } if u.Email == "" && u.FederatedIdentity == "" { return nil } return u }
[ "func", "Current", "(", "c", "context", ".", "Context", ")", "*", "User", "{", "h", ":=", "internal", ".", "IncomingHeaders", "(", "c", ")", "\n", "u", ":=", "&", "User", "{", "Email", ":", "h", ".", "Get", "(", "\"X-AppEngine-User-Email\"", ")", ",", "AuthDomain", ":", "h", ".", "Get", "(", "\"X-AppEngine-Auth-Domain\"", ")", ",", "ID", ":", "h", ".", "Get", "(", "\"X-AppEngine-User-Id\"", ")", ",", "Admin", ":", "h", ".", "Get", "(", "\"X-AppEngine-User-Is-Admin\"", ")", "==", "\"1\"", ",", "FederatedIdentity", ":", "h", ".", "Get", "(", "\"X-AppEngine-Federated-Identity\"", ")", ",", "FederatedProvider", ":", "h", ".", "Get", "(", "\"X-AppEngine-Federated-Provider\"", ")", ",", "}", "\n", "if", "u", ".", "Email", "==", "\"\"", "&&", "u", ".", "FederatedIdentity", "==", "\"\"", "{", "return", "nil", "\n", "}", "\n", "return", "u", "\n", "}" ]
// Current returns the currently logged-in user, // or nil if the user is not signed in.
[ "Current", "returns", "the", "currently", "logged", "-", "in", "user", "or", "nil", "if", "the", "user", "is", "not", "signed", "in", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/user/user_vm.go#L17-L31
test
golang/appengine
user/user_vm.go
IsAdmin
func IsAdmin(c context.Context) bool { h := internal.IncomingHeaders(c) return h.Get("X-AppEngine-User-Is-Admin") == "1" }
go
func IsAdmin(c context.Context) bool { h := internal.IncomingHeaders(c) return h.Get("X-AppEngine-User-Is-Admin") == "1" }
[ "func", "IsAdmin", "(", "c", "context", ".", "Context", ")", "bool", "{", "h", ":=", "internal", ".", "IncomingHeaders", "(", "c", ")", "\n", "return", "h", ".", "Get", "(", "\"X-AppEngine-User-Is-Admin\"", ")", "==", "\"1\"", "\n", "}" ]
// IsAdmin returns true if the current user is signed in and // is currently registered as an administrator of the application.
[ "IsAdmin", "returns", "true", "if", "the", "current", "user", "is", "signed", "in", "and", "is", "currently", "registered", "as", "an", "administrator", "of", "the", "application", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/user/user_vm.go#L35-L38
test
golang/appengine
blobstore/blobstore.go
isErrFieldMismatch
func isErrFieldMismatch(err error) bool { _, ok := err.(*datastore.ErrFieldMismatch) return ok }
go
func isErrFieldMismatch(err error) bool { _, ok := err.(*datastore.ErrFieldMismatch) return ok }
[ "func", "isErrFieldMismatch", "(", "err", "error", ")", "bool", "{", "_", ",", "ok", ":=", "err", ".", "(", "*", "datastore", ".", "ErrFieldMismatch", ")", "\n", "return", "ok", "\n", "}" ]
// isErrFieldMismatch returns whether err is a datastore.ErrFieldMismatch. // // The blobstore stores blob metadata in the datastore. When loading that // metadata, it may contain fields that we don't care about. datastore.Get will // return datastore.ErrFieldMismatch in that case, so we ignore that specific // error.
[ "isErrFieldMismatch", "returns", "whether", "err", "is", "a", "datastore", ".", "ErrFieldMismatch", ".", "The", "blobstore", "stores", "blob", "metadata", "in", "the", "datastore", ".", "When", "loading", "that", "metadata", "it", "may", "contain", "fields", "that", "we", "don", "t", "care", "about", ".", "datastore", ".", "Get", "will", "return", "datastore", ".", "ErrFieldMismatch", "in", "that", "case", "so", "we", "ignore", "that", "specific", "error", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/blobstore/blobstore.go#L63-L66
test
golang/appengine
blobstore/blobstore.go
Stat
func Stat(c context.Context, blobKey appengine.BlobKey) (*BlobInfo, error) { c, _ = appengine.Namespace(c, "") // Blobstore is always in the empty string namespace dskey := datastore.NewKey(c, blobInfoKind, string(blobKey), 0, nil) bi := &BlobInfo{ BlobKey: blobKey, } if err := datastore.Get(c, dskey, bi); err != nil && !isErrFieldMismatch(err) { return nil, err } return bi, nil }
go
func Stat(c context.Context, blobKey appengine.BlobKey) (*BlobInfo, error) { c, _ = appengine.Namespace(c, "") // Blobstore is always in the empty string namespace dskey := datastore.NewKey(c, blobInfoKind, string(blobKey), 0, nil) bi := &BlobInfo{ BlobKey: blobKey, } if err := datastore.Get(c, dskey, bi); err != nil && !isErrFieldMismatch(err) { return nil, err } return bi, nil }
[ "func", "Stat", "(", "c", "context", ".", "Context", ",", "blobKey", "appengine", ".", "BlobKey", ")", "(", "*", "BlobInfo", ",", "error", ")", "{", "c", ",", "_", "=", "appengine", ".", "Namespace", "(", "c", ",", "\"\"", ")", "\n", "dskey", ":=", "datastore", ".", "NewKey", "(", "c", ",", "blobInfoKind", ",", "string", "(", "blobKey", ")", ",", "0", ",", "nil", ")", "\n", "bi", ":=", "&", "BlobInfo", "{", "BlobKey", ":", "blobKey", ",", "}", "\n", "if", "err", ":=", "datastore", ".", "Get", "(", "c", ",", "dskey", ",", "bi", ")", ";", "err", "!=", "nil", "&&", "!", "isErrFieldMismatch", "(", "err", ")", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "bi", ",", "nil", "\n", "}" ]
// Stat returns the BlobInfo for a provided blobKey. If no blob was found for // that key, Stat returns datastore.ErrNoSuchEntity.
[ "Stat", "returns", "the", "BlobInfo", "for", "a", "provided", "blobKey", ".", "If", "no", "blob", "was", "found", "for", "that", "key", "Stat", "returns", "datastore", ".", "ErrNoSuchEntity", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/blobstore/blobstore.go#L70-L80
test
golang/appengine
blobstore/blobstore.go
Send
func Send(response http.ResponseWriter, blobKey appengine.BlobKey) { hdr := response.Header() hdr.Set("X-AppEngine-BlobKey", string(blobKey)) if hdr.Get("Content-Type") == "" { // This value is known to dev_appserver to mean automatic. // In production this is remapped to the empty value which // means automatic. hdr.Set("Content-Type", "application/vnd.google.appengine.auto") } }
go
func Send(response http.ResponseWriter, blobKey appengine.BlobKey) { hdr := response.Header() hdr.Set("X-AppEngine-BlobKey", string(blobKey)) if hdr.Get("Content-Type") == "" { // This value is known to dev_appserver to mean automatic. // In production this is remapped to the empty value which // means automatic. hdr.Set("Content-Type", "application/vnd.google.appengine.auto") } }
[ "func", "Send", "(", "response", "http", ".", "ResponseWriter", ",", "blobKey", "appengine", ".", "BlobKey", ")", "{", "hdr", ":=", "response", ".", "Header", "(", ")", "\n", "hdr", ".", "Set", "(", "\"X-AppEngine-BlobKey\"", ",", "string", "(", "blobKey", ")", ")", "\n", "if", "hdr", ".", "Get", "(", "\"Content-Type\"", ")", "==", "\"\"", "{", "hdr", ".", "Set", "(", "\"Content-Type\"", ",", "\"application/vnd.google.appengine.auto\"", ")", "\n", "}", "\n", "}" ]
// Send sets the headers on response to instruct App Engine to send a blob as // the response body. This is more efficient than reading and writing it out // manually and isn't subject to normal response size limits.
[ "Send", "sets", "the", "headers", "on", "response", "to", "instruct", "App", "Engine", "to", "send", "a", "blob", "as", "the", "response", "body", ".", "This", "is", "more", "efficient", "than", "reading", "and", "writing", "it", "out", "manually", "and", "isn", "t", "subject", "to", "normal", "response", "size", "limits", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/blobstore/blobstore.go#L85-L95
test
golang/appengine
blobstore/blobstore.go
UploadURL
func UploadURL(c context.Context, successPath string, opts *UploadURLOptions) (*url.URL, error) { req := &blobpb.CreateUploadURLRequest{ SuccessPath: proto.String(successPath), } if opts != nil { if n := opts.MaxUploadBytes; n != 0 { req.MaxUploadSizeBytes = &n } if n := opts.MaxUploadBytesPerBlob; n != 0 { req.MaxUploadSizePerBlobBytes = &n } if s := opts.StorageBucket; s != "" { req.GsBucketName = &s } } res := &blobpb.CreateUploadURLResponse{} if err := internal.Call(c, "blobstore", "CreateUploadURL", req, res); err != nil { return nil, err } return url.Parse(*res.Url) }
go
func UploadURL(c context.Context, successPath string, opts *UploadURLOptions) (*url.URL, error) { req := &blobpb.CreateUploadURLRequest{ SuccessPath: proto.String(successPath), } if opts != nil { if n := opts.MaxUploadBytes; n != 0 { req.MaxUploadSizeBytes = &n } if n := opts.MaxUploadBytesPerBlob; n != 0 { req.MaxUploadSizePerBlobBytes = &n } if s := opts.StorageBucket; s != "" { req.GsBucketName = &s } } res := &blobpb.CreateUploadURLResponse{} if err := internal.Call(c, "blobstore", "CreateUploadURL", req, res); err != nil { return nil, err } return url.Parse(*res.Url) }
[ "func", "UploadURL", "(", "c", "context", ".", "Context", ",", "successPath", "string", ",", "opts", "*", "UploadURLOptions", ")", "(", "*", "url", ".", "URL", ",", "error", ")", "{", "req", ":=", "&", "blobpb", ".", "CreateUploadURLRequest", "{", "SuccessPath", ":", "proto", ".", "String", "(", "successPath", ")", ",", "}", "\n", "if", "opts", "!=", "nil", "{", "if", "n", ":=", "opts", ".", "MaxUploadBytes", ";", "n", "!=", "0", "{", "req", ".", "MaxUploadSizeBytes", "=", "&", "n", "\n", "}", "\n", "if", "n", ":=", "opts", ".", "MaxUploadBytesPerBlob", ";", "n", "!=", "0", "{", "req", ".", "MaxUploadSizePerBlobBytes", "=", "&", "n", "\n", "}", "\n", "if", "s", ":=", "opts", ".", "StorageBucket", ";", "s", "!=", "\"\"", "{", "req", ".", "GsBucketName", "=", "&", "s", "\n", "}", "\n", "}", "\n", "res", ":=", "&", "blobpb", ".", "CreateUploadURLResponse", "{", "}", "\n", "if", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"blobstore\"", ",", "\"CreateUploadURL\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "url", ".", "Parse", "(", "*", "res", ".", "Url", ")", "\n", "}" ]
// UploadURL creates an upload URL for the form that the user will // fill out, passing the application path to load when the POST of the // form is completed. These URLs expire and should not be reused. The // opts parameter may be nil.
[ "UploadURL", "creates", "an", "upload", "URL", "for", "the", "form", "that", "the", "user", "will", "fill", "out", "passing", "the", "application", "path", "to", "load", "when", "the", "POST", "of", "the", "form", "is", "completed", ".", "These", "URLs", "expire", "and", "should", "not", "be", "reused", ".", "The", "opts", "parameter", "may", "be", "nil", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/blobstore/blobstore.go#L101-L121
test
golang/appengine
blobstore/blobstore.go
Delete
func Delete(c context.Context, blobKey appengine.BlobKey) error { return DeleteMulti(c, []appengine.BlobKey{blobKey}) }
go
func Delete(c context.Context, blobKey appengine.BlobKey) error { return DeleteMulti(c, []appengine.BlobKey{blobKey}) }
[ "func", "Delete", "(", "c", "context", ".", "Context", ",", "blobKey", "appengine", ".", "BlobKey", ")", "error", "{", "return", "DeleteMulti", "(", "c", ",", "[", "]", "appengine", ".", "BlobKey", "{", "blobKey", "}", ")", "\n", "}" ]
// Delete deletes a blob.
[ "Delete", "deletes", "a", "blob", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/blobstore/blobstore.go#L139-L141
test
golang/appengine
blobstore/blobstore.go
DeleteMulti
func DeleteMulti(c context.Context, blobKey []appengine.BlobKey) error { s := make([]string, len(blobKey)) for i, b := range blobKey { s[i] = string(b) } req := &blobpb.DeleteBlobRequest{ BlobKey: s, } res := &basepb.VoidProto{} if err := internal.Call(c, "blobstore", "DeleteBlob", req, res); err != nil { return err } return nil }
go
func DeleteMulti(c context.Context, blobKey []appengine.BlobKey) error { s := make([]string, len(blobKey)) for i, b := range blobKey { s[i] = string(b) } req := &blobpb.DeleteBlobRequest{ BlobKey: s, } res := &basepb.VoidProto{} if err := internal.Call(c, "blobstore", "DeleteBlob", req, res); err != nil { return err } return nil }
[ "func", "DeleteMulti", "(", "c", "context", ".", "Context", ",", "blobKey", "[", "]", "appengine", ".", "BlobKey", ")", "error", "{", "s", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "blobKey", ")", ")", "\n", "for", "i", ",", "b", ":=", "range", "blobKey", "{", "s", "[", "i", "]", "=", "string", "(", "b", ")", "\n", "}", "\n", "req", ":=", "&", "blobpb", ".", "DeleteBlobRequest", "{", "BlobKey", ":", "s", ",", "}", "\n", "res", ":=", "&", "basepb", ".", "VoidProto", "{", "}", "\n", "if", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"blobstore\"", ",", "\"DeleteBlob\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DeleteMulti deletes multiple blobs.
[ "DeleteMulti", "deletes", "multiple", "blobs", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/blobstore/blobstore.go#L144-L157
test
golang/appengine
blobstore/blobstore.go
NewReader
func NewReader(c context.Context, blobKey appengine.BlobKey) Reader { return openBlob(c, blobKey) }
go
func NewReader(c context.Context, blobKey appengine.BlobKey) Reader { return openBlob(c, blobKey) }
[ "func", "NewReader", "(", "c", "context", ".", "Context", ",", "blobKey", "appengine", ".", "BlobKey", ")", "Reader", "{", "return", "openBlob", "(", "c", ",", "blobKey", ")", "\n", "}" ]
// NewReader returns a reader for a blob. It always succeeds; if the blob does // not exist then an error will be reported upon first read.
[ "NewReader", "returns", "a", "reader", "for", "a", "blob", ".", "It", "always", "succeeds", ";", "if", "the", "blob", "does", "not", "exist", "then", "an", "error", "will", "be", "reported", "upon", "first", "read", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/blobstore/blobstore.go#L291-L293
test
golang/appengine
xmpp/xmpp.go
Handle
func Handle(f func(c context.Context, m *Message)) { http.HandleFunc("/_ah/xmpp/message/chat/", func(_ http.ResponseWriter, r *http.Request) { f(appengine.NewContext(r), &Message{ Sender: r.FormValue("from"), To: []string{r.FormValue("to")}, Body: r.FormValue("body"), }) }) }
go
func Handle(f func(c context.Context, m *Message)) { http.HandleFunc("/_ah/xmpp/message/chat/", func(_ http.ResponseWriter, r *http.Request) { f(appengine.NewContext(r), &Message{ Sender: r.FormValue("from"), To: []string{r.FormValue("to")}, Body: r.FormValue("body"), }) }) }
[ "func", "Handle", "(", "f", "func", "(", "c", "context", ".", "Context", ",", "m", "*", "Message", ")", ")", "{", "http", ".", "HandleFunc", "(", "\"/_ah/xmpp/message/chat/\"", ",", "func", "(", "_", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "f", "(", "appengine", ".", "NewContext", "(", "r", ")", ",", "&", "Message", "{", "Sender", ":", "r", ".", "FormValue", "(", "\"from\"", ")", ",", "To", ":", "[", "]", "string", "{", "r", ".", "FormValue", "(", "\"to\"", ")", "}", ",", "Body", ":", "r", ".", "FormValue", "(", "\"body\"", ")", ",", "}", ")", "\n", "}", ")", "\n", "}" ]
// Handle arranges for f to be called for incoming XMPP messages. // Only messages of type "chat" or "normal" will be handled.
[ "Handle", "arranges", "for", "f", "to", "be", "called", "for", "incoming", "XMPP", "messages", ".", "Only", "messages", "of", "type", "chat", "or", "normal", "will", "be", "handled", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/xmpp/xmpp.go#L86-L94
test
golang/appengine
xmpp/xmpp.go
Send
func (m *Message) Send(c context.Context) error { req := &pb.XmppMessageRequest{ Jid: m.To, Body: &m.Body, RawXml: &m.RawXML, } if m.Type != "" && m.Type != "chat" { req.Type = &m.Type } if m.Sender != "" { req.FromJid = &m.Sender } res := &pb.XmppMessageResponse{} if err := internal.Call(c, "xmpp", "SendMessage", req, res); err != nil { return err } if len(res.Status) != len(req.Jid) { return fmt.Errorf("xmpp: sent message to %d JIDs, but only got %d statuses back", len(req.Jid), len(res.Status)) } me, any := make(appengine.MultiError, len(req.Jid)), false for i, st := range res.Status { if st != pb.XmppMessageResponse_NO_ERROR { me[i] = errors.New(st.String()) any = true } } if any { return me } return nil }
go
func (m *Message) Send(c context.Context) error { req := &pb.XmppMessageRequest{ Jid: m.To, Body: &m.Body, RawXml: &m.RawXML, } if m.Type != "" && m.Type != "chat" { req.Type = &m.Type } if m.Sender != "" { req.FromJid = &m.Sender } res := &pb.XmppMessageResponse{} if err := internal.Call(c, "xmpp", "SendMessage", req, res); err != nil { return err } if len(res.Status) != len(req.Jid) { return fmt.Errorf("xmpp: sent message to %d JIDs, but only got %d statuses back", len(req.Jid), len(res.Status)) } me, any := make(appengine.MultiError, len(req.Jid)), false for i, st := range res.Status { if st != pb.XmppMessageResponse_NO_ERROR { me[i] = errors.New(st.String()) any = true } } if any { return me } return nil }
[ "func", "(", "m", "*", "Message", ")", "Send", "(", "c", "context", ".", "Context", ")", "error", "{", "req", ":=", "&", "pb", ".", "XmppMessageRequest", "{", "Jid", ":", "m", ".", "To", ",", "Body", ":", "&", "m", ".", "Body", ",", "RawXml", ":", "&", "m", ".", "RawXML", ",", "}", "\n", "if", "m", ".", "Type", "!=", "\"\"", "&&", "m", ".", "Type", "!=", "\"chat\"", "{", "req", ".", "Type", "=", "&", "m", ".", "Type", "\n", "}", "\n", "if", "m", ".", "Sender", "!=", "\"\"", "{", "req", ".", "FromJid", "=", "&", "m", ".", "Sender", "\n", "}", "\n", "res", ":=", "&", "pb", ".", "XmppMessageResponse", "{", "}", "\n", "if", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"xmpp\"", ",", "\"SendMessage\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "len", "(", "res", ".", "Status", ")", "!=", "len", "(", "req", ".", "Jid", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"xmpp: sent message to %d JIDs, but only got %d statuses back\"", ",", "len", "(", "req", ".", "Jid", ")", ",", "len", "(", "res", ".", "Status", ")", ")", "\n", "}", "\n", "me", ",", "any", ":=", "make", "(", "appengine", ".", "MultiError", ",", "len", "(", "req", ".", "Jid", ")", ")", ",", "false", "\n", "for", "i", ",", "st", ":=", "range", "res", ".", "Status", "{", "if", "st", "!=", "pb", ".", "XmppMessageResponse_NO_ERROR", "{", "me", "[", "i", "]", "=", "errors", ".", "New", "(", "st", ".", "String", "(", ")", ")", "\n", "any", "=", "true", "\n", "}", "\n", "}", "\n", "if", "any", "{", "return", "me", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Send sends a message. // If any failures occur with specific recipients, the error will be an appengine.MultiError.
[ "Send", "sends", "a", "message", ".", "If", "any", "failures", "occur", "with", "specific", "recipients", "the", "error", "will", "be", "an", "appengine", ".", "MultiError", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/xmpp/xmpp.go#L98-L129
test
golang/appengine
xmpp/xmpp.go
Invite
func Invite(c context.Context, to, from string) error { req := &pb.XmppInviteRequest{ Jid: &to, } if from != "" { req.FromJid = &from } res := &pb.XmppInviteResponse{} return internal.Call(c, "xmpp", "SendInvite", req, res) }
go
func Invite(c context.Context, to, from string) error { req := &pb.XmppInviteRequest{ Jid: &to, } if from != "" { req.FromJid = &from } res := &pb.XmppInviteResponse{} return internal.Call(c, "xmpp", "SendInvite", req, res) }
[ "func", "Invite", "(", "c", "context", ".", "Context", ",", "to", ",", "from", "string", ")", "error", "{", "req", ":=", "&", "pb", ".", "XmppInviteRequest", "{", "Jid", ":", "&", "to", ",", "}", "\n", "if", "from", "!=", "\"\"", "{", "req", ".", "FromJid", "=", "&", "from", "\n", "}", "\n", "res", ":=", "&", "pb", ".", "XmppInviteResponse", "{", "}", "\n", "return", "internal", ".", "Call", "(", "c", ",", "\"xmpp\"", ",", "\"SendInvite\"", ",", "req", ",", "res", ")", "\n", "}" ]
// Invite sends an invitation. If the from address is an empty string // the default (yourapp@appspot.com/bot) will be used.
[ "Invite", "sends", "an", "invitation", ".", "If", "the", "from", "address", "is", "an", "empty", "string", "the", "default", "(", "yourapp" ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/xmpp/xmpp.go#L133-L142
test
golang/appengine
xmpp/xmpp.go
Send
func (p *Presence) Send(c context.Context) error { req := &pb.XmppSendPresenceRequest{ Jid: &p.To, } if p.State != "" { req.Show = &p.State } if p.Type != "" { req.Type = &p.Type } if p.Sender != "" { req.FromJid = &p.Sender } if p.Status != "" { req.Status = &p.Status } res := &pb.XmppSendPresenceResponse{} return internal.Call(c, "xmpp", "SendPresence", req, res) }
go
func (p *Presence) Send(c context.Context) error { req := &pb.XmppSendPresenceRequest{ Jid: &p.To, } if p.State != "" { req.Show = &p.State } if p.Type != "" { req.Type = &p.Type } if p.Sender != "" { req.FromJid = &p.Sender } if p.Status != "" { req.Status = &p.Status } res := &pb.XmppSendPresenceResponse{} return internal.Call(c, "xmpp", "SendPresence", req, res) }
[ "func", "(", "p", "*", "Presence", ")", "Send", "(", "c", "context", ".", "Context", ")", "error", "{", "req", ":=", "&", "pb", ".", "XmppSendPresenceRequest", "{", "Jid", ":", "&", "p", ".", "To", ",", "}", "\n", "if", "p", ".", "State", "!=", "\"\"", "{", "req", ".", "Show", "=", "&", "p", ".", "State", "\n", "}", "\n", "if", "p", ".", "Type", "!=", "\"\"", "{", "req", ".", "Type", "=", "&", "p", ".", "Type", "\n", "}", "\n", "if", "p", ".", "Sender", "!=", "\"\"", "{", "req", ".", "FromJid", "=", "&", "p", ".", "Sender", "\n", "}", "\n", "if", "p", ".", "Status", "!=", "\"\"", "{", "req", ".", "Status", "=", "&", "p", ".", "Status", "\n", "}", "\n", "res", ":=", "&", "pb", ".", "XmppSendPresenceResponse", "{", "}", "\n", "return", "internal", ".", "Call", "(", "c", ",", "\"xmpp\"", ",", "\"SendPresence\"", ",", "req", ",", "res", ")", "\n", "}" ]
// Send sends a presence update.
[ "Send", "sends", "a", "presence", "update", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/xmpp/xmpp.go#L145-L163
test
golang/appengine
xmpp/xmpp.go
GetPresence
func GetPresence(c context.Context, to string, from string) (string, error) { req := &pb.PresenceRequest{ Jid: &to, } if from != "" { req.FromJid = &from } res := &pb.PresenceResponse{} if err := internal.Call(c, "xmpp", "GetPresence", req, res); err != nil { return "", err } if !*res.IsAvailable || res.Presence == nil { return "", ErrPresenceUnavailable } presence, ok := presenceMap[*res.Presence] if ok { return presence, nil } return "", fmt.Errorf("xmpp: unknown presence %v", *res.Presence) }
go
func GetPresence(c context.Context, to string, from string) (string, error) { req := &pb.PresenceRequest{ Jid: &to, } if from != "" { req.FromJid = &from } res := &pb.PresenceResponse{} if err := internal.Call(c, "xmpp", "GetPresence", req, res); err != nil { return "", err } if !*res.IsAvailable || res.Presence == nil { return "", ErrPresenceUnavailable } presence, ok := presenceMap[*res.Presence] if ok { return presence, nil } return "", fmt.Errorf("xmpp: unknown presence %v", *res.Presence) }
[ "func", "GetPresence", "(", "c", "context", ".", "Context", ",", "to", "string", ",", "from", "string", ")", "(", "string", ",", "error", ")", "{", "req", ":=", "&", "pb", ".", "PresenceRequest", "{", "Jid", ":", "&", "to", ",", "}", "\n", "if", "from", "!=", "\"\"", "{", "req", ".", "FromJid", "=", "&", "from", "\n", "}", "\n", "res", ":=", "&", "pb", ".", "PresenceResponse", "{", "}", "\n", "if", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"xmpp\"", ",", "\"GetPresence\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "if", "!", "*", "res", ".", "IsAvailable", "||", "res", ".", "Presence", "==", "nil", "{", "return", "\"\"", ",", "ErrPresenceUnavailable", "\n", "}", "\n", "presence", ",", "ok", ":=", "presenceMap", "[", "*", "res", ".", "Presence", "]", "\n", "if", "ok", "{", "return", "presence", ",", "nil", "\n", "}", "\n", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"xmpp: unknown presence %v\"", ",", "*", "res", ".", "Presence", ")", "\n", "}" ]
// GetPresence retrieves a user's presence. // If the from address is an empty string the default // (yourapp@appspot.com/bot) will be used. // Possible return values are "", "away", "dnd", "chat", "xa". // ErrPresenceUnavailable is returned if the presence is unavailable.
[ "GetPresence", "retrieves", "a", "user", "s", "presence", ".", "If", "the", "from", "address", "is", "an", "empty", "string", "the", "default", "(", "yourapp" ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/xmpp/xmpp.go#L178-L197
test
golang/appengine
xmpp/xmpp.go
GetPresenceMulti
func GetPresenceMulti(c context.Context, to []string, from string) ([]string, error) { req := &pb.BulkPresenceRequest{ Jid: to, } if from != "" { req.FromJid = &from } res := &pb.BulkPresenceResponse{} if err := internal.Call(c, "xmpp", "BulkGetPresence", req, res); err != nil { return nil, err } presences := make([]string, 0, len(res.PresenceResponse)) errs := appengine.MultiError{} addResult := func(presence string, err error) { presences = append(presences, presence) errs = append(errs, err) } anyErr := false for _, subres := range res.PresenceResponse { if !subres.GetValid() { anyErr = true addResult("", ErrInvalidJID) continue } if !*subres.IsAvailable || subres.Presence == nil { anyErr = true addResult("", ErrPresenceUnavailable) continue } presence, ok := presenceMap[*subres.Presence] if ok { addResult(presence, nil) } else { anyErr = true addResult("", fmt.Errorf("xmpp: unknown presence %q", *subres.Presence)) } } if anyErr { return presences, errs } return presences, nil }
go
func GetPresenceMulti(c context.Context, to []string, from string) ([]string, error) { req := &pb.BulkPresenceRequest{ Jid: to, } if from != "" { req.FromJid = &from } res := &pb.BulkPresenceResponse{} if err := internal.Call(c, "xmpp", "BulkGetPresence", req, res); err != nil { return nil, err } presences := make([]string, 0, len(res.PresenceResponse)) errs := appengine.MultiError{} addResult := func(presence string, err error) { presences = append(presences, presence) errs = append(errs, err) } anyErr := false for _, subres := range res.PresenceResponse { if !subres.GetValid() { anyErr = true addResult("", ErrInvalidJID) continue } if !*subres.IsAvailable || subres.Presence == nil { anyErr = true addResult("", ErrPresenceUnavailable) continue } presence, ok := presenceMap[*subres.Presence] if ok { addResult(presence, nil) } else { anyErr = true addResult("", fmt.Errorf("xmpp: unknown presence %q", *subres.Presence)) } } if anyErr { return presences, errs } return presences, nil }
[ "func", "GetPresenceMulti", "(", "c", "context", ".", "Context", ",", "to", "[", "]", "string", ",", "from", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "req", ":=", "&", "pb", ".", "BulkPresenceRequest", "{", "Jid", ":", "to", ",", "}", "\n", "if", "from", "!=", "\"\"", "{", "req", ".", "FromJid", "=", "&", "from", "\n", "}", "\n", "res", ":=", "&", "pb", ".", "BulkPresenceResponse", "{", "}", "\n", "if", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"xmpp\"", ",", "\"BulkGetPresence\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "presences", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "res", ".", "PresenceResponse", ")", ")", "\n", "errs", ":=", "appengine", ".", "MultiError", "{", "}", "\n", "addResult", ":=", "func", "(", "presence", "string", ",", "err", "error", ")", "{", "presences", "=", "append", "(", "presences", ",", "presence", ")", "\n", "errs", "=", "append", "(", "errs", ",", "err", ")", "\n", "}", "\n", "anyErr", ":=", "false", "\n", "for", "_", ",", "subres", ":=", "range", "res", ".", "PresenceResponse", "{", "if", "!", "subres", ".", "GetValid", "(", ")", "{", "anyErr", "=", "true", "\n", "addResult", "(", "\"\"", ",", "ErrInvalidJID", ")", "\n", "continue", "\n", "}", "\n", "if", "!", "*", "subres", ".", "IsAvailable", "||", "subres", ".", "Presence", "==", "nil", "{", "anyErr", "=", "true", "\n", "addResult", "(", "\"\"", ",", "ErrPresenceUnavailable", ")", "\n", "continue", "\n", "}", "\n", "presence", ",", "ok", ":=", "presenceMap", "[", "*", "subres", ".", "Presence", "]", "\n", "if", "ok", "{", "addResult", "(", "presence", ",", "nil", ")", "\n", "}", "else", "{", "anyErr", "=", "true", "\n", "addResult", "(", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"xmpp: unknown presence %q\"", ",", "*", "subres", ".", "Presence", ")", ")", "\n", "}", "\n", "}", "\n", "if", "anyErr", "{", "return", "presences", ",", "errs", "\n", "}", "\n", "return", "presences", ",", "nil", "\n", "}" ]
// GetPresenceMulti retrieves multiple users' presence. // If the from address is an empty string the default // (yourapp@appspot.com/bot) will be used. // Possible return values are "", "away", "dnd", "chat", "xa". // If any presence is unavailable, an appengine.MultiError is returned
[ "GetPresenceMulti", "retrieves", "multiple", "users", "presence", ".", "If", "the", "from", "address", "is", "an", "empty", "string", "the", "default", "(", "yourapp" ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/xmpp/xmpp.go#L204-L249
test
golang/appengine
search/struct.go
newStructFLS
func newStructFLS(p interface{}) (FieldLoadSaver, error) { v := reflect.ValueOf(p) if v.Kind() != reflect.Ptr || v.IsNil() || v.Elem().Kind() != reflect.Struct { return nil, ErrInvalidDocumentType } codec, err := loadCodec(v.Elem().Type()) if err != nil { return nil, err } return structFLS{v.Elem(), codec}, nil }
go
func newStructFLS(p interface{}) (FieldLoadSaver, error) { v := reflect.ValueOf(p) if v.Kind() != reflect.Ptr || v.IsNil() || v.Elem().Kind() != reflect.Struct { return nil, ErrInvalidDocumentType } codec, err := loadCodec(v.Elem().Type()) if err != nil { return nil, err } return structFLS{v.Elem(), codec}, nil }
[ "func", "newStructFLS", "(", "p", "interface", "{", "}", ")", "(", "FieldLoadSaver", ",", "error", ")", "{", "v", ":=", "reflect", ".", "ValueOf", "(", "p", ")", "\n", "if", "v", ".", "Kind", "(", ")", "!=", "reflect", ".", "Ptr", "||", "v", ".", "IsNil", "(", ")", "||", "v", ".", "Elem", "(", ")", ".", "Kind", "(", ")", "!=", "reflect", ".", "Struct", "{", "return", "nil", ",", "ErrInvalidDocumentType", "\n", "}", "\n", "codec", ",", "err", ":=", "loadCodec", "(", "v", ".", "Elem", "(", ")", ".", "Type", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "structFLS", "{", "v", ".", "Elem", "(", ")", ",", "codec", "}", ",", "nil", "\n", "}" ]
// newStructFLS returns a FieldLoadSaver for the struct pointer p.
[ "newStructFLS", "returns", "a", "FieldLoadSaver", "for", "the", "struct", "pointer", "p", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/search/struct.go#L213-L223
test
golang/appengine
search/struct.go
SaveStruct
func SaveStruct(src interface{}) ([]Field, error) { f, _, err := saveStructWithMeta(src) return f, err }
go
func SaveStruct(src interface{}) ([]Field, error) { f, _, err := saveStructWithMeta(src) return f, err }
[ "func", "SaveStruct", "(", "src", "interface", "{", "}", ")", "(", "[", "]", "Field", ",", "error", ")", "{", "f", ",", "_", ",", "err", ":=", "saveStructWithMeta", "(", "src", ")", "\n", "return", "f", ",", "err", "\n", "}" ]
// SaveStruct returns the fields from src as a slice of Field. // src must be a struct pointer.
[ "SaveStruct", "returns", "the", "fields", "from", "src", "as", "a", "slice", "of", "Field", ".", "src", "must", "be", "a", "struct", "pointer", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/search/struct.go#L248-L251
test
golang/appengine
datastore/metadata.go
Namespaces
func Namespaces(ctx context.Context) ([]string, error) { // TODO(djd): Support range queries. q := NewQuery(namespaceKind).KeysOnly() keys, err := q.GetAll(ctx, nil) if err != nil { return nil, err } // The empty namespace key uses a numeric ID (==1), but luckily // the string ID defaults to "" for numeric IDs anyway. return keyNames(keys), nil }
go
func Namespaces(ctx context.Context) ([]string, error) { // TODO(djd): Support range queries. q := NewQuery(namespaceKind).KeysOnly() keys, err := q.GetAll(ctx, nil) if err != nil { return nil, err } // The empty namespace key uses a numeric ID (==1), but luckily // the string ID defaults to "" for numeric IDs anyway. return keyNames(keys), nil }
[ "func", "Namespaces", "(", "ctx", "context", ".", "Context", ")", "(", "[", "]", "string", ",", "error", ")", "{", "q", ":=", "NewQuery", "(", "namespaceKind", ")", ".", "KeysOnly", "(", ")", "\n", "keys", ",", "err", ":=", "q", ".", "GetAll", "(", "ctx", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "keyNames", "(", "keys", ")", ",", "nil", "\n", "}" ]
// Namespaces returns all the datastore namespaces.
[ "Namespaces", "returns", "all", "the", "datastore", "namespaces", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/metadata.go#L17-L27
test
golang/appengine
datastore/metadata.go
Kinds
func Kinds(ctx context.Context) ([]string, error) { // TODO(djd): Support range queries. q := NewQuery(kindKind).KeysOnly() keys, err := q.GetAll(ctx, nil) if err != nil { return nil, err } return keyNames(keys), nil }
go
func Kinds(ctx context.Context) ([]string, error) { // TODO(djd): Support range queries. q := NewQuery(kindKind).KeysOnly() keys, err := q.GetAll(ctx, nil) if err != nil { return nil, err } return keyNames(keys), nil }
[ "func", "Kinds", "(", "ctx", "context", ".", "Context", ")", "(", "[", "]", "string", ",", "error", ")", "{", "q", ":=", "NewQuery", "(", "kindKind", ")", ".", "KeysOnly", "(", ")", "\n", "keys", ",", "err", ":=", "q", ".", "GetAll", "(", "ctx", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "keyNames", "(", "keys", ")", ",", "nil", "\n", "}" ]
// Kinds returns the names of all the kinds in the current namespace.
[ "Kinds", "returns", "the", "names", "of", "all", "the", "kinds", "in", "the", "current", "namespace", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/metadata.go#L30-L38
test
golang/appengine
datastore/transaction.go
RunInTransaction
func RunInTransaction(c context.Context, f func(tc context.Context) error, opts *TransactionOptions) error { xg := false if opts != nil { xg = opts.XG } readOnly := false if opts != nil { readOnly = opts.ReadOnly } attempts := 3 if opts != nil && opts.Attempts > 0 { attempts = opts.Attempts } var t *pb.Transaction var err error for i := 0; i < attempts; i++ { if t, err = internal.RunTransactionOnce(c, f, xg, readOnly, t); err != internal.ErrConcurrentTransaction { return err } } return ErrConcurrentTransaction }
go
func RunInTransaction(c context.Context, f func(tc context.Context) error, opts *TransactionOptions) error { xg := false if opts != nil { xg = opts.XG } readOnly := false if opts != nil { readOnly = opts.ReadOnly } attempts := 3 if opts != nil && opts.Attempts > 0 { attempts = opts.Attempts } var t *pb.Transaction var err error for i := 0; i < attempts; i++ { if t, err = internal.RunTransactionOnce(c, f, xg, readOnly, t); err != internal.ErrConcurrentTransaction { return err } } return ErrConcurrentTransaction }
[ "func", "RunInTransaction", "(", "c", "context", ".", "Context", ",", "f", "func", "(", "tc", "context", ".", "Context", ")", "error", ",", "opts", "*", "TransactionOptions", ")", "error", "{", "xg", ":=", "false", "\n", "if", "opts", "!=", "nil", "{", "xg", "=", "opts", ".", "XG", "\n", "}", "\n", "readOnly", ":=", "false", "\n", "if", "opts", "!=", "nil", "{", "readOnly", "=", "opts", ".", "ReadOnly", "\n", "}", "\n", "attempts", ":=", "3", "\n", "if", "opts", "!=", "nil", "&&", "opts", ".", "Attempts", ">", "0", "{", "attempts", "=", "opts", ".", "Attempts", "\n", "}", "\n", "var", "t", "*", "pb", ".", "Transaction", "\n", "var", "err", "error", "\n", "for", "i", ":=", "0", ";", "i", "<", "attempts", ";", "i", "++", "{", "if", "t", ",", "err", "=", "internal", ".", "RunTransactionOnce", "(", "c", ",", "f", ",", "xg", ",", "readOnly", ",", "t", ")", ";", "err", "!=", "internal", ".", "ErrConcurrentTransaction", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "ErrConcurrentTransaction", "\n", "}" ]
// RunInTransaction runs f in a transaction. It calls f with a transaction // context tc that f should use for all App Engine operations. // // If f returns nil, RunInTransaction attempts to commit the transaction, // returning nil if it succeeds. If the commit fails due to a conflicting // transaction, RunInTransaction retries f, each time with a new transaction // context. It gives up and returns ErrConcurrentTransaction after three // failed attempts. The number of attempts can be configured by specifying // TransactionOptions.Attempts. // // If f returns non-nil, then any datastore changes will not be applied and // RunInTransaction returns that same error. The function f is not retried. // // Note that when f returns, the transaction is not yet committed. Calling code // must be careful not to assume that any of f's changes have been committed // until RunInTransaction returns nil. // // Since f may be called multiple times, f should usually be idempotent. // datastore.Get is not idempotent when unmarshaling slice fields. // // Nested transactions are not supported; c may not be a transaction context.
[ "RunInTransaction", "runs", "f", "in", "a", "transaction", ".", "It", "calls", "f", "with", "a", "transaction", "context", "tc", "that", "f", "should", "use", "for", "all", "App", "Engine", "operations", ".", "If", "f", "returns", "nil", "RunInTransaction", "attempts", "to", "commit", "the", "transaction", "returning", "nil", "if", "it", "succeeds", ".", "If", "the", "commit", "fails", "due", "to", "a", "conflicting", "transaction", "RunInTransaction", "retries", "f", "each", "time", "with", "a", "new", "transaction", "context", ".", "It", "gives", "up", "and", "returns", "ErrConcurrentTransaction", "after", "three", "failed", "attempts", ".", "The", "number", "of", "attempts", "can", "be", "configured", "by", "specifying", "TransactionOptions", ".", "Attempts", ".", "If", "f", "returns", "non", "-", "nil", "then", "any", "datastore", "changes", "will", "not", "be", "applied", "and", "RunInTransaction", "returns", "that", "same", "error", ".", "The", "function", "f", "is", "not", "retried", ".", "Note", "that", "when", "f", "returns", "the", "transaction", "is", "not", "yet", "committed", ".", "Calling", "code", "must", "be", "careful", "not", "to", "assume", "that", "any", "of", "f", "s", "changes", "have", "been", "committed", "until", "RunInTransaction", "returns", "nil", ".", "Since", "f", "may", "be", "called", "multiple", "times", "f", "should", "usually", "be", "idempotent", ".", "datastore", ".", "Get", "is", "not", "idempotent", "when", "unmarshaling", "slice", "fields", ".", "Nested", "transactions", "are", "not", "supported", ";", "c", "may", "not", "be", "a", "transaction", "context", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/transaction.go#L56-L77
test
golang/appengine
cmd/aefix/fix.go
imports
func imports(f *ast.File, path string) bool { return importSpec(f, path) != nil }
go
func imports(f *ast.File, path string) bool { return importSpec(f, path) != nil }
[ "func", "imports", "(", "f", "*", "ast", ".", "File", ",", "path", "string", ")", "bool", "{", "return", "importSpec", "(", "f", ",", "path", ")", "!=", "nil", "\n", "}" ]
// imports returns true if f imports path.
[ "imports", "returns", "true", "if", "f", "imports", "path", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/fix.go#L286-L288
test
golang/appengine
cmd/aefix/fix.go
importSpec
func importSpec(f *ast.File, path string) *ast.ImportSpec { for _, s := range f.Imports { if importPath(s) == path { return s } } return nil }
go
func importSpec(f *ast.File, path string) *ast.ImportSpec { for _, s := range f.Imports { if importPath(s) == path { return s } } return nil }
[ "func", "importSpec", "(", "f", "*", "ast", ".", "File", ",", "path", "string", ")", "*", "ast", ".", "ImportSpec", "{", "for", "_", ",", "s", ":=", "range", "f", ".", "Imports", "{", "if", "importPath", "(", "s", ")", "==", "path", "{", "return", "s", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// importSpec returns the import spec if f imports path, // or nil otherwise.
[ "importSpec", "returns", "the", "import", "spec", "if", "f", "imports", "path", "or", "nil", "otherwise", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/fix.go#L292-L299
test
golang/appengine
cmd/aefix/fix.go
declImports
func declImports(gen *ast.GenDecl, path string) bool { if gen.Tok != token.IMPORT { return false } for _, spec := range gen.Specs { impspec := spec.(*ast.ImportSpec) if importPath(impspec) == path { return true } } return false }
go
func declImports(gen *ast.GenDecl, path string) bool { if gen.Tok != token.IMPORT { return false } for _, spec := range gen.Specs { impspec := spec.(*ast.ImportSpec) if importPath(impspec) == path { return true } } return false }
[ "func", "declImports", "(", "gen", "*", "ast", ".", "GenDecl", ",", "path", "string", ")", "bool", "{", "if", "gen", ".", "Tok", "!=", "token", ".", "IMPORT", "{", "return", "false", "\n", "}", "\n", "for", "_", ",", "spec", ":=", "range", "gen", ".", "Specs", "{", "impspec", ":=", "spec", ".", "(", "*", "ast", ".", "ImportSpec", ")", "\n", "if", "importPath", "(", "impspec", ")", "==", "path", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// declImports reports whether gen contains an import of path.
[ "declImports", "reports", "whether", "gen", "contains", "an", "import", "of", "path", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/fix.go#L312-L323
test
golang/appengine
cmd/aefix/fix.go
isPkgDot
func isPkgDot(t ast.Expr, pkg, name string) bool { sel, ok := t.(*ast.SelectorExpr) return ok && isTopName(sel.X, pkg) && sel.Sel.String() == name }
go
func isPkgDot(t ast.Expr, pkg, name string) bool { sel, ok := t.(*ast.SelectorExpr) return ok && isTopName(sel.X, pkg) && sel.Sel.String() == name }
[ "func", "isPkgDot", "(", "t", "ast", ".", "Expr", ",", "pkg", ",", "name", "string", ")", "bool", "{", "sel", ",", "ok", ":=", "t", ".", "(", "*", "ast", ".", "SelectorExpr", ")", "\n", "return", "ok", "&&", "isTopName", "(", "sel", ".", "X", ",", "pkg", ")", "&&", "sel", ".", "Sel", ".", "String", "(", ")", "==", "name", "\n", "}" ]
// isPkgDot returns true if t is the expression "pkg.name" // where pkg is an imported identifier.
[ "isPkgDot", "returns", "true", "if", "t", "is", "the", "expression", "pkg", ".", "name", "where", "pkg", "is", "an", "imported", "identifier", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/fix.go#L327-L330
test
golang/appengine
cmd/aefix/fix.go
isTopName
func isTopName(n ast.Expr, name string) bool { id, ok := n.(*ast.Ident) return ok && id.Name == name && id.Obj == nil }
go
func isTopName(n ast.Expr, name string) bool { id, ok := n.(*ast.Ident) return ok && id.Name == name && id.Obj == nil }
[ "func", "isTopName", "(", "n", "ast", ".", "Expr", ",", "name", "string", ")", "bool", "{", "id", ",", "ok", ":=", "n", ".", "(", "*", "ast", ".", "Ident", ")", "\n", "return", "ok", "&&", "id", ".", "Name", "==", "name", "&&", "id", ".", "Obj", "==", "nil", "\n", "}" ]
// isTopName returns true if n is a top-level unresolved identifier with the given name.
[ "isTopName", "returns", "true", "if", "n", "is", "a", "top", "-", "level", "unresolved", "identifier", "with", "the", "given", "name", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/fix.go#L340-L343
test
golang/appengine
cmd/aefix/fix.go
isName
func isName(n ast.Expr, name string) bool { id, ok := n.(*ast.Ident) return ok && id.String() == name }
go
func isName(n ast.Expr, name string) bool { id, ok := n.(*ast.Ident) return ok && id.String() == name }
[ "func", "isName", "(", "n", "ast", ".", "Expr", ",", "name", "string", ")", "bool", "{", "id", ",", "ok", ":=", "n", ".", "(", "*", "ast", ".", "Ident", ")", "\n", "return", "ok", "&&", "id", ".", "String", "(", ")", "==", "name", "\n", "}" ]
// isName returns true if n is an identifier with the given name.
[ "isName", "returns", "true", "if", "n", "is", "an", "identifier", "with", "the", "given", "name", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/fix.go#L346-L349
test
golang/appengine
cmd/aefix/fix.go
isCall
func isCall(t ast.Expr, pkg, name string) bool { call, ok := t.(*ast.CallExpr) return ok && isPkgDot(call.Fun, pkg, name) }
go
func isCall(t ast.Expr, pkg, name string) bool { call, ok := t.(*ast.CallExpr) return ok && isPkgDot(call.Fun, pkg, name) }
[ "func", "isCall", "(", "t", "ast", ".", "Expr", ",", "pkg", ",", "name", "string", ")", "bool", "{", "call", ",", "ok", ":=", "t", ".", "(", "*", "ast", ".", "CallExpr", ")", "\n", "return", "ok", "&&", "isPkgDot", "(", "call", ".", "Fun", ",", "pkg", ",", "name", ")", "\n", "}" ]
// isCall returns true if t is a call to pkg.name.
[ "isCall", "returns", "true", "if", "t", "is", "a", "call", "to", "pkg", ".", "name", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/fix.go#L352-L355
test
golang/appengine
cmd/aefix/fix.go
refersTo
func refersTo(n ast.Node, x *ast.Ident) bool { id, ok := n.(*ast.Ident) // The test of id.Name == x.Name handles top-level unresolved // identifiers, which all have Obj == nil. return ok && id.Obj == x.Obj && id.Name == x.Name }
go
func refersTo(n ast.Node, x *ast.Ident) bool { id, ok := n.(*ast.Ident) // The test of id.Name == x.Name handles top-level unresolved // identifiers, which all have Obj == nil. return ok && id.Obj == x.Obj && id.Name == x.Name }
[ "func", "refersTo", "(", "n", "ast", ".", "Node", ",", "x", "*", "ast", ".", "Ident", ")", "bool", "{", "id", ",", "ok", ":=", "n", ".", "(", "*", "ast", ".", "Ident", ")", "\n", "return", "ok", "&&", "id", ".", "Obj", "==", "x", ".", "Obj", "&&", "id", ".", "Name", "==", "x", ".", "Name", "\n", "}" ]
// refersTo returns true if n is a reference to the same object as x.
[ "refersTo", "returns", "true", "if", "n", "is", "a", "reference", "to", "the", "same", "object", "as", "x", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/fix.go#L364-L369
test
golang/appengine
cmd/aefix/fix.go
isEmptyString
func isEmptyString(n ast.Expr) bool { lit, ok := n.(*ast.BasicLit) return ok && lit.Kind == token.STRING && len(lit.Value) == 2 }
go
func isEmptyString(n ast.Expr) bool { lit, ok := n.(*ast.BasicLit) return ok && lit.Kind == token.STRING && len(lit.Value) == 2 }
[ "func", "isEmptyString", "(", "n", "ast", ".", "Expr", ")", "bool", "{", "lit", ",", "ok", ":=", "n", ".", "(", "*", "ast", ".", "BasicLit", ")", "\n", "return", "ok", "&&", "lit", ".", "Kind", "==", "token", ".", "STRING", "&&", "len", "(", "lit", ".", "Value", ")", "==", "2", "\n", "}" ]
// isEmptyString returns true if n is an empty string literal.
[ "isEmptyString", "returns", "true", "if", "n", "is", "an", "empty", "string", "literal", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/fix.go#L377-L380
test
golang/appengine
cmd/aefix/fix.go
countUses
func countUses(x *ast.Ident, scope []ast.Stmt) int { count := 0 ff := func(n interface{}) { if n, ok := n.(ast.Node); ok && refersTo(n, x) { count++ } } for _, n := range scope { walk(n, ff) } return count }
go
func countUses(x *ast.Ident, scope []ast.Stmt) int { count := 0 ff := func(n interface{}) { if n, ok := n.(ast.Node); ok && refersTo(n, x) { count++ } } for _, n := range scope { walk(n, ff) } return count }
[ "func", "countUses", "(", "x", "*", "ast", ".", "Ident", ",", "scope", "[", "]", "ast", ".", "Stmt", ")", "int", "{", "count", ":=", "0", "\n", "ff", ":=", "func", "(", "n", "interface", "{", "}", ")", "{", "if", "n", ",", "ok", ":=", "n", ".", "(", "ast", ".", "Node", ")", ";", "ok", "&&", "refersTo", "(", "n", ",", "x", ")", "{", "count", "++", "\n", "}", "\n", "}", "\n", "for", "_", ",", "n", ":=", "range", "scope", "{", "walk", "(", "n", ",", "ff", ")", "\n", "}", "\n", "return", "count", "\n", "}" ]
// countUses returns the number of uses of the identifier x in scope.
[ "countUses", "returns", "the", "number", "of", "uses", "of", "the", "identifier", "x", "in", "scope", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/fix.go#L392-L403
test
golang/appengine
cmd/aefix/fix.go
assignsTo
func assignsTo(x *ast.Ident, scope []ast.Stmt) bool { assigned := false ff := func(n interface{}) { if assigned { return } switch n := n.(type) { case *ast.UnaryExpr: // use of &x if n.Op == token.AND && refersTo(n.X, x) { assigned = true return } case *ast.AssignStmt: for _, l := range n.Lhs { if refersTo(l, x) { assigned = true return } } } } for _, n := range scope { if assigned { break } walk(n, ff) } return assigned }
go
func assignsTo(x *ast.Ident, scope []ast.Stmt) bool { assigned := false ff := func(n interface{}) { if assigned { return } switch n := n.(type) { case *ast.UnaryExpr: // use of &x if n.Op == token.AND && refersTo(n.X, x) { assigned = true return } case *ast.AssignStmt: for _, l := range n.Lhs { if refersTo(l, x) { assigned = true return } } } } for _, n := range scope { if assigned { break } walk(n, ff) } return assigned }
[ "func", "assignsTo", "(", "x", "*", "ast", ".", "Ident", ",", "scope", "[", "]", "ast", ".", "Stmt", ")", "bool", "{", "assigned", ":=", "false", "\n", "ff", ":=", "func", "(", "n", "interface", "{", "}", ")", "{", "if", "assigned", "{", "return", "\n", "}", "\n", "switch", "n", ":=", "n", ".", "(", "type", ")", "{", "case", "*", "ast", ".", "UnaryExpr", ":", "if", "n", ".", "Op", "==", "token", ".", "AND", "&&", "refersTo", "(", "n", ".", "X", ",", "x", ")", "{", "assigned", "=", "true", "\n", "return", "\n", "}", "\n", "case", "*", "ast", ".", "AssignStmt", ":", "for", "_", ",", "l", ":=", "range", "n", ".", "Lhs", "{", "if", "refersTo", "(", "l", ",", "x", ")", "{", "assigned", "=", "true", "\n", "return", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "for", "_", ",", "n", ":=", "range", "scope", "{", "if", "assigned", "{", "break", "\n", "}", "\n", "walk", "(", "n", ",", "ff", ")", "\n", "}", "\n", "return", "assigned", "\n", "}" ]
// assignsTo returns true if any of the code in scope assigns to or takes the address of x.
[ "assignsTo", "returns", "true", "if", "any", "of", "the", "code", "in", "scope", "assigns", "to", "or", "takes", "the", "address", "of", "x", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/fix.go#L434-L463
test
golang/appengine
cmd/aefix/fix.go
newPkgDot
func newPkgDot(pos token.Pos, pkg, name string) ast.Expr { return &ast.SelectorExpr{ X: &ast.Ident{ NamePos: pos, Name: pkg, }, Sel: &ast.Ident{ NamePos: pos, Name: name, }, } }
go
func newPkgDot(pos token.Pos, pkg, name string) ast.Expr { return &ast.SelectorExpr{ X: &ast.Ident{ NamePos: pos, Name: pkg, }, Sel: &ast.Ident{ NamePos: pos, Name: name, }, } }
[ "func", "newPkgDot", "(", "pos", "token", ".", "Pos", ",", "pkg", ",", "name", "string", ")", "ast", ".", "Expr", "{", "return", "&", "ast", ".", "SelectorExpr", "{", "X", ":", "&", "ast", ".", "Ident", "{", "NamePos", ":", "pos", ",", "Name", ":", "pkg", ",", "}", ",", "Sel", ":", "&", "ast", ".", "Ident", "{", "NamePos", ":", "pos", ",", "Name", ":", "name", ",", "}", ",", "}", "\n", "}" ]
// newPkgDot returns an ast.Expr referring to "pkg.name" at position pos.
[ "newPkgDot", "returns", "an", "ast", ".", "Expr", "referring", "to", "pkg", ".", "name", "at", "position", "pos", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/fix.go#L466-L477
test
golang/appengine
cmd/aefix/fix.go
renameTop
func renameTop(f *ast.File, old, new string) bool { var fixed bool // Rename any conflicting imports // (assuming package name is last element of path). for _, s := range f.Imports { if s.Name != nil { if s.Name.Name == old { s.Name.Name = new fixed = true } } else { _, thisName := path.Split(importPath(s)) if thisName == old { s.Name = ast.NewIdent(new) fixed = true } } } // Rename any top-level declarations. for _, d := range f.Decls { switch d := d.(type) { case *ast.FuncDecl: if d.Recv == nil && d.Name.Name == old { d.Name.Name = new d.Name.Obj.Name = new fixed = true } case *ast.GenDecl: for _, s := range d.Specs { switch s := s.(type) { case *ast.TypeSpec: if s.Name.Name == old { s.Name.Name = new s.Name.Obj.Name = new fixed = true } case *ast.ValueSpec: for _, n := range s.Names { if n.Name == old { n.Name = new n.Obj.Name = new fixed = true } } } } } } // Rename top-level old to new, both unresolved names // (probably defined in another file) and names that resolve // to a declaration we renamed. walk(f, func(n interface{}) { id, ok := n.(*ast.Ident) if ok && isTopName(id, old) { id.Name = new fixed = true } if ok && id.Obj != nil && id.Name == old && id.Obj.Name == new { id.Name = id.Obj.Name fixed = true } }) return fixed }
go
func renameTop(f *ast.File, old, new string) bool { var fixed bool // Rename any conflicting imports // (assuming package name is last element of path). for _, s := range f.Imports { if s.Name != nil { if s.Name.Name == old { s.Name.Name = new fixed = true } } else { _, thisName := path.Split(importPath(s)) if thisName == old { s.Name = ast.NewIdent(new) fixed = true } } } // Rename any top-level declarations. for _, d := range f.Decls { switch d := d.(type) { case *ast.FuncDecl: if d.Recv == nil && d.Name.Name == old { d.Name.Name = new d.Name.Obj.Name = new fixed = true } case *ast.GenDecl: for _, s := range d.Specs { switch s := s.(type) { case *ast.TypeSpec: if s.Name.Name == old { s.Name.Name = new s.Name.Obj.Name = new fixed = true } case *ast.ValueSpec: for _, n := range s.Names { if n.Name == old { n.Name = new n.Obj.Name = new fixed = true } } } } } } // Rename top-level old to new, both unresolved names // (probably defined in another file) and names that resolve // to a declaration we renamed. walk(f, func(n interface{}) { id, ok := n.(*ast.Ident) if ok && isTopName(id, old) { id.Name = new fixed = true } if ok && id.Obj != nil && id.Name == old && id.Obj.Name == new { id.Name = id.Obj.Name fixed = true } }) return fixed }
[ "func", "renameTop", "(", "f", "*", "ast", ".", "File", ",", "old", ",", "new", "string", ")", "bool", "{", "var", "fixed", "bool", "\n", "for", "_", ",", "s", ":=", "range", "f", ".", "Imports", "{", "if", "s", ".", "Name", "!=", "nil", "{", "if", "s", ".", "Name", ".", "Name", "==", "old", "{", "s", ".", "Name", ".", "Name", "=", "new", "\n", "fixed", "=", "true", "\n", "}", "\n", "}", "else", "{", "_", ",", "thisName", ":=", "path", ".", "Split", "(", "importPath", "(", "s", ")", ")", "\n", "if", "thisName", "==", "old", "{", "s", ".", "Name", "=", "ast", ".", "NewIdent", "(", "new", ")", "\n", "fixed", "=", "true", "\n", "}", "\n", "}", "\n", "}", "\n", "for", "_", ",", "d", ":=", "range", "f", ".", "Decls", "{", "switch", "d", ":=", "d", ".", "(", "type", ")", "{", "case", "*", "ast", ".", "FuncDecl", ":", "if", "d", ".", "Recv", "==", "nil", "&&", "d", ".", "Name", ".", "Name", "==", "old", "{", "d", ".", "Name", ".", "Name", "=", "new", "\n", "d", ".", "Name", ".", "Obj", ".", "Name", "=", "new", "\n", "fixed", "=", "true", "\n", "}", "\n", "case", "*", "ast", ".", "GenDecl", ":", "for", "_", ",", "s", ":=", "range", "d", ".", "Specs", "{", "switch", "s", ":=", "s", ".", "(", "type", ")", "{", "case", "*", "ast", ".", "TypeSpec", ":", "if", "s", ".", "Name", ".", "Name", "==", "old", "{", "s", ".", "Name", ".", "Name", "=", "new", "\n", "s", ".", "Name", ".", "Obj", ".", "Name", "=", "new", "\n", "fixed", "=", "true", "\n", "}", "\n", "case", "*", "ast", ".", "ValueSpec", ":", "for", "_", ",", "n", ":=", "range", "s", ".", "Names", "{", "if", "n", ".", "Name", "==", "old", "{", "n", ".", "Name", "=", "new", "\n", "n", ".", "Obj", ".", "Name", "=", "new", "\n", "fixed", "=", "true", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "walk", "(", "f", ",", "func", "(", "n", "interface", "{", "}", ")", "{", "id", ",", "ok", ":=", "n", ".", "(", "*", "ast", ".", "Ident", ")", "\n", "if", "ok", "&&", "isTopName", "(", "id", ",", "old", ")", "{", "id", ".", "Name", "=", "new", "\n", "fixed", "=", "true", "\n", "}", "\n", "if", "ok", "&&", "id", ".", "Obj", "!=", "nil", "&&", "id", ".", "Name", "==", "old", "&&", "id", ".", "Obj", ".", "Name", "==", "new", "{", "id", ".", "Name", "=", "id", ".", "Obj", ".", "Name", "\n", "fixed", "=", "true", "\n", "}", "\n", "}", ")", "\n", "return", "fixed", "\n", "}" ]
// renameTop renames all references to the top-level name old. // It returns true if it makes any changes.
[ "renameTop", "renames", "all", "references", "to", "the", "top", "-", "level", "name", "old", ".", "It", "returns", "true", "if", "it", "makes", "any", "changes", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/fix.go#L481-L548
test
golang/appengine
cmd/aefix/fix.go
matchLen
func matchLen(x, y string) int { i := 0 for i < len(x) && i < len(y) && x[i] == y[i] { i++ } return i }
go
func matchLen(x, y string) int { i := 0 for i < len(x) && i < len(y) && x[i] == y[i] { i++ } return i }
[ "func", "matchLen", "(", "x", ",", "y", "string", ")", "int", "{", "i", ":=", "0", "\n", "for", "i", "<", "len", "(", "x", ")", "&&", "i", "<", "len", "(", "y", ")", "&&", "x", "[", "i", "]", "==", "y", "[", "i", "]", "{", "i", "++", "\n", "}", "\n", "return", "i", "\n", "}" ]
// matchLen returns the length of the longest prefix shared by x and y.
[ "matchLen", "returns", "the", "length", "of", "the", "longest", "prefix", "shared", "by", "x", "and", "y", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/fix.go#L551-L557
test
golang/appengine
cmd/aefix/fix.go
deleteImport
func deleteImport(f *ast.File, path string) (deleted bool) { oldImport := importSpec(f, path) // Find the import node that imports path, if any. for i, decl := range f.Decls { gen, ok := decl.(*ast.GenDecl) if !ok || gen.Tok != token.IMPORT { continue } for j, spec := range gen.Specs { impspec := spec.(*ast.ImportSpec) if oldImport != impspec { continue } // We found an import spec that imports path. // Delete it. deleted = true copy(gen.Specs[j:], gen.Specs[j+1:]) gen.Specs = gen.Specs[:len(gen.Specs)-1] // If this was the last import spec in this decl, // delete the decl, too. if len(gen.Specs) == 0 { copy(f.Decls[i:], f.Decls[i+1:]) f.Decls = f.Decls[:len(f.Decls)-1] } else if len(gen.Specs) == 1 { gen.Lparen = token.NoPos // drop parens } if j > 0 { // We deleted an entry but now there will be // a blank line-sized hole where the import was. // Close the hole by making the previous // import appear to "end" where this one did. gen.Specs[j-1].(*ast.ImportSpec).EndPos = impspec.End() } break } } // Delete it from f.Imports. for i, imp := range f.Imports { if imp == oldImport { copy(f.Imports[i:], f.Imports[i+1:]) f.Imports = f.Imports[:len(f.Imports)-1] break } } return }
go
func deleteImport(f *ast.File, path string) (deleted bool) { oldImport := importSpec(f, path) // Find the import node that imports path, if any. for i, decl := range f.Decls { gen, ok := decl.(*ast.GenDecl) if !ok || gen.Tok != token.IMPORT { continue } for j, spec := range gen.Specs { impspec := spec.(*ast.ImportSpec) if oldImport != impspec { continue } // We found an import spec that imports path. // Delete it. deleted = true copy(gen.Specs[j:], gen.Specs[j+1:]) gen.Specs = gen.Specs[:len(gen.Specs)-1] // If this was the last import spec in this decl, // delete the decl, too. if len(gen.Specs) == 0 { copy(f.Decls[i:], f.Decls[i+1:]) f.Decls = f.Decls[:len(f.Decls)-1] } else if len(gen.Specs) == 1 { gen.Lparen = token.NoPos // drop parens } if j > 0 { // We deleted an entry but now there will be // a blank line-sized hole where the import was. // Close the hole by making the previous // import appear to "end" where this one did. gen.Specs[j-1].(*ast.ImportSpec).EndPos = impspec.End() } break } } // Delete it from f.Imports. for i, imp := range f.Imports { if imp == oldImport { copy(f.Imports[i:], f.Imports[i+1:]) f.Imports = f.Imports[:len(f.Imports)-1] break } } return }
[ "func", "deleteImport", "(", "f", "*", "ast", ".", "File", ",", "path", "string", ")", "(", "deleted", "bool", ")", "{", "oldImport", ":=", "importSpec", "(", "f", ",", "path", ")", "\n", "for", "i", ",", "decl", ":=", "range", "f", ".", "Decls", "{", "gen", ",", "ok", ":=", "decl", ".", "(", "*", "ast", ".", "GenDecl", ")", "\n", "if", "!", "ok", "||", "gen", ".", "Tok", "!=", "token", ".", "IMPORT", "{", "continue", "\n", "}", "\n", "for", "j", ",", "spec", ":=", "range", "gen", ".", "Specs", "{", "impspec", ":=", "spec", ".", "(", "*", "ast", ".", "ImportSpec", ")", "\n", "if", "oldImport", "!=", "impspec", "{", "continue", "\n", "}", "\n", "deleted", "=", "true", "\n", "copy", "(", "gen", ".", "Specs", "[", "j", ":", "]", ",", "gen", ".", "Specs", "[", "j", "+", "1", ":", "]", ")", "\n", "gen", ".", "Specs", "=", "gen", ".", "Specs", "[", ":", "len", "(", "gen", ".", "Specs", ")", "-", "1", "]", "\n", "if", "len", "(", "gen", ".", "Specs", ")", "==", "0", "{", "copy", "(", "f", ".", "Decls", "[", "i", ":", "]", ",", "f", ".", "Decls", "[", "i", "+", "1", ":", "]", ")", "\n", "f", ".", "Decls", "=", "f", ".", "Decls", "[", ":", "len", "(", "f", ".", "Decls", ")", "-", "1", "]", "\n", "}", "else", "if", "len", "(", "gen", ".", "Specs", ")", "==", "1", "{", "gen", ".", "Lparen", "=", "token", ".", "NoPos", "\n", "}", "\n", "if", "j", ">", "0", "{", "gen", ".", "Specs", "[", "j", "-", "1", "]", ".", "(", "*", "ast", ".", "ImportSpec", ")", ".", "EndPos", "=", "impspec", ".", "End", "(", ")", "\n", "}", "\n", "break", "\n", "}", "\n", "}", "\n", "for", "i", ",", "imp", ":=", "range", "f", ".", "Imports", "{", "if", "imp", "==", "oldImport", "{", "copy", "(", "f", ".", "Imports", "[", "i", ":", "]", ",", "f", ".", "Imports", "[", "i", "+", "1", ":", "]", ")", "\n", "f", ".", "Imports", "=", "f", ".", "Imports", "[", ":", "len", "(", "f", ".", "Imports", ")", "-", "1", "]", "\n", "break", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// deleteImport deletes the import path from the file f, if present.
[ "deleteImport", "deletes", "the", "import", "path", "from", "the", "file", "f", "if", "present", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/fix.go#L644-L694
test
golang/appengine
cmd/aefix/fix.go
rewriteImport
func rewriteImport(f *ast.File, oldPath, newPath string) (rewrote bool) { for _, imp := range f.Imports { if importPath(imp) == oldPath { rewrote = true // record old End, because the default is to compute // it using the length of imp.Path.Value. imp.EndPos = imp.End() imp.Path.Value = strconv.Quote(newPath) } } return }
go
func rewriteImport(f *ast.File, oldPath, newPath string) (rewrote bool) { for _, imp := range f.Imports { if importPath(imp) == oldPath { rewrote = true // record old End, because the default is to compute // it using the length of imp.Path.Value. imp.EndPos = imp.End() imp.Path.Value = strconv.Quote(newPath) } } return }
[ "func", "rewriteImport", "(", "f", "*", "ast", ".", "File", ",", "oldPath", ",", "newPath", "string", ")", "(", "rewrote", "bool", ")", "{", "for", "_", ",", "imp", ":=", "range", "f", ".", "Imports", "{", "if", "importPath", "(", "imp", ")", "==", "oldPath", "{", "rewrote", "=", "true", "\n", "imp", ".", "EndPos", "=", "imp", ".", "End", "(", ")", "\n", "imp", ".", "Path", ".", "Value", "=", "strconv", ".", "Quote", "(", "newPath", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// rewriteImport rewrites any import of path oldPath to path newPath.
[ "rewriteImport", "rewrites", "any", "import", "of", "path", "oldPath", "to", "path", "newPath", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aefix/fix.go#L697-L708
test
golang/appengine
internal/api.go
DefaultTicket
func DefaultTicket() string { defaultTicketOnce.Do(func() { if IsDevAppServer() { defaultTicket = "testapp" + defaultTicketSuffix return } appID := partitionlessAppID() escAppID := strings.Replace(strings.Replace(appID, ":", "_", -1), ".", "_", -1) majVersion := VersionID(nil) if i := strings.Index(majVersion, "."); i > 0 { majVersion = majVersion[:i] } defaultTicket = fmt.Sprintf("%s/%s.%s.%s", escAppID, ModuleName(nil), majVersion, InstanceID()) }) return defaultTicket }
go
func DefaultTicket() string { defaultTicketOnce.Do(func() { if IsDevAppServer() { defaultTicket = "testapp" + defaultTicketSuffix return } appID := partitionlessAppID() escAppID := strings.Replace(strings.Replace(appID, ":", "_", -1), ".", "_", -1) majVersion := VersionID(nil) if i := strings.Index(majVersion, "."); i > 0 { majVersion = majVersion[:i] } defaultTicket = fmt.Sprintf("%s/%s.%s.%s", escAppID, ModuleName(nil), majVersion, InstanceID()) }) return defaultTicket }
[ "func", "DefaultTicket", "(", ")", "string", "{", "defaultTicketOnce", ".", "Do", "(", "func", "(", ")", "{", "if", "IsDevAppServer", "(", ")", "{", "defaultTicket", "=", "\"testapp\"", "+", "defaultTicketSuffix", "\n", "return", "\n", "}", "\n", "appID", ":=", "partitionlessAppID", "(", ")", "\n", "escAppID", ":=", "strings", ".", "Replace", "(", "strings", ".", "Replace", "(", "appID", ",", "\":\"", ",", "\"_\"", ",", "-", "1", ")", ",", "\".\"", ",", "\"_\"", ",", "-", "1", ")", "\n", "majVersion", ":=", "VersionID", "(", "nil", ")", "\n", "if", "i", ":=", "strings", ".", "Index", "(", "majVersion", ",", "\".\"", ")", ";", "i", ">", "0", "{", "majVersion", "=", "majVersion", "[", ":", "i", "]", "\n", "}", "\n", "defaultTicket", "=", "fmt", ".", "Sprintf", "(", "\"%s/%s.%s.%s\"", ",", "escAppID", ",", "ModuleName", "(", "nil", ")", ",", "majVersion", ",", "InstanceID", "(", ")", ")", "\n", "}", ")", "\n", "return", "defaultTicket", "\n", "}" ]
// DefaultTicket returns a ticket used for background context or dev_appserver.
[ "DefaultTicket", "returns", "a", "ticket", "used", "for", "background", "context", "or", "dev_appserver", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/internal/api.go#L288-L303
test
golang/appengine
internal/api.go
flushLog
func (c *context) flushLog(force bool) (flushed bool) { c.pendingLogs.Lock() // Grab up to 30 MB. We can get away with up to 32 MB, but let's be cautious. n, rem := 0, 30<<20 for ; n < len(c.pendingLogs.lines); n++ { ll := c.pendingLogs.lines[n] // Each log line will require about 3 bytes of overhead. nb := proto.Size(ll) + 3 if nb > rem { break } rem -= nb } lines := c.pendingLogs.lines[:n] c.pendingLogs.lines = c.pendingLogs.lines[n:] c.pendingLogs.Unlock() if len(lines) == 0 && !force { // Nothing to flush. return false } rescueLogs := false defer func() { if rescueLogs { c.pendingLogs.Lock() c.pendingLogs.lines = append(lines, c.pendingLogs.lines...) c.pendingLogs.Unlock() } }() buf, err := proto.Marshal(&logpb.UserAppLogGroup{ LogLine: lines, }) if err != nil { log.Printf("internal.flushLog: marshaling UserAppLogGroup: %v", err) rescueLogs = true return false } req := &logpb.FlushRequest{ Logs: buf, } res := &basepb.VoidProto{} c.pendingLogs.Lock() c.pendingLogs.flushes++ c.pendingLogs.Unlock() if err := Call(toContext(c), "logservice", "Flush", req, res); err != nil { log.Printf("internal.flushLog: Flush RPC: %v", err) rescueLogs = true return false } return true }
go
func (c *context) flushLog(force bool) (flushed bool) { c.pendingLogs.Lock() // Grab up to 30 MB. We can get away with up to 32 MB, but let's be cautious. n, rem := 0, 30<<20 for ; n < len(c.pendingLogs.lines); n++ { ll := c.pendingLogs.lines[n] // Each log line will require about 3 bytes of overhead. nb := proto.Size(ll) + 3 if nb > rem { break } rem -= nb } lines := c.pendingLogs.lines[:n] c.pendingLogs.lines = c.pendingLogs.lines[n:] c.pendingLogs.Unlock() if len(lines) == 0 && !force { // Nothing to flush. return false } rescueLogs := false defer func() { if rescueLogs { c.pendingLogs.Lock() c.pendingLogs.lines = append(lines, c.pendingLogs.lines...) c.pendingLogs.Unlock() } }() buf, err := proto.Marshal(&logpb.UserAppLogGroup{ LogLine: lines, }) if err != nil { log.Printf("internal.flushLog: marshaling UserAppLogGroup: %v", err) rescueLogs = true return false } req := &logpb.FlushRequest{ Logs: buf, } res := &basepb.VoidProto{} c.pendingLogs.Lock() c.pendingLogs.flushes++ c.pendingLogs.Unlock() if err := Call(toContext(c), "logservice", "Flush", req, res); err != nil { log.Printf("internal.flushLog: Flush RPC: %v", err) rescueLogs = true return false } return true }
[ "func", "(", "c", "*", "context", ")", "flushLog", "(", "force", "bool", ")", "(", "flushed", "bool", ")", "{", "c", ".", "pendingLogs", ".", "Lock", "(", ")", "\n", "n", ",", "rem", ":=", "0", ",", "30", "<<", "20", "\n", "for", ";", "n", "<", "len", "(", "c", ".", "pendingLogs", ".", "lines", ")", ";", "n", "++", "{", "ll", ":=", "c", ".", "pendingLogs", ".", "lines", "[", "n", "]", "\n", "nb", ":=", "proto", ".", "Size", "(", "ll", ")", "+", "3", "\n", "if", "nb", ">", "rem", "{", "break", "\n", "}", "\n", "rem", "-=", "nb", "\n", "}", "\n", "lines", ":=", "c", ".", "pendingLogs", ".", "lines", "[", ":", "n", "]", "\n", "c", ".", "pendingLogs", ".", "lines", "=", "c", ".", "pendingLogs", ".", "lines", "[", "n", ":", "]", "\n", "c", ".", "pendingLogs", ".", "Unlock", "(", ")", "\n", "if", "len", "(", "lines", ")", "==", "0", "&&", "!", "force", "{", "return", "false", "\n", "}", "\n", "rescueLogs", ":=", "false", "\n", "defer", "func", "(", ")", "{", "if", "rescueLogs", "{", "c", ".", "pendingLogs", ".", "Lock", "(", ")", "\n", "c", ".", "pendingLogs", ".", "lines", "=", "append", "(", "lines", ",", "c", ".", "pendingLogs", ".", "lines", "...", ")", "\n", "c", ".", "pendingLogs", ".", "Unlock", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n", "buf", ",", "err", ":=", "proto", ".", "Marshal", "(", "&", "logpb", ".", "UserAppLogGroup", "{", "LogLine", ":", "lines", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"internal.flushLog: marshaling UserAppLogGroup: %v\"", ",", "err", ")", "\n", "rescueLogs", "=", "true", "\n", "return", "false", "\n", "}", "\n", "req", ":=", "&", "logpb", ".", "FlushRequest", "{", "Logs", ":", "buf", ",", "}", "\n", "res", ":=", "&", "basepb", ".", "VoidProto", "{", "}", "\n", "c", ".", "pendingLogs", ".", "Lock", "(", ")", "\n", "c", ".", "pendingLogs", ".", "flushes", "++", "\n", "c", ".", "pendingLogs", ".", "Unlock", "(", ")", "\n", "if", "err", ":=", "Call", "(", "toContext", "(", "c", ")", ",", "\"logservice\"", ",", "\"Flush\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"internal.flushLog: Flush RPC: %v\"", ",", "err", ")", "\n", "rescueLogs", "=", "true", "\n", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// flushLog attempts to flush any pending logs to the appserver. // It should not be called concurrently.
[ "flushLog", "attempts", "to", "flush", "any", "pending", "logs", "to", "the", "appserver", ".", "It", "should", "not", "be", "called", "concurrently", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/internal/api.go#L594-L647
test
golang/appengine
socket/socket_classic.go
withDeadline
func withDeadline(parent context.Context, deadline time.Time) (context.Context, context.CancelFunc) { if deadline.IsZero() { return parent, func() {} } return context.WithDeadline(parent, deadline) }
go
func withDeadline(parent context.Context, deadline time.Time) (context.Context, context.CancelFunc) { if deadline.IsZero() { return parent, func() {} } return context.WithDeadline(parent, deadline) }
[ "func", "withDeadline", "(", "parent", "context", ".", "Context", ",", "deadline", "time", ".", "Time", ")", "(", "context", ".", "Context", ",", "context", ".", "CancelFunc", ")", "{", "if", "deadline", ".", "IsZero", "(", ")", "{", "return", "parent", ",", "func", "(", ")", "{", "}", "\n", "}", "\n", "return", "context", ".", "WithDeadline", "(", "parent", ",", "deadline", ")", "\n", "}" ]
// withDeadline is like context.WithDeadline, except it ignores the zero deadline.
[ "withDeadline", "is", "like", "context", ".", "WithDeadline", "except", "it", "ignores", "the", "zero", "deadline", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/socket/socket_classic.go#L141-L146
test
golang/appengine
socket/socket_classic.go
KeepAlive
func (cn *Conn) KeepAlive() error { req := &pb.GetSocketNameRequest{ SocketDescriptor: &cn.desc, } res := &pb.GetSocketNameReply{} return internal.Call(cn.ctx, "remote_socket", "GetSocketName", req, res) }
go
func (cn *Conn) KeepAlive() error { req := &pb.GetSocketNameRequest{ SocketDescriptor: &cn.desc, } res := &pb.GetSocketNameReply{} return internal.Call(cn.ctx, "remote_socket", "GetSocketName", req, res) }
[ "func", "(", "cn", "*", "Conn", ")", "KeepAlive", "(", ")", "error", "{", "req", ":=", "&", "pb", ".", "GetSocketNameRequest", "{", "SocketDescriptor", ":", "&", "cn", ".", "desc", ",", "}", "\n", "res", ":=", "&", "pb", ".", "GetSocketNameReply", "{", "}", "\n", "return", "internal", ".", "Call", "(", "cn", ".", "ctx", ",", "\"remote_socket\"", ",", "\"GetSocketName\"", ",", "req", ",", "res", ")", "\n", "}" ]
// KeepAlive signals that the connection is still in use. // It may be called to prevent the socket being closed due to inactivity.
[ "KeepAlive", "signals", "that", "the", "connection", "is", "still", "in", "use", ".", "It", "may", "be", "called", "to", "prevent", "the", "socket", "being", "closed", "due", "to", "inactivity", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/socket/socket_classic.go#L280-L286
test
golang/appengine
internal/transaction.go
applyTransaction
func applyTransaction(pb proto.Message, t *pb.Transaction) { v := reflect.ValueOf(pb) if f, ok := transactionSetters[v.Type()]; ok { f.Call([]reflect.Value{v, reflect.ValueOf(t)}) } }
go
func applyTransaction(pb proto.Message, t *pb.Transaction) { v := reflect.ValueOf(pb) if f, ok := transactionSetters[v.Type()]; ok { f.Call([]reflect.Value{v, reflect.ValueOf(t)}) } }
[ "func", "applyTransaction", "(", "pb", "proto", ".", "Message", ",", "t", "*", "pb", ".", "Transaction", ")", "{", "v", ":=", "reflect", ".", "ValueOf", "(", "pb", ")", "\n", "if", "f", ",", "ok", ":=", "transactionSetters", "[", "v", ".", "Type", "(", ")", "]", ";", "ok", "{", "f", ".", "Call", "(", "[", "]", "reflect", ".", "Value", "{", "v", ",", "reflect", ".", "ValueOf", "(", "t", ")", "}", ")", "\n", "}", "\n", "}" ]
// applyTransaction applies the transaction t to message pb // by using the relevant setter passed to RegisterTransactionSetter.
[ "applyTransaction", "applies", "the", "transaction", "t", "to", "message", "pb", "by", "using", "the", "relevant", "setter", "passed", "to", "RegisterTransactionSetter", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/internal/transaction.go#L32-L37
test
golang/appengine
cmd/aebundler/aebundler.go
analyze
func analyze(tags []string) (*app, error) { ctxt := buildContext(tags) hasMain, appFiles, err := checkMain(ctxt) if err != nil { return nil, err } gopath := filepath.SplitList(ctxt.GOPATH) im, err := imports(ctxt, *rootDir, gopath) return &app{ hasMain: hasMain, appFiles: appFiles, imports: im, }, err }
go
func analyze(tags []string) (*app, error) { ctxt := buildContext(tags) hasMain, appFiles, err := checkMain(ctxt) if err != nil { return nil, err } gopath := filepath.SplitList(ctxt.GOPATH) im, err := imports(ctxt, *rootDir, gopath) return &app{ hasMain: hasMain, appFiles: appFiles, imports: im, }, err }
[ "func", "analyze", "(", "tags", "[", "]", "string", ")", "(", "*", "app", ",", "error", ")", "{", "ctxt", ":=", "buildContext", "(", "tags", ")", "\n", "hasMain", ",", "appFiles", ",", "err", ":=", "checkMain", "(", "ctxt", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "gopath", ":=", "filepath", ".", "SplitList", "(", "ctxt", ".", "GOPATH", ")", "\n", "im", ",", "err", ":=", "imports", "(", "ctxt", ",", "*", "rootDir", ",", "gopath", ")", "\n", "return", "&", "app", "{", "hasMain", ":", "hasMain", ",", "appFiles", ":", "appFiles", ",", "imports", ":", "im", ",", "}", ",", "err", "\n", "}" ]
// analyze checks the app for building with the given build tags and returns hasMain, // app files, and a map of full directory import names to original import names.
[ "analyze", "checks", "the", "app", "for", "building", "with", "the", "given", "build", "tags", "and", "returns", "hasMain", "app", "files", "and", "a", "map", "of", "full", "directory", "import", "names", "to", "original", "import", "names", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aebundler/aebundler.go#L100-L113
test
golang/appengine
cmd/aebundler/aebundler.go
buildContext
func buildContext(tags []string) *build.Context { return &build.Context{ GOARCH: build.Default.GOARCH, GOOS: build.Default.GOOS, GOROOT: build.Default.GOROOT, GOPATH: build.Default.GOPATH, Compiler: build.Default.Compiler, BuildTags: append(build.Default.BuildTags, tags...), } }
go
func buildContext(tags []string) *build.Context { return &build.Context{ GOARCH: build.Default.GOARCH, GOOS: build.Default.GOOS, GOROOT: build.Default.GOROOT, GOPATH: build.Default.GOPATH, Compiler: build.Default.Compiler, BuildTags: append(build.Default.BuildTags, tags...), } }
[ "func", "buildContext", "(", "tags", "[", "]", "string", ")", "*", "build", ".", "Context", "{", "return", "&", "build", ".", "Context", "{", "GOARCH", ":", "build", ".", "Default", ".", "GOARCH", ",", "GOOS", ":", "build", ".", "Default", ".", "GOOS", ",", "GOROOT", ":", "build", ".", "Default", ".", "GOROOT", ",", "GOPATH", ":", "build", ".", "Default", ".", "GOPATH", ",", "Compiler", ":", "build", ".", "Default", ".", "Compiler", ",", "BuildTags", ":", "append", "(", "build", ".", "Default", ".", "BuildTags", ",", "tags", "...", ")", ",", "}", "\n", "}" ]
// buildContext returns the context for building the source.
[ "buildContext", "returns", "the", "context", "for", "building", "the", "source", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aebundler/aebundler.go#L116-L125
test
golang/appengine
cmd/aebundler/aebundler.go
synthesizeMain
func synthesizeMain(tw *tar.Writer, appFiles []string) error { appMap := make(map[string]bool) for _, f := range appFiles { appMap[f] = true } var f string for i := 0; i < 100; i++ { f = fmt.Sprintf("app_main%d.go", i) if !appMap[filepath.Join(*rootDir, f)] { break } } if appMap[filepath.Join(*rootDir, f)] { return fmt.Errorf("unable to find unique name for %v", f) } hdr := &tar.Header{ Name: f, Mode: 0644, Size: int64(len(newMain)), } if err := tw.WriteHeader(hdr); err != nil { return fmt.Errorf("unable to write header for %v: %v", f, err) } if _, err := tw.Write([]byte(newMain)); err != nil { return fmt.Errorf("unable to write %v to tar file: %v", f, err) } return nil }
go
func synthesizeMain(tw *tar.Writer, appFiles []string) error { appMap := make(map[string]bool) for _, f := range appFiles { appMap[f] = true } var f string for i := 0; i < 100; i++ { f = fmt.Sprintf("app_main%d.go", i) if !appMap[filepath.Join(*rootDir, f)] { break } } if appMap[filepath.Join(*rootDir, f)] { return fmt.Errorf("unable to find unique name for %v", f) } hdr := &tar.Header{ Name: f, Mode: 0644, Size: int64(len(newMain)), } if err := tw.WriteHeader(hdr); err != nil { return fmt.Errorf("unable to write header for %v: %v", f, err) } if _, err := tw.Write([]byte(newMain)); err != nil { return fmt.Errorf("unable to write %v to tar file: %v", f, err) } return nil }
[ "func", "synthesizeMain", "(", "tw", "*", "tar", ".", "Writer", ",", "appFiles", "[", "]", "string", ")", "error", "{", "appMap", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "for", "_", ",", "f", ":=", "range", "appFiles", "{", "appMap", "[", "f", "]", "=", "true", "\n", "}", "\n", "var", "f", "string", "\n", "for", "i", ":=", "0", ";", "i", "<", "100", ";", "i", "++", "{", "f", "=", "fmt", ".", "Sprintf", "(", "\"app_main%d.go\"", ",", "i", ")", "\n", "if", "!", "appMap", "[", "filepath", ".", "Join", "(", "*", "rootDir", ",", "f", ")", "]", "{", "break", "\n", "}", "\n", "}", "\n", "if", "appMap", "[", "filepath", ".", "Join", "(", "*", "rootDir", ",", "f", ")", "]", "{", "return", "fmt", ".", "Errorf", "(", "\"unable to find unique name for %v\"", ",", "f", ")", "\n", "}", "\n", "hdr", ":=", "&", "tar", ".", "Header", "{", "Name", ":", "f", ",", "Mode", ":", "0644", ",", "Size", ":", "int64", "(", "len", "(", "newMain", ")", ")", ",", "}", "\n", "if", "err", ":=", "tw", ".", "WriteHeader", "(", "hdr", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"unable to write header for %v: %v\"", ",", "f", ",", "err", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "tw", ".", "Write", "(", "[", "]", "byte", "(", "newMain", ")", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"unable to write %v to tar file: %v\"", ",", "f", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// synthesizeMain generates a new main func and writes it to the tarball.
[ "synthesizeMain", "generates", "a", "new", "main", "func", "and", "writes", "it", "to", "the", "tarball", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aebundler/aebundler.go#L168-L195
test
golang/appengine
cmd/aebundler/aebundler.go
findInGopath
func findInGopath(dir string, gopath []string) (string, error) { for _, v := range gopath { dst := filepath.Join(v, "src", dir) if _, err := os.Stat(dst); err == nil { return dst, nil } } return "", fmt.Errorf("unable to find package %v in gopath %v", dir, gopath) }
go
func findInGopath(dir string, gopath []string) (string, error) { for _, v := range gopath { dst := filepath.Join(v, "src", dir) if _, err := os.Stat(dst); err == nil { return dst, nil } } return "", fmt.Errorf("unable to find package %v in gopath %v", dir, gopath) }
[ "func", "findInGopath", "(", "dir", "string", ",", "gopath", "[", "]", "string", ")", "(", "string", ",", "error", ")", "{", "for", "_", ",", "v", ":=", "range", "gopath", "{", "dst", ":=", "filepath", ".", "Join", "(", "v", ",", "\"src\"", ",", "dir", ")", "\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "dst", ")", ";", "err", "==", "nil", "{", "return", "dst", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"unable to find package %v in gopath %v\"", ",", "dir", ",", "gopath", ")", "\n", "}" ]
// findInGopath searches the gopath for the named import directory.
[ "findInGopath", "searches", "the", "gopath", "for", "the", "named", "import", "directory", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aebundler/aebundler.go#L228-L236
test
golang/appengine
cmd/aebundler/aebundler.go
copyTree
func copyTree(tw *tar.Writer, dstDir, srcDir string) error { entries, err := ioutil.ReadDir(srcDir) if err != nil { return fmt.Errorf("unable to read dir %v: %v", srcDir, err) } for _, entry := range entries { n := entry.Name() if skipFiles[n] { continue } s := filepath.Join(srcDir, n) d := filepath.Join(dstDir, n) if entry.IsDir() { if err := copyTree(tw, d, s); err != nil { return fmt.Errorf("unable to copy dir %v to %v: %v", s, d, err) } continue } if err := copyFile(tw, d, s); err != nil { return fmt.Errorf("unable to copy dir %v to %v: %v", s, d, err) } } return nil }
go
func copyTree(tw *tar.Writer, dstDir, srcDir string) error { entries, err := ioutil.ReadDir(srcDir) if err != nil { return fmt.Errorf("unable to read dir %v: %v", srcDir, err) } for _, entry := range entries { n := entry.Name() if skipFiles[n] { continue } s := filepath.Join(srcDir, n) d := filepath.Join(dstDir, n) if entry.IsDir() { if err := copyTree(tw, d, s); err != nil { return fmt.Errorf("unable to copy dir %v to %v: %v", s, d, err) } continue } if err := copyFile(tw, d, s); err != nil { return fmt.Errorf("unable to copy dir %v to %v: %v", s, d, err) } } return nil }
[ "func", "copyTree", "(", "tw", "*", "tar", ".", "Writer", ",", "dstDir", ",", "srcDir", "string", ")", "error", "{", "entries", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "srcDir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"unable to read dir %v: %v\"", ",", "srcDir", ",", "err", ")", "\n", "}", "\n", "for", "_", ",", "entry", ":=", "range", "entries", "{", "n", ":=", "entry", ".", "Name", "(", ")", "\n", "if", "skipFiles", "[", "n", "]", "{", "continue", "\n", "}", "\n", "s", ":=", "filepath", ".", "Join", "(", "srcDir", ",", "n", ")", "\n", "d", ":=", "filepath", ".", "Join", "(", "dstDir", ",", "n", ")", "\n", "if", "entry", ".", "IsDir", "(", ")", "{", "if", "err", ":=", "copyTree", "(", "tw", ",", "d", ",", "s", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"unable to copy dir %v to %v: %v\"", ",", "s", ",", "d", ",", "err", ")", "\n", "}", "\n", "continue", "\n", "}", "\n", "if", "err", ":=", "copyFile", "(", "tw", ",", "d", ",", "s", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"unable to copy dir %v to %v: %v\"", ",", "s", ",", "d", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// copyTree copies srcDir to tar file dstDir, ignoring skipFiles.
[ "copyTree", "copies", "srcDir", "to", "tar", "file", "dstDir", "ignoring", "skipFiles", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aebundler/aebundler.go#L239-L262
test
golang/appengine
cmd/aebundler/aebundler.go
copyFile
func copyFile(tw *tar.Writer, dst, src string) error { s, err := os.Open(src) if err != nil { return fmt.Errorf("unable to open %v: %v", src, err) } defer s.Close() fi, err := s.Stat() if err != nil { return fmt.Errorf("unable to stat %v: %v", src, err) } hdr, err := tar.FileInfoHeader(fi, dst) if err != nil { return fmt.Errorf("unable to create tar header for %v: %v", dst, err) } hdr.Name = dst if err := tw.WriteHeader(hdr); err != nil { return fmt.Errorf("unable to write header for %v: %v", dst, err) } _, err = io.Copy(tw, s) if err != nil { return fmt.Errorf("unable to copy %v to %v: %v", src, dst, err) } return nil }
go
func copyFile(tw *tar.Writer, dst, src string) error { s, err := os.Open(src) if err != nil { return fmt.Errorf("unable to open %v: %v", src, err) } defer s.Close() fi, err := s.Stat() if err != nil { return fmt.Errorf("unable to stat %v: %v", src, err) } hdr, err := tar.FileInfoHeader(fi, dst) if err != nil { return fmt.Errorf("unable to create tar header for %v: %v", dst, err) } hdr.Name = dst if err := tw.WriteHeader(hdr); err != nil { return fmt.Errorf("unable to write header for %v: %v", dst, err) } _, err = io.Copy(tw, s) if err != nil { return fmt.Errorf("unable to copy %v to %v: %v", src, dst, err) } return nil }
[ "func", "copyFile", "(", "tw", "*", "tar", ".", "Writer", ",", "dst", ",", "src", "string", ")", "error", "{", "s", ",", "err", ":=", "os", ".", "Open", "(", "src", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"unable to open %v: %v\"", ",", "src", ",", "err", ")", "\n", "}", "\n", "defer", "s", ".", "Close", "(", ")", "\n", "fi", ",", "err", ":=", "s", ".", "Stat", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"unable to stat %v: %v\"", ",", "src", ",", "err", ")", "\n", "}", "\n", "hdr", ",", "err", ":=", "tar", ".", "FileInfoHeader", "(", "fi", ",", "dst", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"unable to create tar header for %v: %v\"", ",", "dst", ",", "err", ")", "\n", "}", "\n", "hdr", ".", "Name", "=", "dst", "\n", "if", "err", ":=", "tw", ".", "WriteHeader", "(", "hdr", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"unable to write header for %v: %v\"", ",", "dst", ",", "err", ")", "\n", "}", "\n", "_", ",", "err", "=", "io", ".", "Copy", "(", "tw", ",", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"unable to copy %v to %v: %v\"", ",", "src", ",", "dst", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// copyFile copies src to tar file dst.
[ "copyFile", "copies", "src", "to", "tar", "file", "dst", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aebundler/aebundler.go#L265-L289
test
golang/appengine
cmd/aebundler/aebundler.go
checkMain
func checkMain(ctxt *build.Context) (bool, []string, error) { pkg, err := ctxt.ImportDir(*rootDir, 0) if err != nil { return false, nil, fmt.Errorf("unable to analyze source: %v", err) } if !pkg.IsCommand() { errorf("Your app's package needs to be changed from %q to \"main\".\n", pkg.Name) } // Search for a "func main" var hasMain bool var appFiles []string for _, f := range pkg.GoFiles { n := filepath.Join(*rootDir, f) appFiles = append(appFiles, n) if hasMain, err = readFile(n); err != nil { return false, nil, fmt.Errorf("error parsing %q: %v", n, err) } } return hasMain, appFiles, nil }
go
func checkMain(ctxt *build.Context) (bool, []string, error) { pkg, err := ctxt.ImportDir(*rootDir, 0) if err != nil { return false, nil, fmt.Errorf("unable to analyze source: %v", err) } if !pkg.IsCommand() { errorf("Your app's package needs to be changed from %q to \"main\".\n", pkg.Name) } // Search for a "func main" var hasMain bool var appFiles []string for _, f := range pkg.GoFiles { n := filepath.Join(*rootDir, f) appFiles = append(appFiles, n) if hasMain, err = readFile(n); err != nil { return false, nil, fmt.Errorf("error parsing %q: %v", n, err) } } return hasMain, appFiles, nil }
[ "func", "checkMain", "(", "ctxt", "*", "build", ".", "Context", ")", "(", "bool", ",", "[", "]", "string", ",", "error", ")", "{", "pkg", ",", "err", ":=", "ctxt", ".", "ImportDir", "(", "*", "rootDir", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "nil", ",", "fmt", ".", "Errorf", "(", "\"unable to analyze source: %v\"", ",", "err", ")", "\n", "}", "\n", "if", "!", "pkg", ".", "IsCommand", "(", ")", "{", "errorf", "(", "\"Your app's package needs to be changed from %q to \\\"main\\\".\\n\"", ",", "\\\"", ")", "\n", "}", "\n", "\\\"", "\n", "\\n", "\n", "pkg", ".", "Name", "\n", "var", "hasMain", "bool", "\n", "}" ]
// checkMain verifies that there is a single "main" function. // It also returns a list of all Go source files in the app.
[ "checkMain", "verifies", "that", "there", "is", "a", "single", "main", "function", ".", "It", "also", "returns", "a", "list", "of", "all", "Go", "source", "files", "in", "the", "app", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aebundler/aebundler.go#L293-L312
test
golang/appengine
cmd/aebundler/aebundler.go
isMain
func isMain(f *ast.FuncDecl) bool { ft := f.Type return f.Name.Name == "main" && f.Recv == nil && ft.Params.NumFields() == 0 && ft.Results.NumFields() == 0 }
go
func isMain(f *ast.FuncDecl) bool { ft := f.Type return f.Name.Name == "main" && f.Recv == nil && ft.Params.NumFields() == 0 && ft.Results.NumFields() == 0 }
[ "func", "isMain", "(", "f", "*", "ast", ".", "FuncDecl", ")", "bool", "{", "ft", ":=", "f", ".", "Type", "\n", "return", "f", ".", "Name", ".", "Name", "==", "\"main\"", "&&", "f", ".", "Recv", "==", "nil", "&&", "ft", ".", "Params", ".", "NumFields", "(", ")", "==", "0", "&&", "ft", ".", "Results", ".", "NumFields", "(", ")", "==", "0", "\n", "}" ]
// isMain returns whether the given function declaration is a main function. // Such a function must be called "main", not have a receiver, and have no arguments or return types.
[ "isMain", "returns", "whether", "the", "given", "function", "declaration", "is", "a", "main", "function", ".", "Such", "a", "function", "must", "be", "called", "main", "not", "have", "a", "receiver", "and", "have", "no", "arguments", "or", "return", "types", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aebundler/aebundler.go#L316-L319
test
golang/appengine
cmd/aebundler/aebundler.go
readFile
func readFile(filename string) (hasMain bool, err error) { var src []byte src, err = ioutil.ReadFile(filename) if err != nil { return } fset := token.NewFileSet() file, err := parser.ParseFile(fset, filename, src, 0) for _, decl := range file.Decls { funcDecl, ok := decl.(*ast.FuncDecl) if !ok { continue } if !isMain(funcDecl) { continue } hasMain = true break } return }
go
func readFile(filename string) (hasMain bool, err error) { var src []byte src, err = ioutil.ReadFile(filename) if err != nil { return } fset := token.NewFileSet() file, err := parser.ParseFile(fset, filename, src, 0) for _, decl := range file.Decls { funcDecl, ok := decl.(*ast.FuncDecl) if !ok { continue } if !isMain(funcDecl) { continue } hasMain = true break } return }
[ "func", "readFile", "(", "filename", "string", ")", "(", "hasMain", "bool", ",", "err", "error", ")", "{", "var", "src", "[", "]", "byte", "\n", "src", ",", "err", "=", "ioutil", ".", "ReadFile", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "fset", ":=", "token", ".", "NewFileSet", "(", ")", "\n", "file", ",", "err", ":=", "parser", ".", "ParseFile", "(", "fset", ",", "filename", ",", "src", ",", "0", ")", "\n", "for", "_", ",", "decl", ":=", "range", "file", ".", "Decls", "{", "funcDecl", ",", "ok", ":=", "decl", ".", "(", "*", "ast", ".", "FuncDecl", ")", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n", "if", "!", "isMain", "(", "funcDecl", ")", "{", "continue", "\n", "}", "\n", "hasMain", "=", "true", "\n", "break", "\n", "}", "\n", "return", "\n", "}" ]
// readFile reads and parses the Go source code file and returns whether it has a main function.
[ "readFile", "reads", "and", "parses", "the", "Go", "source", "code", "file", "and", "returns", "whether", "it", "has", "a", "main", "function", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/cmd/aebundler/aebundler.go#L322-L342
test
golang/appengine
datastore/load.go
initField
func initField(val reflect.Value, index []int) reflect.Value { for _, i := range index[:len(index)-1] { val = val.Field(i) if val.Kind() == reflect.Ptr { if val.IsNil() { val.Set(reflect.New(val.Type().Elem())) } val = val.Elem() } } return val.Field(index[len(index)-1]) }
go
func initField(val reflect.Value, index []int) reflect.Value { for _, i := range index[:len(index)-1] { val = val.Field(i) if val.Kind() == reflect.Ptr { if val.IsNil() { val.Set(reflect.New(val.Type().Elem())) } val = val.Elem() } } return val.Field(index[len(index)-1]) }
[ "func", "initField", "(", "val", "reflect", ".", "Value", ",", "index", "[", "]", "int", ")", "reflect", ".", "Value", "{", "for", "_", ",", "i", ":=", "range", "index", "[", ":", "len", "(", "index", ")", "-", "1", "]", "{", "val", "=", "val", ".", "Field", "(", "i", ")", "\n", "if", "val", ".", "Kind", "(", ")", "==", "reflect", ".", "Ptr", "{", "if", "val", ".", "IsNil", "(", ")", "{", "val", ".", "Set", "(", "reflect", ".", "New", "(", "val", ".", "Type", "(", ")", ".", "Elem", "(", ")", ")", ")", "\n", "}", "\n", "val", "=", "val", ".", "Elem", "(", ")", "\n", "}", "\n", "}", "\n", "return", "val", ".", "Field", "(", "index", "[", "len", "(", "index", ")", "-", "1", "]", ")", "\n", "}" ]
// initField is similar to reflect's Value.FieldByIndex, in that it // returns the nested struct field corresponding to index, but it // initialises any nil pointers encountered when traversing the structure.
[ "initField", "is", "similar", "to", "reflect", "s", "Value", ".", "FieldByIndex", "in", "that", "it", "returns", "the", "nested", "struct", "field", "corresponding", "to", "index", "but", "it", "initialises", "any", "nil", "pointers", "encountered", "when", "traversing", "the", "structure", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/load.go#L285-L296
test
golang/appengine
datastore/load.go
loadEntity
func loadEntity(dst interface{}, src *pb.EntityProto) (err error) { ent, err := protoToEntity(src) if err != nil { return err } if e, ok := dst.(PropertyLoadSaver); ok { return e.Load(ent.Properties) } return LoadStruct(dst, ent.Properties) }
go
func loadEntity(dst interface{}, src *pb.EntityProto) (err error) { ent, err := protoToEntity(src) if err != nil { return err } if e, ok := dst.(PropertyLoadSaver); ok { return e.Load(ent.Properties) } return LoadStruct(dst, ent.Properties) }
[ "func", "loadEntity", "(", "dst", "interface", "{", "}", ",", "src", "*", "pb", ".", "EntityProto", ")", "(", "err", "error", ")", "{", "ent", ",", "err", ":=", "protoToEntity", "(", "src", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "e", ",", "ok", ":=", "dst", ".", "(", "PropertyLoadSaver", ")", ";", "ok", "{", "return", "e", ".", "Load", "(", "ent", ".", "Properties", ")", "\n", "}", "\n", "return", "LoadStruct", "(", "dst", ",", "ent", ".", "Properties", ")", "\n", "}" ]
// loadEntity loads an EntityProto into PropertyLoadSaver or struct pointer.
[ "loadEntity", "loads", "an", "EntityProto", "into", "PropertyLoadSaver", "or", "struct", "pointer", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/load.go#L299-L308
test
golang/appengine
search/search.go
validIndexNameOrDocID
func validIndexNameOrDocID(s string) bool { if strings.HasPrefix(s, "!") { return false } for _, c := range s { if c < 0x21 || 0x7f <= c { return false } } return true }
go
func validIndexNameOrDocID(s string) bool { if strings.HasPrefix(s, "!") { return false } for _, c := range s { if c < 0x21 || 0x7f <= c { return false } } return true }
[ "func", "validIndexNameOrDocID", "(", "s", "string", ")", "bool", "{", "if", "strings", ".", "HasPrefix", "(", "s", ",", "\"!\"", ")", "{", "return", "false", "\n", "}", "\n", "for", "_", ",", "c", ":=", "range", "s", "{", "if", "c", "<", "0x21", "||", "0x7f", "<=", "c", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// validIndexNameOrDocID is the Go equivalent of Python's // _ValidateVisiblePrintableAsciiNotReserved.
[ "validIndexNameOrDocID", "is", "the", "Go", "equivalent", "of", "Python", "s", "_ValidateVisiblePrintableAsciiNotReserved", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/search/search.go#L57-L67
test
golang/appengine
search/search.go
Open
func Open(name string) (*Index, error) { if !validIndexNameOrDocID(name) { return nil, fmt.Errorf("search: invalid index name %q", name) } return &Index{ spec: pb.IndexSpec{ Name: &name, }, }, nil }
go
func Open(name string) (*Index, error) { if !validIndexNameOrDocID(name) { return nil, fmt.Errorf("search: invalid index name %q", name) } return &Index{ spec: pb.IndexSpec{ Name: &name, }, }, nil }
[ "func", "Open", "(", "name", "string", ")", "(", "*", "Index", ",", "error", ")", "{", "if", "!", "validIndexNameOrDocID", "(", "name", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"search: invalid index name %q\"", ",", "name", ")", "\n", "}", "\n", "return", "&", "Index", "{", "spec", ":", "pb", ".", "IndexSpec", "{", "Name", ":", "&", "name", ",", "}", ",", "}", ",", "nil", "\n", "}" ]
// Open opens the index with the given name. The index is created if it does // not already exist. // // The name is a human-readable ASCII string. It must contain no whitespace // characters and not start with "!".
[ "Open", "opens", "the", "index", "with", "the", "given", "name", ".", "The", "index", "is", "created", "if", "it", "does", "not", "already", "exist", ".", "The", "name", "is", "a", "human", "-", "readable", "ASCII", "string", ".", "It", "must", "contain", "no", "whitespace", "characters", "and", "not", "start", "with", "!", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/search/search.go#L108-L117
test
golang/appengine
search/search.go
Put
func (x *Index) Put(c context.Context, id string, src interface{}) (string, error) { ids, err := x.PutMulti(c, []string{id}, []interface{}{src}) if err != nil { return "", err } return ids[0], nil }
go
func (x *Index) Put(c context.Context, id string, src interface{}) (string, error) { ids, err := x.PutMulti(c, []string{id}, []interface{}{src}) if err != nil { return "", err } return ids[0], nil }
[ "func", "(", "x", "*", "Index", ")", "Put", "(", "c", "context", ".", "Context", ",", "id", "string", ",", "src", "interface", "{", "}", ")", "(", "string", ",", "error", ")", "{", "ids", ",", "err", ":=", "x", ".", "PutMulti", "(", "c", ",", "[", "]", "string", "{", "id", "}", ",", "[", "]", "interface", "{", "}", "{", "src", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "return", "ids", "[", "0", "]", ",", "nil", "\n", "}" ]
// Put saves src to the index. If id is empty, a new ID is allocated by the // service and returned. If id is not empty, any existing index entry for that // ID is replaced. // // The ID is a human-readable ASCII string. It must contain no whitespace // characters and not start with "!". // // src must be a non-nil struct pointer or implement the FieldLoadSaver // interface.
[ "Put", "saves", "src", "to", "the", "index", ".", "If", "id", "is", "empty", "a", "new", "ID", "is", "allocated", "by", "the", "service", "and", "returned", ".", "If", "id", "is", "not", "empty", "any", "existing", "index", "entry", "for", "that", "ID", "is", "replaced", ".", "The", "ID", "is", "a", "human", "-", "readable", "ASCII", "string", ".", "It", "must", "contain", "no", "whitespace", "characters", "and", "not", "start", "with", "!", ".", "src", "must", "be", "a", "non", "-", "nil", "struct", "pointer", "or", "implement", "the", "FieldLoadSaver", "interface", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/search/search.go#L128-L134
test
golang/appengine
search/search.go
Get
func (x *Index) Get(c context.Context, id string, dst interface{}) error { if id == "" || !validIndexNameOrDocID(id) { return fmt.Errorf("search: invalid ID %q", id) } req := &pb.ListDocumentsRequest{ Params: &pb.ListDocumentsParams{ IndexSpec: &x.spec, StartDocId: proto.String(id), Limit: proto.Int32(1), }, } res := &pb.ListDocumentsResponse{} if err := internal.Call(c, "search", "ListDocuments", req, res); err != nil { return err } if res.Status == nil || res.Status.GetCode() != pb.SearchServiceError_OK { return fmt.Errorf("search: %s: %s", res.Status.GetCode(), res.Status.GetErrorDetail()) } if len(res.Document) != 1 || res.Document[0].GetId() != id { return ErrNoSuchDocument } return loadDoc(dst, res.Document[0], nil) }
go
func (x *Index) Get(c context.Context, id string, dst interface{}) error { if id == "" || !validIndexNameOrDocID(id) { return fmt.Errorf("search: invalid ID %q", id) } req := &pb.ListDocumentsRequest{ Params: &pb.ListDocumentsParams{ IndexSpec: &x.spec, StartDocId: proto.String(id), Limit: proto.Int32(1), }, } res := &pb.ListDocumentsResponse{} if err := internal.Call(c, "search", "ListDocuments", req, res); err != nil { return err } if res.Status == nil || res.Status.GetCode() != pb.SearchServiceError_OK { return fmt.Errorf("search: %s: %s", res.Status.GetCode(), res.Status.GetErrorDetail()) } if len(res.Document) != 1 || res.Document[0].GetId() != id { return ErrNoSuchDocument } return loadDoc(dst, res.Document[0], nil) }
[ "func", "(", "x", "*", "Index", ")", "Get", "(", "c", "context", ".", "Context", ",", "id", "string", ",", "dst", "interface", "{", "}", ")", "error", "{", "if", "id", "==", "\"\"", "||", "!", "validIndexNameOrDocID", "(", "id", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"search: invalid ID %q\"", ",", "id", ")", "\n", "}", "\n", "req", ":=", "&", "pb", ".", "ListDocumentsRequest", "{", "Params", ":", "&", "pb", ".", "ListDocumentsParams", "{", "IndexSpec", ":", "&", "x", ".", "spec", ",", "StartDocId", ":", "proto", ".", "String", "(", "id", ")", ",", "Limit", ":", "proto", ".", "Int32", "(", "1", ")", ",", "}", ",", "}", "\n", "res", ":=", "&", "pb", ".", "ListDocumentsResponse", "{", "}", "\n", "if", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"search\"", ",", "\"ListDocuments\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "res", ".", "Status", "==", "nil", "||", "res", ".", "Status", ".", "GetCode", "(", ")", "!=", "pb", ".", "SearchServiceError_OK", "{", "return", "fmt", ".", "Errorf", "(", "\"search: %s: %s\"", ",", "res", ".", "Status", ".", "GetCode", "(", ")", ",", "res", ".", "Status", ".", "GetErrorDetail", "(", ")", ")", "\n", "}", "\n", "if", "len", "(", "res", ".", "Document", ")", "!=", "1", "||", "res", ".", "Document", "[", "0", "]", ".", "GetId", "(", ")", "!=", "id", "{", "return", "ErrNoSuchDocument", "\n", "}", "\n", "return", "loadDoc", "(", "dst", ",", "res", ".", "Document", "[", "0", "]", ",", "nil", ")", "\n", "}" ]
// Get loads the document with the given ID into dst. // // The ID is a human-readable ASCII string. It must be non-empty, contain no // whitespace characters and not start with "!". // // dst must be a non-nil struct pointer or implement the FieldLoadSaver // interface. // // ErrFieldMismatch is returned when a field is to be loaded into a different // type than the one it was stored from, or when a field is missing or // unexported in the destination struct. ErrFieldMismatch is only returned if // dst is a struct pointer. It is up to the callee to decide whether this error // is fatal, recoverable, or ignorable.
[ "Get", "loads", "the", "document", "with", "the", "given", "ID", "into", "dst", ".", "The", "ID", "is", "a", "human", "-", "readable", "ASCII", "string", ".", "It", "must", "be", "non", "-", "empty", "contain", "no", "whitespace", "characters", "and", "not", "start", "with", "!", ".", "dst", "must", "be", "a", "non", "-", "nil", "struct", "pointer", "or", "implement", "the", "FieldLoadSaver", "interface", ".", "ErrFieldMismatch", "is", "returned", "when", "a", "field", "is", "to", "be", "loaded", "into", "a", "different", "type", "than", "the", "one", "it", "was", "stored", "from", "or", "when", "a", "field", "is", "missing", "or", "unexported", "in", "the", "destination", "struct", ".", "ErrFieldMismatch", "is", "only", "returned", "if", "dst", "is", "a", "struct", "pointer", ".", "It", "is", "up", "to", "the", "callee", "to", "decide", "whether", "this", "error", "is", "fatal", "recoverable", "or", "ignorable", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/search/search.go#L216-L238
test
golang/appengine
search/search.go
Delete
func (x *Index) Delete(c context.Context, id string) error { return x.DeleteMulti(c, []string{id}) }
go
func (x *Index) Delete(c context.Context, id string) error { return x.DeleteMulti(c, []string{id}) }
[ "func", "(", "x", "*", "Index", ")", "Delete", "(", "c", "context", ".", "Context", ",", "id", "string", ")", "error", "{", "return", "x", ".", "DeleteMulti", "(", "c", ",", "[", "]", "string", "{", "id", "}", ")", "\n", "}" ]
// Delete deletes a document from the index.
[ "Delete", "deletes", "a", "document", "from", "the", "index", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/search/search.go#L241-L243
test
golang/appengine
search/search.go
DeleteMulti
func (x *Index) DeleteMulti(c context.Context, ids []string) error { if len(ids) > maxDocumentsPerPutDelete { return ErrTooManyDocuments } req := &pb.DeleteDocumentRequest{ Params: &pb.DeleteDocumentParams{ DocId: ids, IndexSpec: &x.spec, }, } res := &pb.DeleteDocumentResponse{} if err := internal.Call(c, "search", "DeleteDocument", req, res); err != nil { return err } if len(res.Status) != len(ids) { return fmt.Errorf("search: internal error: wrong number of results (%d, expected %d)", len(res.Status), len(ids)) } multiErr, hasErr := make(appengine.MultiError, len(ids)), false for i, s := range res.Status { if s.GetCode() != pb.SearchServiceError_OK { multiErr[i] = fmt.Errorf("search: %s: %s", s.GetCode(), s.GetErrorDetail()) hasErr = true } } if hasErr { return multiErr } return nil }
go
func (x *Index) DeleteMulti(c context.Context, ids []string) error { if len(ids) > maxDocumentsPerPutDelete { return ErrTooManyDocuments } req := &pb.DeleteDocumentRequest{ Params: &pb.DeleteDocumentParams{ DocId: ids, IndexSpec: &x.spec, }, } res := &pb.DeleteDocumentResponse{} if err := internal.Call(c, "search", "DeleteDocument", req, res); err != nil { return err } if len(res.Status) != len(ids) { return fmt.Errorf("search: internal error: wrong number of results (%d, expected %d)", len(res.Status), len(ids)) } multiErr, hasErr := make(appengine.MultiError, len(ids)), false for i, s := range res.Status { if s.GetCode() != pb.SearchServiceError_OK { multiErr[i] = fmt.Errorf("search: %s: %s", s.GetCode(), s.GetErrorDetail()) hasErr = true } } if hasErr { return multiErr } return nil }
[ "func", "(", "x", "*", "Index", ")", "DeleteMulti", "(", "c", "context", ".", "Context", ",", "ids", "[", "]", "string", ")", "error", "{", "if", "len", "(", "ids", ")", ">", "maxDocumentsPerPutDelete", "{", "return", "ErrTooManyDocuments", "\n", "}", "\n", "req", ":=", "&", "pb", ".", "DeleteDocumentRequest", "{", "Params", ":", "&", "pb", ".", "DeleteDocumentParams", "{", "DocId", ":", "ids", ",", "IndexSpec", ":", "&", "x", ".", "spec", ",", "}", ",", "}", "\n", "res", ":=", "&", "pb", ".", "DeleteDocumentResponse", "{", "}", "\n", "if", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"search\"", ",", "\"DeleteDocument\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "len", "(", "res", ".", "Status", ")", "!=", "len", "(", "ids", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"search: internal error: wrong number of results (%d, expected %d)\"", ",", "len", "(", "res", ".", "Status", ")", ",", "len", "(", "ids", ")", ")", "\n", "}", "\n", "multiErr", ",", "hasErr", ":=", "make", "(", "appengine", ".", "MultiError", ",", "len", "(", "ids", ")", ")", ",", "false", "\n", "for", "i", ",", "s", ":=", "range", "res", ".", "Status", "{", "if", "s", ".", "GetCode", "(", ")", "!=", "pb", ".", "SearchServiceError_OK", "{", "multiErr", "[", "i", "]", "=", "fmt", ".", "Errorf", "(", "\"search: %s: %s\"", ",", "s", ".", "GetCode", "(", ")", ",", "s", ".", "GetErrorDetail", "(", ")", ")", "\n", "hasErr", "=", "true", "\n", "}", "\n", "}", "\n", "if", "hasErr", "{", "return", "multiErr", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// DeleteMulti deletes multiple documents from the index. // // The returned error may be an instance of appengine.MultiError, in which case // it will be the same size as srcs and the individual errors inside will // correspond with the items in srcs.
[ "DeleteMulti", "deletes", "multiple", "documents", "from", "the", "index", ".", "The", "returned", "error", "may", "be", "an", "instance", "of", "appengine", ".", "MultiError", "in", "which", "case", "it", "will", "be", "the", "same", "size", "as", "srcs", "and", "the", "individual", "errors", "inside", "will", "correspond", "with", "the", "items", "in", "srcs", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/search/search.go#L250-L280
test
golang/appengine
search/search.go
Search
func (x *Index) Search(c context.Context, query string, opts *SearchOptions) *Iterator { t := &Iterator{ c: c, index: x, searchQuery: query, more: moreSearch, } if opts != nil { if opts.Cursor != "" { if opts.Offset != 0 { return errIter("at most one of Cursor and Offset may be specified") } t.searchCursor = proto.String(string(opts.Cursor)) } t.limit = opts.Limit t.fields = opts.Fields t.idsOnly = opts.IDsOnly t.sort = opts.Sort t.exprs = opts.Expressions t.refinements = opts.Refinements t.facetOpts = opts.Facets t.searchOffset = opts.Offset t.countAccuracy = opts.CountAccuracy } return t }
go
func (x *Index) Search(c context.Context, query string, opts *SearchOptions) *Iterator { t := &Iterator{ c: c, index: x, searchQuery: query, more: moreSearch, } if opts != nil { if opts.Cursor != "" { if opts.Offset != 0 { return errIter("at most one of Cursor and Offset may be specified") } t.searchCursor = proto.String(string(opts.Cursor)) } t.limit = opts.Limit t.fields = opts.Fields t.idsOnly = opts.IDsOnly t.sort = opts.Sort t.exprs = opts.Expressions t.refinements = opts.Refinements t.facetOpts = opts.Facets t.searchOffset = opts.Offset t.countAccuracy = opts.CountAccuracy } return t }
[ "func", "(", "x", "*", "Index", ")", "Search", "(", "c", "context", ".", "Context", ",", "query", "string", ",", "opts", "*", "SearchOptions", ")", "*", "Iterator", "{", "t", ":=", "&", "Iterator", "{", "c", ":", "c", ",", "index", ":", "x", ",", "searchQuery", ":", "query", ",", "more", ":", "moreSearch", ",", "}", "\n", "if", "opts", "!=", "nil", "{", "if", "opts", ".", "Cursor", "!=", "\"\"", "{", "if", "opts", ".", "Offset", "!=", "0", "{", "return", "errIter", "(", "\"at most one of Cursor and Offset may be specified\"", ")", "\n", "}", "\n", "t", ".", "searchCursor", "=", "proto", ".", "String", "(", "string", "(", "opts", ".", "Cursor", ")", ")", "\n", "}", "\n", "t", ".", "limit", "=", "opts", ".", "Limit", "\n", "t", ".", "fields", "=", "opts", ".", "Fields", "\n", "t", ".", "idsOnly", "=", "opts", ".", "IDsOnly", "\n", "t", ".", "sort", "=", "opts", ".", "Sort", "\n", "t", ".", "exprs", "=", "opts", ".", "Expressions", "\n", "t", ".", "refinements", "=", "opts", ".", "Refinements", "\n", "t", ".", "facetOpts", "=", "opts", ".", "Facets", "\n", "t", ".", "searchOffset", "=", "opts", ".", "Offset", "\n", "t", ".", "countAccuracy", "=", "opts", ".", "CountAccuracy", "\n", "}", "\n", "return", "t", "\n", "}" ]
// Search searches the index for the given query.
[ "Search", "searches", "the", "index", "for", "the", "given", "query", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/search/search.go#L351-L376
test
golang/appengine
search/search.go
fetchMore
func (t *Iterator) fetchMore() { if t.err == nil && len(t.listRes)+len(t.searchRes) == 0 && t.more != nil { t.err = t.more(t) } }
go
func (t *Iterator) fetchMore() { if t.err == nil && len(t.listRes)+len(t.searchRes) == 0 && t.more != nil { t.err = t.more(t) } }
[ "func", "(", "t", "*", "Iterator", ")", "fetchMore", "(", ")", "{", "if", "t", ".", "err", "==", "nil", "&&", "len", "(", "t", ".", "listRes", ")", "+", "len", "(", "t", ".", "searchRes", ")", "==", "0", "&&", "t", ".", "more", "!=", "nil", "{", "t", ".", "err", "=", "t", ".", "more", "(", "t", ")", "\n", "}", "\n", "}" ]
// fetchMore retrieves more results, if there are no errors or pending results.
[ "fetchMore", "retrieves", "more", "results", "if", "there", "are", "no", "errors", "or", "pending", "results", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/search/search.go#L826-L830
test
golang/appengine
search/search.go
Next
func (t *Iterator) Next(dst interface{}) (string, error) { t.fetchMore() if t.err != nil { return "", t.err } var doc *pb.Document var exprs []*pb.Field switch { case len(t.listRes) != 0: doc = t.listRes[0] t.listRes = t.listRes[1:] case len(t.searchRes) != 0: doc = t.searchRes[0].Document exprs = t.searchRes[0].Expression t.searchCursor = t.searchRes[0].Cursor t.searchRes = t.searchRes[1:] default: return "", Done } if doc == nil { return "", errors.New("search: internal error: no document returned") } if !t.idsOnly && dst != nil { if err := loadDoc(dst, doc, exprs); err != nil { return "", err } } return doc.GetId(), nil }
go
func (t *Iterator) Next(dst interface{}) (string, error) { t.fetchMore() if t.err != nil { return "", t.err } var doc *pb.Document var exprs []*pb.Field switch { case len(t.listRes) != 0: doc = t.listRes[0] t.listRes = t.listRes[1:] case len(t.searchRes) != 0: doc = t.searchRes[0].Document exprs = t.searchRes[0].Expression t.searchCursor = t.searchRes[0].Cursor t.searchRes = t.searchRes[1:] default: return "", Done } if doc == nil { return "", errors.New("search: internal error: no document returned") } if !t.idsOnly && dst != nil { if err := loadDoc(dst, doc, exprs); err != nil { return "", err } } return doc.GetId(), nil }
[ "func", "(", "t", "*", "Iterator", ")", "Next", "(", "dst", "interface", "{", "}", ")", "(", "string", ",", "error", ")", "{", "t", ".", "fetchMore", "(", ")", "\n", "if", "t", ".", "err", "!=", "nil", "{", "return", "\"\"", ",", "t", ".", "err", "\n", "}", "\n", "var", "doc", "*", "pb", ".", "Document", "\n", "var", "exprs", "[", "]", "*", "pb", ".", "Field", "\n", "switch", "{", "case", "len", "(", "t", ".", "listRes", ")", "!=", "0", ":", "doc", "=", "t", ".", "listRes", "[", "0", "]", "\n", "t", ".", "listRes", "=", "t", ".", "listRes", "[", "1", ":", "]", "\n", "case", "len", "(", "t", ".", "searchRes", ")", "!=", "0", ":", "doc", "=", "t", ".", "searchRes", "[", "0", "]", ".", "Document", "\n", "exprs", "=", "t", ".", "searchRes", "[", "0", "]", ".", "Expression", "\n", "t", ".", "searchCursor", "=", "t", ".", "searchRes", "[", "0", "]", ".", "Cursor", "\n", "t", ".", "searchRes", "=", "t", ".", "searchRes", "[", "1", ":", "]", "\n", "default", ":", "return", "\"\"", ",", "Done", "\n", "}", "\n", "if", "doc", "==", "nil", "{", "return", "\"\"", ",", "errors", ".", "New", "(", "\"search: internal error: no document returned\"", ")", "\n", "}", "\n", "if", "!", "t", ".", "idsOnly", "&&", "dst", "!=", "nil", "{", "if", "err", ":=", "loadDoc", "(", "dst", ",", "doc", ",", "exprs", ")", ";", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "}", "\n", "return", "doc", ".", "GetId", "(", ")", ",", "nil", "\n", "}" ]
// Next returns the ID of the next result. When there are no more results, // Done is returned as the error. // // dst must be a non-nil struct pointer, implement the FieldLoadSaver // interface, or be a nil interface value. If a non-nil dst is provided, it // will be filled with the indexed fields. dst is ignored if this iterator was // created with an IDsOnly option.
[ "Next", "returns", "the", "ID", "of", "the", "next", "result", ".", "When", "there", "are", "no", "more", "results", "Done", "is", "returned", "as", "the", "error", ".", "dst", "must", "be", "a", "non", "-", "nil", "struct", "pointer", "implement", "the", "FieldLoadSaver", "interface", "or", "be", "a", "nil", "interface", "value", ".", "If", "a", "non", "-", "nil", "dst", "is", "provided", "it", "will", "be", "filled", "with", "the", "indexed", "fields", ".", "dst", "is", "ignored", "if", "this", "iterator", "was", "created", "with", "an", "IDsOnly", "option", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/search/search.go#L839-L868
test
golang/appengine
search/search.go
Facets
func (t *Iterator) Facets() ([][]FacetResult, error) { t.fetchMore() if t.err != nil && t.err != Done { return nil, t.err } var facets [][]FacetResult for _, f := range t.facetRes { fres := make([]FacetResult, 0, len(f.Value)) for _, v := range f.Value { ref := v.Refinement facet := FacetResult{ Facet: Facet{Name: ref.GetName()}, Count: int(v.GetCount()), } if ref.Value != nil { facet.Value = Atom(*ref.Value) } else { facet.Value = protoToRange(ref.Range) } fres = append(fres, facet) } facets = append(facets, fres) } return facets, nil }
go
func (t *Iterator) Facets() ([][]FacetResult, error) { t.fetchMore() if t.err != nil && t.err != Done { return nil, t.err } var facets [][]FacetResult for _, f := range t.facetRes { fres := make([]FacetResult, 0, len(f.Value)) for _, v := range f.Value { ref := v.Refinement facet := FacetResult{ Facet: Facet{Name: ref.GetName()}, Count: int(v.GetCount()), } if ref.Value != nil { facet.Value = Atom(*ref.Value) } else { facet.Value = protoToRange(ref.Range) } fres = append(fres, facet) } facets = append(facets, fres) } return facets, nil }
[ "func", "(", "t", "*", "Iterator", ")", "Facets", "(", ")", "(", "[", "]", "[", "]", "FacetResult", ",", "error", ")", "{", "t", ".", "fetchMore", "(", ")", "\n", "if", "t", ".", "err", "!=", "nil", "&&", "t", ".", "err", "!=", "Done", "{", "return", "nil", ",", "t", ".", "err", "\n", "}", "\n", "var", "facets", "[", "]", "[", "]", "FacetResult", "\n", "for", "_", ",", "f", ":=", "range", "t", ".", "facetRes", "{", "fres", ":=", "make", "(", "[", "]", "FacetResult", ",", "0", ",", "len", "(", "f", ".", "Value", ")", ")", "\n", "for", "_", ",", "v", ":=", "range", "f", ".", "Value", "{", "ref", ":=", "v", ".", "Refinement", "\n", "facet", ":=", "FacetResult", "{", "Facet", ":", "Facet", "{", "Name", ":", "ref", ".", "GetName", "(", ")", "}", ",", "Count", ":", "int", "(", "v", ".", "GetCount", "(", ")", ")", ",", "}", "\n", "if", "ref", ".", "Value", "!=", "nil", "{", "facet", ".", "Value", "=", "Atom", "(", "*", "ref", ".", "Value", ")", "\n", "}", "else", "{", "facet", ".", "Value", "=", "protoToRange", "(", "ref", ".", "Range", ")", "\n", "}", "\n", "fres", "=", "append", "(", "fres", ",", "facet", ")", "\n", "}", "\n", "facets", "=", "append", "(", "facets", ",", "fres", ")", "\n", "}", "\n", "return", "facets", ",", "nil", "\n", "}" ]
// Facets returns the facets found within the search results, if any facets // were requested in the SearchOptions.
[ "Facets", "returns", "the", "facets", "found", "within", "the", "search", "results", "if", "any", "facets", "were", "requested", "in", "the", "SearchOptions", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/search/search.go#L884-L909
test
golang/appengine
file/file.go
DefaultBucketName
func DefaultBucketName(c context.Context) (string, error) { req := &aipb.GetDefaultGcsBucketNameRequest{} res := &aipb.GetDefaultGcsBucketNameResponse{} err := internal.Call(c, "app_identity_service", "GetDefaultGcsBucketName", req, res) if err != nil { return "", fmt.Errorf("file: no default bucket name returned in RPC response: %v", res) } return res.GetDefaultGcsBucketName(), nil }
go
func DefaultBucketName(c context.Context) (string, error) { req := &aipb.GetDefaultGcsBucketNameRequest{} res := &aipb.GetDefaultGcsBucketNameResponse{} err := internal.Call(c, "app_identity_service", "GetDefaultGcsBucketName", req, res) if err != nil { return "", fmt.Errorf("file: no default bucket name returned in RPC response: %v", res) } return res.GetDefaultGcsBucketName(), nil }
[ "func", "DefaultBucketName", "(", "c", "context", ".", "Context", ")", "(", "string", ",", "error", ")", "{", "req", ":=", "&", "aipb", ".", "GetDefaultGcsBucketNameRequest", "{", "}", "\n", "res", ":=", "&", "aipb", ".", "GetDefaultGcsBucketNameResponse", "{", "}", "\n", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"app_identity_service\"", ",", "\"GetDefaultGcsBucketName\"", ",", "req", ",", "res", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"file: no default bucket name returned in RPC response: %v\"", ",", "res", ")", "\n", "}", "\n", "return", "res", ".", "GetDefaultGcsBucketName", "(", ")", ",", "nil", "\n", "}" ]
// DefaultBucketName returns the name of this application's // default Google Cloud Storage bucket.
[ "DefaultBucketName", "returns", "the", "name", "of", "this", "application", "s", "default", "Google", "Cloud", "Storage", "bucket", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/file/file.go#L19-L28
test
golang/appengine
datastore/key.go
valid
func (k *Key) valid() bool { if k == nil { return false } for ; k != nil; k = k.parent { if k.kind == "" || k.appID == "" { return false } if k.stringID != "" && k.intID != 0 { return false } if k.parent != nil { if k.parent.Incomplete() { return false } if k.parent.appID != k.appID || k.parent.namespace != k.namespace { return false } } } return true }
go
func (k *Key) valid() bool { if k == nil { return false } for ; k != nil; k = k.parent { if k.kind == "" || k.appID == "" { return false } if k.stringID != "" && k.intID != 0 { return false } if k.parent != nil { if k.parent.Incomplete() { return false } if k.parent.appID != k.appID || k.parent.namespace != k.namespace { return false } } } return true }
[ "func", "(", "k", "*", "Key", ")", "valid", "(", ")", "bool", "{", "if", "k", "==", "nil", "{", "return", "false", "\n", "}", "\n", "for", ";", "k", "!=", "nil", ";", "k", "=", "k", ".", "parent", "{", "if", "k", ".", "kind", "==", "\"\"", "||", "k", ".", "appID", "==", "\"\"", "{", "return", "false", "\n", "}", "\n", "if", "k", ".", "stringID", "!=", "\"\"", "&&", "k", ".", "intID", "!=", "0", "{", "return", "false", "\n", "}", "\n", "if", "k", ".", "parent", "!=", "nil", "{", "if", "k", ".", "parent", ".", "Incomplete", "(", ")", "{", "return", "false", "\n", "}", "\n", "if", "k", ".", "parent", ".", "appID", "!=", "k", ".", "appID", "||", "k", ".", "parent", ".", "namespace", "!=", "k", ".", "namespace", "{", "return", "false", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// valid returns whether the key is valid.
[ "valid", "returns", "whether", "the", "key", "is", "valid", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/key.go#L91-L112
test
golang/appengine
datastore/key.go
Equal
func (k *Key) Equal(o *Key) bool { for k != nil && o != nil { if k.kind != o.kind || k.stringID != o.stringID || k.intID != o.intID || k.appID != o.appID || k.namespace != o.namespace { return false } k, o = k.parent, o.parent } return k == o }
go
func (k *Key) Equal(o *Key) bool { for k != nil && o != nil { if k.kind != o.kind || k.stringID != o.stringID || k.intID != o.intID || k.appID != o.appID || k.namespace != o.namespace { return false } k, o = k.parent, o.parent } return k == o }
[ "func", "(", "k", "*", "Key", ")", "Equal", "(", "o", "*", "Key", ")", "bool", "{", "for", "k", "!=", "nil", "&&", "o", "!=", "nil", "{", "if", "k", ".", "kind", "!=", "o", ".", "kind", "||", "k", ".", "stringID", "!=", "o", ".", "stringID", "||", "k", ".", "intID", "!=", "o", ".", "intID", "||", "k", ".", "appID", "!=", "o", ".", "appID", "||", "k", ".", "namespace", "!=", "o", ".", "namespace", "{", "return", "false", "\n", "}", "\n", "k", ",", "o", "=", "k", ".", "parent", ",", "o", ".", "parent", "\n", "}", "\n", "return", "k", "==", "o", "\n", "}" ]
// Equal returns whether two keys are equal.
[ "Equal", "returns", "whether", "two", "keys", "are", "equal", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/key.go#L115-L123
test
golang/appengine
datastore/key.go
root
func (k *Key) root() *Key { for k.parent != nil { k = k.parent } return k }
go
func (k *Key) root() *Key { for k.parent != nil { k = k.parent } return k }
[ "func", "(", "k", "*", "Key", ")", "root", "(", ")", "*", "Key", "{", "for", "k", ".", "parent", "!=", "nil", "{", "k", "=", "k", ".", "parent", "\n", "}", "\n", "return", "k", "\n", "}" ]
// root returns the furthest ancestor of a key, which may be itself.
[ "root", "returns", "the", "furthest", "ancestor", "of", "a", "key", "which", "may", "be", "itself", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/key.go#L126-L131
test
golang/appengine
datastore/key.go
marshal
func (k *Key) marshal(b *bytes.Buffer) { if k.parent != nil { k.parent.marshal(b) } b.WriteByte('/') b.WriteString(k.kind) b.WriteByte(',') if k.stringID != "" { b.WriteString(k.stringID) } else { b.WriteString(strconv.FormatInt(k.intID, 10)) } }
go
func (k *Key) marshal(b *bytes.Buffer) { if k.parent != nil { k.parent.marshal(b) } b.WriteByte('/') b.WriteString(k.kind) b.WriteByte(',') if k.stringID != "" { b.WriteString(k.stringID) } else { b.WriteString(strconv.FormatInt(k.intID, 10)) } }
[ "func", "(", "k", "*", "Key", ")", "marshal", "(", "b", "*", "bytes", ".", "Buffer", ")", "{", "if", "k", ".", "parent", "!=", "nil", "{", "k", ".", "parent", ".", "marshal", "(", "b", ")", "\n", "}", "\n", "b", ".", "WriteByte", "(", "'/'", ")", "\n", "b", ".", "WriteString", "(", "k", ".", "kind", ")", "\n", "b", ".", "WriteByte", "(", "','", ")", "\n", "if", "k", ".", "stringID", "!=", "\"\"", "{", "b", ".", "WriteString", "(", "k", ".", "stringID", ")", "\n", "}", "else", "{", "b", ".", "WriteString", "(", "strconv", ".", "FormatInt", "(", "k", ".", "intID", ",", "10", ")", ")", "\n", "}", "\n", "}" ]
// marshal marshals the key's string representation to the buffer.
[ "marshal", "marshals", "the", "key", "s", "string", "representation", "to", "the", "buffer", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/key.go#L134-L146
test
golang/appengine
datastore/key.go
String
func (k *Key) String() string { if k == nil { return "" } b := bytes.NewBuffer(make([]byte, 0, 512)) k.marshal(b) return b.String() }
go
func (k *Key) String() string { if k == nil { return "" } b := bytes.NewBuffer(make([]byte, 0, 512)) k.marshal(b) return b.String() }
[ "func", "(", "k", "*", "Key", ")", "String", "(", ")", "string", "{", "if", "k", "==", "nil", "{", "return", "\"\"", "\n", "}", "\n", "b", ":=", "bytes", ".", "NewBuffer", "(", "make", "(", "[", "]", "byte", ",", "0", ",", "512", ")", ")", "\n", "k", ".", "marshal", "(", "b", ")", "\n", "return", "b", ".", "String", "(", ")", "\n", "}" ]
// String returns a string representation of the key.
[ "String", "returns", "a", "string", "representation", "of", "the", "key", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/key.go#L149-L156
test
golang/appengine
datastore/key.go
Encode
func (k *Key) Encode() string { ref := keyToProto("", k) b, err := proto.Marshal(ref) if err != nil { panic(err) } // Trailing padding is stripped. return strings.TrimRight(base64.URLEncoding.EncodeToString(b), "=") }
go
func (k *Key) Encode() string { ref := keyToProto("", k) b, err := proto.Marshal(ref) if err != nil { panic(err) } // Trailing padding is stripped. return strings.TrimRight(base64.URLEncoding.EncodeToString(b), "=") }
[ "func", "(", "k", "*", "Key", ")", "Encode", "(", ")", "string", "{", "ref", ":=", "keyToProto", "(", "\"\"", ",", "k", ")", "\n", "b", ",", "err", ":=", "proto", ".", "Marshal", "(", "ref", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "err", ")", "\n", "}", "\n", "return", "strings", ".", "TrimRight", "(", "base64", ".", "URLEncoding", ".", "EncodeToString", "(", "b", ")", ",", "\"=\"", ")", "\n", "}" ]
// Encode returns an opaque representation of the key // suitable for use in HTML and URLs. // This is compatible with the Python and Java runtimes.
[ "Encode", "returns", "an", "opaque", "representation", "of", "the", "key", "suitable", "for", "use", "in", "HTML", "and", "URLs", ".", "This", "is", "compatible", "with", "the", "Python", "and", "Java", "runtimes", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/key.go#L231-L241
test
golang/appengine
datastore/key.go
DecodeKey
func DecodeKey(encoded string) (*Key, error) { // Re-add padding. if m := len(encoded) % 4; m != 0 { encoded += strings.Repeat("=", 4-m) } b, err := base64.URLEncoding.DecodeString(encoded) if err != nil { return nil, err } ref := new(pb.Reference) if err := proto.Unmarshal(b, ref); err != nil { return nil, err } return protoToKey(ref) }
go
func DecodeKey(encoded string) (*Key, error) { // Re-add padding. if m := len(encoded) % 4; m != 0 { encoded += strings.Repeat("=", 4-m) } b, err := base64.URLEncoding.DecodeString(encoded) if err != nil { return nil, err } ref := new(pb.Reference) if err := proto.Unmarshal(b, ref); err != nil { return nil, err } return protoToKey(ref) }
[ "func", "DecodeKey", "(", "encoded", "string", ")", "(", "*", "Key", ",", "error", ")", "{", "if", "m", ":=", "len", "(", "encoded", ")", "%", "4", ";", "m", "!=", "0", "{", "encoded", "+=", "strings", ".", "Repeat", "(", "\"=\"", ",", "4", "-", "m", ")", "\n", "}", "\n", "b", ",", "err", ":=", "base64", ".", "URLEncoding", ".", "DecodeString", "(", "encoded", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "ref", ":=", "new", "(", "pb", ".", "Reference", ")", "\n", "if", "err", ":=", "proto", ".", "Unmarshal", "(", "b", ",", "ref", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "protoToKey", "(", "ref", ")", "\n", "}" ]
// DecodeKey decodes a key from the opaque representation returned by Encode.
[ "DecodeKey", "decodes", "a", "key", "from", "the", "opaque", "representation", "returned", "by", "Encode", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/key.go#L244-L261
test
golang/appengine
datastore/key.go
NewIncompleteKey
func NewIncompleteKey(c context.Context, kind string, parent *Key) *Key { return NewKey(c, kind, "", 0, parent) }
go
func NewIncompleteKey(c context.Context, kind string, parent *Key) *Key { return NewKey(c, kind, "", 0, parent) }
[ "func", "NewIncompleteKey", "(", "c", "context", ".", "Context", ",", "kind", "string", ",", "parent", "*", "Key", ")", "*", "Key", "{", "return", "NewKey", "(", "c", ",", "kind", ",", "\"\"", ",", "0", ",", "parent", ")", "\n", "}" ]
// NewIncompleteKey creates a new incomplete key. // kind cannot be empty.
[ "NewIncompleteKey", "creates", "a", "new", "incomplete", "key", ".", "kind", "cannot", "be", "empty", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/key.go#L265-L267
test
golang/appengine
datastore/key.go
NewKey
func NewKey(c context.Context, kind, stringID string, intID int64, parent *Key) *Key { // If there's a parent key, use its namespace. // Otherwise, use any namespace attached to the context. var namespace string if parent != nil { namespace = parent.namespace } else { namespace = internal.NamespaceFromContext(c) } return &Key{ kind: kind, stringID: stringID, intID: intID, parent: parent, appID: internal.FullyQualifiedAppID(c), namespace: namespace, } }
go
func NewKey(c context.Context, kind, stringID string, intID int64, parent *Key) *Key { // If there's a parent key, use its namespace. // Otherwise, use any namespace attached to the context. var namespace string if parent != nil { namespace = parent.namespace } else { namespace = internal.NamespaceFromContext(c) } return &Key{ kind: kind, stringID: stringID, intID: intID, parent: parent, appID: internal.FullyQualifiedAppID(c), namespace: namespace, } }
[ "func", "NewKey", "(", "c", "context", ".", "Context", ",", "kind", ",", "stringID", "string", ",", "intID", "int64", ",", "parent", "*", "Key", ")", "*", "Key", "{", "var", "namespace", "string", "\n", "if", "parent", "!=", "nil", "{", "namespace", "=", "parent", ".", "namespace", "\n", "}", "else", "{", "namespace", "=", "internal", ".", "NamespaceFromContext", "(", "c", ")", "\n", "}", "\n", "return", "&", "Key", "{", "kind", ":", "kind", ",", "stringID", ":", "stringID", ",", "intID", ":", "intID", ",", "parent", ":", "parent", ",", "appID", ":", "internal", ".", "FullyQualifiedAppID", "(", "c", ")", ",", "namespace", ":", "namespace", ",", "}", "\n", "}" ]
// NewKey creates a new key. // kind cannot be empty. // Either one or both of stringID and intID must be zero. If both are zero, // the key returned is incomplete. // parent must either be a complete key or nil.
[ "NewKey", "creates", "a", "new", "key", ".", "kind", "cannot", "be", "empty", ".", "Either", "one", "or", "both", "of", "stringID", "and", "intID", "must", "be", "zero", ".", "If", "both", "are", "zero", "the", "key", "returned", "is", "incomplete", ".", "parent", "must", "either", "be", "a", "complete", "key", "or", "nil", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/key.go#L274-L292
test
golang/appengine
datastore/key.go
AllocateIDs
func AllocateIDs(c context.Context, kind string, parent *Key, n int) (low, high int64, err error) { if kind == "" { return 0, 0, errors.New("datastore: AllocateIDs given an empty kind") } if n < 0 { return 0, 0, fmt.Errorf("datastore: AllocateIDs given a negative count: %d", n) } if n == 0 { return 0, 0, nil } req := &pb.AllocateIdsRequest{ ModelKey: keyToProto("", NewIncompleteKey(c, kind, parent)), Size: proto.Int64(int64(n)), } res := &pb.AllocateIdsResponse{} if err := internal.Call(c, "datastore_v3", "AllocateIds", req, res); err != nil { return 0, 0, err } // The protobuf is inclusive at both ends. Idiomatic Go (e.g. slices, for loops) // is inclusive at the low end and exclusive at the high end, so we add 1. low = res.GetStart() high = res.GetEnd() + 1 if low+int64(n) != high { return 0, 0, fmt.Errorf("datastore: internal error: could not allocate %d IDs", n) } return low, high, nil }
go
func AllocateIDs(c context.Context, kind string, parent *Key, n int) (low, high int64, err error) { if kind == "" { return 0, 0, errors.New("datastore: AllocateIDs given an empty kind") } if n < 0 { return 0, 0, fmt.Errorf("datastore: AllocateIDs given a negative count: %d", n) } if n == 0 { return 0, 0, nil } req := &pb.AllocateIdsRequest{ ModelKey: keyToProto("", NewIncompleteKey(c, kind, parent)), Size: proto.Int64(int64(n)), } res := &pb.AllocateIdsResponse{} if err := internal.Call(c, "datastore_v3", "AllocateIds", req, res); err != nil { return 0, 0, err } // The protobuf is inclusive at both ends. Idiomatic Go (e.g. slices, for loops) // is inclusive at the low end and exclusive at the high end, so we add 1. low = res.GetStart() high = res.GetEnd() + 1 if low+int64(n) != high { return 0, 0, fmt.Errorf("datastore: internal error: could not allocate %d IDs", n) } return low, high, nil }
[ "func", "AllocateIDs", "(", "c", "context", ".", "Context", ",", "kind", "string", ",", "parent", "*", "Key", ",", "n", "int", ")", "(", "low", ",", "high", "int64", ",", "err", "error", ")", "{", "if", "kind", "==", "\"\"", "{", "return", "0", ",", "0", ",", "errors", ".", "New", "(", "\"datastore: AllocateIDs given an empty kind\"", ")", "\n", "}", "\n", "if", "n", "<", "0", "{", "return", "0", ",", "0", ",", "fmt", ".", "Errorf", "(", "\"datastore: AllocateIDs given a negative count: %d\"", ",", "n", ")", "\n", "}", "\n", "if", "n", "==", "0", "{", "return", "0", ",", "0", ",", "nil", "\n", "}", "\n", "req", ":=", "&", "pb", ".", "AllocateIdsRequest", "{", "ModelKey", ":", "keyToProto", "(", "\"\"", ",", "NewIncompleteKey", "(", "c", ",", "kind", ",", "parent", ")", ")", ",", "Size", ":", "proto", ".", "Int64", "(", "int64", "(", "n", ")", ")", ",", "}", "\n", "res", ":=", "&", "pb", ".", "AllocateIdsResponse", "{", "}", "\n", "if", "err", ":=", "internal", ".", "Call", "(", "c", ",", "\"datastore_v3\"", ",", "\"AllocateIds\"", ",", "req", ",", "res", ")", ";", "err", "!=", "nil", "{", "return", "0", ",", "0", ",", "err", "\n", "}", "\n", "low", "=", "res", ".", "GetStart", "(", ")", "\n", "high", "=", "res", ".", "GetEnd", "(", ")", "+", "1", "\n", "if", "low", "+", "int64", "(", "n", ")", "!=", "high", "{", "return", "0", ",", "0", ",", "fmt", ".", "Errorf", "(", "\"datastore: internal error: could not allocate %d IDs\"", ",", "n", ")", "\n", "}", "\n", "return", "low", ",", "high", ",", "nil", "\n", "}" ]
// AllocateIDs returns a range of n integer IDs with the given kind and parent // combination. kind cannot be empty; parent may be nil. The IDs in the range // returned will not be used by the datastore's automatic ID sequence generator // and may be used with NewKey without conflict. // // The range is inclusive at the low end and exclusive at the high end. In // other words, valid intIDs x satisfy low <= x && x < high. // // If no error is returned, low + n == high.
[ "AllocateIDs", "returns", "a", "range", "of", "n", "integer", "IDs", "with", "the", "given", "kind", "and", "parent", "combination", ".", "kind", "cannot", "be", "empty", ";", "parent", "may", "be", "nil", ".", "The", "IDs", "in", "the", "range", "returned", "will", "not", "be", "used", "by", "the", "datastore", "s", "automatic", "ID", "sequence", "generator", "and", "may", "be", "used", "with", "NewKey", "without", "conflict", ".", "The", "range", "is", "inclusive", "at", "the", "low", "end", "and", "exclusive", "at", "the", "high", "end", ".", "In", "other", "words", "valid", "intIDs", "x", "satisfy", "low", "<", "=", "x", "&&", "x", "<", "high", ".", "If", "no", "error", "is", "returned", "low", "+", "n", "==", "high", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/datastore/key.go#L303-L329
test
golang/appengine
errors.go
IsOverQuota
func IsOverQuota(err error) bool { callErr, ok := err.(*internal.CallError) return ok && callErr.Code == 4 }
go
func IsOverQuota(err error) bool { callErr, ok := err.(*internal.CallError) return ok && callErr.Code == 4 }
[ "func", "IsOverQuota", "(", "err", "error", ")", "bool", "{", "callErr", ",", "ok", ":=", "err", ".", "(", "*", "internal", ".", "CallError", ")", "\n", "return", "ok", "&&", "callErr", ".", "Code", "==", "4", "\n", "}" ]
// IsOverQuota reports whether err represents an API call failure // due to insufficient available quota.
[ "IsOverQuota", "reports", "whether", "err", "represents", "an", "API", "call", "failure", "due", "to", "insufficient", "available", "quota", "." ]
54a98f90d1c46b7731eb8fb305d2a321c30ef610
https://github.com/golang/appengine/blob/54a98f90d1c46b7731eb8fb305d2a321c30ef610/errors.go#L17-L20
test