repo
stringlengths 5
54
| path
stringlengths 4
155
| func_name
stringlengths 1
118
| original_string
stringlengths 52
85.5k
| language
stringclasses 1
value | code
stringlengths 52
85.5k
| code_tokens
list | docstring
stringlengths 6
2.61k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 85
252
| partition
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
perkeep/perkeep
|
pkg/sorted/mysql/mysqlkv.go
|
CreateDB
|
func CreateDB(db *sql.DB, dbname string) error {
if dbname == "" {
return errors.New("can not create database: database name is missing")
}
if _, err := db.Exec(fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s", dbname)); err != nil {
return fmt.Errorf("error creating database %v: %v", dbname, err)
}
return nil
}
|
go
|
func CreateDB(db *sql.DB, dbname string) error {
if dbname == "" {
return errors.New("can not create database: database name is missing")
}
if _, err := db.Exec(fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s", dbname)); err != nil {
return fmt.Errorf("error creating database %v: %v", dbname, err)
}
return nil
}
|
[
"func",
"CreateDB",
"(",
"db",
"*",
"sql",
".",
"DB",
",",
"dbname",
"string",
")",
"error",
"{",
"if",
"dbname",
"==",
"\"",
"\"",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"err",
":=",
"db",
".",
"Exec",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"dbname",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"dbname",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// CreateDB creates the named database if it does not already exist.
|
[
"CreateDB",
"creates",
"the",
"named",
"database",
"if",
"it",
"does",
"not",
"already",
"exist",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/sorted/mysql/mysqlkv.go#L164-L172
|
train
|
perkeep/perkeep
|
pkg/sorted/mysql/mysqlkv.go
|
Close
|
func (kv *keyValue) Close() error {
dbsmu.Lock()
defer dbsmu.Unlock()
delete(dbs, kv.dsn)
return kv.DB.Close()
}
|
go
|
func (kv *keyValue) Close() error {
dbsmu.Lock()
defer dbsmu.Unlock()
delete(dbs, kv.dsn)
return kv.DB.Close()
}
|
[
"func",
"(",
"kv",
"*",
"keyValue",
")",
"Close",
"(",
")",
"error",
"{",
"dbsmu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"dbsmu",
".",
"Unlock",
"(",
")",
"\n",
"delete",
"(",
"dbs",
",",
"kv",
".",
"dsn",
")",
"\n",
"return",
"kv",
".",
"DB",
".",
"Close",
"(",
")",
"\n",
"}"
] |
// Close overrides KeyValue.Close because we need to remove the DB from the pool
// when closing.
|
[
"Close",
"overrides",
"KeyValue",
".",
"Close",
"because",
"we",
"need",
"to",
"remove",
"the",
"DB",
"from",
"the",
"pool",
"when",
"closing",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/sorted/mysql/mysqlkv.go#L223-L228
|
train
|
perkeep/perkeep
|
website/pk-web/email.go
|
emailOnTimeout
|
func emailOnTimeout(fnName string, d time.Duration, fn func() error) error {
c := make(chan error, 1)
go func() {
c <- fn()
}()
select {
case <-time.After(d):
log.Printf("timeout for %s, sending e-mail about it", fnName)
m := mailGun.NewMessage(
"noreply@perkeep.org",
"timeout for docker on pk-web",
"Because "+fnName+" is stuck.",
"mathieu.lonjaret@gmail.com",
)
if _, _, err := mailGun.Send(m); err != nil {
return fmt.Errorf("failed to send docker restart e-mail: %v", err)
}
return nil
case err := <-c:
return err
}
}
|
go
|
func emailOnTimeout(fnName string, d time.Duration, fn func() error) error {
c := make(chan error, 1)
go func() {
c <- fn()
}()
select {
case <-time.After(d):
log.Printf("timeout for %s, sending e-mail about it", fnName)
m := mailGun.NewMessage(
"noreply@perkeep.org",
"timeout for docker on pk-web",
"Because "+fnName+" is stuck.",
"mathieu.lonjaret@gmail.com",
)
if _, _, err := mailGun.Send(m); err != nil {
return fmt.Errorf("failed to send docker restart e-mail: %v", err)
}
return nil
case err := <-c:
return err
}
}
|
[
"func",
"emailOnTimeout",
"(",
"fnName",
"string",
",",
"d",
"time",
".",
"Duration",
",",
"fn",
"func",
"(",
")",
"error",
")",
"error",
"{",
"c",
":=",
"make",
"(",
"chan",
"error",
",",
"1",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"c",
"<-",
"fn",
"(",
")",
"\n",
"}",
"(",
")",
"\n",
"select",
"{",
"case",
"<-",
"time",
".",
"After",
"(",
"d",
")",
":",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"fnName",
")",
"\n",
"m",
":=",
"mailGun",
".",
"NewMessage",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"+",
"fnName",
"+",
"\"",
"\"",
",",
"\"",
"\"",
",",
")",
"\n",
"if",
"_",
",",
"_",
",",
"err",
":=",
"mailGun",
".",
"Send",
"(",
"m",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"case",
"err",
":=",
"<-",
"c",
":",
"return",
"err",
"\n",
"}",
"\n",
"}"
] |
// emailOnTimeout runs fn in a goroutine. If fn is not done after d,
// a message about fnName is logged, and an e-mail about it is sent.
|
[
"emailOnTimeout",
"runs",
"fn",
"in",
"a",
"goroutine",
".",
"If",
"fn",
"is",
"not",
"done",
"after",
"d",
"a",
"message",
"about",
"fnName",
"is",
"logged",
"and",
"an",
"e",
"-",
"mail",
"about",
"it",
"is",
"sent",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/website/pk-web/email.go#L207-L228
|
train
|
perkeep/perkeep
|
pkg/blobserver/files/files.go
|
u32
|
func u32(n int64) uint32 {
if n < 0 || n > math.MaxUint32 {
panic("bad size " + fmt.Sprint(n))
}
return uint32(n)
}
|
go
|
func u32(n int64) uint32 {
if n < 0 || n > math.MaxUint32 {
panic("bad size " + fmt.Sprint(n))
}
return uint32(n)
}
|
[
"func",
"u32",
"(",
"n",
"int64",
")",
"uint32",
"{",
"if",
"n",
"<",
"0",
"||",
"n",
">",
"math",
".",
"MaxUint32",
"{",
"panic",
"(",
"\"",
"\"",
"+",
"fmt",
".",
"Sprint",
"(",
"n",
")",
")",
"\n",
"}",
"\n",
"return",
"uint32",
"(",
"n",
")",
"\n",
"}"
] |
// u32 converts n to an uint32, or panics if n is out of range
|
[
"u32",
"converts",
"n",
"to",
"an",
"uint32",
"or",
"panics",
"if",
"n",
"is",
"out",
"of",
"range"
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/files/files.go#L131-L136
|
train
|
perkeep/perkeep
|
pkg/blobserver/files/files.go
|
fetch
|
func (ds *Storage) fetch(ctx context.Context, br blob.Ref, offset, length int64) (rc io.ReadCloser, size uint32, err error) {
// TODO: use ctx, if the os package ever supports that.
fileName := ds.blobPath(br)
stat, err := ds.fs.Stat(fileName)
if os.IsNotExist(err) {
return nil, 0, os.ErrNotExist
}
size = u32(stat.Size())
file, err := ds.fs.Open(fileName)
if err != nil {
if os.IsNotExist(err) {
err = os.ErrNotExist
}
return nil, 0, err
}
// normal Fetch
if length < 0 && offset == 0 {
return file, size, nil
}
// SubFetch:
if offset < 0 || offset > stat.Size() {
if offset < 0 {
return nil, 0, blob.ErrNegativeSubFetch
}
return nil, 0, blob.ErrOutOfRangeOffsetSubFetch
}
if offset != 0 {
if at, err := file.Seek(offset, io.SeekStart); err != nil || at != offset {
file.Close()
return nil, 0, fmt.Errorf("localdisk: error seeking to %d: got %v, %v", offset, at, err)
}
}
return struct {
io.Reader
io.Closer
}{
Reader: io.LimitReader(file, length),
Closer: file,
}, 0 /* unused */, nil
}
|
go
|
func (ds *Storage) fetch(ctx context.Context, br blob.Ref, offset, length int64) (rc io.ReadCloser, size uint32, err error) {
// TODO: use ctx, if the os package ever supports that.
fileName := ds.blobPath(br)
stat, err := ds.fs.Stat(fileName)
if os.IsNotExist(err) {
return nil, 0, os.ErrNotExist
}
size = u32(stat.Size())
file, err := ds.fs.Open(fileName)
if err != nil {
if os.IsNotExist(err) {
err = os.ErrNotExist
}
return nil, 0, err
}
// normal Fetch
if length < 0 && offset == 0 {
return file, size, nil
}
// SubFetch:
if offset < 0 || offset > stat.Size() {
if offset < 0 {
return nil, 0, blob.ErrNegativeSubFetch
}
return nil, 0, blob.ErrOutOfRangeOffsetSubFetch
}
if offset != 0 {
if at, err := file.Seek(offset, io.SeekStart); err != nil || at != offset {
file.Close()
return nil, 0, fmt.Errorf("localdisk: error seeking to %d: got %v, %v", offset, at, err)
}
}
return struct {
io.Reader
io.Closer
}{
Reader: io.LimitReader(file, length),
Closer: file,
}, 0 /* unused */, nil
}
|
[
"func",
"(",
"ds",
"*",
"Storage",
")",
"fetch",
"(",
"ctx",
"context",
".",
"Context",
",",
"br",
"blob",
".",
"Ref",
",",
"offset",
",",
"length",
"int64",
")",
"(",
"rc",
"io",
".",
"ReadCloser",
",",
"size",
"uint32",
",",
"err",
"error",
")",
"{",
"// TODO: use ctx, if the os package ever supports that.",
"fileName",
":=",
"ds",
".",
"blobPath",
"(",
"br",
")",
"\n",
"stat",
",",
"err",
":=",
"ds",
".",
"fs",
".",
"Stat",
"(",
"fileName",
")",
"\n",
"if",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"nil",
",",
"0",
",",
"os",
".",
"ErrNotExist",
"\n",
"}",
"\n",
"size",
"=",
"u32",
"(",
"stat",
".",
"Size",
"(",
")",
")",
"\n",
"file",
",",
"err",
":=",
"ds",
".",
"fs",
".",
"Open",
"(",
"fileName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"err",
"=",
"os",
".",
"ErrNotExist",
"\n",
"}",
"\n",
"return",
"nil",
",",
"0",
",",
"err",
"\n",
"}",
"\n",
"// normal Fetch",
"if",
"length",
"<",
"0",
"&&",
"offset",
"==",
"0",
"{",
"return",
"file",
",",
"size",
",",
"nil",
"\n",
"}",
"\n",
"// SubFetch:",
"if",
"offset",
"<",
"0",
"||",
"offset",
">",
"stat",
".",
"Size",
"(",
")",
"{",
"if",
"offset",
"<",
"0",
"{",
"return",
"nil",
",",
"0",
",",
"blob",
".",
"ErrNegativeSubFetch",
"\n",
"}",
"\n",
"return",
"nil",
",",
"0",
",",
"blob",
".",
"ErrOutOfRangeOffsetSubFetch",
"\n",
"}",
"\n",
"if",
"offset",
"!=",
"0",
"{",
"if",
"at",
",",
"err",
":=",
"file",
".",
"Seek",
"(",
"offset",
",",
"io",
".",
"SeekStart",
")",
";",
"err",
"!=",
"nil",
"||",
"at",
"!=",
"offset",
"{",
"file",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"offset",
",",
"at",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"struct",
"{",
"io",
".",
"Reader",
"\n",
"io",
".",
"Closer",
"\n",
"}",
"{",
"Reader",
":",
"io",
".",
"LimitReader",
"(",
"file",
",",
"length",
")",
",",
"Closer",
":",
"file",
",",
"}",
",",
"0",
"/* unused */",
",",
"nil",
"\n",
"}"
] |
// length -1 means entire file
|
[
"length",
"-",
"1",
"means",
"entire",
"file"
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/files/files.go#L139-L178
|
train
|
perkeep/perkeep
|
pkg/client/config.go
|
AddFlags
|
func AddFlags() {
defaultPath := "/x/y/z/we're/in-a-test"
if !buildinfo.TestingLinked() {
defaultPath = osutil.UserClientConfigPath()
}
flag.StringVar(&flagServer, "server", "", "Perkeep server prefix. If blank, the default from the \"server\" field of "+defaultPath+" is used. Acceptable forms: https://you.example.com, example.com:1345 (https assumed), or http://you.example.com/alt-root")
osutil.AddSecretRingFlag()
}
|
go
|
func AddFlags() {
defaultPath := "/x/y/z/we're/in-a-test"
if !buildinfo.TestingLinked() {
defaultPath = osutil.UserClientConfigPath()
}
flag.StringVar(&flagServer, "server", "", "Perkeep server prefix. If blank, the default from the \"server\" field of "+defaultPath+" is used. Acceptable forms: https://you.example.com, example.com:1345 (https assumed), or http://you.example.com/alt-root")
osutil.AddSecretRingFlag()
}
|
[
"func",
"AddFlags",
"(",
")",
"{",
"defaultPath",
":=",
"\"",
"\"",
"\n",
"if",
"!",
"buildinfo",
".",
"TestingLinked",
"(",
")",
"{",
"defaultPath",
"=",
"osutil",
".",
"UserClientConfigPath",
"(",
")",
"\n",
"}",
"\n",
"flag",
".",
"StringVar",
"(",
"&",
"flagServer",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\\\"",
"\\\"",
"\"",
"+",
"defaultPath",
"+",
"\"",
"\"",
")",
"\n",
"osutil",
".",
"AddSecretRingFlag",
"(",
")",
"\n",
"}"
] |
// AddFlags registers the "server" and "secret-keyring" string flags.
|
[
"AddFlags",
"registers",
"the",
"server",
"and",
"secret",
"-",
"keyring",
"string",
"flags",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/config.go#L52-L59
|
train
|
perkeep/perkeep
|
pkg/client/config.go
|
parseConfig
|
func (c *Client) parseConfig() {
if android.OnAndroid() {
panic("parseConfig should never have been called on Android")
}
if configDisabled {
panic("parseConfig should never have been called with CAMLI_DISABLE_CLIENT_CONFIG_FILE set")
}
configPath := osutil.UserClientConfigPath()
if _, err := wkfs.Stat(configPath); os.IsNotExist(err) {
if c != nil && c.isSharePrefix {
return
}
errMsg := fmt.Sprintf("Client configuration file %v does not exist. See 'pk-put init' to generate it.", configPath)
if keyID := serverKeyId(); keyID != "" {
hint := fmt.Sprintf("\nThe key id %v was found in the server config %v, so you might want:\n'pk-put init -gpgkey %v'", keyID, osutil.UserServerConfigPath(), keyID)
errMsg += hint
}
log.Fatal(errMsg)
}
// TODO: instead of using jsonconfig, we could read the file,
// and unmarshal into the structs that we now have in
// pkg/types/clientconfig. But we'll have to add the old
// fields (before the name changes, and before the
// multi-servers change) to the structs as well for our
// graceful conversion/error messages to work.
conf, err := osutil.NewJSONConfigParser().ReadFile(configPath)
if err != nil {
log.Fatal(err.Error())
}
cfg := jsonconfig.Obj(conf)
if singleServerAuth := cfg.OptionalString("auth", ""); singleServerAuth != "" {
newConf, err := convertToMultiServers(cfg)
if err != nil {
log.Print(err)
} else {
cfg = newConf
}
}
config = &clientconfig.Config{
Identity: cfg.OptionalString("identity", ""),
IdentitySecretRing: cfg.OptionalString("identitySecretRing", ""),
IgnoredFiles: cfg.OptionalList("ignoredFiles"),
}
serversList := make(map[string]*clientconfig.Server)
servers := cfg.OptionalObject("servers")
for alias, vei := range servers {
// An alias should never be confused with a host name,
// so we forbid anything looking like one.
if isURLOrHostPort(alias) {
log.Fatalf("Server alias %q looks like a hostname; \".\" or \";\" are not allowed.", alias)
}
serverMap, ok := vei.(map[string]interface{})
if !ok {
log.Fatalf("entry %q in servers section is a %T, want an object", alias, vei)
}
serverConf := jsonconfig.Obj(serverMap)
serverStr, err := cleanServer(serverConf.OptionalString("server", ""))
if err != nil {
log.Fatalf("invalid server alias %q: %v", alias, err)
}
server := &clientconfig.Server{
Server: serverStr,
Auth: serverConf.OptionalString("auth", ""),
IsDefault: serverConf.OptionalBool("default", false),
TrustedCerts: serverConf.OptionalList("trustedCerts"),
}
if err := serverConf.Validate(); err != nil {
log.Fatalf("Error in servers section of config file for server %q: %v", alias, err)
}
serversList[alias] = server
}
config.Servers = serversList
if err := cfg.Validate(); err != nil {
printConfigChangeHelp(cfg)
log.Fatalf("Error in config file: %v", err)
}
}
|
go
|
func (c *Client) parseConfig() {
if android.OnAndroid() {
panic("parseConfig should never have been called on Android")
}
if configDisabled {
panic("parseConfig should never have been called with CAMLI_DISABLE_CLIENT_CONFIG_FILE set")
}
configPath := osutil.UserClientConfigPath()
if _, err := wkfs.Stat(configPath); os.IsNotExist(err) {
if c != nil && c.isSharePrefix {
return
}
errMsg := fmt.Sprintf("Client configuration file %v does not exist. See 'pk-put init' to generate it.", configPath)
if keyID := serverKeyId(); keyID != "" {
hint := fmt.Sprintf("\nThe key id %v was found in the server config %v, so you might want:\n'pk-put init -gpgkey %v'", keyID, osutil.UserServerConfigPath(), keyID)
errMsg += hint
}
log.Fatal(errMsg)
}
// TODO: instead of using jsonconfig, we could read the file,
// and unmarshal into the structs that we now have in
// pkg/types/clientconfig. But we'll have to add the old
// fields (before the name changes, and before the
// multi-servers change) to the structs as well for our
// graceful conversion/error messages to work.
conf, err := osutil.NewJSONConfigParser().ReadFile(configPath)
if err != nil {
log.Fatal(err.Error())
}
cfg := jsonconfig.Obj(conf)
if singleServerAuth := cfg.OptionalString("auth", ""); singleServerAuth != "" {
newConf, err := convertToMultiServers(cfg)
if err != nil {
log.Print(err)
} else {
cfg = newConf
}
}
config = &clientconfig.Config{
Identity: cfg.OptionalString("identity", ""),
IdentitySecretRing: cfg.OptionalString("identitySecretRing", ""),
IgnoredFiles: cfg.OptionalList("ignoredFiles"),
}
serversList := make(map[string]*clientconfig.Server)
servers := cfg.OptionalObject("servers")
for alias, vei := range servers {
// An alias should never be confused with a host name,
// so we forbid anything looking like one.
if isURLOrHostPort(alias) {
log.Fatalf("Server alias %q looks like a hostname; \".\" or \";\" are not allowed.", alias)
}
serverMap, ok := vei.(map[string]interface{})
if !ok {
log.Fatalf("entry %q in servers section is a %T, want an object", alias, vei)
}
serverConf := jsonconfig.Obj(serverMap)
serverStr, err := cleanServer(serverConf.OptionalString("server", ""))
if err != nil {
log.Fatalf("invalid server alias %q: %v", alias, err)
}
server := &clientconfig.Server{
Server: serverStr,
Auth: serverConf.OptionalString("auth", ""),
IsDefault: serverConf.OptionalBool("default", false),
TrustedCerts: serverConf.OptionalList("trustedCerts"),
}
if err := serverConf.Validate(); err != nil {
log.Fatalf("Error in servers section of config file for server %q: %v", alias, err)
}
serversList[alias] = server
}
config.Servers = serversList
if err := cfg.Validate(); err != nil {
printConfigChangeHelp(cfg)
log.Fatalf("Error in config file: %v", err)
}
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"parseConfig",
"(",
")",
"{",
"if",
"android",
".",
"OnAndroid",
"(",
")",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"configDisabled",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"configPath",
":=",
"osutil",
".",
"UserClientConfigPath",
"(",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"wkfs",
".",
"Stat",
"(",
"configPath",
")",
";",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"if",
"c",
"!=",
"nil",
"&&",
"c",
".",
"isSharePrefix",
"{",
"return",
"\n",
"}",
"\n",
"errMsg",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"configPath",
")",
"\n",
"if",
"keyID",
":=",
"serverKeyId",
"(",
")",
";",
"keyID",
"!=",
"\"",
"\"",
"{",
"hint",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\\n",
"\"",
",",
"keyID",
",",
"osutil",
".",
"UserServerConfigPath",
"(",
")",
",",
"keyID",
")",
"\n",
"errMsg",
"+=",
"hint",
"\n",
"}",
"\n",
"log",
".",
"Fatal",
"(",
"errMsg",
")",
"\n",
"}",
"\n",
"// TODO: instead of using jsonconfig, we could read the file,",
"// and unmarshal into the structs that we now have in",
"// pkg/types/clientconfig. But we'll have to add the old",
"// fields (before the name changes, and before the",
"// multi-servers change) to the structs as well for our",
"// graceful conversion/error messages to work.",
"conf",
",",
"err",
":=",
"osutil",
".",
"NewJSONConfigParser",
"(",
")",
".",
"ReadFile",
"(",
"configPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatal",
"(",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"cfg",
":=",
"jsonconfig",
".",
"Obj",
"(",
"conf",
")",
"\n\n",
"if",
"singleServerAuth",
":=",
"cfg",
".",
"OptionalString",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
";",
"singleServerAuth",
"!=",
"\"",
"\"",
"{",
"newConf",
",",
"err",
":=",
"convertToMultiServers",
"(",
"cfg",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Print",
"(",
"err",
")",
"\n",
"}",
"else",
"{",
"cfg",
"=",
"newConf",
"\n",
"}",
"\n",
"}",
"\n\n",
"config",
"=",
"&",
"clientconfig",
".",
"Config",
"{",
"Identity",
":",
"cfg",
".",
"OptionalString",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"IdentitySecretRing",
":",
"cfg",
".",
"OptionalString",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"IgnoredFiles",
":",
"cfg",
".",
"OptionalList",
"(",
"\"",
"\"",
")",
",",
"}",
"\n",
"serversList",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"*",
"clientconfig",
".",
"Server",
")",
"\n",
"servers",
":=",
"cfg",
".",
"OptionalObject",
"(",
"\"",
"\"",
")",
"\n",
"for",
"alias",
",",
"vei",
":=",
"range",
"servers",
"{",
"// An alias should never be confused with a host name,",
"// so we forbid anything looking like one.",
"if",
"isURLOrHostPort",
"(",
"alias",
")",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\\\"",
"\\\"",
"\\\"",
"\\\"",
"\"",
",",
"alias",
")",
"\n",
"}",
"\n",
"serverMap",
",",
"ok",
":=",
"vei",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
"\n",
"if",
"!",
"ok",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"alias",
",",
"vei",
")",
"\n",
"}",
"\n",
"serverConf",
":=",
"jsonconfig",
".",
"Obj",
"(",
"serverMap",
")",
"\n",
"serverStr",
",",
"err",
":=",
"cleanServer",
"(",
"serverConf",
".",
"OptionalString",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"alias",
",",
"err",
")",
"\n",
"}",
"\n",
"server",
":=",
"&",
"clientconfig",
".",
"Server",
"{",
"Server",
":",
"serverStr",
",",
"Auth",
":",
"serverConf",
".",
"OptionalString",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"IsDefault",
":",
"serverConf",
".",
"OptionalBool",
"(",
"\"",
"\"",
",",
"false",
")",
",",
"TrustedCerts",
":",
"serverConf",
".",
"OptionalList",
"(",
"\"",
"\"",
")",
",",
"}",
"\n",
"if",
"err",
":=",
"serverConf",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"alias",
",",
"err",
")",
"\n",
"}",
"\n",
"serversList",
"[",
"alias",
"]",
"=",
"server",
"\n",
"}",
"\n",
"config",
".",
"Servers",
"=",
"serversList",
"\n",
"if",
"err",
":=",
"cfg",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"printConfigChangeHelp",
"(",
"cfg",
")",
"\n",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}"
] |
// lazy config parsing when there's a known client already.
// The client c may be nil.
|
[
"lazy",
"config",
"parsing",
"when",
"there",
"s",
"a",
"known",
"client",
"already",
".",
"The",
"client",
"c",
"may",
"be",
"nil",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/config.go#L84-L162
|
train
|
perkeep/perkeep
|
pkg/client/config.go
|
convertToMultiServers
|
func convertToMultiServers(conf jsonconfig.Obj) (jsonconfig.Obj, error) {
server := conf.OptionalString("server", "")
if server == "" {
return nil, errors.New("could not convert config to multi-servers style: no \"server\" key found")
}
newConf := jsonconfig.Obj{
"servers": map[string]interface{}{
"server": map[string]interface{}{
"auth": conf.OptionalString("auth", ""),
"default": true,
"server": server,
},
},
"identity": conf.OptionalString("identity", ""),
"identitySecretRing": conf.OptionalString("identitySecretRing", ""),
}
if ignoredFiles := conf.OptionalList("ignoredFiles"); ignoredFiles != nil {
var list []interface{}
for _, v := range ignoredFiles {
list = append(list, v)
}
newConf["ignoredFiles"] = list
}
return newConf, nil
}
|
go
|
func convertToMultiServers(conf jsonconfig.Obj) (jsonconfig.Obj, error) {
server := conf.OptionalString("server", "")
if server == "" {
return nil, errors.New("could not convert config to multi-servers style: no \"server\" key found")
}
newConf := jsonconfig.Obj{
"servers": map[string]interface{}{
"server": map[string]interface{}{
"auth": conf.OptionalString("auth", ""),
"default": true,
"server": server,
},
},
"identity": conf.OptionalString("identity", ""),
"identitySecretRing": conf.OptionalString("identitySecretRing", ""),
}
if ignoredFiles := conf.OptionalList("ignoredFiles"); ignoredFiles != nil {
var list []interface{}
for _, v := range ignoredFiles {
list = append(list, v)
}
newConf["ignoredFiles"] = list
}
return newConf, nil
}
|
[
"func",
"convertToMultiServers",
"(",
"conf",
"jsonconfig",
".",
"Obj",
")",
"(",
"jsonconfig",
".",
"Obj",
",",
"error",
")",
"{",
"server",
":=",
"conf",
".",
"OptionalString",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"server",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\\\"",
"\\\"",
"\"",
")",
"\n",
"}",
"\n",
"newConf",
":=",
"jsonconfig",
".",
"Obj",
"{",
"\"",
"\"",
":",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"",
"\"",
":",
"conf",
".",
"OptionalString",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"\"",
"\"",
":",
"true",
",",
"\"",
"\"",
":",
"server",
",",
"}",
",",
"}",
",",
"\"",
"\"",
":",
"conf",
".",
"OptionalString",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"\"",
"\"",
":",
"conf",
".",
"OptionalString",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"}",
"\n",
"if",
"ignoredFiles",
":=",
"conf",
".",
"OptionalList",
"(",
"\"",
"\"",
")",
";",
"ignoredFiles",
"!=",
"nil",
"{",
"var",
"list",
"[",
"]",
"interface",
"{",
"}",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"ignoredFiles",
"{",
"list",
"=",
"append",
"(",
"list",
",",
"v",
")",
"\n",
"}",
"\n",
"newConf",
"[",
"\"",
"\"",
"]",
"=",
"list",
"\n",
"}",
"\n",
"return",
"newConf",
",",
"nil",
"\n",
"}"
] |
// convertToMultiServers takes an old style single-server client configuration and maps it to new a multi-servers configuration that is returned.
|
[
"convertToMultiServers",
"takes",
"an",
"old",
"style",
"single",
"-",
"server",
"client",
"configuration",
"and",
"maps",
"it",
"to",
"new",
"a",
"multi",
"-",
"servers",
"configuration",
"that",
"is",
"returned",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/config.go#L172-L196
|
train
|
perkeep/perkeep
|
pkg/client/config.go
|
printConfigChangeHelp
|
func printConfigChangeHelp(conf jsonconfig.Obj) {
// rename maps from old key names to the new ones.
// If there is no new one, the value is the empty string.
rename := map[string]string{
"keyId": "identity",
"publicKeyBlobref": "",
"selfPubKeyDir": "",
"secretRing": "identitySecretRing",
}
oldConfig := false
configChangedMsg := fmt.Sprintf("The client configuration file (%s) keys have changed.\n", osutil.UserClientConfigPath())
for _, unknown := range conf.UnknownKeys() {
v, ok := rename[unknown]
if ok {
if v != "" {
configChangedMsg += fmt.Sprintf("%q should be renamed %q.\n", unknown, v)
} else {
configChangedMsg += fmt.Sprintf("%q should be removed.\n", unknown)
}
oldConfig = true
}
}
if oldConfig {
configChangedMsg += "Please see https://perkeep.org/doc/client-config, or use pk-put init to recreate a default one."
log.Print(configChangedMsg)
}
}
|
go
|
func printConfigChangeHelp(conf jsonconfig.Obj) {
// rename maps from old key names to the new ones.
// If there is no new one, the value is the empty string.
rename := map[string]string{
"keyId": "identity",
"publicKeyBlobref": "",
"selfPubKeyDir": "",
"secretRing": "identitySecretRing",
}
oldConfig := false
configChangedMsg := fmt.Sprintf("The client configuration file (%s) keys have changed.\n", osutil.UserClientConfigPath())
for _, unknown := range conf.UnknownKeys() {
v, ok := rename[unknown]
if ok {
if v != "" {
configChangedMsg += fmt.Sprintf("%q should be renamed %q.\n", unknown, v)
} else {
configChangedMsg += fmt.Sprintf("%q should be removed.\n", unknown)
}
oldConfig = true
}
}
if oldConfig {
configChangedMsg += "Please see https://perkeep.org/doc/client-config, or use pk-put init to recreate a default one."
log.Print(configChangedMsg)
}
}
|
[
"func",
"printConfigChangeHelp",
"(",
"conf",
"jsonconfig",
".",
"Obj",
")",
"{",
"// rename maps from old key names to the new ones.",
"// If there is no new one, the value is the empty string.",
"rename",
":=",
"map",
"[",
"string",
"]",
"string",
"{",
"\"",
"\"",
":",
"\"",
"\"",
",",
"\"",
"\"",
":",
"\"",
"\"",
",",
"\"",
"\"",
":",
"\"",
"\"",
",",
"\"",
"\"",
":",
"\"",
"\"",
",",
"}",
"\n",
"oldConfig",
":=",
"false",
"\n",
"configChangedMsg",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\"",
",",
"osutil",
".",
"UserClientConfigPath",
"(",
")",
")",
"\n",
"for",
"_",
",",
"unknown",
":=",
"range",
"conf",
".",
"UnknownKeys",
"(",
")",
"{",
"v",
",",
"ok",
":=",
"rename",
"[",
"unknown",
"]",
"\n",
"if",
"ok",
"{",
"if",
"v",
"!=",
"\"",
"\"",
"{",
"configChangedMsg",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\"",
",",
"unknown",
",",
"v",
")",
"\n",
"}",
"else",
"{",
"configChangedMsg",
"+=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\\n",
"\"",
",",
"unknown",
")",
"\n",
"}",
"\n",
"oldConfig",
"=",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"oldConfig",
"{",
"configChangedMsg",
"+=",
"\"",
"\"",
"\n",
"log",
".",
"Print",
"(",
"configChangedMsg",
")",
"\n",
"}",
"\n",
"}"
] |
// printConfigChangeHelp checks if conf contains obsolete keys,
// and prints additional help in this case.
|
[
"printConfigChangeHelp",
"checks",
"if",
"conf",
"contains",
"obsolete",
"keys",
"and",
"prints",
"additional",
"help",
"in",
"this",
"case",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/config.go#L200-L226
|
train
|
perkeep/perkeep
|
pkg/client/config.go
|
getServer
|
func getServer() (string, error) {
if s := os.Getenv("CAMLI_SERVER"); s != "" {
return cleanServer(s)
}
if flagServer != "" {
if !isURLOrHostPort(flagServer) {
configOnce.Do(parseConfig)
serverConf, ok := config.Servers[flagServer]
if ok {
return serverConf.Server, nil
}
log.Printf("%q looks like a server alias, but no such alias found in config.", flagServer)
} else {
return cleanServer(flagServer)
}
}
server, err := defaultServer()
if err != nil {
return "", err
}
if server == "" {
return "", camtypes.ErrClientNoServer
}
return cleanServer(server)
}
|
go
|
func getServer() (string, error) {
if s := os.Getenv("CAMLI_SERVER"); s != "" {
return cleanServer(s)
}
if flagServer != "" {
if !isURLOrHostPort(flagServer) {
configOnce.Do(parseConfig)
serverConf, ok := config.Servers[flagServer]
if ok {
return serverConf.Server, nil
}
log.Printf("%q looks like a server alias, but no such alias found in config.", flagServer)
} else {
return cleanServer(flagServer)
}
}
server, err := defaultServer()
if err != nil {
return "", err
}
if server == "" {
return "", camtypes.ErrClientNoServer
}
return cleanServer(server)
}
|
[
"func",
"getServer",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"s",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
";",
"s",
"!=",
"\"",
"\"",
"{",
"return",
"cleanServer",
"(",
"s",
")",
"\n",
"}",
"\n",
"if",
"flagServer",
"!=",
"\"",
"\"",
"{",
"if",
"!",
"isURLOrHostPort",
"(",
"flagServer",
")",
"{",
"configOnce",
".",
"Do",
"(",
"parseConfig",
")",
"\n",
"serverConf",
",",
"ok",
":=",
"config",
".",
"Servers",
"[",
"flagServer",
"]",
"\n",
"if",
"ok",
"{",
"return",
"serverConf",
".",
"Server",
",",
"nil",
"\n",
"}",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"flagServer",
")",
"\n",
"}",
"else",
"{",
"return",
"cleanServer",
"(",
"flagServer",
")",
"\n",
"}",
"\n",
"}",
"\n",
"server",
",",
"err",
":=",
"defaultServer",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"if",
"server",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
",",
"camtypes",
".",
"ErrClientNoServer",
"\n",
"}",
"\n",
"return",
"cleanServer",
"(",
"server",
")",
"\n",
"}"
] |
// getServer returns the server's URL found either as a command-line flag,
// or as the default server in the config file.
|
[
"getServer",
"returns",
"the",
"server",
"s",
"URL",
"found",
"either",
"as",
"a",
"command",
"-",
"line",
"flag",
"or",
"as",
"the",
"default",
"server",
"in",
"the",
"config",
"file",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/config.go#L269-L293
|
train
|
perkeep/perkeep
|
pkg/client/config.go
|
SetupAuth
|
func (c *Client) SetupAuth() error {
if c.noExtConfig {
if c.authMode != nil {
if _, ok := c.authMode.(*auth.None); !ok {
return nil
}
}
return errors.New("client: noExtConfig set; auth should not be configured from config or env vars")
}
// env var takes precedence, but only if we're in dev mode or on android.
// Too risky otherwise.
if android.OnAndroid() ||
env.IsDev() ||
configDisabled {
authMode, err := auth.FromEnv()
if err == nil {
c.authMode = authMode
return nil
}
if err != auth.ErrNoAuth {
return fmt.Errorf("Could not set up auth from env var CAMLI_AUTH: %v", err)
}
}
if c.server == "" {
return fmt.Errorf("no server defined for this client: can not set up auth")
}
authConf := serverAuth(c.server)
if authConf == "" {
c.authErr = fmt.Errorf("could not find auth key for server %q in config, defaulting to no auth", c.server)
c.authMode = auth.None{}
return nil
}
var err error
c.authMode, err = auth.FromConfig(authConf)
return err
}
|
go
|
func (c *Client) SetupAuth() error {
if c.noExtConfig {
if c.authMode != nil {
if _, ok := c.authMode.(*auth.None); !ok {
return nil
}
}
return errors.New("client: noExtConfig set; auth should not be configured from config or env vars")
}
// env var takes precedence, but only if we're in dev mode or on android.
// Too risky otherwise.
if android.OnAndroid() ||
env.IsDev() ||
configDisabled {
authMode, err := auth.FromEnv()
if err == nil {
c.authMode = authMode
return nil
}
if err != auth.ErrNoAuth {
return fmt.Errorf("Could not set up auth from env var CAMLI_AUTH: %v", err)
}
}
if c.server == "" {
return fmt.Errorf("no server defined for this client: can not set up auth")
}
authConf := serverAuth(c.server)
if authConf == "" {
c.authErr = fmt.Errorf("could not find auth key for server %q in config, defaulting to no auth", c.server)
c.authMode = auth.None{}
return nil
}
var err error
c.authMode, err = auth.FromConfig(authConf)
return err
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"SetupAuth",
"(",
")",
"error",
"{",
"if",
"c",
".",
"noExtConfig",
"{",
"if",
"c",
".",
"authMode",
"!=",
"nil",
"{",
"if",
"_",
",",
"ok",
":=",
"c",
".",
"authMode",
".",
"(",
"*",
"auth",
".",
"None",
")",
";",
"!",
"ok",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"// env var takes precedence, but only if we're in dev mode or on android.",
"// Too risky otherwise.",
"if",
"android",
".",
"OnAndroid",
"(",
")",
"||",
"env",
".",
"IsDev",
"(",
")",
"||",
"configDisabled",
"{",
"authMode",
",",
"err",
":=",
"auth",
".",
"FromEnv",
"(",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"c",
".",
"authMode",
"=",
"authMode",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"auth",
".",
"ErrNoAuth",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"c",
".",
"server",
"==",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"authConf",
":=",
"serverAuth",
"(",
"c",
".",
"server",
")",
"\n",
"if",
"authConf",
"==",
"\"",
"\"",
"{",
"c",
".",
"authErr",
"=",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"c",
".",
"server",
")",
"\n",
"c",
".",
"authMode",
"=",
"auth",
".",
"None",
"{",
"}",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"var",
"err",
"error",
"\n",
"c",
".",
"authMode",
",",
"err",
"=",
"auth",
".",
"FromConfig",
"(",
"authConf",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// SetupAuth sets the client's authMode. It tries from the environment first if we're on android or in dev mode, and then from the client configuration.
|
[
"SetupAuth",
"sets",
"the",
"client",
"s",
"authMode",
".",
"It",
"tries",
"from",
"the",
"environment",
"first",
"if",
"we",
"re",
"on",
"android",
"or",
"in",
"dev",
"mode",
"and",
"then",
"from",
"the",
"client",
"configuration",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/config.go#L311-L346
|
train
|
perkeep/perkeep
|
pkg/client/config.go
|
serverAuth
|
func serverAuth(server string) string {
configOnce.Do(parseConfig)
alias := config.Alias(server)
if alias == "" {
return ""
}
return config.Servers[alias].Auth
}
|
go
|
func serverAuth(server string) string {
configOnce.Do(parseConfig)
alias := config.Alias(server)
if alias == "" {
return ""
}
return config.Servers[alias].Auth
}
|
[
"func",
"serverAuth",
"(",
"server",
"string",
")",
"string",
"{",
"configOnce",
".",
"Do",
"(",
"parseConfig",
")",
"\n",
"alias",
":=",
"config",
".",
"Alias",
"(",
"server",
")",
"\n",
"if",
"alias",
"==",
"\"",
"\"",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"config",
".",
"Servers",
"[",
"alias",
"]",
".",
"Auth",
"\n",
"}"
] |
// serverAuth returns the auth scheme for server from the config, or the empty string if the server was not found in the config.
|
[
"serverAuth",
"returns",
"the",
"auth",
"scheme",
"for",
"server",
"from",
"the",
"config",
"or",
"the",
"empty",
"string",
"if",
"the",
"server",
"was",
"not",
"found",
"in",
"the",
"config",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/config.go#L349-L356
|
train
|
perkeep/perkeep
|
pkg/client/config.go
|
SetupAuthFromString
|
func (c *Client) SetupAuthFromString(a string) error {
// TODO(mpl): review the one using that (pkg/blobserver/remote/remote.go)
var err error
c.authMode, err = auth.FromConfig(a)
return err
}
|
go
|
func (c *Client) SetupAuthFromString(a string) error {
// TODO(mpl): review the one using that (pkg/blobserver/remote/remote.go)
var err error
c.authMode, err = auth.FromConfig(a)
return err
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"SetupAuthFromString",
"(",
"a",
"string",
")",
"error",
"{",
"// TODO(mpl): review the one using that (pkg/blobserver/remote/remote.go)",
"var",
"err",
"error",
"\n",
"c",
".",
"authMode",
",",
"err",
"=",
"auth",
".",
"FromConfig",
"(",
"a",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// SetupAuthFromString configures the clients authentication mode from
// an explicit auth string.
|
[
"SetupAuthFromString",
"configures",
"the",
"clients",
"authentication",
"mode",
"from",
"an",
"explicit",
"auth",
"string",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/config.go#L360-L365
|
train
|
perkeep/perkeep
|
pkg/client/config.go
|
serverTrustedCerts
|
func (c *Client) serverTrustedCerts(server string) []string {
configOnce.Do(c.parseConfig)
if config == nil {
return nil
}
alias := config.Alias(server)
if alias == "" {
return nil
}
return config.Servers[alias].TrustedCerts
}
|
go
|
func (c *Client) serverTrustedCerts(server string) []string {
configOnce.Do(c.parseConfig)
if config == nil {
return nil
}
alias := config.Alias(server)
if alias == "" {
return nil
}
return config.Servers[alias].TrustedCerts
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"serverTrustedCerts",
"(",
"server",
"string",
")",
"[",
"]",
"string",
"{",
"configOnce",
".",
"Do",
"(",
"c",
".",
"parseConfig",
")",
"\n",
"if",
"config",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"alias",
":=",
"config",
".",
"Alias",
"(",
"server",
")",
"\n",
"if",
"alias",
"==",
"\"",
"\"",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"config",
".",
"Servers",
"[",
"alias",
"]",
".",
"TrustedCerts",
"\n",
"}"
] |
// serverTrustedCerts returns the trusted certs for server from the config.
|
[
"serverTrustedCerts",
"returns",
"the",
"trusted",
"certs",
"for",
"server",
"from",
"the",
"config",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/config.go#L463-L473
|
train
|
perkeep/perkeep
|
pkg/client/config.go
|
newIgnoreChecker
|
func newIgnoreChecker(ignoredFiles []string) func(path string) (shouldIgnore bool) {
var fns []func(string) bool
// copy of ignoredFiles for us to mutate
ignFiles := append([]string(nil), ignoredFiles...)
for k, v := range ignFiles {
if strings.HasPrefix(v, filepath.FromSlash("~/")) {
ignFiles[k] = filepath.Join(osutilHomeDir(), v[2:])
}
}
// We cache the ignoredFiles patterns in 3 categories (not necessarily exclusive):
// 1) shell patterns
// 3) absolute paths
// 4) paths components
for _, pattern := range ignFiles {
pattern := pattern
_, err := filepath.Match(pattern, "whatever")
if err == nil {
fns = append(fns, func(v string) bool { return isShellPatternMatch(pattern, v) })
}
}
for _, pattern := range ignFiles {
pattern := pattern
if filepath.IsAbs(pattern) {
fns = append(fns, func(v string) bool { return hasDirPrefix(filepath.Clean(pattern), v) })
} else {
fns = append(fns, func(v string) bool { return hasComponent(filepath.Clean(pattern), v) })
}
}
return func(path string) bool {
for _, fn := range fns {
if fn(path) {
return true
}
}
return false
}
}
|
go
|
func newIgnoreChecker(ignoredFiles []string) func(path string) (shouldIgnore bool) {
var fns []func(string) bool
// copy of ignoredFiles for us to mutate
ignFiles := append([]string(nil), ignoredFiles...)
for k, v := range ignFiles {
if strings.HasPrefix(v, filepath.FromSlash("~/")) {
ignFiles[k] = filepath.Join(osutilHomeDir(), v[2:])
}
}
// We cache the ignoredFiles patterns in 3 categories (not necessarily exclusive):
// 1) shell patterns
// 3) absolute paths
// 4) paths components
for _, pattern := range ignFiles {
pattern := pattern
_, err := filepath.Match(pattern, "whatever")
if err == nil {
fns = append(fns, func(v string) bool { return isShellPatternMatch(pattern, v) })
}
}
for _, pattern := range ignFiles {
pattern := pattern
if filepath.IsAbs(pattern) {
fns = append(fns, func(v string) bool { return hasDirPrefix(filepath.Clean(pattern), v) })
} else {
fns = append(fns, func(v string) bool { return hasComponent(filepath.Clean(pattern), v) })
}
}
return func(path string) bool {
for _, fn := range fns {
if fn(path) {
return true
}
}
return false
}
}
|
[
"func",
"newIgnoreChecker",
"(",
"ignoredFiles",
"[",
"]",
"string",
")",
"func",
"(",
"path",
"string",
")",
"(",
"shouldIgnore",
"bool",
")",
"{",
"var",
"fns",
"[",
"]",
"func",
"(",
"string",
")",
"bool",
"\n\n",
"// copy of ignoredFiles for us to mutate",
"ignFiles",
":=",
"append",
"(",
"[",
"]",
"string",
"(",
"nil",
")",
",",
"ignoredFiles",
"...",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"ignFiles",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"v",
",",
"filepath",
".",
"FromSlash",
"(",
"\"",
"\"",
")",
")",
"{",
"ignFiles",
"[",
"k",
"]",
"=",
"filepath",
".",
"Join",
"(",
"osutilHomeDir",
"(",
")",
",",
"v",
"[",
"2",
":",
"]",
")",
"\n",
"}",
"\n",
"}",
"\n",
"// We cache the ignoredFiles patterns in 3 categories (not necessarily exclusive):",
"// 1) shell patterns",
"// 3) absolute paths",
"// 4) paths components",
"for",
"_",
",",
"pattern",
":=",
"range",
"ignFiles",
"{",
"pattern",
":=",
"pattern",
"\n",
"_",
",",
"err",
":=",
"filepath",
".",
"Match",
"(",
"pattern",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"fns",
"=",
"append",
"(",
"fns",
",",
"func",
"(",
"v",
"string",
")",
"bool",
"{",
"return",
"isShellPatternMatch",
"(",
"pattern",
",",
"v",
")",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n",
"for",
"_",
",",
"pattern",
":=",
"range",
"ignFiles",
"{",
"pattern",
":=",
"pattern",
"\n",
"if",
"filepath",
".",
"IsAbs",
"(",
"pattern",
")",
"{",
"fns",
"=",
"append",
"(",
"fns",
",",
"func",
"(",
"v",
"string",
")",
"bool",
"{",
"return",
"hasDirPrefix",
"(",
"filepath",
".",
"Clean",
"(",
"pattern",
")",
",",
"v",
")",
"}",
")",
"\n",
"}",
"else",
"{",
"fns",
"=",
"append",
"(",
"fns",
",",
"func",
"(",
"v",
"string",
")",
"bool",
"{",
"return",
"hasComponent",
"(",
"filepath",
".",
"Clean",
"(",
"pattern",
")",
",",
"v",
")",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"return",
"func",
"(",
"path",
"string",
")",
"bool",
"{",
"for",
"_",
",",
"fn",
":=",
"range",
"fns",
"{",
"if",
"fn",
"(",
"path",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}",
"\n",
"}"
] |
// newIgnoreChecker uses ignoredFiles to build and return a func that returns whether the file path argument should be ignored. See IsIgnoredFile for the ignore rules.
|
[
"newIgnoreChecker",
"uses",
"ignoredFiles",
"to",
"build",
"and",
"return",
"a",
"func",
"that",
"returns",
"whether",
"the",
"file",
"path",
"argument",
"should",
"be",
"ignored",
".",
"See",
"IsIgnoredFile",
"for",
"the",
"ignore",
"rules",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/config.go#L502-L540
|
train
|
perkeep/perkeep
|
pkg/client/config.go
|
hasDirPrefix
|
func hasDirPrefix(dirPrefix, fullpath string) bool {
if !strings.HasPrefix(fullpath, dirPrefix) {
return false
}
if len(fullpath) == len(dirPrefix) {
return true
}
if fullpath[len(dirPrefix)] == filepath.Separator {
return true
}
return false
}
|
go
|
func hasDirPrefix(dirPrefix, fullpath string) bool {
if !strings.HasPrefix(fullpath, dirPrefix) {
return false
}
if len(fullpath) == len(dirPrefix) {
return true
}
if fullpath[len(dirPrefix)] == filepath.Separator {
return true
}
return false
}
|
[
"func",
"hasDirPrefix",
"(",
"dirPrefix",
",",
"fullpath",
"string",
")",
"bool",
"{",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"fullpath",
",",
"dirPrefix",
")",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"len",
"(",
"fullpath",
")",
"==",
"len",
"(",
"dirPrefix",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"fullpath",
"[",
"len",
"(",
"dirPrefix",
")",
"]",
"==",
"filepath",
".",
"Separator",
"{",
"return",
"true",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// hasDirPrefix reports whether the path has the provided directory prefix.
// Both should be absolute paths.
|
[
"hasDirPrefix",
"reports",
"whether",
"the",
"path",
"has",
"the",
"provided",
"directory",
"prefix",
".",
"Both",
"should",
"be",
"absolute",
"paths",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/config.go#L561-L572
|
train
|
perkeep/perkeep
|
pkg/client/config.go
|
hasComponent
|
func hasComponent(component, fullpath string) bool {
// trim Windows volume name
fullpath = strings.TrimPrefix(fullpath, filepath.VolumeName(fullpath))
for {
i := strings.Index(fullpath, component)
if i == -1 {
return false
}
if i != 0 && fullpath[i-1] == filepath.Separator {
componentEnd := i + len(component)
if componentEnd == len(fullpath) {
return true
}
if fullpath[componentEnd] == filepath.Separator {
return true
}
}
fullpath = fullpath[i+1:]
}
panic("unreachable")
}
|
go
|
func hasComponent(component, fullpath string) bool {
// trim Windows volume name
fullpath = strings.TrimPrefix(fullpath, filepath.VolumeName(fullpath))
for {
i := strings.Index(fullpath, component)
if i == -1 {
return false
}
if i != 0 && fullpath[i-1] == filepath.Separator {
componentEnd := i + len(component)
if componentEnd == len(fullpath) {
return true
}
if fullpath[componentEnd] == filepath.Separator {
return true
}
}
fullpath = fullpath[i+1:]
}
panic("unreachable")
}
|
[
"func",
"hasComponent",
"(",
"component",
",",
"fullpath",
"string",
")",
"bool",
"{",
"// trim Windows volume name",
"fullpath",
"=",
"strings",
".",
"TrimPrefix",
"(",
"fullpath",
",",
"filepath",
".",
"VolumeName",
"(",
"fullpath",
")",
")",
"\n",
"for",
"{",
"i",
":=",
"strings",
".",
"Index",
"(",
"fullpath",
",",
"component",
")",
"\n",
"if",
"i",
"==",
"-",
"1",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"i",
"!=",
"0",
"&&",
"fullpath",
"[",
"i",
"-",
"1",
"]",
"==",
"filepath",
".",
"Separator",
"{",
"componentEnd",
":=",
"i",
"+",
"len",
"(",
"component",
")",
"\n",
"if",
"componentEnd",
"==",
"len",
"(",
"fullpath",
")",
"{",
"return",
"true",
"\n",
"}",
"\n",
"if",
"fullpath",
"[",
"componentEnd",
"]",
"==",
"filepath",
".",
"Separator",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"fullpath",
"=",
"fullpath",
"[",
"i",
"+",
"1",
":",
"]",
"\n",
"}",
"\n",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}"
] |
// hasComponent returns whether the pathComponent is a path component of
// fullpath. i.e it is a part of fullpath that fits exactly between two path
// separators.
|
[
"hasComponent",
"returns",
"whether",
"the",
"pathComponent",
"is",
"a",
"path",
"component",
"of",
"fullpath",
".",
"i",
".",
"e",
"it",
"is",
"a",
"part",
"of",
"fullpath",
"that",
"fits",
"exactly",
"between",
"two",
"path",
"separators",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/config.go#L577-L597
|
train
|
perkeep/perkeep
|
misc/release/make-release.go
|
genAll
|
func genAll() ([]string, error) {
zipSource()
for _, platform := range []string{"linux", "darwin", "windows"} {
genBinaries(platform)
packBinaries(platform)
}
getVersions()
return []string{
"perkeep-darwin.tar.gz",
"perkeep-linux.tar.gz",
"perkeep-src.zip",
"perkeep-windows.zip",
}, nil
}
|
go
|
func genAll() ([]string, error) {
zipSource()
for _, platform := range []string{"linux", "darwin", "windows"} {
genBinaries(platform)
packBinaries(platform)
}
getVersions()
return []string{
"perkeep-darwin.tar.gz",
"perkeep-linux.tar.gz",
"perkeep-src.zip",
"perkeep-windows.zip",
}, nil
}
|
[
"func",
"genAll",
"(",
")",
"(",
"[",
"]",
"string",
",",
"error",
")",
"{",
"zipSource",
"(",
")",
"\n",
"for",
"_",
",",
"platform",
":=",
"range",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"{",
"genBinaries",
"(",
"platform",
")",
"\n",
"packBinaries",
"(",
"platform",
")",
"\n",
"}",
"\n",
"getVersions",
"(",
")",
"\n",
"return",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// genAll creates all the zips and tarballs, and returns their filenames.
|
[
"genAll",
"creates",
"all",
"the",
"zips",
"and",
"tarballs",
"and",
"returns",
"their",
"filenames",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/misc/release/make-release.go#L196-L209
|
train
|
perkeep/perkeep
|
misc/release/make-release.go
|
getVersions
|
func getVersions() {
pkBin := filepath.Join(workDir, runtime.GOOS, "bin", "perkeepd")
cmd := exec.Command(pkBin, "-version")
var buf bytes.Buffer
cmd.Stderr = &buf
if err := cmd.Run(); err != nil {
log.Fatalf("Error getting version from perkeepd: %v, %v", err, buf.String())
}
sc := bufio.NewScanner(&buf)
for sc.Scan() {
l := sc.Text()
fields := strings.Fields(l)
if pkVersion == "" {
if len(fields) != 4 || fields[0] != "perkeepd" {
log.Fatalf("Unexpected perkeepd -version output: %q", l)
}
pkVersion = fields[3]
continue
}
if len(fields) != 4 || fields[0] != "Go" {
log.Fatalf("Unexpected perkeepd -version output: %q", l)
}
goVersion = fields[2]
break
}
if err := sc.Err(); err != nil {
log.Fatal(err)
}
}
|
go
|
func getVersions() {
pkBin := filepath.Join(workDir, runtime.GOOS, "bin", "perkeepd")
cmd := exec.Command(pkBin, "-version")
var buf bytes.Buffer
cmd.Stderr = &buf
if err := cmd.Run(); err != nil {
log.Fatalf("Error getting version from perkeepd: %v, %v", err, buf.String())
}
sc := bufio.NewScanner(&buf)
for sc.Scan() {
l := sc.Text()
fields := strings.Fields(l)
if pkVersion == "" {
if len(fields) != 4 || fields[0] != "perkeepd" {
log.Fatalf("Unexpected perkeepd -version output: %q", l)
}
pkVersion = fields[3]
continue
}
if len(fields) != 4 || fields[0] != "Go" {
log.Fatalf("Unexpected perkeepd -version output: %q", l)
}
goVersion = fields[2]
break
}
if err := sc.Err(); err != nil {
log.Fatal(err)
}
}
|
[
"func",
"getVersions",
"(",
")",
"{",
"pkBin",
":=",
"filepath",
".",
"Join",
"(",
"workDir",
",",
"runtime",
".",
"GOOS",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"cmd",
":=",
"exec",
".",
"Command",
"(",
"pkBin",
",",
"\"",
"\"",
")",
"\n",
"var",
"buf",
"bytes",
".",
"Buffer",
"\n",
"cmd",
".",
"Stderr",
"=",
"&",
"buf",
"\n",
"if",
"err",
":=",
"cmd",
".",
"Run",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"err",
",",
"buf",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"sc",
":=",
"bufio",
".",
"NewScanner",
"(",
"&",
"buf",
")",
"\n",
"for",
"sc",
".",
"Scan",
"(",
")",
"{",
"l",
":=",
"sc",
".",
"Text",
"(",
")",
"\n",
"fields",
":=",
"strings",
".",
"Fields",
"(",
"l",
")",
"\n",
"if",
"pkVersion",
"==",
"\"",
"\"",
"{",
"if",
"len",
"(",
"fields",
")",
"!=",
"4",
"||",
"fields",
"[",
"0",
"]",
"!=",
"\"",
"\"",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"l",
")",
"\n",
"}",
"\n",
"pkVersion",
"=",
"fields",
"[",
"3",
"]",
"\n",
"continue",
"\n",
"}",
"\n",
"if",
"len",
"(",
"fields",
")",
"!=",
"4",
"||",
"fields",
"[",
"0",
"]",
"!=",
"\"",
"\"",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"l",
")",
"\n",
"}",
"\n",
"goVersion",
"=",
"fields",
"[",
"2",
"]",
"\n",
"break",
"\n",
"}",
"\n",
"if",
"err",
":=",
"sc",
".",
"Err",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatal",
"(",
"err",
")",
"\n",
"}",
"\n",
"}"
] |
// getVersions uses the freshly built perkeepd binary to get the Perkeep and Go
// versions used to build the release.
|
[
"getVersions",
"uses",
"the",
"freshly",
"built",
"perkeepd",
"binary",
"to",
"get",
"the",
"Perkeep",
"and",
"Go",
"versions",
"used",
"to",
"build",
"the",
"release",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/misc/release/make-release.go#L213-L241
|
train
|
perkeep/perkeep
|
misc/release/make-release.go
|
zipSource
|
func zipSource() string {
cwd := filepath.Join(workDir, "src")
check(os.MkdirAll(cwd, 0755))
image := goDockerImage
args := []string{
"run",
"--rm",
"--volume=" + cwd + ":/OUT",
"--volume=" + path.Join(releaseDir, "zip-source.go") + ":" + zipSourceProgram + ":ro",
}
if isWIP() {
args = append(args, "--volume="+localCamliSource()+":/IN:ro",
image, goCmd, "run", zipSourceProgram, "--rev=WIP:/IN")
} else {
args = append(args, image, goCmd, "run", zipSourceProgram, "--rev="+rev())
}
cmd := exec.Command("docker", args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Fatalf("Error zipping Perkeep source in go container: %v", err)
}
archiveName := "perkeep-src.zip"
// can't use os.Rename because invalid cross-device link error likely
cmd = exec.Command("mv", filepath.Join(cwd, archiveName), releaseDir)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Fatalf("Error moving source zip from %v to %v: %v", filepath.Join(cwd, archiveName), releaseDir, err)
}
fmt.Printf("Perkeep source successfully zipped in %v\n", releaseDir)
return archiveName
}
|
go
|
func zipSource() string {
cwd := filepath.Join(workDir, "src")
check(os.MkdirAll(cwd, 0755))
image := goDockerImage
args := []string{
"run",
"--rm",
"--volume=" + cwd + ":/OUT",
"--volume=" + path.Join(releaseDir, "zip-source.go") + ":" + zipSourceProgram + ":ro",
}
if isWIP() {
args = append(args, "--volume="+localCamliSource()+":/IN:ro",
image, goCmd, "run", zipSourceProgram, "--rev=WIP:/IN")
} else {
args = append(args, image, goCmd, "run", zipSourceProgram, "--rev="+rev())
}
cmd := exec.Command("docker", args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Fatalf("Error zipping Perkeep source in go container: %v", err)
}
archiveName := "perkeep-src.zip"
// can't use os.Rename because invalid cross-device link error likely
cmd = exec.Command("mv", filepath.Join(cwd, archiveName), releaseDir)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Fatalf("Error moving source zip from %v to %v: %v", filepath.Join(cwd, archiveName), releaseDir, err)
}
fmt.Printf("Perkeep source successfully zipped in %v\n", releaseDir)
return archiveName
}
|
[
"func",
"zipSource",
"(",
")",
"string",
"{",
"cwd",
":=",
"filepath",
".",
"Join",
"(",
"workDir",
",",
"\"",
"\"",
")",
"\n",
"check",
"(",
"os",
".",
"MkdirAll",
"(",
"cwd",
",",
"0755",
")",
")",
"\n",
"image",
":=",
"goDockerImage",
"\n",
"args",
":=",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"+",
"cwd",
"+",
"\"",
"\"",
",",
"\"",
"\"",
"+",
"path",
".",
"Join",
"(",
"releaseDir",
",",
"\"",
"\"",
")",
"+",
"\"",
"\"",
"+",
"zipSourceProgram",
"+",
"\"",
"\"",
",",
"}",
"\n",
"if",
"isWIP",
"(",
")",
"{",
"args",
"=",
"append",
"(",
"args",
",",
"\"",
"\"",
"+",
"localCamliSource",
"(",
")",
"+",
"\"",
"\"",
",",
"image",
",",
"goCmd",
",",
"\"",
"\"",
",",
"zipSourceProgram",
",",
"\"",
"\"",
")",
"\n",
"}",
"else",
"{",
"args",
"=",
"append",
"(",
"args",
",",
"image",
",",
"goCmd",
",",
"\"",
"\"",
",",
"zipSourceProgram",
",",
"\"",
"\"",
"+",
"rev",
"(",
")",
")",
"\n",
"}",
"\n",
"cmd",
":=",
"exec",
".",
"Command",
"(",
"\"",
"\"",
",",
"args",
"...",
")",
"\n",
"cmd",
".",
"Stdout",
"=",
"os",
".",
"Stdout",
"\n",
"cmd",
".",
"Stderr",
"=",
"os",
".",
"Stderr",
"\n",
"if",
"err",
":=",
"cmd",
".",
"Run",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"archiveName",
":=",
"\"",
"\"",
"\n",
"// can't use os.Rename because invalid cross-device link error likely",
"cmd",
"=",
"exec",
".",
"Command",
"(",
"\"",
"\"",
",",
"filepath",
".",
"Join",
"(",
"cwd",
",",
"archiveName",
")",
",",
"releaseDir",
")",
"\n",
"cmd",
".",
"Stdout",
"=",
"os",
".",
"Stdout",
"\n",
"cmd",
".",
"Stderr",
"=",
"os",
".",
"Stderr",
"\n",
"if",
"err",
":=",
"cmd",
".",
"Run",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"filepath",
".",
"Join",
"(",
"cwd",
",",
"archiveName",
")",
",",
"releaseDir",
",",
"err",
")",
"\n",
"}",
"\n",
"fmt",
".",
"Printf",
"(",
"\"",
"\\n",
"\"",
",",
"releaseDir",
")",
"\n",
"return",
"archiveName",
"\n",
"}"
] |
// zipSource builds the zip archive that contains the source code of Perkeep.
|
[
"zipSource",
"builds",
"the",
"zip",
"archive",
"that",
"contains",
"the",
"source",
"code",
"of",
"Perkeep",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/misc/release/make-release.go#L378-L410
|
train
|
perkeep/perkeep
|
misc/release/make-release.go
|
committers
|
func committers() (map[string]string, error) {
cmd := exec.Command("git", "shortlog", "-n", "-e", "-s", *flagStatsFrom+".."+revOrHEAD())
out, err := cmd.CombinedOutput()
if err != nil {
return nil, fmt.Errorf("%v; %v", err, string(out))
}
rxp := regexp.MustCompile(`^\s+(\d+)\s+(.*)<(.*)>.*$`)
sc := bufio.NewScanner(bytes.NewReader(out))
// maps email to name
committers := make(map[string]string)
// remember the count, to keep the committer that has the most count, when same name.
commitCountByEmail := make(map[string]int)
for sc.Scan() {
m := rxp.FindStringSubmatch(sc.Text())
if len(m) != 4 {
return nil, fmt.Errorf("commit line regexp didn't match properly")
}
count, err := strconv.Atoi(m[1])
if err != nil {
return nil, fmt.Errorf("couldn't convert %q as a number of commits: %v", m[1], err)
}
name := strings.TrimSpace(m[2])
email := m[3]
// uniq by e-mail. first one encountered wins as it has more commits.
if _, ok := committers[email]; !ok {
committers[email] = name
}
commitCountByEmail[email] += count
}
if err := sc.Err(); err != nil {
return nil, err
}
// uniq by name
committerByName := make(map[string]string)
for email, name := range committers {
firstEmail, ok := committerByName[name]
if !ok {
committerByName[name] = email
continue
}
c1, _ := commitCountByEmail[firstEmail]
c2, _ := commitCountByEmail[email]
if c1 < c2 {
delete(committers, firstEmail)
} else {
delete(committers, email)
}
}
return committers, nil
}
|
go
|
func committers() (map[string]string, error) {
cmd := exec.Command("git", "shortlog", "-n", "-e", "-s", *flagStatsFrom+".."+revOrHEAD())
out, err := cmd.CombinedOutput()
if err != nil {
return nil, fmt.Errorf("%v; %v", err, string(out))
}
rxp := regexp.MustCompile(`^\s+(\d+)\s+(.*)<(.*)>.*$`)
sc := bufio.NewScanner(bytes.NewReader(out))
// maps email to name
committers := make(map[string]string)
// remember the count, to keep the committer that has the most count, when same name.
commitCountByEmail := make(map[string]int)
for sc.Scan() {
m := rxp.FindStringSubmatch(sc.Text())
if len(m) != 4 {
return nil, fmt.Errorf("commit line regexp didn't match properly")
}
count, err := strconv.Atoi(m[1])
if err != nil {
return nil, fmt.Errorf("couldn't convert %q as a number of commits: %v", m[1], err)
}
name := strings.TrimSpace(m[2])
email := m[3]
// uniq by e-mail. first one encountered wins as it has more commits.
if _, ok := committers[email]; !ok {
committers[email] = name
}
commitCountByEmail[email] += count
}
if err := sc.Err(); err != nil {
return nil, err
}
// uniq by name
committerByName := make(map[string]string)
for email, name := range committers {
firstEmail, ok := committerByName[name]
if !ok {
committerByName[name] = email
continue
}
c1, _ := commitCountByEmail[firstEmail]
c2, _ := commitCountByEmail[email]
if c1 < c2 {
delete(committers, firstEmail)
} else {
delete(committers, email)
}
}
return committers, nil
}
|
[
"func",
"committers",
"(",
")",
"(",
"map",
"[",
"string",
"]",
"string",
",",
"error",
")",
"{",
"cmd",
":=",
"exec",
".",
"Command",
"(",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"*",
"flagStatsFrom",
"+",
"\"",
"\"",
"+",
"revOrHEAD",
"(",
")",
")",
"\n",
"out",
",",
"err",
":=",
"cmd",
".",
"CombinedOutput",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
",",
"string",
"(",
"out",
")",
")",
"\n",
"}",
"\n",
"rxp",
":=",
"regexp",
".",
"MustCompile",
"(",
"`^\\s+(\\d+)\\s+(.*)<(.*)>.*$`",
")",
"\n",
"sc",
":=",
"bufio",
".",
"NewScanner",
"(",
"bytes",
".",
"NewReader",
"(",
"out",
")",
")",
"\n",
"// maps email to name",
"committers",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"// remember the count, to keep the committer that has the most count, when same name.",
"commitCountByEmail",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"int",
")",
"\n",
"for",
"sc",
".",
"Scan",
"(",
")",
"{",
"m",
":=",
"rxp",
".",
"FindStringSubmatch",
"(",
"sc",
".",
"Text",
"(",
")",
")",
"\n",
"if",
"len",
"(",
"m",
")",
"!=",
"4",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"count",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"m",
"[",
"1",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"m",
"[",
"1",
"]",
",",
"err",
")",
"\n",
"}",
"\n",
"name",
":=",
"strings",
".",
"TrimSpace",
"(",
"m",
"[",
"2",
"]",
")",
"\n",
"email",
":=",
"m",
"[",
"3",
"]",
"\n",
"// uniq by e-mail. first one encountered wins as it has more commits.",
"if",
"_",
",",
"ok",
":=",
"committers",
"[",
"email",
"]",
";",
"!",
"ok",
"{",
"committers",
"[",
"email",
"]",
"=",
"name",
"\n",
"}",
"\n",
"commitCountByEmail",
"[",
"email",
"]",
"+=",
"count",
"\n",
"}",
"\n",
"if",
"err",
":=",
"sc",
".",
"Err",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// uniq by name",
"committerByName",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"for",
"email",
",",
"name",
":=",
"range",
"committers",
"{",
"firstEmail",
",",
"ok",
":=",
"committerByName",
"[",
"name",
"]",
"\n",
"if",
"!",
"ok",
"{",
"committerByName",
"[",
"name",
"]",
"=",
"email",
"\n",
"continue",
"\n",
"}",
"\n",
"c1",
",",
"_",
":=",
"commitCountByEmail",
"[",
"firstEmail",
"]",
"\n",
"c2",
",",
"_",
":=",
"commitCountByEmail",
"[",
"email",
"]",
"\n",
"if",
"c1",
"<",
"c2",
"{",
"delete",
"(",
"committers",
",",
"firstEmail",
")",
"\n",
"}",
"else",
"{",
"delete",
"(",
"committers",
",",
"email",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"committers",
",",
"nil",
"\n",
"}"
] |
// returns commiters names mapped by e-mail, uniqued first by e-mail, then by name.
// When uniquing, higher count of commits wins.
|
[
"returns",
"commiters",
"names",
"mapped",
"by",
"e",
"-",
"mail",
"uniqued",
"first",
"by",
"e",
"-",
"mail",
"then",
"by",
"name",
".",
"When",
"uniquing",
"higher",
"count",
"of",
"commits",
"wins",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/misc/release/make-release.go#L690-L739
|
train
|
perkeep/perkeep
|
misc/release/make-release.go
|
ProjectTokenSource
|
func ProjectTokenSource(proj string, scopes ...string) (oauth2.TokenSource, error) {
// TODO(bradfitz): try different strategies too, like
// three-legged flow if the service account doesn't exist, and
// then cache the token file on disk somewhere. Or maybe that should be an
// option, for environments without stdin/stdout available to the user.
// We'll figure it out as needed.
fileName := filepath.Join(homedir(), "keys", proj+".key.json")
jsonConf, err := ioutil.ReadFile(fileName)
if err != nil {
if os.IsNotExist(err) {
return nil, fmt.Errorf("Missing JSON key configuration. Download the Service Account JSON key from https://console.developers.google.com/project/%s/apiui/credential and place it at %s", proj, fileName)
}
return nil, err
}
conf, err := google.JWTConfigFromJSON(jsonConf, scopes...)
if err != nil {
return nil, fmt.Errorf("reading JSON config from %s: %v", fileName, err)
}
return conf.TokenSource(oauth2.NoContext), nil
}
|
go
|
func ProjectTokenSource(proj string, scopes ...string) (oauth2.TokenSource, error) {
// TODO(bradfitz): try different strategies too, like
// three-legged flow if the service account doesn't exist, and
// then cache the token file on disk somewhere. Or maybe that should be an
// option, for environments without stdin/stdout available to the user.
// We'll figure it out as needed.
fileName := filepath.Join(homedir(), "keys", proj+".key.json")
jsonConf, err := ioutil.ReadFile(fileName)
if err != nil {
if os.IsNotExist(err) {
return nil, fmt.Errorf("Missing JSON key configuration. Download the Service Account JSON key from https://console.developers.google.com/project/%s/apiui/credential and place it at %s", proj, fileName)
}
return nil, err
}
conf, err := google.JWTConfigFromJSON(jsonConf, scopes...)
if err != nil {
return nil, fmt.Errorf("reading JSON config from %s: %v", fileName, err)
}
return conf.TokenSource(oauth2.NoContext), nil
}
|
[
"func",
"ProjectTokenSource",
"(",
"proj",
"string",
",",
"scopes",
"...",
"string",
")",
"(",
"oauth2",
".",
"TokenSource",
",",
"error",
")",
"{",
"// TODO(bradfitz): try different strategies too, like",
"// three-legged flow if the service account doesn't exist, and",
"// then cache the token file on disk somewhere. Or maybe that should be an",
"// option, for environments without stdin/stdout available to the user.",
"// We'll figure it out as needed.",
"fileName",
":=",
"filepath",
".",
"Join",
"(",
"homedir",
"(",
")",
",",
"\"",
"\"",
",",
"proj",
"+",
"\"",
"\"",
")",
"\n",
"jsonConf",
",",
"err",
":=",
"ioutil",
".",
"ReadFile",
"(",
"fileName",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"if",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"proj",
",",
"fileName",
")",
"\n",
"}",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"conf",
",",
"err",
":=",
"google",
".",
"JWTConfigFromJSON",
"(",
"jsonConf",
",",
"scopes",
"...",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"fileName",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"conf",
".",
"TokenSource",
"(",
"oauth2",
".",
"NoContext",
")",
",",
"nil",
"\n",
"}"
] |
// ProjectTokenSource returns an OAuth2 TokenSource for the given Google Project ID.
|
[
"ProjectTokenSource",
"returns",
"an",
"OAuth2",
"TokenSource",
"for",
"the",
"given",
"Google",
"Project",
"ID",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/misc/release/make-release.go#L907-L926
|
train
|
perkeep/perkeep
|
internal/hashutil/hashutil.go
|
SHA256Prefix
|
func SHA256Prefix(data []byte) string {
h := sha256.New()
h.Write(data)
return fmt.Sprintf("%x", h.Sum(nil))[:20]
}
|
go
|
func SHA256Prefix(data []byte) string {
h := sha256.New()
h.Write(data)
return fmt.Sprintf("%x", h.Sum(nil))[:20]
}
|
[
"func",
"SHA256Prefix",
"(",
"data",
"[",
"]",
"byte",
")",
"string",
"{",
"h",
":=",
"sha256",
".",
"New",
"(",
")",
"\n",
"h",
".",
"Write",
"(",
"data",
")",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"h",
".",
"Sum",
"(",
"nil",
")",
")",
"[",
":",
"20",
"]",
"\n",
"}"
] |
// SHA256Prefix computes the SHA-256 digest of data and returns
// its first twenty lowercase hex digits.
|
[
"SHA256Prefix",
"computes",
"the",
"SHA",
"-",
"256",
"digest",
"of",
"data",
"and",
"returns",
"its",
"first",
"twenty",
"lowercase",
"hex",
"digits",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/hashutil/hashutil.go#L32-L36
|
train
|
perkeep/perkeep
|
internal/hashutil/hashutil.go
|
SHA1Prefix
|
func SHA1Prefix(data []byte) string {
h := sha1.New()
h.Write(data)
return fmt.Sprintf("%x", h.Sum(nil))[:20]
}
|
go
|
func SHA1Prefix(data []byte) string {
h := sha1.New()
h.Write(data)
return fmt.Sprintf("%x", h.Sum(nil))[:20]
}
|
[
"func",
"SHA1Prefix",
"(",
"data",
"[",
"]",
"byte",
")",
"string",
"{",
"h",
":=",
"sha1",
".",
"New",
"(",
")",
"\n",
"h",
".",
"Write",
"(",
"data",
")",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"h",
".",
"Sum",
"(",
"nil",
")",
")",
"[",
":",
"20",
"]",
"\n",
"}"
] |
// SHA1Prefix computes the SHA-1 digest of data and returns
// its first twenty lowercase hex digits.
|
[
"SHA1Prefix",
"computes",
"the",
"SHA",
"-",
"1",
"digest",
"of",
"data",
"and",
"returns",
"its",
"first",
"twenty",
"lowercase",
"hex",
"digits",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/hashutil/hashutil.go#L40-L44
|
train
|
perkeep/perkeep
|
internal/osutil/paths.go
|
HomeDir
|
func HomeDir() string {
failInTests()
if runtime.GOOS == "windows" {
return os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
}
return os.Getenv("HOME")
}
|
go
|
func HomeDir() string {
failInTests()
if runtime.GOOS == "windows" {
return os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
}
return os.Getenv("HOME")
}
|
[
"func",
"HomeDir",
"(",
")",
"string",
"{",
"failInTests",
"(",
")",
"\n",
"if",
"runtime",
".",
"GOOS",
"==",
"\"",
"\"",
"{",
"return",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"+",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\n",
"}"
] |
// HomeDir returns the path to the user's home directory.
// It returns the empty string if the value isn't known.
|
[
"HomeDir",
"returns",
"the",
"path",
"to",
"the",
"user",
"s",
"home",
"directory",
".",
"It",
"returns",
"the",
"empty",
"string",
"if",
"the",
"value",
"isn",
"t",
"known",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/osutil/paths.go#L37-L43
|
train
|
perkeep/perkeep
|
internal/osutil/paths.go
|
NewJSONConfigParser
|
func NewJSONConfigParser() *jsonconfig.ConfigParser {
var cp jsonconfig.ConfigParser
dir, err := PerkeepConfigDir()
if err != nil {
log.Fatalf("NewJSONConfigParser error: %v", err)
}
cp.IncludeDirs = append([]string{dir}, filepath.SplitList(os.Getenv("CAMLI_INCLUDE_PATH"))...)
return &cp
}
|
go
|
func NewJSONConfigParser() *jsonconfig.ConfigParser {
var cp jsonconfig.ConfigParser
dir, err := PerkeepConfigDir()
if err != nil {
log.Fatalf("NewJSONConfigParser error: %v", err)
}
cp.IncludeDirs = append([]string{dir}, filepath.SplitList(os.Getenv("CAMLI_INCLUDE_PATH"))...)
return &cp
}
|
[
"func",
"NewJSONConfigParser",
"(",
")",
"*",
"jsonconfig",
".",
"ConfigParser",
"{",
"var",
"cp",
"jsonconfig",
".",
"ConfigParser",
"\n",
"dir",
",",
"err",
":=",
"PerkeepConfigDir",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"cp",
".",
"IncludeDirs",
"=",
"append",
"(",
"[",
"]",
"string",
"{",
"dir",
"}",
",",
"filepath",
".",
"SplitList",
"(",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
")",
"...",
")",
"\n",
"return",
"&",
"cp",
"\n",
"}"
] |
// NewJSONConfigParser returns a jsonconfig.ConfigParser with its IncludeDirs
// set with PerkeepConfigDir and the contents of CAMLI_INCLUDE_PATH.
|
[
"NewJSONConfigParser",
"returns",
"a",
"jsonconfig",
".",
"ConfigParser",
"with",
"its",
"IncludeDirs",
"set",
"with",
"PerkeepConfigDir",
"and",
"the",
"contents",
"of",
"CAMLI_INCLUDE_PATH",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/osutil/paths.go#L332-L340
|
train
|
perkeep/perkeep
|
pkg/sorted/mem.go
|
NewMemoryKeyValue
|
func NewMemoryKeyValue() KeyValue {
db := memdb.New(comparer.DefaultComparer, 128)
return &memKeys{db: db}
}
|
go
|
func NewMemoryKeyValue() KeyValue {
db := memdb.New(comparer.DefaultComparer, 128)
return &memKeys{db: db}
}
|
[
"func",
"NewMemoryKeyValue",
"(",
")",
"KeyValue",
"{",
"db",
":=",
"memdb",
".",
"New",
"(",
"comparer",
".",
"DefaultComparer",
",",
"128",
")",
"\n",
"return",
"&",
"memKeys",
"{",
"db",
":",
"db",
"}",
"\n",
"}"
] |
// NewMemoryKeyValue returns a KeyValue implementation that's backed only
// by memory. It's mostly useful for tests and development.
|
[
"NewMemoryKeyValue",
"returns",
"a",
"KeyValue",
"implementation",
"that",
"s",
"backed",
"only",
"by",
"memory",
".",
"It",
"s",
"mostly",
"useful",
"for",
"tests",
"and",
"development",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/sorted/mem.go#L33-L36
|
train
|
perkeep/perkeep
|
app/publisher/zip.go
|
blobsFromDir
|
func (zh *zipHandler) blobsFromDir(dirPath string, dirBlob blob.Ref) ([]*blobFile, error) {
var list []*blobFile
dr, err := schema.NewDirReader(context.TODO(), zh.fetcher, dirBlob)
if err != nil {
return nil, fmt.Errorf("Could not read dir blob %v: %v", dirBlob, err)
}
ent, err := dr.Readdir(context.TODO(), -1)
if err != nil {
return nil, fmt.Errorf("Could not read dir entries: %v", err)
}
for _, v := range ent {
fullpath := path.Join(dirPath, v.FileName())
switch v.CamliType() {
case "file":
list = append(list, &blobFile{v.BlobRef(), fullpath})
case "directory":
children, err := zh.blobsFromDir(fullpath, v.BlobRef())
if err != nil {
return nil, fmt.Errorf("Could not get list of blobs from %v: %v", v.BlobRef(), err)
}
list = append(list, children...)
}
}
return list, nil
}
|
go
|
func (zh *zipHandler) blobsFromDir(dirPath string, dirBlob blob.Ref) ([]*blobFile, error) {
var list []*blobFile
dr, err := schema.NewDirReader(context.TODO(), zh.fetcher, dirBlob)
if err != nil {
return nil, fmt.Errorf("Could not read dir blob %v: %v", dirBlob, err)
}
ent, err := dr.Readdir(context.TODO(), -1)
if err != nil {
return nil, fmt.Errorf("Could not read dir entries: %v", err)
}
for _, v := range ent {
fullpath := path.Join(dirPath, v.FileName())
switch v.CamliType() {
case "file":
list = append(list, &blobFile{v.BlobRef(), fullpath})
case "directory":
children, err := zh.blobsFromDir(fullpath, v.BlobRef())
if err != nil {
return nil, fmt.Errorf("Could not get list of blobs from %v: %v", v.BlobRef(), err)
}
list = append(list, children...)
}
}
return list, nil
}
|
[
"func",
"(",
"zh",
"*",
"zipHandler",
")",
"blobsFromDir",
"(",
"dirPath",
"string",
",",
"dirBlob",
"blob",
".",
"Ref",
")",
"(",
"[",
"]",
"*",
"blobFile",
",",
"error",
")",
"{",
"var",
"list",
"[",
"]",
"*",
"blobFile",
"\n",
"dr",
",",
"err",
":=",
"schema",
".",
"NewDirReader",
"(",
"context",
".",
"TODO",
"(",
")",
",",
"zh",
".",
"fetcher",
",",
"dirBlob",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"dirBlob",
",",
"err",
")",
"\n",
"}",
"\n",
"ent",
",",
"err",
":=",
"dr",
".",
"Readdir",
"(",
"context",
".",
"TODO",
"(",
")",
",",
"-",
"1",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"ent",
"{",
"fullpath",
":=",
"path",
".",
"Join",
"(",
"dirPath",
",",
"v",
".",
"FileName",
"(",
")",
")",
"\n",
"switch",
"v",
".",
"CamliType",
"(",
")",
"{",
"case",
"\"",
"\"",
":",
"list",
"=",
"append",
"(",
"list",
",",
"&",
"blobFile",
"{",
"v",
".",
"BlobRef",
"(",
")",
",",
"fullpath",
"}",
")",
"\n",
"case",
"\"",
"\"",
":",
"children",
",",
"err",
":=",
"zh",
".",
"blobsFromDir",
"(",
"fullpath",
",",
"v",
".",
"BlobRef",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"v",
".",
"BlobRef",
"(",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"list",
"=",
"append",
"(",
"list",
",",
"children",
"...",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"list",
",",
"nil",
"\n",
"}"
] |
// blobsFromDir returns the list of file blobs in directory dirBlob.
// It only traverses permanode directories.
|
[
"blobsFromDir",
"returns",
"the",
"list",
"of",
"file",
"blobs",
"in",
"directory",
"dirBlob",
".",
"It",
"only",
"traverses",
"permanode",
"directories",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/publisher/zip.go#L159-L183
|
train
|
perkeep/perkeep
|
app/publisher/zip.go
|
renameDuplicates
|
func renameDuplicates(bf []*blobFile) sortedFiles {
noDup := make(map[string]blob.Ref)
// use a map to detect duplicates and rename them
for _, file := range bf {
if _, ok := noDup[file.path]; ok {
// path already exists, so rename
suffix := 0
var newname string
for {
suffix++
ext := path.Ext(file.path)
newname = fmt.Sprintf("%s(%d)%s",
file.path[:len(file.path)-len(ext)], suffix, ext)
if _, ok := noDup[newname]; !ok {
break
}
}
noDup[newname] = file.blobRef
} else {
noDup[file.path] = file.blobRef
}
}
// reinsert in a slice and sort it
var sorted sortedFiles
for p, b := range noDup {
sorted = append(sorted, &blobFile{path: p, blobRef: b})
}
sort.Sort(sorted)
return sorted
}
|
go
|
func renameDuplicates(bf []*blobFile) sortedFiles {
noDup := make(map[string]blob.Ref)
// use a map to detect duplicates and rename them
for _, file := range bf {
if _, ok := noDup[file.path]; ok {
// path already exists, so rename
suffix := 0
var newname string
for {
suffix++
ext := path.Ext(file.path)
newname = fmt.Sprintf("%s(%d)%s",
file.path[:len(file.path)-len(ext)], suffix, ext)
if _, ok := noDup[newname]; !ok {
break
}
}
noDup[newname] = file.blobRef
} else {
noDup[file.path] = file.blobRef
}
}
// reinsert in a slice and sort it
var sorted sortedFiles
for p, b := range noDup {
sorted = append(sorted, &blobFile{path: p, blobRef: b})
}
sort.Sort(sorted)
return sorted
}
|
[
"func",
"renameDuplicates",
"(",
"bf",
"[",
"]",
"*",
"blobFile",
")",
"sortedFiles",
"{",
"noDup",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"blob",
".",
"Ref",
")",
"\n",
"// use a map to detect duplicates and rename them",
"for",
"_",
",",
"file",
":=",
"range",
"bf",
"{",
"if",
"_",
",",
"ok",
":=",
"noDup",
"[",
"file",
".",
"path",
"]",
";",
"ok",
"{",
"// path already exists, so rename",
"suffix",
":=",
"0",
"\n",
"var",
"newname",
"string",
"\n",
"for",
"{",
"suffix",
"++",
"\n",
"ext",
":=",
"path",
".",
"Ext",
"(",
"file",
".",
"path",
")",
"\n",
"newname",
"=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"file",
".",
"path",
"[",
":",
"len",
"(",
"file",
".",
"path",
")",
"-",
"len",
"(",
"ext",
")",
"]",
",",
"suffix",
",",
"ext",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"noDup",
"[",
"newname",
"]",
";",
"!",
"ok",
"{",
"break",
"\n",
"}",
"\n",
"}",
"\n",
"noDup",
"[",
"newname",
"]",
"=",
"file",
".",
"blobRef",
"\n",
"}",
"else",
"{",
"noDup",
"[",
"file",
".",
"path",
"]",
"=",
"file",
".",
"blobRef",
"\n",
"}",
"\n",
"}",
"\n\n",
"// reinsert in a slice and sort it",
"var",
"sorted",
"sortedFiles",
"\n",
"for",
"p",
",",
"b",
":=",
"range",
"noDup",
"{",
"sorted",
"=",
"append",
"(",
"sorted",
",",
"&",
"blobFile",
"{",
"path",
":",
"p",
",",
"blobRef",
":",
"b",
"}",
")",
"\n",
"}",
"\n",
"sort",
".",
"Sort",
"(",
"sorted",
")",
"\n",
"return",
"sorted",
"\n",
"}"
] |
// renameDuplicates goes through bf to check for duplicate filepaths.
// It renames duplicate filepaths and returns a new slice, sorted by
// file path.
|
[
"renameDuplicates",
"goes",
"through",
"bf",
"to",
"check",
"for",
"duplicate",
"filepaths",
".",
"It",
"renames",
"duplicate",
"filepaths",
"and",
"returns",
"a",
"new",
"slice",
"sorted",
"by",
"file",
"path",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/publisher/zip.go#L188-L218
|
train
|
perkeep/perkeep
|
app/publisher/zip.go
|
ServeHTTP
|
func (zh *zipHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
// TODO: use http.ServeContent, so Range requests work and downloads can be resumed.
// Will require calculating the zip length once first (ideally as cheaply as possible,
// with dummy counting writer and dummy all-zero-byte-files of a fixed size),
// and then making a dummy ReadSeeker for ServeContent that can seek to the end,
// and then seek back to the beginning, but then seeks forward make it remember
// to skip that many bytes from the archive/zip writer when answering Reads.
if !httputil.IsGet(req) {
http.Error(rw, "Invalid method", http.StatusMethodNotAllowed)
return
}
bf, err := zh.blobList("", zh.root)
if err != nil {
log.Printf("Could not serve zip for %v: %v", zh.root, err)
http.Error(rw, "Server error", http.StatusInternalServerError)
return
}
blobFiles := renameDuplicates(bf)
// TODO(mpl): streaming directly won't work on appengine if the size goes
// over 32 MB. Deal with that.
h := rw.Header()
h.Set("Content-Type", "application/zip")
filename := zh.filename
if filename == "" {
filename = "download.zip"
}
h.Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": filename}))
zw := zip.NewWriter(rw)
etag := sha1.New()
for _, file := range blobFiles {
etag.Write([]byte(file.blobRef.String()))
}
h.Set("Etag", fmt.Sprintf(`"%x"`, etag.Sum(nil)))
for _, file := range blobFiles {
fr, err := schema.NewFileReader(context.TODO(), zh.fetcher, file.blobRef)
if err != nil {
log.Printf("Can not add %v in zip, not a file: %v", file.blobRef, err)
http.Error(rw, "Server error", http.StatusInternalServerError)
return
}
zh := zip.FileHeader{
Name: file.path,
Method: zip.Store,
}
zh.SetModTime(fr.ModTime())
f, err := zw.CreateHeader(&zh)
if err != nil {
log.Printf("Could not create %q in zip: %v", file.path, err)
http.Error(rw, "Server error", http.StatusInternalServerError)
return
}
_, err = io.Copy(f, fr)
fr.Close()
if err != nil {
log.Printf("Could not zip %q: %v", file.path, err)
return
}
}
err = zw.Close()
if err != nil {
log.Printf("Could not close zipwriter: %v", err)
return
}
}
|
go
|
func (zh *zipHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
// TODO: use http.ServeContent, so Range requests work and downloads can be resumed.
// Will require calculating the zip length once first (ideally as cheaply as possible,
// with dummy counting writer and dummy all-zero-byte-files of a fixed size),
// and then making a dummy ReadSeeker for ServeContent that can seek to the end,
// and then seek back to the beginning, but then seeks forward make it remember
// to skip that many bytes from the archive/zip writer when answering Reads.
if !httputil.IsGet(req) {
http.Error(rw, "Invalid method", http.StatusMethodNotAllowed)
return
}
bf, err := zh.blobList("", zh.root)
if err != nil {
log.Printf("Could not serve zip for %v: %v", zh.root, err)
http.Error(rw, "Server error", http.StatusInternalServerError)
return
}
blobFiles := renameDuplicates(bf)
// TODO(mpl): streaming directly won't work on appengine if the size goes
// over 32 MB. Deal with that.
h := rw.Header()
h.Set("Content-Type", "application/zip")
filename := zh.filename
if filename == "" {
filename = "download.zip"
}
h.Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": filename}))
zw := zip.NewWriter(rw)
etag := sha1.New()
for _, file := range blobFiles {
etag.Write([]byte(file.blobRef.String()))
}
h.Set("Etag", fmt.Sprintf(`"%x"`, etag.Sum(nil)))
for _, file := range blobFiles {
fr, err := schema.NewFileReader(context.TODO(), zh.fetcher, file.blobRef)
if err != nil {
log.Printf("Can not add %v in zip, not a file: %v", file.blobRef, err)
http.Error(rw, "Server error", http.StatusInternalServerError)
return
}
zh := zip.FileHeader{
Name: file.path,
Method: zip.Store,
}
zh.SetModTime(fr.ModTime())
f, err := zw.CreateHeader(&zh)
if err != nil {
log.Printf("Could not create %q in zip: %v", file.path, err)
http.Error(rw, "Server error", http.StatusInternalServerError)
return
}
_, err = io.Copy(f, fr)
fr.Close()
if err != nil {
log.Printf("Could not zip %q: %v", file.path, err)
return
}
}
err = zw.Close()
if err != nil {
log.Printf("Could not close zipwriter: %v", err)
return
}
}
|
[
"func",
"(",
"zh",
"*",
"zipHandler",
")",
"ServeHTTP",
"(",
"rw",
"http",
".",
"ResponseWriter",
",",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"// TODO: use http.ServeContent, so Range requests work and downloads can be resumed.",
"// Will require calculating the zip length once first (ideally as cheaply as possible,",
"// with dummy counting writer and dummy all-zero-byte-files of a fixed size),",
"// and then making a dummy ReadSeeker for ServeContent that can seek to the end,",
"// and then seek back to the beginning, but then seeks forward make it remember",
"// to skip that many bytes from the archive/zip writer when answering Reads.",
"if",
"!",
"httputil",
".",
"IsGet",
"(",
"req",
")",
"{",
"http",
".",
"Error",
"(",
"rw",
",",
"\"",
"\"",
",",
"http",
".",
"StatusMethodNotAllowed",
")",
"\n",
"return",
"\n",
"}",
"\n",
"bf",
",",
"err",
":=",
"zh",
".",
"blobList",
"(",
"\"",
"\"",
",",
"zh",
".",
"root",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"zh",
".",
"root",
",",
"err",
")",
"\n",
"http",
".",
"Error",
"(",
"rw",
",",
"\"",
"\"",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"blobFiles",
":=",
"renameDuplicates",
"(",
"bf",
")",
"\n\n",
"// TODO(mpl): streaming directly won't work on appengine if the size goes",
"// over 32 MB. Deal with that.",
"h",
":=",
"rw",
".",
"Header",
"(",
")",
"\n",
"h",
".",
"Set",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"filename",
":=",
"zh",
".",
"filename",
"\n",
"if",
"filename",
"==",
"\"",
"\"",
"{",
"filename",
"=",
"\"",
"\"",
"\n",
"}",
"\n",
"h",
".",
"Set",
"(",
"\"",
"\"",
",",
"mime",
".",
"FormatMediaType",
"(",
"\"",
"\"",
",",
"map",
"[",
"string",
"]",
"string",
"{",
"\"",
"\"",
":",
"filename",
"}",
")",
")",
"\n",
"zw",
":=",
"zip",
".",
"NewWriter",
"(",
"rw",
")",
"\n",
"etag",
":=",
"sha1",
".",
"New",
"(",
")",
"\n",
"for",
"_",
",",
"file",
":=",
"range",
"blobFiles",
"{",
"etag",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"file",
".",
"blobRef",
".",
"String",
"(",
")",
")",
")",
"\n",
"}",
"\n",
"h",
".",
"Set",
"(",
"\"",
"\"",
",",
"fmt",
".",
"Sprintf",
"(",
"`\"%x\"`",
",",
"etag",
".",
"Sum",
"(",
"nil",
")",
")",
")",
"\n\n",
"for",
"_",
",",
"file",
":=",
"range",
"blobFiles",
"{",
"fr",
",",
"err",
":=",
"schema",
".",
"NewFileReader",
"(",
"context",
".",
"TODO",
"(",
")",
",",
"zh",
".",
"fetcher",
",",
"file",
".",
"blobRef",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"file",
".",
"blobRef",
",",
"err",
")",
"\n",
"http",
".",
"Error",
"(",
"rw",
",",
"\"",
"\"",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"zh",
":=",
"zip",
".",
"FileHeader",
"{",
"Name",
":",
"file",
".",
"path",
",",
"Method",
":",
"zip",
".",
"Store",
",",
"}",
"\n",
"zh",
".",
"SetModTime",
"(",
"fr",
".",
"ModTime",
"(",
")",
")",
"\n",
"f",
",",
"err",
":=",
"zw",
".",
"CreateHeader",
"(",
"&",
"zh",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"file",
".",
"path",
",",
"err",
")",
"\n",
"http",
".",
"Error",
"(",
"rw",
",",
"\"",
"\"",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"_",
",",
"err",
"=",
"io",
".",
"Copy",
"(",
"f",
",",
"fr",
")",
"\n",
"fr",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"file",
".",
"path",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"err",
"=",
"zw",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}"
] |
// ServeHTTP streams a zip archive of all the files "under"
// zh.root. That is, all the files pointed by file permanodes,
// which are directly members of zh.root or recursively down
// directory permanodes and permanodes members.
// To build the fullpath of a file in a collection, it uses
// the collection title if present, its blobRef otherwise, as
// a directory name.
|
[
"ServeHTTP",
"streams",
"a",
"zip",
"archive",
"of",
"all",
"the",
"files",
"under",
"zh",
".",
"root",
".",
"That",
"is",
"all",
"the",
"files",
"pointed",
"by",
"file",
"permanodes",
"which",
"are",
"directly",
"members",
"of",
"zh",
".",
"root",
"or",
"recursively",
"down",
"directory",
"permanodes",
"and",
"permanodes",
"members",
".",
"To",
"build",
"the",
"fullpath",
"of",
"a",
"file",
"in",
"a",
"collection",
"it",
"uses",
"the",
"collection",
"title",
"if",
"present",
"its",
"blobRef",
"otherwise",
"as",
"a",
"directory",
"name",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/publisher/zip.go#L227-L292
|
train
|
perkeep/perkeep
|
server/perkeepd/ui/goui/sharebutton/gen_ShareItemsBtn_reactGen.go
|
Props
|
func (s ShareItemsBtnDef) Props() ShareItemsBtnProps {
uprops := s.ComponentDef.Props()
return uprops.(ShareItemsBtnProps)
}
|
go
|
func (s ShareItemsBtnDef) Props() ShareItemsBtnProps {
uprops := s.ComponentDef.Props()
return uprops.(ShareItemsBtnProps)
}
|
[
"func",
"(",
"s",
"ShareItemsBtnDef",
")",
"Props",
"(",
")",
"ShareItemsBtnProps",
"{",
"uprops",
":=",
"s",
".",
"ComponentDef",
".",
"Props",
"(",
")",
"\n",
"return",
"uprops",
".",
"(",
"ShareItemsBtnProps",
")",
"\n",
"}"
] |
// Props is an auto-generated proxy to the current props of ShareItemsBtn
|
[
"Props",
"is",
"an",
"auto",
"-",
"generated",
"proxy",
"to",
"the",
"current",
"props",
"of",
"ShareItemsBtn"
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/server/perkeepd/ui/goui/sharebutton/gen_ShareItemsBtn_reactGen.go#L30-L33
|
train
|
perkeep/perkeep
|
app/publisher/main.go
|
appConfig
|
func appConfig() (*config, error) {
configURL := os.Getenv("CAMLI_APP_CONFIG_URL")
if configURL == "" {
return nil, fmt.Errorf("Publisher application needs a CAMLI_APP_CONFIG_URL env var")
}
cl, err := app.Client()
if err != nil {
return nil, fmt.Errorf("could not get a client to fetch extra config: %v", err)
}
conf := &config{}
pause := time.Second
giveupTime := time.Now().Add(time.Hour)
for {
err := cl.GetJSON(context.TODO(), configURL, conf)
if err == nil {
break
}
if time.Now().After(giveupTime) {
logger.Fatalf("Giving up on starting: could not get app config at %v: %v", configURL, err)
}
logger.Printf("could not get app config at %v: %v. Will retry in a while.", configURL, err)
time.Sleep(pause)
pause *= 2
}
return conf, nil
}
|
go
|
func appConfig() (*config, error) {
configURL := os.Getenv("CAMLI_APP_CONFIG_URL")
if configURL == "" {
return nil, fmt.Errorf("Publisher application needs a CAMLI_APP_CONFIG_URL env var")
}
cl, err := app.Client()
if err != nil {
return nil, fmt.Errorf("could not get a client to fetch extra config: %v", err)
}
conf := &config{}
pause := time.Second
giveupTime := time.Now().Add(time.Hour)
for {
err := cl.GetJSON(context.TODO(), configURL, conf)
if err == nil {
break
}
if time.Now().After(giveupTime) {
logger.Fatalf("Giving up on starting: could not get app config at %v: %v", configURL, err)
}
logger.Printf("could not get app config at %v: %v. Will retry in a while.", configURL, err)
time.Sleep(pause)
pause *= 2
}
return conf, nil
}
|
[
"func",
"appConfig",
"(",
")",
"(",
"*",
"config",
",",
"error",
")",
"{",
"configURL",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\n",
"if",
"configURL",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"cl",
",",
"err",
":=",
"app",
".",
"Client",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"conf",
":=",
"&",
"config",
"{",
"}",
"\n",
"pause",
":=",
"time",
".",
"Second",
"\n",
"giveupTime",
":=",
"time",
".",
"Now",
"(",
")",
".",
"Add",
"(",
"time",
".",
"Hour",
")",
"\n",
"for",
"{",
"err",
":=",
"cl",
".",
"GetJSON",
"(",
"context",
".",
"TODO",
"(",
")",
",",
"configURL",
",",
"conf",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"break",
"\n",
"}",
"\n",
"if",
"time",
".",
"Now",
"(",
")",
".",
"After",
"(",
"giveupTime",
")",
"{",
"logger",
".",
"Fatalf",
"(",
"\"",
"\"",
",",
"configURL",
",",
"err",
")",
"\n",
"}",
"\n",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"configURL",
",",
"err",
")",
"\n",
"time",
".",
"Sleep",
"(",
"pause",
")",
"\n",
"pause",
"*=",
"2",
"\n",
"}",
"\n",
"return",
"conf",
",",
"nil",
"\n",
"}"
] |
// appConfig keeps on trying to fetch the extra config from the app handler. If
// it doesn't succed after an hour has passed, the program exits.
|
[
"appConfig",
"keeps",
"on",
"trying",
"to",
"fetch",
"the",
"extra",
"config",
"from",
"the",
"app",
"handler",
".",
"If",
"it",
"doesn",
"t",
"succed",
"after",
"an",
"hour",
"has",
"passed",
"the",
"program",
"exits",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/publisher/main.go#L93-L118
|
train
|
perkeep/perkeep
|
app/publisher/main.go
|
setMasterQuery
|
func (ph *publishHandler) setMasterQuery(topNode blob.Ref) error {
query := &search.SearchQuery{
Sort: search.CreatedDesc,
Limit: -1,
Constraint: &search.Constraint{
Permanode: &search.PermanodeConstraint{
Relation: &search.RelationConstraint{
Relation: "parent",
Any: &search.Constraint{
BlobRefPrefix: topNode.String(),
},
},
},
},
Describe: &search.DescribeRequest{
Depth: 1,
Rules: []*search.DescribeRule{
{Attrs: []string{"camliContent", "camliContentImage", "camliMember", "camliPath:*"}},
},
},
}
data, err := json.Marshal(query)
if err != nil {
return err
}
// TODO(mpl): we should use app.Client instead, but a *client.Client
// Post method doesn't let us get the body.
req, err := http.NewRequest("POST", ph.masterQueryURL, bytes.NewReader(data))
if err != nil {
return err
}
if err := addAuth(req); err != nil {
return err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if string(body) != "OK" {
return fmt.Errorf("error setting master query on app handler: %v", string(body))
}
return nil
}
|
go
|
func (ph *publishHandler) setMasterQuery(topNode blob.Ref) error {
query := &search.SearchQuery{
Sort: search.CreatedDesc,
Limit: -1,
Constraint: &search.Constraint{
Permanode: &search.PermanodeConstraint{
Relation: &search.RelationConstraint{
Relation: "parent",
Any: &search.Constraint{
BlobRefPrefix: topNode.String(),
},
},
},
},
Describe: &search.DescribeRequest{
Depth: 1,
Rules: []*search.DescribeRule{
{Attrs: []string{"camliContent", "camliContentImage", "camliMember", "camliPath:*"}},
},
},
}
data, err := json.Marshal(query)
if err != nil {
return err
}
// TODO(mpl): we should use app.Client instead, but a *client.Client
// Post method doesn't let us get the body.
req, err := http.NewRequest("POST", ph.masterQueryURL, bytes.NewReader(data))
if err != nil {
return err
}
if err := addAuth(req); err != nil {
return err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if string(body) != "OK" {
return fmt.Errorf("error setting master query on app handler: %v", string(body))
}
return nil
}
|
[
"func",
"(",
"ph",
"*",
"publishHandler",
")",
"setMasterQuery",
"(",
"topNode",
"blob",
".",
"Ref",
")",
"error",
"{",
"query",
":=",
"&",
"search",
".",
"SearchQuery",
"{",
"Sort",
":",
"search",
".",
"CreatedDesc",
",",
"Limit",
":",
"-",
"1",
",",
"Constraint",
":",
"&",
"search",
".",
"Constraint",
"{",
"Permanode",
":",
"&",
"search",
".",
"PermanodeConstraint",
"{",
"Relation",
":",
"&",
"search",
".",
"RelationConstraint",
"{",
"Relation",
":",
"\"",
"\"",
",",
"Any",
":",
"&",
"search",
".",
"Constraint",
"{",
"BlobRefPrefix",
":",
"topNode",
".",
"String",
"(",
")",
",",
"}",
",",
"}",
",",
"}",
",",
"}",
",",
"Describe",
":",
"&",
"search",
".",
"DescribeRequest",
"{",
"Depth",
":",
"1",
",",
"Rules",
":",
"[",
"]",
"*",
"search",
".",
"DescribeRule",
"{",
"{",
"Attrs",
":",
"[",
"]",
"string",
"{",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
",",
"\"",
"\"",
"}",
"}",
",",
"}",
",",
"}",
",",
"}",
"\n",
"data",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"query",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"// TODO(mpl): we should use app.Client instead, but a *client.Client",
"// Post method doesn't let us get the body.",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"\"",
"\"",
",",
"ph",
".",
"masterQueryURL",
",",
"bytes",
".",
"NewReader",
"(",
"data",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
":=",
"addAuth",
"(",
"req",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"resp",
",",
"err",
":=",
"http",
".",
"DefaultClient",
".",
"Do",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"body",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"resp",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"string",
"(",
"body",
")",
"!=",
"\"",
"\"",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"string",
"(",
"body",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// setMasterQuery registers with the app handler a master query that includes
// topNode and all its descendants as the search response.
|
[
"setMasterQuery",
"registers",
"with",
"the",
"app",
"handler",
"a",
"master",
"query",
"that",
"includes",
"topNode",
"and",
"all",
"its",
"descendants",
"as",
"the",
"search",
"response",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/publisher/main.go#L122-L169
|
train
|
perkeep/perkeep
|
app/publisher/main.go
|
resolvePrefixHop
|
func (ph *publishHandler) resolvePrefixHop(parent blob.Ref, prefix string) (child blob.Ref, err error) {
// TODO: this is a linear scan right now. this should be
// optimized to use a new database table of members so this is
// a quick lookup. in the meantime it should be in memcached
// at least.
if len(prefix) < 8 {
return blob.Ref{}, fmt.Errorf("Member prefix %q too small", prefix)
}
des, err := ph.describe(parent)
if err != nil {
return blob.Ref{}, fmt.Errorf("Failed to describe member %q in parent %q", prefix, parent)
}
if des.Permanode != nil {
cr, ok := des.ContentRef()
if ok && strings.HasPrefix(cr.Digest(), prefix) {
return cr, nil
}
for _, member := range des.Members() {
if strings.HasPrefix(member.BlobRef.Digest(), prefix) {
return member.BlobRef, nil
}
}
crdes, err := ph.describe(cr)
if err != nil {
return blob.Ref{}, fmt.Errorf("Failed to describe content %q of parent %q", cr, parent)
}
if crdes.Dir != nil {
return ph.resolvePrefixHop(cr, prefix)
}
} else if des.Dir != nil {
for _, child := range des.DirChildren {
if strings.HasPrefix(child.Digest(), prefix) {
return child, nil
}
}
}
return blob.Ref{}, fmt.Errorf("Member prefix %q not found in %q", prefix, parent)
}
|
go
|
func (ph *publishHandler) resolvePrefixHop(parent blob.Ref, prefix string) (child blob.Ref, err error) {
// TODO: this is a linear scan right now. this should be
// optimized to use a new database table of members so this is
// a quick lookup. in the meantime it should be in memcached
// at least.
if len(prefix) < 8 {
return blob.Ref{}, fmt.Errorf("Member prefix %q too small", prefix)
}
des, err := ph.describe(parent)
if err != nil {
return blob.Ref{}, fmt.Errorf("Failed to describe member %q in parent %q", prefix, parent)
}
if des.Permanode != nil {
cr, ok := des.ContentRef()
if ok && strings.HasPrefix(cr.Digest(), prefix) {
return cr, nil
}
for _, member := range des.Members() {
if strings.HasPrefix(member.BlobRef.Digest(), prefix) {
return member.BlobRef, nil
}
}
crdes, err := ph.describe(cr)
if err != nil {
return blob.Ref{}, fmt.Errorf("Failed to describe content %q of parent %q", cr, parent)
}
if crdes.Dir != nil {
return ph.resolvePrefixHop(cr, prefix)
}
} else if des.Dir != nil {
for _, child := range des.DirChildren {
if strings.HasPrefix(child.Digest(), prefix) {
return child, nil
}
}
}
return blob.Ref{}, fmt.Errorf("Member prefix %q not found in %q", prefix, parent)
}
|
[
"func",
"(",
"ph",
"*",
"publishHandler",
")",
"resolvePrefixHop",
"(",
"parent",
"blob",
".",
"Ref",
",",
"prefix",
"string",
")",
"(",
"child",
"blob",
".",
"Ref",
",",
"err",
"error",
")",
"{",
"// TODO: this is a linear scan right now. this should be",
"// optimized to use a new database table of members so this is",
"// a quick lookup. in the meantime it should be in memcached",
"// at least.",
"if",
"len",
"(",
"prefix",
")",
"<",
"8",
"{",
"return",
"blob",
".",
"Ref",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"prefix",
")",
"\n",
"}",
"\n",
"des",
",",
"err",
":=",
"ph",
".",
"describe",
"(",
"parent",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"blob",
".",
"Ref",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"prefix",
",",
"parent",
")",
"\n",
"}",
"\n",
"if",
"des",
".",
"Permanode",
"!=",
"nil",
"{",
"cr",
",",
"ok",
":=",
"des",
".",
"ContentRef",
"(",
")",
"\n",
"if",
"ok",
"&&",
"strings",
".",
"HasPrefix",
"(",
"cr",
".",
"Digest",
"(",
")",
",",
"prefix",
")",
"{",
"return",
"cr",
",",
"nil",
"\n",
"}",
"\n",
"for",
"_",
",",
"member",
":=",
"range",
"des",
".",
"Members",
"(",
")",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"member",
".",
"BlobRef",
".",
"Digest",
"(",
")",
",",
"prefix",
")",
"{",
"return",
"member",
".",
"BlobRef",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"crdes",
",",
"err",
":=",
"ph",
".",
"describe",
"(",
"cr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"blob",
".",
"Ref",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"cr",
",",
"parent",
")",
"\n",
"}",
"\n",
"if",
"crdes",
".",
"Dir",
"!=",
"nil",
"{",
"return",
"ph",
".",
"resolvePrefixHop",
"(",
"cr",
",",
"prefix",
")",
"\n",
"}",
"\n",
"}",
"else",
"if",
"des",
".",
"Dir",
"!=",
"nil",
"{",
"for",
"_",
",",
"child",
":=",
"range",
"des",
".",
"DirChildren",
"{",
"if",
"strings",
".",
"HasPrefix",
"(",
"child",
".",
"Digest",
"(",
")",
",",
"prefix",
")",
"{",
"return",
"child",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"blob",
".",
"Ref",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"prefix",
",",
"parent",
")",
"\n",
"}"
] |
// Given a blobref and a few hex characters of the digest of the next hop, return the complete
// blobref of the prefix, if that's a valid next hop.
|
[
"Given",
"a",
"blobref",
"and",
"a",
"few",
"hex",
"characters",
"of",
"the",
"digest",
"of",
"the",
"next",
"hop",
"return",
"the",
"complete",
"blobref",
"of",
"the",
"prefix",
"if",
"that",
"s",
"a",
"valid",
"next",
"hop",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/publisher/main.go#L565-L602
|
train
|
perkeep/perkeep
|
app/publisher/main.go
|
serveSubjectTemplate
|
func (pr *publishRequest) serveSubjectTemplate() {
res, err := pr.ph.deepDescribe(pr.subject)
if err != nil {
httputil.ServeError(pr.rw, pr.req, err)
return
}
pr.ph.cacheDescribed(res.Meta)
subdes := res.Meta[pr.subject.String()]
if subdes.CamliType == "file" {
pr.serveFileDownload(subdes)
return
}
headerFunc := func() *publish.PageHeader {
return pr.subjectHeader(res.Meta)
}
fileFunc := func() *publish.PageFile {
file, err := pr.subjectFile(res.Meta)
if err != nil {
logf("%v", err)
return nil
}
return file
}
membersFunc := func() *publish.PageMembers {
members, err := pr.subjectMembers(res.Meta)
if err != nil {
logf("%v", err)
return nil
}
return members
}
page := &publish.SubjectPage{
Header: headerFunc,
File: fileFunc,
Members: membersFunc,
}
err = pr.ph.goTemplate.Execute(pr.rw, page)
if err != nil {
logf("Error serving subject template: %v", err)
http.Error(pr.rw, "Error serving template", http.StatusInternalServerError)
return
}
}
|
go
|
func (pr *publishRequest) serveSubjectTemplate() {
res, err := pr.ph.deepDescribe(pr.subject)
if err != nil {
httputil.ServeError(pr.rw, pr.req, err)
return
}
pr.ph.cacheDescribed(res.Meta)
subdes := res.Meta[pr.subject.String()]
if subdes.CamliType == "file" {
pr.serveFileDownload(subdes)
return
}
headerFunc := func() *publish.PageHeader {
return pr.subjectHeader(res.Meta)
}
fileFunc := func() *publish.PageFile {
file, err := pr.subjectFile(res.Meta)
if err != nil {
logf("%v", err)
return nil
}
return file
}
membersFunc := func() *publish.PageMembers {
members, err := pr.subjectMembers(res.Meta)
if err != nil {
logf("%v", err)
return nil
}
return members
}
page := &publish.SubjectPage{
Header: headerFunc,
File: fileFunc,
Members: membersFunc,
}
err = pr.ph.goTemplate.Execute(pr.rw, page)
if err != nil {
logf("Error serving subject template: %v", err)
http.Error(pr.rw, "Error serving template", http.StatusInternalServerError)
return
}
}
|
[
"func",
"(",
"pr",
"*",
"publishRequest",
")",
"serveSubjectTemplate",
"(",
")",
"{",
"res",
",",
"err",
":=",
"pr",
".",
"ph",
".",
"deepDescribe",
"(",
"pr",
".",
"subject",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"httputil",
".",
"ServeError",
"(",
"pr",
".",
"rw",
",",
"pr",
".",
"req",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"pr",
".",
"ph",
".",
"cacheDescribed",
"(",
"res",
".",
"Meta",
")",
"\n\n",
"subdes",
":=",
"res",
".",
"Meta",
"[",
"pr",
".",
"subject",
".",
"String",
"(",
")",
"]",
"\n",
"if",
"subdes",
".",
"CamliType",
"==",
"\"",
"\"",
"{",
"pr",
".",
"serveFileDownload",
"(",
"subdes",
")",
"\n",
"return",
"\n",
"}",
"\n\n",
"headerFunc",
":=",
"func",
"(",
")",
"*",
"publish",
".",
"PageHeader",
"{",
"return",
"pr",
".",
"subjectHeader",
"(",
"res",
".",
"Meta",
")",
"\n",
"}",
"\n",
"fileFunc",
":=",
"func",
"(",
")",
"*",
"publish",
".",
"PageFile",
"{",
"file",
",",
"err",
":=",
"pr",
".",
"subjectFile",
"(",
"res",
".",
"Meta",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"file",
"\n",
"}",
"\n",
"membersFunc",
":=",
"func",
"(",
")",
"*",
"publish",
".",
"PageMembers",
"{",
"members",
",",
"err",
":=",
"pr",
".",
"subjectMembers",
"(",
"res",
".",
"Meta",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"members",
"\n",
"}",
"\n",
"page",
":=",
"&",
"publish",
".",
"SubjectPage",
"{",
"Header",
":",
"headerFunc",
",",
"File",
":",
"fileFunc",
",",
"Members",
":",
"membersFunc",
",",
"}",
"\n\n",
"err",
"=",
"pr",
".",
"ph",
".",
"goTemplate",
".",
"Execute",
"(",
"pr",
".",
"rw",
",",
"page",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"http",
".",
"Error",
"(",
"pr",
".",
"rw",
",",
"\"",
"\"",
",",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}"
] |
// serveSubjectTemplate creates the funcs to generate the PageHeader, PageFile,
// and pageMembers that can be used by the subject template, and serves the template.
|
[
"serveSubjectTemplate",
"creates",
"the",
"funcs",
"to",
"generate",
"the",
"PageHeader",
"PageFile",
"and",
"pageMembers",
"that",
"can",
"be",
"used",
"by",
"the",
"subject",
"template",
"and",
"serves",
"the",
"template",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/publisher/main.go#L863-L908
|
train
|
perkeep/perkeep
|
app/publisher/main.go
|
subjectHeader
|
func (pr *publishRequest) subjectHeader(described map[string]*search.DescribedBlob) *publish.PageHeader {
subdes := described[pr.subject.String()]
header := &publish.PageHeader{
Title: html.EscapeString(getTitle(subdes.BlobRef, described)),
CSSFiles: pr.cssFiles(),
JSDeps: pr.jsDeps(),
Subject: pr.subject,
Host: pr.req.Host,
SubjectBasePath: pr.subjectBasePath,
PathPrefix: pr.base,
PublishedRoot: pr.publishedRoot,
}
return header
}
|
go
|
func (pr *publishRequest) subjectHeader(described map[string]*search.DescribedBlob) *publish.PageHeader {
subdes := described[pr.subject.String()]
header := &publish.PageHeader{
Title: html.EscapeString(getTitle(subdes.BlobRef, described)),
CSSFiles: pr.cssFiles(),
JSDeps: pr.jsDeps(),
Subject: pr.subject,
Host: pr.req.Host,
SubjectBasePath: pr.subjectBasePath,
PathPrefix: pr.base,
PublishedRoot: pr.publishedRoot,
}
return header
}
|
[
"func",
"(",
"pr",
"*",
"publishRequest",
")",
"subjectHeader",
"(",
"described",
"map",
"[",
"string",
"]",
"*",
"search",
".",
"DescribedBlob",
")",
"*",
"publish",
".",
"PageHeader",
"{",
"subdes",
":=",
"described",
"[",
"pr",
".",
"subject",
".",
"String",
"(",
")",
"]",
"\n",
"header",
":=",
"&",
"publish",
".",
"PageHeader",
"{",
"Title",
":",
"html",
".",
"EscapeString",
"(",
"getTitle",
"(",
"subdes",
".",
"BlobRef",
",",
"described",
")",
")",
",",
"CSSFiles",
":",
"pr",
".",
"cssFiles",
"(",
")",
",",
"JSDeps",
":",
"pr",
".",
"jsDeps",
"(",
")",
",",
"Subject",
":",
"pr",
".",
"subject",
",",
"Host",
":",
"pr",
".",
"req",
".",
"Host",
",",
"SubjectBasePath",
":",
"pr",
".",
"subjectBasePath",
",",
"PathPrefix",
":",
"pr",
".",
"base",
",",
"PublishedRoot",
":",
"pr",
".",
"publishedRoot",
",",
"}",
"\n",
"return",
"header",
"\n",
"}"
] |
// subjectHeader returns the PageHeader corresponding to the described subject.
|
[
"subjectHeader",
"returns",
"the",
"PageHeader",
"corresponding",
"to",
"the",
"described",
"subject",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/publisher/main.go#L977-L990
|
train
|
perkeep/perkeep
|
app/publisher/main.go
|
subjectFile
|
func (pr *publishRequest) subjectFile(described map[string]*search.DescribedBlob) (*publish.PageFile, error) {
subdes := described[pr.subject.String()]
contentRef, ok := subdes.ContentRef()
if !ok {
return nil, nil
}
fileDes, err := pr.ph.describe(contentRef)
if err != nil {
return nil, err
}
if fileDes.File == nil {
// most likely a dir
return nil, nil
}
path := []blob.Ref{pr.subject, contentRef}
downloadURL := pr.SubresFileURL(path, fileDes.File.FileName)
thumbnailURL := ""
if fileDes.File.IsImage() {
thumbnailURL = pr.SubresThumbnailURL(path, fileDes.File.FileName, 600)
}
fileName := html.EscapeString(fileDes.File.FileName)
return &publish.PageFile{
FileName: fileName,
Size: fileDes.File.Size,
MIMEType: fileDes.File.MIMEType,
IsImage: fileDes.File.IsImage(),
DownloadURL: downloadURL,
ThumbnailURL: thumbnailURL,
DomID: contentRef.DomID(),
Nav: func() *publish.Nav {
return nil
},
}, nil
}
|
go
|
func (pr *publishRequest) subjectFile(described map[string]*search.DescribedBlob) (*publish.PageFile, error) {
subdes := described[pr.subject.String()]
contentRef, ok := subdes.ContentRef()
if !ok {
return nil, nil
}
fileDes, err := pr.ph.describe(contentRef)
if err != nil {
return nil, err
}
if fileDes.File == nil {
// most likely a dir
return nil, nil
}
path := []blob.Ref{pr.subject, contentRef}
downloadURL := pr.SubresFileURL(path, fileDes.File.FileName)
thumbnailURL := ""
if fileDes.File.IsImage() {
thumbnailURL = pr.SubresThumbnailURL(path, fileDes.File.FileName, 600)
}
fileName := html.EscapeString(fileDes.File.FileName)
return &publish.PageFile{
FileName: fileName,
Size: fileDes.File.Size,
MIMEType: fileDes.File.MIMEType,
IsImage: fileDes.File.IsImage(),
DownloadURL: downloadURL,
ThumbnailURL: thumbnailURL,
DomID: contentRef.DomID(),
Nav: func() *publish.Nav {
return nil
},
}, nil
}
|
[
"func",
"(",
"pr",
"*",
"publishRequest",
")",
"subjectFile",
"(",
"described",
"map",
"[",
"string",
"]",
"*",
"search",
".",
"DescribedBlob",
")",
"(",
"*",
"publish",
".",
"PageFile",
",",
"error",
")",
"{",
"subdes",
":=",
"described",
"[",
"pr",
".",
"subject",
".",
"String",
"(",
")",
"]",
"\n",
"contentRef",
",",
"ok",
":=",
"subdes",
".",
"ContentRef",
"(",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"fileDes",
",",
"err",
":=",
"pr",
".",
"ph",
".",
"describe",
"(",
"contentRef",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"fileDes",
".",
"File",
"==",
"nil",
"{",
"// most likely a dir",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"path",
":=",
"[",
"]",
"blob",
".",
"Ref",
"{",
"pr",
".",
"subject",
",",
"contentRef",
"}",
"\n",
"downloadURL",
":=",
"pr",
".",
"SubresFileURL",
"(",
"path",
",",
"fileDes",
".",
"File",
".",
"FileName",
")",
"\n",
"thumbnailURL",
":=",
"\"",
"\"",
"\n",
"if",
"fileDes",
".",
"File",
".",
"IsImage",
"(",
")",
"{",
"thumbnailURL",
"=",
"pr",
".",
"SubresThumbnailURL",
"(",
"path",
",",
"fileDes",
".",
"File",
".",
"FileName",
",",
"600",
")",
"\n",
"}",
"\n",
"fileName",
":=",
"html",
".",
"EscapeString",
"(",
"fileDes",
".",
"File",
".",
"FileName",
")",
"\n",
"return",
"&",
"publish",
".",
"PageFile",
"{",
"FileName",
":",
"fileName",
",",
"Size",
":",
"fileDes",
".",
"File",
".",
"Size",
",",
"MIMEType",
":",
"fileDes",
".",
"File",
".",
"MIMEType",
",",
"IsImage",
":",
"fileDes",
".",
"File",
".",
"IsImage",
"(",
")",
",",
"DownloadURL",
":",
"downloadURL",
",",
"ThumbnailURL",
":",
"thumbnailURL",
",",
"DomID",
":",
"contentRef",
".",
"DomID",
"(",
")",
",",
"Nav",
":",
"func",
"(",
")",
"*",
"publish",
".",
"Nav",
"{",
"return",
"nil",
"\n",
"}",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// subjectFile returns the relevant PageFile if the described subject is a file permanode.
|
[
"subjectFile",
"returns",
"the",
"relevant",
"PageFile",
"if",
"the",
"described",
"subject",
"is",
"a",
"file",
"permanode",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/publisher/main.go#L1037-L1071
|
train
|
perkeep/perkeep
|
app/publisher/main.go
|
subjectMembers
|
func (pr *publishRequest) subjectMembers(resMap map[string]*search.DescribedBlob) (*publish.PageMembers, error) {
subdes := resMap[pr.subject.String()]
res, err := pr.ph.describeMembers(pr.subject)
if err != nil {
return nil, err
}
members := []*search.DescribedBlob{}
for _, v := range res.Blobs {
members = append(members, res.Describe.Meta[v.Blob.String()])
}
if len(members) == 0 {
return nil, nil
}
zipName := ""
if title := getTitle(subdes.BlobRef, resMap); title == "" {
zipName = "download.zip"
} else {
zipName = title + ".zip"
}
subjectPath := pr.subjectBasePath
if !strings.Contains(subjectPath, "/-/") {
subjectPath += "/-"
}
return &publish.PageMembers{
SubjectPath: subjectPath,
ZipName: zipName,
Members: members,
Description: func(member *search.DescribedBlob) string {
des := member.Description()
if des != "" {
des = " - " + des
}
return des
},
Title: func(member *search.DescribedBlob) string {
memberTitle := getTitle(member.BlobRef, resMap)
if memberTitle == "" {
memberTitle = member.BlobRef.DigestPrefix(10)
}
return html.EscapeString(memberTitle)
},
Path: func(member *search.DescribedBlob) string {
return pr.memberPath(member.BlobRef)
},
DomID: func(member *search.DescribedBlob) string {
return member.DomID()
},
FileInfo: func(member *search.DescribedBlob) *publish.MemberFileInfo {
if path, fileInfo, ok := getFileInfo(member.BlobRef, resMap); ok {
info := &publish.MemberFileInfo{
FileName: fileInfo.FileName,
FileDomID: path[len(path)-1].DomID(),
FilePath: html.EscapeString(pr.SubresFileURL(path, fileInfo.FileName)),
}
if fileInfo.IsImage() {
info.FileThumbnailURL = pr.SubresThumbnailURL(path, fileInfo.FileName, 200)
}
return info
}
return nil
},
}, nil
}
|
go
|
func (pr *publishRequest) subjectMembers(resMap map[string]*search.DescribedBlob) (*publish.PageMembers, error) {
subdes := resMap[pr.subject.String()]
res, err := pr.ph.describeMembers(pr.subject)
if err != nil {
return nil, err
}
members := []*search.DescribedBlob{}
for _, v := range res.Blobs {
members = append(members, res.Describe.Meta[v.Blob.String()])
}
if len(members) == 0 {
return nil, nil
}
zipName := ""
if title := getTitle(subdes.BlobRef, resMap); title == "" {
zipName = "download.zip"
} else {
zipName = title + ".zip"
}
subjectPath := pr.subjectBasePath
if !strings.Contains(subjectPath, "/-/") {
subjectPath += "/-"
}
return &publish.PageMembers{
SubjectPath: subjectPath,
ZipName: zipName,
Members: members,
Description: func(member *search.DescribedBlob) string {
des := member.Description()
if des != "" {
des = " - " + des
}
return des
},
Title: func(member *search.DescribedBlob) string {
memberTitle := getTitle(member.BlobRef, resMap)
if memberTitle == "" {
memberTitle = member.BlobRef.DigestPrefix(10)
}
return html.EscapeString(memberTitle)
},
Path: func(member *search.DescribedBlob) string {
return pr.memberPath(member.BlobRef)
},
DomID: func(member *search.DescribedBlob) string {
return member.DomID()
},
FileInfo: func(member *search.DescribedBlob) *publish.MemberFileInfo {
if path, fileInfo, ok := getFileInfo(member.BlobRef, resMap); ok {
info := &publish.MemberFileInfo{
FileName: fileInfo.FileName,
FileDomID: path[len(path)-1].DomID(),
FilePath: html.EscapeString(pr.SubresFileURL(path, fileInfo.FileName)),
}
if fileInfo.IsImage() {
info.FileThumbnailURL = pr.SubresThumbnailURL(path, fileInfo.FileName, 200)
}
return info
}
return nil
},
}, nil
}
|
[
"func",
"(",
"pr",
"*",
"publishRequest",
")",
"subjectMembers",
"(",
"resMap",
"map",
"[",
"string",
"]",
"*",
"search",
".",
"DescribedBlob",
")",
"(",
"*",
"publish",
".",
"PageMembers",
",",
"error",
")",
"{",
"subdes",
":=",
"resMap",
"[",
"pr",
".",
"subject",
".",
"String",
"(",
")",
"]",
"\n",
"res",
",",
"err",
":=",
"pr",
".",
"ph",
".",
"describeMembers",
"(",
"pr",
".",
"subject",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"members",
":=",
"[",
"]",
"*",
"search",
".",
"DescribedBlob",
"{",
"}",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"res",
".",
"Blobs",
"{",
"members",
"=",
"append",
"(",
"members",
",",
"res",
".",
"Describe",
".",
"Meta",
"[",
"v",
".",
"Blob",
".",
"String",
"(",
")",
"]",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"members",
")",
"==",
"0",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n\n",
"zipName",
":=",
"\"",
"\"",
"\n",
"if",
"title",
":=",
"getTitle",
"(",
"subdes",
".",
"BlobRef",
",",
"resMap",
")",
";",
"title",
"==",
"\"",
"\"",
"{",
"zipName",
"=",
"\"",
"\"",
"\n",
"}",
"else",
"{",
"zipName",
"=",
"title",
"+",
"\"",
"\"",
"\n",
"}",
"\n",
"subjectPath",
":=",
"pr",
".",
"subjectBasePath",
"\n",
"if",
"!",
"strings",
".",
"Contains",
"(",
"subjectPath",
",",
"\"",
"\"",
")",
"{",
"subjectPath",
"+=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"return",
"&",
"publish",
".",
"PageMembers",
"{",
"SubjectPath",
":",
"subjectPath",
",",
"ZipName",
":",
"zipName",
",",
"Members",
":",
"members",
",",
"Description",
":",
"func",
"(",
"member",
"*",
"search",
".",
"DescribedBlob",
")",
"string",
"{",
"des",
":=",
"member",
".",
"Description",
"(",
")",
"\n",
"if",
"des",
"!=",
"\"",
"\"",
"{",
"des",
"=",
"\"",
"\"",
"+",
"des",
"\n",
"}",
"\n",
"return",
"des",
"\n",
"}",
",",
"Title",
":",
"func",
"(",
"member",
"*",
"search",
".",
"DescribedBlob",
")",
"string",
"{",
"memberTitle",
":=",
"getTitle",
"(",
"member",
".",
"BlobRef",
",",
"resMap",
")",
"\n",
"if",
"memberTitle",
"==",
"\"",
"\"",
"{",
"memberTitle",
"=",
"member",
".",
"BlobRef",
".",
"DigestPrefix",
"(",
"10",
")",
"\n",
"}",
"\n",
"return",
"html",
".",
"EscapeString",
"(",
"memberTitle",
")",
"\n",
"}",
",",
"Path",
":",
"func",
"(",
"member",
"*",
"search",
".",
"DescribedBlob",
")",
"string",
"{",
"return",
"pr",
".",
"memberPath",
"(",
"member",
".",
"BlobRef",
")",
"\n",
"}",
",",
"DomID",
":",
"func",
"(",
"member",
"*",
"search",
".",
"DescribedBlob",
")",
"string",
"{",
"return",
"member",
".",
"DomID",
"(",
")",
"\n",
"}",
",",
"FileInfo",
":",
"func",
"(",
"member",
"*",
"search",
".",
"DescribedBlob",
")",
"*",
"publish",
".",
"MemberFileInfo",
"{",
"if",
"path",
",",
"fileInfo",
",",
"ok",
":=",
"getFileInfo",
"(",
"member",
".",
"BlobRef",
",",
"resMap",
")",
";",
"ok",
"{",
"info",
":=",
"&",
"publish",
".",
"MemberFileInfo",
"{",
"FileName",
":",
"fileInfo",
".",
"FileName",
",",
"FileDomID",
":",
"path",
"[",
"len",
"(",
"path",
")",
"-",
"1",
"]",
".",
"DomID",
"(",
")",
",",
"FilePath",
":",
"html",
".",
"EscapeString",
"(",
"pr",
".",
"SubresFileURL",
"(",
"path",
",",
"fileInfo",
".",
"FileName",
")",
")",
",",
"}",
"\n",
"if",
"fileInfo",
".",
"IsImage",
"(",
")",
"{",
"info",
".",
"FileThumbnailURL",
"=",
"pr",
".",
"SubresThumbnailURL",
"(",
"path",
",",
"fileInfo",
".",
"FileName",
",",
"200",
")",
"\n",
"}",
"\n",
"return",
"info",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// subjectMembers returns the relevant PageMembers if the described subject is a permanode with members.
|
[
"subjectMembers",
"returns",
"the",
"relevant",
"PageMembers",
"if",
"the",
"described",
"subject",
"is",
"a",
"permanode",
"with",
"members",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/publisher/main.go#L1102-L1166
|
train
|
perkeep/perkeep
|
app/publisher/main.go
|
serveZip
|
func (pr *publishRequest) serveZip() {
filename := ""
if len(pr.subres) > len("/=z/") {
filename = pr.subres[4:]
}
zh := &zipHandler{
fetcher: pr.ph.cl,
cl: pr.ph.cl,
root: pr.subject,
filename: filename,
}
zh.ServeHTTP(pr.rw, pr.req)
}
|
go
|
func (pr *publishRequest) serveZip() {
filename := ""
if len(pr.subres) > len("/=z/") {
filename = pr.subres[4:]
}
zh := &zipHandler{
fetcher: pr.ph.cl,
cl: pr.ph.cl,
root: pr.subject,
filename: filename,
}
zh.ServeHTTP(pr.rw, pr.req)
}
|
[
"func",
"(",
"pr",
"*",
"publishRequest",
")",
"serveZip",
"(",
")",
"{",
"filename",
":=",
"\"",
"\"",
"\n",
"if",
"len",
"(",
"pr",
".",
"subres",
")",
">",
"len",
"(",
"\"",
"\"",
")",
"{",
"filename",
"=",
"pr",
".",
"subres",
"[",
"4",
":",
"]",
"\n",
"}",
"\n",
"zh",
":=",
"&",
"zipHandler",
"{",
"fetcher",
":",
"pr",
".",
"ph",
".",
"cl",
",",
"cl",
":",
"pr",
".",
"ph",
".",
"cl",
",",
"root",
":",
"pr",
".",
"subject",
",",
"filename",
":",
"filename",
",",
"}",
"\n",
"zh",
".",
"ServeHTTP",
"(",
"pr",
".",
"rw",
",",
"pr",
".",
"req",
")",
"\n",
"}"
] |
// serveZip streams a zip archive of all the files "under"
// pr.subject. That is, all the files pointed by file permanodes,
// which are directly members of pr.subject or recursively down
// directory permanodes and permanodes members.
|
[
"serveZip",
"streams",
"a",
"zip",
"archive",
"of",
"all",
"the",
"files",
"under",
"pr",
".",
"subject",
".",
"That",
"is",
"all",
"the",
"files",
"pointed",
"by",
"file",
"permanodes",
"which",
"are",
"directly",
"members",
"of",
"pr",
".",
"subject",
"or",
"recursively",
"down",
"directory",
"permanodes",
"and",
"permanodes",
"members",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/publisher/main.go#L1244-L1256
|
train
|
perkeep/perkeep
|
pkg/blobserver/blobpacked/subfetch.go
|
SubFetch
|
func (s *storage) SubFetch(ctx context.Context, ref blob.Ref, offset, length int64) (io.ReadCloser, error) {
// TODO: pass ctx to more calls within this method.
m, err := s.getMetaRow(ref)
if err != nil {
return nil, err
}
if m.isPacked() {
length, err = capOffsetLength(m.size, offset, length)
if err != nil {
return nil, err
}
// get the blob from the large subfetcher
return s.large.SubFetch(ctx, m.largeRef, int64(m.largeOff)+offset, length)
}
if sf, ok := s.small.(blob.SubFetcher); ok {
rc, err := sf.SubFetch(ctx, ref, offset, length)
if err != blob.ErrUnimplemented {
return rc, err
}
}
rc, size, err := s.small.Fetch(ctx, ref)
if err != nil {
return rc, err
}
length, err = capOffsetLength(size, offset, length)
if err != nil {
rc.Close()
return nil, err
}
if offset != 0 {
if _, err = io.CopyN(ioutil.Discard, rc, offset); err != nil {
rc.Close()
return nil, err
}
}
return struct {
io.Reader
io.Closer
}{io.LimitReader(rc, length), rc}, nil
}
|
go
|
func (s *storage) SubFetch(ctx context.Context, ref blob.Ref, offset, length int64) (io.ReadCloser, error) {
// TODO: pass ctx to more calls within this method.
m, err := s.getMetaRow(ref)
if err != nil {
return nil, err
}
if m.isPacked() {
length, err = capOffsetLength(m.size, offset, length)
if err != nil {
return nil, err
}
// get the blob from the large subfetcher
return s.large.SubFetch(ctx, m.largeRef, int64(m.largeOff)+offset, length)
}
if sf, ok := s.small.(blob.SubFetcher); ok {
rc, err := sf.SubFetch(ctx, ref, offset, length)
if err != blob.ErrUnimplemented {
return rc, err
}
}
rc, size, err := s.small.Fetch(ctx, ref)
if err != nil {
return rc, err
}
length, err = capOffsetLength(size, offset, length)
if err != nil {
rc.Close()
return nil, err
}
if offset != 0 {
if _, err = io.CopyN(ioutil.Discard, rc, offset); err != nil {
rc.Close()
return nil, err
}
}
return struct {
io.Reader
io.Closer
}{io.LimitReader(rc, length), rc}, nil
}
|
[
"func",
"(",
"s",
"*",
"storage",
")",
"SubFetch",
"(",
"ctx",
"context",
".",
"Context",
",",
"ref",
"blob",
".",
"Ref",
",",
"offset",
",",
"length",
"int64",
")",
"(",
"io",
".",
"ReadCloser",
",",
"error",
")",
"{",
"// TODO: pass ctx to more calls within this method.",
"m",
",",
"err",
":=",
"s",
".",
"getMetaRow",
"(",
"ref",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"m",
".",
"isPacked",
"(",
")",
"{",
"length",
",",
"err",
"=",
"capOffsetLength",
"(",
"m",
".",
"size",
",",
"offset",
",",
"length",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// get the blob from the large subfetcher",
"return",
"s",
".",
"large",
".",
"SubFetch",
"(",
"ctx",
",",
"m",
".",
"largeRef",
",",
"int64",
"(",
"m",
".",
"largeOff",
")",
"+",
"offset",
",",
"length",
")",
"\n",
"}",
"\n",
"if",
"sf",
",",
"ok",
":=",
"s",
".",
"small",
".",
"(",
"blob",
".",
"SubFetcher",
")",
";",
"ok",
"{",
"rc",
",",
"err",
":=",
"sf",
".",
"SubFetch",
"(",
"ctx",
",",
"ref",
",",
"offset",
",",
"length",
")",
"\n",
"if",
"err",
"!=",
"blob",
".",
"ErrUnimplemented",
"{",
"return",
"rc",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"rc",
",",
"size",
",",
"err",
":=",
"s",
".",
"small",
".",
"Fetch",
"(",
"ctx",
",",
"ref",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"rc",
",",
"err",
"\n",
"}",
"\n",
"length",
",",
"err",
"=",
"capOffsetLength",
"(",
"size",
",",
"offset",
",",
"length",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"rc",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"if",
"offset",
"!=",
"0",
"{",
"if",
"_",
",",
"err",
"=",
"io",
".",
"CopyN",
"(",
"ioutil",
".",
"Discard",
",",
"rc",
",",
"offset",
")",
";",
"err",
"!=",
"nil",
"{",
"rc",
".",
"Close",
"(",
")",
"\n",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"struct",
"{",
"io",
".",
"Reader",
"\n",
"io",
".",
"Closer",
"\n",
"}",
"{",
"io",
".",
"LimitReader",
"(",
"rc",
",",
"length",
")",
",",
"rc",
"}",
",",
"nil",
"\n",
"}"
] |
// SubFetch returns part of a blob.
// The caller must close the returned io.ReadCloser.
// The Reader may return fewer than 'length' bytes. Callers should
// check. The returned error should be os.ErrNotExist if the blob
// doesn't exist.
|
[
"SubFetch",
"returns",
"part",
"of",
"a",
"blob",
".",
"The",
"caller",
"must",
"close",
"the",
"returned",
"io",
".",
"ReadCloser",
".",
"The",
"Reader",
"may",
"return",
"fewer",
"than",
"length",
"bytes",
".",
"Callers",
"should",
"check",
".",
"The",
"returned",
"error",
"should",
"be",
"os",
".",
"ErrNotExist",
"if",
"the",
"blob",
"doesn",
"t",
"exist",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/blobpacked/subfetch.go#L35-L74
|
train
|
perkeep/perkeep
|
pkg/deploy/gce/handler.go
|
NewDeployHandlerFromConfig
|
func NewDeployHandlerFromConfig(host, prefix string, cfg *Config) (*DeployHandler, error) {
if cfg == nil {
panic("NewDeployHandlerFromConfig: nil config")
}
if cfg.ClientID == "" {
return nil, errors.New("oauth2 clientID required in config")
}
if cfg.ClientSecret == "" {
return nil, errors.New("oauth2 clientSecret required in config")
}
os.Setenv("CAMLI_GCE_CLIENTID", cfg.ClientID)
os.Setenv("CAMLI_GCE_CLIENTSECRET", cfg.ClientSecret)
os.Setenv("CAMLI_GCE_PROJECT", cfg.Project)
os.Setenv("CAMLI_GCE_SERVICE_ACCOUNT", cfg.ServiceAccount)
os.Setenv("CAMLI_GCE_DATA", cfg.DataDir)
return NewDeployHandler(host, prefix)
}
|
go
|
func NewDeployHandlerFromConfig(host, prefix string, cfg *Config) (*DeployHandler, error) {
if cfg == nil {
panic("NewDeployHandlerFromConfig: nil config")
}
if cfg.ClientID == "" {
return nil, errors.New("oauth2 clientID required in config")
}
if cfg.ClientSecret == "" {
return nil, errors.New("oauth2 clientSecret required in config")
}
os.Setenv("CAMLI_GCE_CLIENTID", cfg.ClientID)
os.Setenv("CAMLI_GCE_CLIENTSECRET", cfg.ClientSecret)
os.Setenv("CAMLI_GCE_PROJECT", cfg.Project)
os.Setenv("CAMLI_GCE_SERVICE_ACCOUNT", cfg.ServiceAccount)
os.Setenv("CAMLI_GCE_DATA", cfg.DataDir)
return NewDeployHandler(host, prefix)
}
|
[
"func",
"NewDeployHandlerFromConfig",
"(",
"host",
",",
"prefix",
"string",
",",
"cfg",
"*",
"Config",
")",
"(",
"*",
"DeployHandler",
",",
"error",
")",
"{",
"if",
"cfg",
"==",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"cfg",
".",
"ClientID",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"if",
"cfg",
".",
"ClientSecret",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"os",
".",
"Setenv",
"(",
"\"",
"\"",
",",
"cfg",
".",
"ClientID",
")",
"\n",
"os",
".",
"Setenv",
"(",
"\"",
"\"",
",",
"cfg",
".",
"ClientSecret",
")",
"\n",
"os",
".",
"Setenv",
"(",
"\"",
"\"",
",",
"cfg",
".",
"Project",
")",
"\n",
"os",
".",
"Setenv",
"(",
"\"",
"\"",
",",
"cfg",
".",
"ServiceAccount",
")",
"\n",
"os",
".",
"Setenv",
"(",
"\"",
"\"",
",",
"cfg",
".",
"DataDir",
")",
"\n",
"return",
"NewDeployHandler",
"(",
"host",
",",
"prefix",
")",
"\n",
"}"
] |
// NewDeployHandlerFromConfig initializes a DeployHandler from cfg.
// Host and prefix have the same meaning as for NewDeployHandler. cfg should not be nil.
|
[
"NewDeployHandlerFromConfig",
"initializes",
"a",
"DeployHandler",
"from",
"cfg",
".",
"Host",
"and",
"prefix",
"have",
"the",
"same",
"meaning",
"as",
"for",
"NewDeployHandler",
".",
"cfg",
"should",
"not",
"be",
"nil",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/deploy/gce/handler.go#L128-L144
|
train
|
perkeep/perkeep
|
pkg/deploy/gce/handler.go
|
serveRoot
|
func (h *DeployHandler) serveRoot(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
h.serveSetup(w, r)
return
}
_, err := r.Cookie("user")
if err != nil {
http.SetCookie(w, newCookie())
}
camliRev := h.camliRev()
if r.FormValue("WIP") == "1" {
camliRev = "WORKINPROGRESS"
}
h.tplMu.RLock()
defer h.tplMu.RUnlock()
if err := h.tpl.ExecuteTemplate(w, "withform", &TemplateData{
ProjectID: r.FormValue("project"),
Prefix: h.prefix,
Help: h.help,
ZoneValues: h.zoneValues(),
MachineValues: machineValues,
CamliVersion: camliRev,
}); err != nil {
h.logger.Print(err)
}
}
|
go
|
func (h *DeployHandler) serveRoot(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
h.serveSetup(w, r)
return
}
_, err := r.Cookie("user")
if err != nil {
http.SetCookie(w, newCookie())
}
camliRev := h.camliRev()
if r.FormValue("WIP") == "1" {
camliRev = "WORKINPROGRESS"
}
h.tplMu.RLock()
defer h.tplMu.RUnlock()
if err := h.tpl.ExecuteTemplate(w, "withform", &TemplateData{
ProjectID: r.FormValue("project"),
Prefix: h.prefix,
Help: h.help,
ZoneValues: h.zoneValues(),
MachineValues: machineValues,
CamliVersion: camliRev,
}); err != nil {
h.logger.Print(err)
}
}
|
[
"func",
"(",
"h",
"*",
"DeployHandler",
")",
"serveRoot",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"r",
".",
"Method",
"==",
"\"",
"\"",
"{",
"h",
".",
"serveSetup",
"(",
"w",
",",
"r",
")",
"\n",
"return",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"r",
".",
"Cookie",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"SetCookie",
"(",
"w",
",",
"newCookie",
"(",
")",
")",
"\n",
"}",
"\n",
"camliRev",
":=",
"h",
".",
"camliRev",
"(",
")",
"\n",
"if",
"r",
".",
"FormValue",
"(",
"\"",
"\"",
")",
"==",
"\"",
"\"",
"{",
"camliRev",
"=",
"\"",
"\"",
"\n",
"}",
"\n\n",
"h",
".",
"tplMu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"h",
".",
"tplMu",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"err",
":=",
"h",
".",
"tpl",
".",
"ExecuteTemplate",
"(",
"w",
",",
"\"",
"\"",
",",
"&",
"TemplateData",
"{",
"ProjectID",
":",
"r",
".",
"FormValue",
"(",
"\"",
"\"",
")",
",",
"Prefix",
":",
"h",
".",
"prefix",
",",
"Help",
":",
"h",
".",
"help",
",",
"ZoneValues",
":",
"h",
".",
"zoneValues",
"(",
")",
",",
"MachineValues",
":",
"machineValues",
",",
"CamliVersion",
":",
"camliRev",
",",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"h",
".",
"logger",
".",
"Print",
"(",
"err",
")",
"\n",
"}",
"\n",
"}"
] |
// if there's project as a query parameter, it means we've just created a
// project for them and we're redirecting them to the form, but with the projectID
// field pre-filled for them this time.
|
[
"if",
"there",
"s",
"project",
"as",
"a",
"query",
"parameter",
"it",
"means",
"we",
"ve",
"just",
"created",
"a",
"project",
"for",
"them",
"and",
"we",
"re",
"redirecting",
"them",
"to",
"the",
"form",
"but",
"with",
"the",
"projectID",
"field",
"pre",
"-",
"filled",
"for",
"them",
"this",
"time",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/deploy/gce/handler.go#L351-L377
|
train
|
perkeep/perkeep
|
pkg/deploy/gce/handler.go
|
serveOldInstance
|
func (h *DeployHandler) serveOldInstance(w http.ResponseWriter, br blob.Ref, depl *Deployer) (found bool) {
inst, err := depl.Get()
if err != nil {
// TODO(mpl,bradfitz): log or do something more
// drastic if the error is something other than
// instance not found.
return false
}
h.logger.Printf("Reusing existing instance for (%v, %v, %v)", depl.Conf.Project, depl.Conf.Name, depl.Conf.Zone)
if err := h.recordState(br, &creationState{
InstConf: br,
InstAddr: addr(inst),
Exists: true,
}); err != nil {
h.logger.Printf("Could not record creation state for %v: %v", br, err)
h.serveErrorPage(w, fmt.Errorf("An error occurred while recording the state of your instance. %v", fileIssue(br.String())))
return true
}
h.serveProgress(w, br)
return true
}
|
go
|
func (h *DeployHandler) serveOldInstance(w http.ResponseWriter, br blob.Ref, depl *Deployer) (found bool) {
inst, err := depl.Get()
if err != nil {
// TODO(mpl,bradfitz): log or do something more
// drastic if the error is something other than
// instance not found.
return false
}
h.logger.Printf("Reusing existing instance for (%v, %v, %v)", depl.Conf.Project, depl.Conf.Name, depl.Conf.Zone)
if err := h.recordState(br, &creationState{
InstConf: br,
InstAddr: addr(inst),
Exists: true,
}); err != nil {
h.logger.Printf("Could not record creation state for %v: %v", br, err)
h.serveErrorPage(w, fmt.Errorf("An error occurred while recording the state of your instance. %v", fileIssue(br.String())))
return true
}
h.serveProgress(w, br)
return true
}
|
[
"func",
"(",
"h",
"*",
"DeployHandler",
")",
"serveOldInstance",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"br",
"blob",
".",
"Ref",
",",
"depl",
"*",
"Deployer",
")",
"(",
"found",
"bool",
")",
"{",
"inst",
",",
"err",
":=",
"depl",
".",
"Get",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// TODO(mpl,bradfitz): log or do something more",
"// drastic if the error is something other than",
"// instance not found.",
"return",
"false",
"\n",
"}",
"\n",
"h",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"depl",
".",
"Conf",
".",
"Project",
",",
"depl",
".",
"Conf",
".",
"Name",
",",
"depl",
".",
"Conf",
".",
"Zone",
")",
"\n\n",
"if",
"err",
":=",
"h",
".",
"recordState",
"(",
"br",
",",
"&",
"creationState",
"{",
"InstConf",
":",
"br",
",",
"InstAddr",
":",
"addr",
"(",
"inst",
")",
",",
"Exists",
":",
"true",
",",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"h",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"br",
",",
"err",
")",
"\n",
"h",
".",
"serveErrorPage",
"(",
"w",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"fileIssue",
"(",
"br",
".",
"String",
"(",
")",
")",
")",
")",
"\n",
"return",
"true",
"\n",
"}",
"\n",
"h",
".",
"serveProgress",
"(",
"w",
",",
"br",
")",
"\n",
"return",
"true",
"\n",
"}"
] |
// serveOldInstance looks on GCE for an instance such as defined in depl.Conf, and if
// found, serves the appropriate page depending on whether the instance is usable. It does
// not serve anything if the instance is not found.
|
[
"serveOldInstance",
"looks",
"on",
"GCE",
"for",
"an",
"instance",
"such",
"as",
"defined",
"in",
"depl",
".",
"Conf",
"and",
"if",
"found",
"serves",
"the",
"appropriate",
"page",
"depending",
"on",
"whether",
"the",
"instance",
"is",
"usable",
".",
"It",
"does",
"not",
"serve",
"anything",
"if",
"the",
"instance",
"is",
"not",
"found",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/deploy/gce/handler.go#L564-L585
|
train
|
perkeep/perkeep
|
pkg/deploy/gce/handler.go
|
serveInstanceState
|
func (h *DeployHandler) serveInstanceState(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if r.Method != "GET" {
h.serveError(w, r, fmt.Errorf("Wrong method: %v", r.Method))
return
}
br := r.URL.Query().Get("instancekey")
stateValue, err := h.instState.Get(br)
if err != nil {
http.Error(w, "unknown instance", http.StatusNotFound)
return
}
var state creationState
if err := json.Unmarshal([]byte(stateValue), &state); err != nil {
h.serveError(w, r, fmt.Errorf("could not json decode instance state: %v", err))
return
}
if state.Err != "" {
// No need to log that error here since we're already doing it in serveCallback
h.serveErrorPage(w, fmt.Errorf("an error occurred while creating your instance: %v", state.Err))
return
}
if state.Success || state.Exists {
conf, err := h.instanceConf(ctx, state.InstConf)
if err != nil {
h.logger.Printf("Could not get parameters for success message: %v", err)
h.serveErrorPage(w, fmt.Errorf("your instance was created and should soon be up at https://%s but there might have been a problem in the creation process. %v", state.Err, fileIssue(br)))
return
}
h.serveSuccess(w, &TemplateData{
Prefix: h.prefix,
Help: h.help,
InstanceIP: state.InstAddr,
InstanceHostname: state.InstHostname,
ProjectConsoleURL: fmt.Sprintf("%s/project/%s/compute", ConsoleURL, conf.Project),
Conf: conf,
ZoneValues: h.zoneValues(),
MachineValues: machineValues,
})
return
}
h.recordStateErrMu.RLock()
defer h.recordStateErrMu.RUnlock()
if _, ok := h.recordStateErr[br]; ok {
// No need to log that error here since we're already doing it in serveCallback
h.serveErrorPage(w, fmt.Errorf("An error occurred while recording the state of your instance. %v", fileIssue(br)))
return
}
fmt.Fprintf(w, "running")
}
|
go
|
func (h *DeployHandler) serveInstanceState(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if r.Method != "GET" {
h.serveError(w, r, fmt.Errorf("Wrong method: %v", r.Method))
return
}
br := r.URL.Query().Get("instancekey")
stateValue, err := h.instState.Get(br)
if err != nil {
http.Error(w, "unknown instance", http.StatusNotFound)
return
}
var state creationState
if err := json.Unmarshal([]byte(stateValue), &state); err != nil {
h.serveError(w, r, fmt.Errorf("could not json decode instance state: %v", err))
return
}
if state.Err != "" {
// No need to log that error here since we're already doing it in serveCallback
h.serveErrorPage(w, fmt.Errorf("an error occurred while creating your instance: %v", state.Err))
return
}
if state.Success || state.Exists {
conf, err := h.instanceConf(ctx, state.InstConf)
if err != nil {
h.logger.Printf("Could not get parameters for success message: %v", err)
h.serveErrorPage(w, fmt.Errorf("your instance was created and should soon be up at https://%s but there might have been a problem in the creation process. %v", state.Err, fileIssue(br)))
return
}
h.serveSuccess(w, &TemplateData{
Prefix: h.prefix,
Help: h.help,
InstanceIP: state.InstAddr,
InstanceHostname: state.InstHostname,
ProjectConsoleURL: fmt.Sprintf("%s/project/%s/compute", ConsoleURL, conf.Project),
Conf: conf,
ZoneValues: h.zoneValues(),
MachineValues: machineValues,
})
return
}
h.recordStateErrMu.RLock()
defer h.recordStateErrMu.RUnlock()
if _, ok := h.recordStateErr[br]; ok {
// No need to log that error here since we're already doing it in serveCallback
h.serveErrorPage(w, fmt.Errorf("An error occurred while recording the state of your instance. %v", fileIssue(br)))
return
}
fmt.Fprintf(w, "running")
}
|
[
"func",
"(",
"h",
"*",
"DeployHandler",
")",
"serveInstanceState",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"ctx",
":=",
"r",
".",
"Context",
"(",
")",
"\n",
"if",
"r",
".",
"Method",
"!=",
"\"",
"\"",
"{",
"h",
".",
"serveError",
"(",
"w",
",",
"r",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"r",
".",
"Method",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"br",
":=",
"r",
".",
"URL",
".",
"Query",
"(",
")",
".",
"Get",
"(",
"\"",
"\"",
")",
"\n",
"stateValue",
",",
"err",
":=",
"h",
".",
"instState",
".",
"Get",
"(",
"br",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusNotFound",
")",
"\n",
"return",
"\n",
"}",
"\n",
"var",
"state",
"creationState",
"\n",
"if",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"[",
"]",
"byte",
"(",
"stateValue",
")",
",",
"&",
"state",
")",
";",
"err",
"!=",
"nil",
"{",
"h",
".",
"serveError",
"(",
"w",
",",
"r",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"state",
".",
"Err",
"!=",
"\"",
"\"",
"{",
"// No need to log that error here since we're already doing it in serveCallback",
"h",
".",
"serveErrorPage",
"(",
"w",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"state",
".",
"Err",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"state",
".",
"Success",
"||",
"state",
".",
"Exists",
"{",
"conf",
",",
"err",
":=",
"h",
".",
"instanceConf",
"(",
"ctx",
",",
"state",
".",
"InstConf",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"h",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"h",
".",
"serveErrorPage",
"(",
"w",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"state",
".",
"Err",
",",
"fileIssue",
"(",
"br",
")",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"h",
".",
"serveSuccess",
"(",
"w",
",",
"&",
"TemplateData",
"{",
"Prefix",
":",
"h",
".",
"prefix",
",",
"Help",
":",
"h",
".",
"help",
",",
"InstanceIP",
":",
"state",
".",
"InstAddr",
",",
"InstanceHostname",
":",
"state",
".",
"InstHostname",
",",
"ProjectConsoleURL",
":",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"ConsoleURL",
",",
"conf",
".",
"Project",
")",
",",
"Conf",
":",
"conf",
",",
"ZoneValues",
":",
"h",
".",
"zoneValues",
"(",
")",
",",
"MachineValues",
":",
"machineValues",
",",
"}",
")",
"\n",
"return",
"\n",
"}",
"\n",
"h",
".",
"recordStateErrMu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"h",
".",
"recordStateErrMu",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"_",
",",
"ok",
":=",
"h",
".",
"recordStateErr",
"[",
"br",
"]",
";",
"ok",
"{",
"// No need to log that error here since we're already doing it in serveCallback",
"h",
".",
"serveErrorPage",
"(",
"w",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"fileIssue",
"(",
"br",
")",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"fmt",
".",
"Fprintf",
"(",
"w",
",",
"\"",
"\"",
")",
"\n",
"}"
] |
// serveInstanceState serves the state of the requested Google Cloud Engine VM creation
// process. If the operation was successful, it serves a success page. If it failed, it
// serves an error page. If it isn't finished yet, it replies with "running".
|
[
"serveInstanceState",
"serves",
"the",
"state",
"of",
"the",
"requested",
"Google",
"Cloud",
"Engine",
"VM",
"creation",
"process",
".",
"If",
"the",
"operation",
"was",
"successful",
"it",
"serves",
"a",
"success",
"page",
".",
"If",
"it",
"failed",
"it",
"serves",
"an",
"error",
"page",
".",
"If",
"it",
"isn",
"t",
"finished",
"yet",
"it",
"replies",
"with",
"running",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/deploy/gce/handler.go#L612-L661
|
train
|
perkeep/perkeep
|
pkg/deploy/gce/handler.go
|
serveProgress
|
func (h *DeployHandler) serveProgress(w http.ResponseWriter, instanceKey blob.Ref) {
h.tplMu.RLock()
defer h.tplMu.RUnlock()
if err := h.tpl.ExecuteTemplate(w, "withform", &TemplateData{
Prefix: h.prefix,
InstanceKey: instanceKey.String(),
PiggyGIF: h.piggyGIF,
}); err != nil {
h.logger.Printf("Could not serve progress: %v", err)
}
}
|
go
|
func (h *DeployHandler) serveProgress(w http.ResponseWriter, instanceKey blob.Ref) {
h.tplMu.RLock()
defer h.tplMu.RUnlock()
if err := h.tpl.ExecuteTemplate(w, "withform", &TemplateData{
Prefix: h.prefix,
InstanceKey: instanceKey.String(),
PiggyGIF: h.piggyGIF,
}); err != nil {
h.logger.Printf("Could not serve progress: %v", err)
}
}
|
[
"func",
"(",
"h",
"*",
"DeployHandler",
")",
"serveProgress",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"instanceKey",
"blob",
".",
"Ref",
")",
"{",
"h",
".",
"tplMu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"h",
".",
"tplMu",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"err",
":=",
"h",
".",
"tpl",
".",
"ExecuteTemplate",
"(",
"w",
",",
"\"",
"\"",
",",
"&",
"TemplateData",
"{",
"Prefix",
":",
"h",
".",
"prefix",
",",
"InstanceKey",
":",
"instanceKey",
".",
"String",
"(",
")",
",",
"PiggyGIF",
":",
"h",
".",
"piggyGIF",
",",
"}",
")",
";",
"err",
"!=",
"nil",
"{",
"h",
".",
"logger",
".",
"Printf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}"
] |
// serveProgress serves a page with some javascript code that regularly queries
// the server about the progress of the requested Google Cloud Engine VM creation.
// The server replies through serveInstanceState.
|
[
"serveProgress",
"serves",
"a",
"page",
"with",
"some",
"javascript",
"code",
"that",
"regularly",
"queries",
"the",
"server",
"about",
"the",
"progress",
"of",
"the",
"requested",
"Google",
"Cloud",
"Engine",
"VM",
"creation",
".",
"The",
"server",
"replies",
"through",
"serveInstanceState",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/deploy/gce/handler.go#L666-L676
|
train
|
perkeep/perkeep
|
pkg/deploy/gce/handler.go
|
randomZone
|
func (h *DeployHandler) randomZone(region string) string {
h.zonesMu.RLock()
defer h.zonesMu.RUnlock()
zones, ok := h.zones[region]
if !ok {
return fallbackZone
}
return region + zones[rand.Intn(len(zones))]
}
|
go
|
func (h *DeployHandler) randomZone(region string) string {
h.zonesMu.RLock()
defer h.zonesMu.RUnlock()
zones, ok := h.zones[region]
if !ok {
return fallbackZone
}
return region + zones[rand.Intn(len(zones))]
}
|
[
"func",
"(",
"h",
"*",
"DeployHandler",
")",
"randomZone",
"(",
"region",
"string",
")",
"string",
"{",
"h",
".",
"zonesMu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"h",
".",
"zonesMu",
".",
"RUnlock",
"(",
")",
"\n",
"zones",
",",
"ok",
":=",
"h",
".",
"zones",
"[",
"region",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"fallbackZone",
"\n",
"}",
"\n",
"return",
"region",
"+",
"zones",
"[",
"rand",
".",
"Intn",
"(",
"len",
"(",
"zones",
")",
")",
"]",
"\n",
"}"
] |
// randomZone picks one of the zone suffixes for region and returns it
// appended to region, as a fully-qualified zone name.
// If the given region is invalid, the default Zone is returned instead.
|
[
"randomZone",
"picks",
"one",
"of",
"the",
"zone",
"suffixes",
"for",
"region",
"and",
"returns",
"it",
"appended",
"to",
"region",
"as",
"a",
"fully",
"-",
"qualified",
"zone",
"name",
".",
"If",
"the",
"given",
"region",
"is",
"invalid",
"the",
"default",
"Zone",
"is",
"returned",
"instead",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/deploy/gce/handler.go#L770-L778
|
train
|
perkeep/perkeep
|
pkg/deploy/gce/handler.go
|
fromState
|
func fromState(r *http.Request) (br blob.Ref, xsrfToken string, err error) {
params := strings.Split(r.FormValue("state"), ":")
if len(params) != 2 {
return br, "", fmt.Errorf("Invalid format for state parameter: %q, wanted blobRef:xsrfToken", r.FormValue("state"))
}
br, ok := blob.Parse(params[0])
if !ok {
return br, "", fmt.Errorf("Invalid blobRef in state parameter: %q", params[0])
}
token, err := hex.DecodeString(params[1])
if err != nil {
return br, "", fmt.Errorf("can't decode hex xsrftoken %q: %v", params[1], err)
}
return br, string(token), nil
}
|
go
|
func fromState(r *http.Request) (br blob.Ref, xsrfToken string, err error) {
params := strings.Split(r.FormValue("state"), ":")
if len(params) != 2 {
return br, "", fmt.Errorf("Invalid format for state parameter: %q, wanted blobRef:xsrfToken", r.FormValue("state"))
}
br, ok := blob.Parse(params[0])
if !ok {
return br, "", fmt.Errorf("Invalid blobRef in state parameter: %q", params[0])
}
token, err := hex.DecodeString(params[1])
if err != nil {
return br, "", fmt.Errorf("can't decode hex xsrftoken %q: %v", params[1], err)
}
return br, string(token), nil
}
|
[
"func",
"fromState",
"(",
"r",
"*",
"http",
".",
"Request",
")",
"(",
"br",
"blob",
".",
"Ref",
",",
"xsrfToken",
"string",
",",
"err",
"error",
")",
"{",
"params",
":=",
"strings",
".",
"Split",
"(",
"r",
".",
"FormValue",
"(",
"\"",
"\"",
")",
",",
"\"",
"\"",
")",
"\n",
"if",
"len",
"(",
"params",
")",
"!=",
"2",
"{",
"return",
"br",
",",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"r",
".",
"FormValue",
"(",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"br",
",",
"ok",
":=",
"blob",
".",
"Parse",
"(",
"params",
"[",
"0",
"]",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"br",
",",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"params",
"[",
"0",
"]",
")",
"\n",
"}",
"\n",
"token",
",",
"err",
":=",
"hex",
".",
"DecodeString",
"(",
"params",
"[",
"1",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"br",
",",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"params",
"[",
"1",
"]",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"br",
",",
"string",
"(",
"token",
")",
",",
"nil",
"\n",
"}"
] |
// fromState parses the oauth state parameter from r to extract the blobRef of the
// instance configuration and the xsrftoken that were stored during serveSetup.
|
[
"fromState",
"parses",
"the",
"oauth",
"state",
"parameter",
"from",
"r",
"to",
"extract",
"the",
"blobRef",
"of",
"the",
"instance",
"configuration",
"and",
"the",
"xsrftoken",
"that",
"were",
"stored",
"during",
"serveSetup",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/deploy/gce/handler.go#L799-L813
|
train
|
perkeep/perkeep
|
pkg/deploy/gce/handler.go
|
dataStores
|
func dataStores() (blobserver.Storage, sorted.KeyValue, error) {
dataDir := os.Getenv("CAMLI_GCE_DATA")
if dataDir == "" {
var err error
dataDir, err = ioutil.TempDir("", "camli-gcedeployer-data")
if err != nil {
return nil, nil, err
}
log.Printf("data dir not provided as env var CAMLI_GCE_DATA, so defaulting to %v", dataDir)
}
blobsDir := filepath.Join(dataDir, "instance-conf")
if err := os.MkdirAll(blobsDir, 0700); err != nil {
return nil, nil, err
}
instConf, err := localdisk.New(blobsDir)
if err != nil {
return nil, nil, err
}
instState, err := leveldb.NewStorage(filepath.Join(dataDir, "instance-state"))
if err != nil {
return nil, nil, err
}
return instConf, instState, nil
}
|
go
|
func dataStores() (blobserver.Storage, sorted.KeyValue, error) {
dataDir := os.Getenv("CAMLI_GCE_DATA")
if dataDir == "" {
var err error
dataDir, err = ioutil.TempDir("", "camli-gcedeployer-data")
if err != nil {
return nil, nil, err
}
log.Printf("data dir not provided as env var CAMLI_GCE_DATA, so defaulting to %v", dataDir)
}
blobsDir := filepath.Join(dataDir, "instance-conf")
if err := os.MkdirAll(blobsDir, 0700); err != nil {
return nil, nil, err
}
instConf, err := localdisk.New(blobsDir)
if err != nil {
return nil, nil, err
}
instState, err := leveldb.NewStorage(filepath.Join(dataDir, "instance-state"))
if err != nil {
return nil, nil, err
}
return instConf, instState, nil
}
|
[
"func",
"dataStores",
"(",
")",
"(",
"blobserver",
".",
"Storage",
",",
"sorted",
".",
"KeyValue",
",",
"error",
")",
"{",
"dataDir",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\n",
"if",
"dataDir",
"==",
"\"",
"\"",
"{",
"var",
"err",
"error",
"\n",
"dataDir",
",",
"err",
"=",
"ioutil",
".",
"TempDir",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"log",
".",
"Printf",
"(",
"\"",
"\"",
",",
"dataDir",
")",
"\n",
"}",
"\n",
"blobsDir",
":=",
"filepath",
".",
"Join",
"(",
"dataDir",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
":=",
"os",
".",
"MkdirAll",
"(",
"blobsDir",
",",
"0700",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"instConf",
",",
"err",
":=",
"localdisk",
".",
"New",
"(",
"blobsDir",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"instState",
",",
"err",
":=",
"leveldb",
".",
"NewStorage",
"(",
"filepath",
".",
"Join",
"(",
"dataDir",
",",
"\"",
"\"",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"instConf",
",",
"instState",
",",
"nil",
"\n",
"}"
] |
// dataStores returns the blobserver that stores the instances configurations, and the kv
// store for the instances states.
|
[
"dataStores",
"returns",
"the",
"blobserver",
"that",
"stores",
"the",
"instances",
"configurations",
"and",
"the",
"kv",
"store",
"for",
"the",
"instances",
"states",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/deploy/gce/handler.go#L886-L909
|
train
|
perkeep/perkeep
|
pkg/server/app/app.go
|
handleMasterQuery
|
func (a *Handler) handleMasterQuery(w http.ResponseWriter, r *http.Request) {
if !(a.auth.AllowedAccess(r)&auth.OpAll == auth.OpAll) {
auth.SendUnauthorized(w, r)
return
}
if r.Method != http.MethodPost {
http.Error(w, "not a POST", http.StatusMethodNotAllowed)
return
}
if a.sh == nil {
http.Error(w, "app proxy has no search handler", 500)
return
}
if refresh, _ := strconv.ParseBool(r.FormValue("refresh")); refresh {
if err := a.refreshDomainBlobs(); err != nil {
if err == errRefreshSuppress {
http.Error(w, "too many refresh requests", http.StatusTooManyRequests)
} else {
http.Error(w, fmt.Sprintf("%v", err), 500)
}
return
}
w.Write([]byte("OK"))
return
}
sq := new(search.SearchQuery)
if err := sq.FromHTTP(r); err != nil {
http.Error(w, fmt.Sprintf("error reading master query: %v", err), 500)
return
}
var masterQuery search.SearchQuery = *(sq)
des := *(masterQuery.Describe)
masterQuery.Describe = &des
sr, err := a.sh.Query(r.Context(), sq)
if err != nil {
http.Error(w, fmt.Sprintf("error running master query: %v", err), 500)
return
}
a.masterQueryMu.Lock()
defer a.masterQueryMu.Unlock()
a.masterQuery = &masterQuery
a.domainBlobs = make(map[blob.Ref]bool, len(sr.Describe.Meta))
for _, v := range sr.Describe.Meta {
a.domainBlobs[v.BlobRef] = true
}
a.domainBlobsRefresh = time.Now()
w.Write([]byte("OK"))
}
|
go
|
func (a *Handler) handleMasterQuery(w http.ResponseWriter, r *http.Request) {
if !(a.auth.AllowedAccess(r)&auth.OpAll == auth.OpAll) {
auth.SendUnauthorized(w, r)
return
}
if r.Method != http.MethodPost {
http.Error(w, "not a POST", http.StatusMethodNotAllowed)
return
}
if a.sh == nil {
http.Error(w, "app proxy has no search handler", 500)
return
}
if refresh, _ := strconv.ParseBool(r.FormValue("refresh")); refresh {
if err := a.refreshDomainBlobs(); err != nil {
if err == errRefreshSuppress {
http.Error(w, "too many refresh requests", http.StatusTooManyRequests)
} else {
http.Error(w, fmt.Sprintf("%v", err), 500)
}
return
}
w.Write([]byte("OK"))
return
}
sq := new(search.SearchQuery)
if err := sq.FromHTTP(r); err != nil {
http.Error(w, fmt.Sprintf("error reading master query: %v", err), 500)
return
}
var masterQuery search.SearchQuery = *(sq)
des := *(masterQuery.Describe)
masterQuery.Describe = &des
sr, err := a.sh.Query(r.Context(), sq)
if err != nil {
http.Error(w, fmt.Sprintf("error running master query: %v", err), 500)
return
}
a.masterQueryMu.Lock()
defer a.masterQueryMu.Unlock()
a.masterQuery = &masterQuery
a.domainBlobs = make(map[blob.Ref]bool, len(sr.Describe.Meta))
for _, v := range sr.Describe.Meta {
a.domainBlobs[v.BlobRef] = true
}
a.domainBlobsRefresh = time.Now()
w.Write([]byte("OK"))
}
|
[
"func",
"(",
"a",
"*",
"Handler",
")",
"handleMasterQuery",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"!",
"(",
"a",
".",
"auth",
".",
"AllowedAccess",
"(",
"r",
")",
"&",
"auth",
".",
"OpAll",
"==",
"auth",
".",
"OpAll",
")",
"{",
"auth",
".",
"SendUnauthorized",
"(",
"w",
",",
"r",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"r",
".",
"Method",
"!=",
"http",
".",
"MethodPost",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusMethodNotAllowed",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"a",
".",
"sh",
"==",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"500",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"refresh",
",",
"_",
":=",
"strconv",
".",
"ParseBool",
"(",
"r",
".",
"FormValue",
"(",
"\"",
"\"",
")",
")",
";",
"refresh",
"{",
"if",
"err",
":=",
"a",
".",
"refreshDomainBlobs",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"if",
"err",
"==",
"errRefreshSuppress",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusTooManyRequests",
")",
"\n",
"}",
"else",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
",",
"500",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}",
"\n",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"sq",
":=",
"new",
"(",
"search",
".",
"SearchQuery",
")",
"\n",
"if",
"err",
":=",
"sq",
".",
"FromHTTP",
"(",
"r",
")",
";",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
",",
"500",
")",
"\n",
"return",
"\n",
"}",
"\n",
"var",
"masterQuery",
"search",
".",
"SearchQuery",
"=",
"*",
"(",
"sq",
")",
"\n",
"des",
":=",
"*",
"(",
"masterQuery",
".",
"Describe",
")",
"\n",
"masterQuery",
".",
"Describe",
"=",
"&",
"des",
"\n",
"sr",
",",
"err",
":=",
"a",
".",
"sh",
".",
"Query",
"(",
"r",
".",
"Context",
"(",
")",
",",
"sq",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"err",
")",
",",
"500",
")",
"\n",
"return",
"\n",
"}",
"\n",
"a",
".",
"masterQueryMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"a",
".",
"masterQueryMu",
".",
"Unlock",
"(",
")",
"\n",
"a",
".",
"masterQuery",
"=",
"&",
"masterQuery",
"\n",
"a",
".",
"domainBlobs",
"=",
"make",
"(",
"map",
"[",
"blob",
".",
"Ref",
"]",
"bool",
",",
"len",
"(",
"sr",
".",
"Describe",
".",
"Meta",
")",
")",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"sr",
".",
"Describe",
".",
"Meta",
"{",
"a",
".",
"domainBlobs",
"[",
"v",
".",
"BlobRef",
"]",
"=",
"true",
"\n",
"}",
"\n",
"a",
".",
"domainBlobsRefresh",
"=",
"time",
".",
"Now",
"(",
")",
"\n",
"w",
".",
"Write",
"(",
"[",
"]",
"byte",
"(",
"\"",
"\"",
")",
")",
"\n",
"}"
] |
// handleMasterQuery allows an app to register the master query that defines the
// domain limiting all subsequent search queries.
|
[
"handleMasterQuery",
"allows",
"an",
"app",
"to",
"register",
"the",
"master",
"query",
"that",
"defines",
"the",
"domain",
"limiting",
"all",
"subsequent",
"search",
"queries",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/server/app/app.go#L111-L158
|
train
|
perkeep/perkeep
|
pkg/server/app/app.go
|
handleSearch
|
func (a *Handler) handleSearch(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
camhttputil.BadRequestError(w, camhttputil.InvalidMethodError{}.Error())
return
}
if a.sh == nil {
http.Error(w, "app proxy has no search handler", 500)
return
}
a.masterQueryMu.RLock()
if a.masterQuery == nil {
http.Error(w, "search is not allowed", http.StatusForbidden)
a.masterQueryMu.RUnlock()
return
}
a.masterQueryMu.RUnlock()
var sq search.SearchQuery
if err := sq.FromHTTP(r); err != nil {
camhttputil.ServeJSONError(w, err)
return
}
sr, err := a.sh.Query(r.Context(), &sq)
if err != nil {
camhttputil.ServeJSONError(w, err)
return
}
// check this search is in the allowed domain
if !a.allowProxySearchResponse(sr) {
// there's a chance our domainBlobs cache is expired so let's
// refresh it and retry, but no more than once per minute.
if err := a.refreshDomainBlobs(); err != nil {
http.Error(w, "search scope is forbidden", http.StatusForbidden)
return
}
if !a.allowProxySearchResponse(sr) {
http.Error(w, "search scope is forbidden", http.StatusForbidden)
return
}
}
camhttputil.ReturnJSON(w, sr)
}
|
go
|
func (a *Handler) handleSearch(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
camhttputil.BadRequestError(w, camhttputil.InvalidMethodError{}.Error())
return
}
if a.sh == nil {
http.Error(w, "app proxy has no search handler", 500)
return
}
a.masterQueryMu.RLock()
if a.masterQuery == nil {
http.Error(w, "search is not allowed", http.StatusForbidden)
a.masterQueryMu.RUnlock()
return
}
a.masterQueryMu.RUnlock()
var sq search.SearchQuery
if err := sq.FromHTTP(r); err != nil {
camhttputil.ServeJSONError(w, err)
return
}
sr, err := a.sh.Query(r.Context(), &sq)
if err != nil {
camhttputil.ServeJSONError(w, err)
return
}
// check this search is in the allowed domain
if !a.allowProxySearchResponse(sr) {
// there's a chance our domainBlobs cache is expired so let's
// refresh it and retry, but no more than once per minute.
if err := a.refreshDomainBlobs(); err != nil {
http.Error(w, "search scope is forbidden", http.StatusForbidden)
return
}
if !a.allowProxySearchResponse(sr) {
http.Error(w, "search scope is forbidden", http.StatusForbidden)
return
}
}
camhttputil.ReturnJSON(w, sr)
}
|
[
"func",
"(",
"a",
"*",
"Handler",
")",
"handleSearch",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"r",
".",
"Method",
"!=",
"http",
".",
"MethodPost",
"{",
"camhttputil",
".",
"BadRequestError",
"(",
"w",
",",
"camhttputil",
".",
"InvalidMethodError",
"{",
"}",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"a",
".",
"sh",
"==",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"500",
")",
"\n",
"return",
"\n",
"}",
"\n",
"a",
".",
"masterQueryMu",
".",
"RLock",
"(",
")",
"\n",
"if",
"a",
".",
"masterQuery",
"==",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusForbidden",
")",
"\n",
"a",
".",
"masterQueryMu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"\n",
"}",
"\n",
"a",
".",
"masterQueryMu",
".",
"RUnlock",
"(",
")",
"\n",
"var",
"sq",
"search",
".",
"SearchQuery",
"\n",
"if",
"err",
":=",
"sq",
".",
"FromHTTP",
"(",
"r",
")",
";",
"err",
"!=",
"nil",
"{",
"camhttputil",
".",
"ServeJSONError",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"sr",
",",
"err",
":=",
"a",
".",
"sh",
".",
"Query",
"(",
"r",
".",
"Context",
"(",
")",
",",
"&",
"sq",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"camhttputil",
".",
"ServeJSONError",
"(",
"w",
",",
"err",
")",
"\n",
"return",
"\n",
"}",
"\n",
"// check this search is in the allowed domain",
"if",
"!",
"a",
".",
"allowProxySearchResponse",
"(",
"sr",
")",
"{",
"// there's a chance our domainBlobs cache is expired so let's",
"// refresh it and retry, but no more than once per minute.",
"if",
"err",
":=",
"a",
".",
"refreshDomainBlobs",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusForbidden",
")",
"\n",
"return",
"\n",
"}",
"\n",
"if",
"!",
"a",
".",
"allowProxySearchResponse",
"(",
"sr",
")",
"{",
"http",
".",
"Error",
"(",
"w",
",",
"\"",
"\"",
",",
"http",
".",
"StatusForbidden",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"camhttputil",
".",
"ReturnJSON",
"(",
"w",
",",
"sr",
")",
"\n",
"}"
] |
// handleSearch runs the requested search query against the search handler, and
// if the results are within the domain allowed by the master query, forwards them
// back to the client.
|
[
"handleSearch",
"runs",
"the",
"requested",
"search",
"query",
"against",
"the",
"search",
"handler",
"and",
"if",
"the",
"results",
"are",
"within",
"the",
"domain",
"allowed",
"by",
"the",
"master",
"query",
"forwards",
"them",
"back",
"to",
"the",
"client",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/server/app/app.go#L190-L230
|
train
|
perkeep/perkeep
|
pkg/server/app/app.go
|
allowProxySearchResponse
|
func (a *Handler) allowProxySearchResponse(sr *search.SearchResult) bool {
a.masterQueryMu.RLock()
defer a.masterQueryMu.RUnlock()
for _, v := range sr.Blobs {
if _, ok := a.domainBlobs[v.Blob]; !ok {
return false
}
}
return true
}
|
go
|
func (a *Handler) allowProxySearchResponse(sr *search.SearchResult) bool {
a.masterQueryMu.RLock()
defer a.masterQueryMu.RUnlock()
for _, v := range sr.Blobs {
if _, ok := a.domainBlobs[v.Blob]; !ok {
return false
}
}
return true
}
|
[
"func",
"(",
"a",
"*",
"Handler",
")",
"allowProxySearchResponse",
"(",
"sr",
"*",
"search",
".",
"SearchResult",
")",
"bool",
"{",
"a",
".",
"masterQueryMu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"a",
".",
"masterQueryMu",
".",
"RUnlock",
"(",
")",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"sr",
".",
"Blobs",
"{",
"if",
"_",
",",
"ok",
":=",
"a",
".",
"domainBlobs",
"[",
"v",
".",
"Blob",
"]",
";",
"!",
"ok",
"{",
"return",
"false",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"true",
"\n",
"}"
] |
// allowProxySearchResponse checks whether the blobs in sr are within the domain
// defined by the masterQuery, and hence if the client is allowed to get that
// response.
|
[
"allowProxySearchResponse",
"checks",
"whether",
"the",
"blobs",
"in",
"sr",
"are",
"within",
"the",
"domain",
"defined",
"by",
"the",
"masterQuery",
"and",
"hence",
"if",
"the",
"client",
"is",
"allowed",
"to",
"get",
"that",
"response",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/server/app/app.go#L235-L244
|
train
|
perkeep/perkeep
|
pkg/server/app/app.go
|
randListenFn
|
func randListenFn(listenAddr string, randPortFn func() (int, error)) (string, error) {
portIdx := strings.LastIndex(listenAddr, ":") + 1
if portIdx <= 0 || portIdx >= len(listenAddr) {
return "", errors.New("invalid listen addr, no port found")
}
port, err := randPortFn()
if err != nil {
return "", err
}
return fmt.Sprintf("%s%d", listenAddr[:portIdx], port), nil
}
|
go
|
func randListenFn(listenAddr string, randPortFn func() (int, error)) (string, error) {
portIdx := strings.LastIndex(listenAddr, ":") + 1
if portIdx <= 0 || portIdx >= len(listenAddr) {
return "", errors.New("invalid listen addr, no port found")
}
port, err := randPortFn()
if err != nil {
return "", err
}
return fmt.Sprintf("%s%d", listenAddr[:portIdx], port), nil
}
|
[
"func",
"randListenFn",
"(",
"listenAddr",
"string",
",",
"randPortFn",
"func",
"(",
")",
"(",
"int",
",",
"error",
")",
")",
"(",
"string",
",",
"error",
")",
"{",
"portIdx",
":=",
"strings",
".",
"LastIndex",
"(",
"listenAddr",
",",
"\"",
"\"",
")",
"+",
"1",
"\n",
"if",
"portIdx",
"<=",
"0",
"||",
"portIdx",
">=",
"len",
"(",
"listenAddr",
")",
"{",
"return",
"\"",
"\"",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"port",
",",
"err",
":=",
"randPortFn",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"err",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"listenAddr",
"[",
":",
"portIdx",
"]",
",",
"port",
")",
",",
"nil",
"\n",
"}"
] |
// randListenFn only exists to allow testing of randListen, by letting the caller
// replace randPort with a func that actually has a predictable result.
|
[
"randListenFn",
"only",
"exists",
"to",
"allow",
"testing",
"of",
"randListen",
"by",
"letting",
"the",
"caller",
"replace",
"randPort",
"with",
"a",
"func",
"that",
"actually",
"has",
"a",
"predictable",
"result",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/server/app/app.go#L253-L263
|
train
|
perkeep/perkeep
|
pkg/server/app/app.go
|
baseURL
|
func baseURL(serverBaseURL, listenAddr string) (string, error) {
backendURL, err := url.Parse(serverBaseURL)
if err != nil {
return "", fmt.Errorf("invalid baseURL %q: %v", serverBaseURL, err)
}
scheme := backendURL.Scheme
host := backendURL.Host
if netutil.HasPort(host) {
host = host[:strings.LastIndex(host, ":")]
}
port := portMap[scheme]
if netutil.HasPort(listenAddr) {
port = listenAddr[strings.LastIndex(listenAddr, ":")+1:]
}
return fmt.Sprintf("%s://%s:%s/", scheme, host, port), nil
}
|
go
|
func baseURL(serverBaseURL, listenAddr string) (string, error) {
backendURL, err := url.Parse(serverBaseURL)
if err != nil {
return "", fmt.Errorf("invalid baseURL %q: %v", serverBaseURL, err)
}
scheme := backendURL.Scheme
host := backendURL.Host
if netutil.HasPort(host) {
host = host[:strings.LastIndex(host, ":")]
}
port := portMap[scheme]
if netutil.HasPort(listenAddr) {
port = listenAddr[strings.LastIndex(listenAddr, ":")+1:]
}
return fmt.Sprintf("%s://%s:%s/", scheme, host, port), nil
}
|
[
"func",
"baseURL",
"(",
"serverBaseURL",
",",
"listenAddr",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"backendURL",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"serverBaseURL",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"serverBaseURL",
",",
"err",
")",
"\n",
"}",
"\n",
"scheme",
":=",
"backendURL",
".",
"Scheme",
"\n",
"host",
":=",
"backendURL",
".",
"Host",
"\n",
"if",
"netutil",
".",
"HasPort",
"(",
"host",
")",
"{",
"host",
"=",
"host",
"[",
":",
"strings",
".",
"LastIndex",
"(",
"host",
",",
"\"",
"\"",
")",
"]",
"\n",
"}",
"\n",
"port",
":=",
"portMap",
"[",
"scheme",
"]",
"\n",
"if",
"netutil",
".",
"HasPort",
"(",
"listenAddr",
")",
"{",
"port",
"=",
"listenAddr",
"[",
"strings",
".",
"LastIndex",
"(",
"listenAddr",
",",
"\"",
"\"",
")",
"+",
"1",
":",
"]",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"scheme",
",",
"host",
",",
"port",
")",
",",
"nil",
"\n",
"}"
] |
// baseURL returns the concatenation of the scheme and host parts of
// serverBaseURL with the port of listenAddr.
|
[
"baseURL",
"returns",
"the",
"concatenation",
"of",
"the",
"scheme",
"and",
"host",
"parts",
"of",
"serverBaseURL",
"with",
"the",
"port",
"of",
"listenAddr",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/server/app/app.go#L272-L287
|
train
|
perkeep/perkeep
|
pkg/server/app/app.go
|
FromJSONConfig
|
func FromJSONConfig(config jsonconfig.Obj, prefix, serverBaseURL string) (HandlerConfig, error) {
hc := HandlerConfig{
Program: config.RequiredString("program"),
Prefix: config.OptionalString("prefix", prefix),
BackendURL: config.OptionalString("backendURL", ""),
Listen: config.OptionalString("listen", ""),
APIHost: config.OptionalString("apiHost", ""),
ServerListen: config.OptionalString("serverListen", ""),
ServerBaseURL: config.OptionalString("serverBaseURL", serverBaseURL),
AppConfig: config.OptionalObject("appConfig"),
}
if err := config.Validate(); err != nil {
return HandlerConfig{}, err
}
return hc, nil
}
|
go
|
func FromJSONConfig(config jsonconfig.Obj, prefix, serverBaseURL string) (HandlerConfig, error) {
hc := HandlerConfig{
Program: config.RequiredString("program"),
Prefix: config.OptionalString("prefix", prefix),
BackendURL: config.OptionalString("backendURL", ""),
Listen: config.OptionalString("listen", ""),
APIHost: config.OptionalString("apiHost", ""),
ServerListen: config.OptionalString("serverListen", ""),
ServerBaseURL: config.OptionalString("serverBaseURL", serverBaseURL),
AppConfig: config.OptionalObject("appConfig"),
}
if err := config.Validate(); err != nil {
return HandlerConfig{}, err
}
return hc, nil
}
|
[
"func",
"FromJSONConfig",
"(",
"config",
"jsonconfig",
".",
"Obj",
",",
"prefix",
",",
"serverBaseURL",
"string",
")",
"(",
"HandlerConfig",
",",
"error",
")",
"{",
"hc",
":=",
"HandlerConfig",
"{",
"Program",
":",
"config",
".",
"RequiredString",
"(",
"\"",
"\"",
")",
",",
"Prefix",
":",
"config",
".",
"OptionalString",
"(",
"\"",
"\"",
",",
"prefix",
")",
",",
"BackendURL",
":",
"config",
".",
"OptionalString",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"Listen",
":",
"config",
".",
"OptionalString",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"APIHost",
":",
"config",
".",
"OptionalString",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"ServerListen",
":",
"config",
".",
"OptionalString",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
",",
"ServerBaseURL",
":",
"config",
".",
"OptionalString",
"(",
"\"",
"\"",
",",
"serverBaseURL",
")",
",",
"AppConfig",
":",
"config",
".",
"OptionalObject",
"(",
"\"",
"\"",
")",
",",
"}",
"\n",
"if",
"err",
":=",
"config",
".",
"Validate",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"HandlerConfig",
"{",
"}",
",",
"err",
"\n",
"}",
"\n",
"return",
"hc",
",",
"nil",
"\n",
"}"
] |
// FromJSONConfig creates an HandlerConfig from the contents of config.
// prefix and serverBaseURL are used if not found in config.
|
[
"FromJSONConfig",
"creates",
"an",
"HandlerConfig",
"from",
"the",
"contents",
"of",
"config",
".",
"prefix",
"and",
"serverBaseURL",
"are",
"used",
"if",
"not",
"found",
"in",
"config",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/server/app/app.go#L340-L355
|
train
|
perkeep/perkeep
|
pkg/server/app/app.go
|
InitHandler
|
func (a *Handler) InitHandler(hl blobserver.FindHandlerByTyper) error {
apName := a.ProgramName()
searchPrefix, _, err := hl.FindHandlerByType("search")
if err != nil {
return fmt.Errorf("No search handler configured, which is necessary for the %v app handler", apName)
}
var sh *search.Handler
_, hi := hl.AllHandlers()
h, ok := hi[searchPrefix]
if !ok {
return fmt.Errorf("failed to find the \"search\" handler for %v", apName)
}
sh = h.(*search.Handler)
a.sh = sh
return nil
}
|
go
|
func (a *Handler) InitHandler(hl blobserver.FindHandlerByTyper) error {
apName := a.ProgramName()
searchPrefix, _, err := hl.FindHandlerByType("search")
if err != nil {
return fmt.Errorf("No search handler configured, which is necessary for the %v app handler", apName)
}
var sh *search.Handler
_, hi := hl.AllHandlers()
h, ok := hi[searchPrefix]
if !ok {
return fmt.Errorf("failed to find the \"search\" handler for %v", apName)
}
sh = h.(*search.Handler)
a.sh = sh
return nil
}
|
[
"func",
"(",
"a",
"*",
"Handler",
")",
"InitHandler",
"(",
"hl",
"blobserver",
".",
"FindHandlerByTyper",
")",
"error",
"{",
"apName",
":=",
"a",
".",
"ProgramName",
"(",
")",
"\n",
"searchPrefix",
",",
"_",
",",
"err",
":=",
"hl",
".",
"FindHandlerByType",
"(",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"apName",
")",
"\n",
"}",
"\n",
"var",
"sh",
"*",
"search",
".",
"Handler",
"\n",
"_",
",",
"hi",
":=",
"hl",
".",
"AllHandlers",
"(",
")",
"\n",
"h",
",",
"ok",
":=",
"hi",
"[",
"searchPrefix",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\\\"",
"\\\"",
"\"",
",",
"apName",
")",
"\n",
"}",
"\n",
"sh",
"=",
"h",
".",
"(",
"*",
"search",
".",
"Handler",
")",
"\n",
"a",
".",
"sh",
"=",
"sh",
"\n",
"return",
"nil",
"\n",
"}"
] |
// InitHandler sets the app handler's search handler, if the app handler was configured
// to have one with HasSearch.
|
[
"InitHandler",
"sets",
"the",
"app",
"handler",
"s",
"search",
"handler",
"if",
"the",
"app",
"handler",
"was",
"configured",
"to",
"have",
"one",
"with",
"HasSearch",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/server/app/app.go#L442-L457
|
train
|
perkeep/perkeep
|
pkg/server/app/app.go
|
Quit
|
func (a *Handler) Quit() error {
err := a.process.Signal(os.Interrupt)
if err != nil {
return err
}
c := make(chan error)
go func() {
_, err := a.process.Wait()
c <- err
}()
select {
case err = <-c:
case <-time.After(5 * time.Second):
// TODO Do we want to SIGKILL here or just leave the app alone?
err = errProcessTookTooLong
}
return err
}
|
go
|
func (a *Handler) Quit() error {
err := a.process.Signal(os.Interrupt)
if err != nil {
return err
}
c := make(chan error)
go func() {
_, err := a.process.Wait()
c <- err
}()
select {
case err = <-c:
case <-time.After(5 * time.Second):
// TODO Do we want to SIGKILL here or just leave the app alone?
err = errProcessTookTooLong
}
return err
}
|
[
"func",
"(",
"a",
"*",
"Handler",
")",
"Quit",
"(",
")",
"error",
"{",
"err",
":=",
"a",
".",
"process",
".",
"Signal",
"(",
"os",
".",
"Interrupt",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n\n",
"c",
":=",
"make",
"(",
"chan",
"error",
")",
"\n",
"go",
"func",
"(",
")",
"{",
"_",
",",
"err",
":=",
"a",
".",
"process",
".",
"Wait",
"(",
")",
"\n",
"c",
"<-",
"err",
"\n",
"}",
"(",
")",
"\n",
"select",
"{",
"case",
"err",
"=",
"<-",
"c",
":",
"case",
"<-",
"time",
".",
"After",
"(",
"5",
"*",
"time",
".",
"Second",
")",
":",
"// TODO Do we want to SIGKILL here or just leave the app alone?",
"err",
"=",
"errProcessTookTooLong",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] |
// Quit sends the app's process a SIGINT, and waits up to 5 seconds for it
// to exit, returning an error if it doesn't.
|
[
"Quit",
"sends",
"the",
"app",
"s",
"process",
"a",
"SIGINT",
"and",
"waits",
"up",
"to",
"5",
"seconds",
"for",
"it",
"to",
"exit",
"returning",
"an",
"error",
"if",
"it",
"doesn",
"t",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/server/app/app.go#L536-L554
|
train
|
perkeep/perkeep
|
pkg/cacher/cacher.go
|
NewCachingFetcher
|
func NewCachingFetcher(cache blobserver.Cache, fetcher blob.Fetcher) *CachingFetcher {
return &CachingFetcher{c: cache, sf: fetcher}
}
|
go
|
func NewCachingFetcher(cache blobserver.Cache, fetcher blob.Fetcher) *CachingFetcher {
return &CachingFetcher{c: cache, sf: fetcher}
}
|
[
"func",
"NewCachingFetcher",
"(",
"cache",
"blobserver",
".",
"Cache",
",",
"fetcher",
"blob",
".",
"Fetcher",
")",
"*",
"CachingFetcher",
"{",
"return",
"&",
"CachingFetcher",
"{",
"c",
":",
"cache",
",",
"sf",
":",
"fetcher",
"}",
"\n",
"}"
] |
// NewCachingFetcher returns a CachingFetcher that fetches from
// fetcher and writes to and serves from cache.
|
[
"NewCachingFetcher",
"returns",
"a",
"CachingFetcher",
"that",
"fetches",
"from",
"fetcher",
"and",
"writes",
"to",
"and",
"serves",
"from",
"cache",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/cacher/cacher.go#L38-L40
|
train
|
perkeep/perkeep
|
pkg/cacher/cacher.go
|
SetCacheHitHook
|
func (cf *CachingFetcher) SetCacheHitHook(fn func(br blob.Ref, rc io.ReadCloser) (io.ReadCloser, error)) {
cf.cacheHitHook = fn
}
|
go
|
func (cf *CachingFetcher) SetCacheHitHook(fn func(br blob.Ref, rc io.ReadCloser) (io.ReadCloser, error)) {
cf.cacheHitHook = fn
}
|
[
"func",
"(",
"cf",
"*",
"CachingFetcher",
")",
"SetCacheHitHook",
"(",
"fn",
"func",
"(",
"br",
"blob",
".",
"Ref",
",",
"rc",
"io",
".",
"ReadCloser",
")",
"(",
"io",
".",
"ReadCloser",
",",
"error",
")",
")",
"{",
"cf",
".",
"cacheHitHook",
"=",
"fn",
"\n",
"}"
] |
// SetCacheHitHook sets a function that will modify the return values from Fetch
// in the case of a cache hit.
// Its purpose is to add potential side-effects from calling the Fetcher that would
// have happened if we had had a cache miss. It is the responsibility of fn to
// return a ReadCloser equivalent to the state that rc was given in.
|
[
"SetCacheHitHook",
"sets",
"a",
"function",
"that",
"will",
"modify",
"the",
"return",
"values",
"from",
"Fetch",
"in",
"the",
"case",
"of",
"a",
"cache",
"hit",
".",
"Its",
"purpose",
"is",
"to",
"add",
"potential",
"side",
"-",
"effects",
"from",
"calling",
"the",
"Fetcher",
"that",
"would",
"have",
"happened",
"if",
"we",
"had",
"had",
"a",
"cache",
"miss",
".",
"It",
"is",
"the",
"responsibility",
"of",
"fn",
"to",
"return",
"a",
"ReadCloser",
"equivalent",
"to",
"the",
"state",
"that",
"rc",
"was",
"given",
"in",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/cacher/cacher.go#L60-L62
|
train
|
perkeep/perkeep
|
pkg/fs/mut.go
|
maybeAddChild
|
func (n *mutDir) maybeAddChild(name string, permanode *search.DescribedPermanode,
child mutFileOrDir) {
if current, ok := n.children[name]; !ok ||
current.permanodeString() != child.permanodeString() {
child.xattr().load(permanode)
n.children[name] = child
}
}
|
go
|
func (n *mutDir) maybeAddChild(name string, permanode *search.DescribedPermanode,
child mutFileOrDir) {
if current, ok := n.children[name]; !ok ||
current.permanodeString() != child.permanodeString() {
child.xattr().load(permanode)
n.children[name] = child
}
}
|
[
"func",
"(",
"n",
"*",
"mutDir",
")",
"maybeAddChild",
"(",
"name",
"string",
",",
"permanode",
"*",
"search",
".",
"DescribedPermanode",
",",
"child",
"mutFileOrDir",
")",
"{",
"if",
"current",
",",
"ok",
":=",
"n",
".",
"children",
"[",
"name",
"]",
";",
"!",
"ok",
"||",
"current",
".",
"permanodeString",
"(",
")",
"!=",
"child",
".",
"permanodeString",
"(",
")",
"{",
"child",
".",
"xattr",
"(",
")",
".",
"load",
"(",
"permanode",
")",
"\n",
"n",
".",
"children",
"[",
"name",
"]",
"=",
"child",
"\n",
"}",
"\n",
"}"
] |
// maybeAddChild adds a child directory to this mutable directory
// unless it already has one with this name and permanode.
|
[
"maybeAddChild",
"adds",
"a",
"child",
"directory",
"to",
"this",
"mutable",
"directory",
"unless",
"it",
"already",
"has",
"one",
"with",
"this",
"name",
"and",
"permanode",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/fs/mut.go#L233-L241
|
train
|
perkeep/perkeep
|
pkg/fs/mut.go
|
Release
|
func (h *mutFileHandle) Release(ctx context.Context, req *fuse.ReleaseRequest) error {
h.tmp.Close()
os.Remove(h.tmp.Name())
h.tmp = nil
return nil
}
|
go
|
func (h *mutFileHandle) Release(ctx context.Context, req *fuse.ReleaseRequest) error {
h.tmp.Close()
os.Remove(h.tmp.Name())
h.tmp = nil
return nil
}
|
[
"func",
"(",
"h",
"*",
"mutFileHandle",
")",
"Release",
"(",
"ctx",
"context",
".",
"Context",
",",
"req",
"*",
"fuse",
".",
"ReleaseRequest",
")",
"error",
"{",
"h",
".",
"tmp",
".",
"Close",
"(",
")",
"\n",
"os",
".",
"Remove",
"(",
"h",
".",
"tmp",
".",
"Name",
"(",
")",
")",
"\n",
"h",
".",
"tmp",
"=",
"nil",
"\n\n",
"return",
"nil",
"\n",
"}"
] |
// Release is called when a file handle is no longer needed. This is
// called asynchronously after the last handle to a file is closed.
|
[
"Release",
"is",
"called",
"when",
"a",
"file",
"handle",
"is",
"no",
"longer",
"needed",
".",
"This",
"is",
"called",
"asynchronously",
"after",
"the",
"last",
"handle",
"to",
"a",
"file",
"is",
"closed",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/fs/mut.go#L871-L877
|
train
|
perkeep/perkeep
|
pkg/fs/time.go
|
parseCanonicalTime
|
func parseCanonicalTime(in string) (time.Time, error) {
if len(in) < 20 || in[len(in)-1] != 'Z' {
return time.Time{}, errUnparseableTimestamp
}
if !(in[4] == '-' && in[7] == '-' && in[10] == 'T' &&
in[13] == ':' && in[16] == ':' && (in[19] == '.' || in[19] == 'Z')) {
return time.Time{}, fmt.Errorf("positionally incorrect: %v", in)
}
// 2012-08-28T21:24:35.37465188Z
// 4 7 10 13 16 19
// -----------------------------
// 0-4 5 8 11 14 17 20
year, err := strconv.Atoi(in[0:4])
if err != nil {
return time.Time{}, fmt.Errorf("error parsing year: %v", err)
}
month, err := strconv.Atoi(in[5:7])
if err != nil {
return time.Time{}, fmt.Errorf("error parsing month: %v", err)
}
day, err := strconv.Atoi(in[8:10])
if err != nil {
return time.Time{}, fmt.Errorf("error parsing day: %v", err)
}
hour, err := strconv.Atoi(in[11:13])
if err != nil {
return time.Time{}, fmt.Errorf("error parsing hour: %v", err)
}
minute, err := strconv.Atoi(in[14:16])
if err != nil {
return time.Time{}, fmt.Errorf("error parsing minute: %v", err)
}
second, err := strconv.Atoi(in[17:19])
if err != nil {
return time.Time{}, fmt.Errorf("error parsing second: %v", err)
}
var nsecstr string
if in[19] != 'Z' {
nsecstr = in[20 : len(in)-1]
}
var nsec int
if nsecstr != "" {
nsec, err = strconv.Atoi(nsecstr)
if err != nil {
return time.Time{}, fmt.Errorf("error parsing nanoseconds: %v", err)
}
}
nsec *= powTable[len(nsecstr)]
return time.Date(year, time.Month(month), day,
hour, minute, second, nsec, time.UTC), nil
}
|
go
|
func parseCanonicalTime(in string) (time.Time, error) {
if len(in) < 20 || in[len(in)-1] != 'Z' {
return time.Time{}, errUnparseableTimestamp
}
if !(in[4] == '-' && in[7] == '-' && in[10] == 'T' &&
in[13] == ':' && in[16] == ':' && (in[19] == '.' || in[19] == 'Z')) {
return time.Time{}, fmt.Errorf("positionally incorrect: %v", in)
}
// 2012-08-28T21:24:35.37465188Z
// 4 7 10 13 16 19
// -----------------------------
// 0-4 5 8 11 14 17 20
year, err := strconv.Atoi(in[0:4])
if err != nil {
return time.Time{}, fmt.Errorf("error parsing year: %v", err)
}
month, err := strconv.Atoi(in[5:7])
if err != nil {
return time.Time{}, fmt.Errorf("error parsing month: %v", err)
}
day, err := strconv.Atoi(in[8:10])
if err != nil {
return time.Time{}, fmt.Errorf("error parsing day: %v", err)
}
hour, err := strconv.Atoi(in[11:13])
if err != nil {
return time.Time{}, fmt.Errorf("error parsing hour: %v", err)
}
minute, err := strconv.Atoi(in[14:16])
if err != nil {
return time.Time{}, fmt.Errorf("error parsing minute: %v", err)
}
second, err := strconv.Atoi(in[17:19])
if err != nil {
return time.Time{}, fmt.Errorf("error parsing second: %v", err)
}
var nsecstr string
if in[19] != 'Z' {
nsecstr = in[20 : len(in)-1]
}
var nsec int
if nsecstr != "" {
nsec, err = strconv.Atoi(nsecstr)
if err != nil {
return time.Time{}, fmt.Errorf("error parsing nanoseconds: %v", err)
}
}
nsec *= powTable[len(nsecstr)]
return time.Date(year, time.Month(month), day,
hour, minute, second, nsec, time.UTC), nil
}
|
[
"func",
"parseCanonicalTime",
"(",
"in",
"string",
")",
"(",
"time",
".",
"Time",
",",
"error",
")",
"{",
"if",
"len",
"(",
"in",
")",
"<",
"20",
"||",
"in",
"[",
"len",
"(",
"in",
")",
"-",
"1",
"]",
"!=",
"'Z'",
"{",
"return",
"time",
".",
"Time",
"{",
"}",
",",
"errUnparseableTimestamp",
"\n",
"}",
"\n\n",
"if",
"!",
"(",
"in",
"[",
"4",
"]",
"==",
"'-'",
"&&",
"in",
"[",
"7",
"]",
"==",
"'-'",
"&&",
"in",
"[",
"10",
"]",
"==",
"'T'",
"&&",
"in",
"[",
"13",
"]",
"==",
"':'",
"&&",
"in",
"[",
"16",
"]",
"==",
"':'",
"&&",
"(",
"in",
"[",
"19",
"]",
"==",
"'.'",
"||",
"in",
"[",
"19",
"]",
"==",
"'Z'",
")",
")",
"{",
"return",
"time",
".",
"Time",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"in",
")",
"\n",
"}",
"\n\n",
"// 2012-08-28T21:24:35.37465188Z",
"// 4 7 10 13 16 19",
"// -----------------------------",
"// 0-4 5 8 11 14 17 20",
"year",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"in",
"[",
"0",
":",
"4",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"time",
".",
"Time",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"month",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"in",
"[",
"5",
":",
"7",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"time",
".",
"Time",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"day",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"in",
"[",
"8",
":",
"10",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"time",
".",
"Time",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"hour",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"in",
"[",
"11",
":",
"13",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"time",
".",
"Time",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"minute",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"in",
"[",
"14",
":",
"16",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"time",
".",
"Time",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"second",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"in",
"[",
"17",
":",
"19",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"time",
".",
"Time",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n\n",
"var",
"nsecstr",
"string",
"\n",
"if",
"in",
"[",
"19",
"]",
"!=",
"'Z'",
"{",
"nsecstr",
"=",
"in",
"[",
"20",
":",
"len",
"(",
"in",
")",
"-",
"1",
"]",
"\n",
"}",
"\n",
"var",
"nsec",
"int",
"\n\n",
"if",
"nsecstr",
"!=",
"\"",
"\"",
"{",
"nsec",
",",
"err",
"=",
"strconv",
".",
"Atoi",
"(",
"nsecstr",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"time",
".",
"Time",
"{",
"}",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n\n",
"nsec",
"*=",
"powTable",
"[",
"len",
"(",
"nsecstr",
")",
"]",
"\n\n",
"return",
"time",
".",
"Date",
"(",
"year",
",",
"time",
".",
"Month",
"(",
"month",
")",
",",
"day",
",",
"hour",
",",
"minute",
",",
"second",
",",
"nsec",
",",
"time",
".",
"UTC",
")",
",",
"nil",
"\n",
"}"
] |
// Hand crafted this parser since it's a really common path.
|
[
"Hand",
"crafted",
"this",
"parser",
"since",
"it",
"s",
"a",
"really",
"common",
"path",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/fs/time.go#L60-L122
|
train
|
perkeep/perkeep
|
pkg/index/memindex.go
|
NewMemoryIndex
|
func NewMemoryIndex() *Index {
ix, err := New(sorted.NewMemoryKeyValue())
if err != nil {
// Nothing to fail in memory, so worth panicing about
// if we ever see something.
panic(err)
}
return ix
}
|
go
|
func NewMemoryIndex() *Index {
ix, err := New(sorted.NewMemoryKeyValue())
if err != nil {
// Nothing to fail in memory, so worth panicing about
// if we ever see something.
panic(err)
}
return ix
}
|
[
"func",
"NewMemoryIndex",
"(",
")",
"*",
"Index",
"{",
"ix",
",",
"err",
":=",
"New",
"(",
"sorted",
".",
"NewMemoryKeyValue",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// Nothing to fail in memory, so worth panicing about",
"// if we ever see something.",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"return",
"ix",
"\n",
"}"
] |
// NewMemoryIndex returns an Index backed only by memory, for use in tests.
|
[
"NewMemoryIndex",
"returns",
"an",
"Index",
"backed",
"only",
"by",
"memory",
"for",
"use",
"in",
"tests",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/memindex.go#L31-L39
|
train
|
perkeep/perkeep
|
app/scanningcabinet/scancab/pdf.go
|
pageCountPoppler
|
func pageCountPoppler(filename string) (cnt int, err error) {
cmd := exec.Command("pdfinfo", filename)
out, err := cmd.CombinedOutput()
if err != nil {
return cnt, fmt.Errorf("could not get page count with pdfinfo: %v, %v", err, string(out))
}
sc := bufio.NewScanner(bytes.NewReader(out))
for sc.Scan() {
l := sc.Text()
if !strings.HasPrefix(l, "Pages: ") {
continue
}
return strconv.Atoi(strings.TrimSpace(strings.TrimPrefix(l, "Pages:")))
}
if err := sc.Err(); err != nil {
return 0, err
}
return 0, errors.New("page count not found in pdfinfo output")
}
|
go
|
func pageCountPoppler(filename string) (cnt int, err error) {
cmd := exec.Command("pdfinfo", filename)
out, err := cmd.CombinedOutput()
if err != nil {
return cnt, fmt.Errorf("could not get page count with pdfinfo: %v, %v", err, string(out))
}
sc := bufio.NewScanner(bytes.NewReader(out))
for sc.Scan() {
l := sc.Text()
if !strings.HasPrefix(l, "Pages: ") {
continue
}
return strconv.Atoi(strings.TrimSpace(strings.TrimPrefix(l, "Pages:")))
}
if err := sc.Err(); err != nil {
return 0, err
}
return 0, errors.New("page count not found in pdfinfo output")
}
|
[
"func",
"pageCountPoppler",
"(",
"filename",
"string",
")",
"(",
"cnt",
"int",
",",
"err",
"error",
")",
"{",
"cmd",
":=",
"exec",
".",
"Command",
"(",
"\"",
"\"",
",",
"filename",
")",
"\n",
"out",
",",
"err",
":=",
"cmd",
".",
"CombinedOutput",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"cnt",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
",",
"string",
"(",
"out",
")",
")",
"\n",
"}",
"\n",
"sc",
":=",
"bufio",
".",
"NewScanner",
"(",
"bytes",
".",
"NewReader",
"(",
"out",
")",
")",
"\n",
"for",
"sc",
".",
"Scan",
"(",
")",
"{",
"l",
":=",
"sc",
".",
"Text",
"(",
")",
"\n",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"l",
",",
"\"",
"\"",
")",
"{",
"continue",
"\n",
"}",
"\n",
"return",
"strconv",
".",
"Atoi",
"(",
"strings",
".",
"TrimSpace",
"(",
"strings",
".",
"TrimPrefix",
"(",
"l",
",",
"\"",
"\"",
")",
")",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"sc",
".",
"Err",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}"
] |
// pageCountPoppler calls the tool pdfinfo from the Poppler project for
// filename and parses the output for the page count which is then returned. If
// any error occurs or the pages count information is not found, an error is
// returned.
|
[
"pageCountPoppler",
"calls",
"the",
"tool",
"pdfinfo",
"from",
"the",
"Poppler",
"project",
"for",
"filename",
"and",
"parses",
"the",
"output",
"for",
"the",
"page",
"count",
"which",
"is",
"then",
"returned",
".",
"If",
"any",
"error",
"occurs",
"or",
"the",
"pages",
"count",
"information",
"is",
"not",
"found",
"an",
"error",
"is",
"returned",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/scanningcabinet/scancab/pdf.go#L37-L55
|
train
|
perkeep/perkeep
|
app/scanningcabinet/scancab/pdf.go
|
pageCountNative
|
func pageCountNative(filename string) (int, error) {
f, err := os.Open(filename)
if err != nil {
return 0, err
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return 0, err
}
p, err := pdf.NewReader(f, fi.Size())
if err != nil {
return 0, err
}
c := p.NumPage()
if c < 1 {
return 0, errors.New("encountered PDF without any pages")
}
return p.NumPage(), nil
}
|
go
|
func pageCountNative(filename string) (int, error) {
f, err := os.Open(filename)
if err != nil {
return 0, err
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return 0, err
}
p, err := pdf.NewReader(f, fi.Size())
if err != nil {
return 0, err
}
c := p.NumPage()
if c < 1 {
return 0, errors.New("encountered PDF without any pages")
}
return p.NumPage(), nil
}
|
[
"func",
"pageCountNative",
"(",
"filename",
"string",
")",
"(",
"int",
",",
"error",
")",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"defer",
"f",
".",
"Close",
"(",
")",
"\n",
"fi",
",",
"err",
":=",
"f",
".",
"Stat",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"p",
",",
"err",
":=",
"pdf",
".",
"NewReader",
"(",
"f",
",",
"fi",
".",
"Size",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"c",
":=",
"p",
".",
"NumPage",
"(",
")",
"\n",
"if",
"c",
"<",
"1",
"{",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"return",
"p",
".",
"NumPage",
"(",
")",
",",
"nil",
"\n",
"}"
] |
// pageCountNative uses a native Go library to extract and return the number of
// pages in the PDF document. It returns an error if the filename is not of a
// PDF file, or if it failed to decode the PDF.
|
[
"pageCountNative",
"uses",
"a",
"native",
"Go",
"library",
"to",
"extract",
"and",
"return",
"the",
"number",
"of",
"pages",
"in",
"the",
"PDF",
"document",
".",
"It",
"returns",
"an",
"error",
"if",
"the",
"filename",
"is",
"not",
"of",
"a",
"PDF",
"file",
"or",
"if",
"it",
"failed",
"to",
"decode",
"the",
"PDF",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/scanningcabinet/scancab/pdf.go#L60-L79
|
train
|
perkeep/perkeep
|
app/scanningcabinet/scancab/pdf.go
|
pageCount
|
func pageCount(filename string) (int, error) {
n, err := pageCountNative(filename)
if err != nil {
// fallback to using pdfinfo when internal count failed
n, err = pageCountPoppler(filename)
}
return n, err
}
|
go
|
func pageCount(filename string) (int, error) {
n, err := pageCountNative(filename)
if err != nil {
// fallback to using pdfinfo when internal count failed
n, err = pageCountPoppler(filename)
}
return n, err
}
|
[
"func",
"pageCount",
"(",
"filename",
"string",
")",
"(",
"int",
",",
"error",
")",
"{",
"n",
",",
"err",
":=",
"pageCountNative",
"(",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"// fallback to using pdfinfo when internal count failed",
"n",
",",
"err",
"=",
"pageCountPoppler",
"(",
"filename",
")",
"\n",
"}",
"\n",
"return",
"n",
",",
"err",
"\n",
"}"
] |
// pageCount returns the number of pages in the given PDF file, or an error if
// it could not be determined. The function may trigger calls to external tools
// to achieve a valid count after native counting has been tried without
// success.
|
[
"pageCount",
"returns",
"the",
"number",
"of",
"pages",
"in",
"the",
"given",
"PDF",
"file",
"or",
"an",
"error",
"if",
"it",
"could",
"not",
"be",
"determined",
".",
"The",
"function",
"may",
"trigger",
"calls",
"to",
"external",
"tools",
"to",
"achieve",
"a",
"valid",
"count",
"after",
"native",
"counting",
"has",
"been",
"tried",
"without",
"success",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/scanningcabinet/scancab/pdf.go#L85-L92
|
train
|
perkeep/perkeep
|
pkg/search/predicate.go
|
SearchHelp
|
func SearchHelp() string {
type help struct{ Name, Description string }
h := []help{}
for _, p := range keywords {
h = append(h, help{p.Name(), p.Description()})
}
b, err := json.MarshalIndent(h, "", " ")
if err != nil {
return "Error marshalling"
}
return string(b)
}
|
go
|
func SearchHelp() string {
type help struct{ Name, Description string }
h := []help{}
for _, p := range keywords {
h = append(h, help{p.Name(), p.Description()})
}
b, err := json.MarshalIndent(h, "", " ")
if err != nil {
return "Error marshalling"
}
return string(b)
}
|
[
"func",
"SearchHelp",
"(",
")",
"string",
"{",
"type",
"help",
"struct",
"{",
"Name",
",",
"Description",
"string",
"}",
"\n",
"h",
":=",
"[",
"]",
"help",
"{",
"}",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"keywords",
"{",
"h",
"=",
"append",
"(",
"h",
",",
"help",
"{",
"p",
".",
"Name",
"(",
")",
",",
"p",
".",
"Description",
"(",
")",
"}",
")",
"\n",
"}",
"\n",
"b",
",",
"err",
":=",
"json",
".",
"MarshalIndent",
"(",
"h",
",",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"",
"\"",
"\n",
"}",
"\n",
"return",
"string",
"(",
"b",
")",
"\n",
"}"
] |
// SearchHelp returns JSON of an array of predicate names and descriptions.
|
[
"SearchHelp",
"returns",
"JSON",
"of",
"an",
"array",
"of",
"predicate",
"names",
"and",
"descriptions",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/search/predicate.go#L91-L102
|
train
|
perkeep/perkeep
|
pkg/blobserver/receive.go
|
ReceiveString
|
func ReceiveString(ctx context.Context, dst BlobReceiver, s string) (blob.SizedRef, error) {
return Receive(ctx, dst, blob.RefFromString(s), strings.NewReader(s))
}
|
go
|
func ReceiveString(ctx context.Context, dst BlobReceiver, s string) (blob.SizedRef, error) {
return Receive(ctx, dst, blob.RefFromString(s), strings.NewReader(s))
}
|
[
"func",
"ReceiveString",
"(",
"ctx",
"context",
".",
"Context",
",",
"dst",
"BlobReceiver",
",",
"s",
"string",
")",
"(",
"blob",
".",
"SizedRef",
",",
"error",
")",
"{",
"return",
"Receive",
"(",
"ctx",
",",
"dst",
",",
"blob",
".",
"RefFromString",
"(",
"s",
")",
",",
"strings",
".",
"NewReader",
"(",
"s",
")",
")",
"\n",
"}"
] |
// ReceiveString uploads the blob given by the string s to dst
// and returns its blobref and size.
|
[
"ReceiveString",
"uploads",
"the",
"blob",
"given",
"by",
"the",
"string",
"s",
"to",
"dst",
"and",
"returns",
"its",
"blobref",
"and",
"size",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/receive.go#L35-L37
|
train
|
perkeep/perkeep
|
pkg/blobserver/receive.go
|
Receive
|
func Receive(ctx context.Context, dst BlobReceiver, br blob.Ref, src io.Reader) (blob.SizedRef, error) {
return receive(ctx, dst, br, src, true)
}
|
go
|
func Receive(ctx context.Context, dst BlobReceiver, br blob.Ref, src io.Reader) (blob.SizedRef, error) {
return receive(ctx, dst, br, src, true)
}
|
[
"func",
"Receive",
"(",
"ctx",
"context",
".",
"Context",
",",
"dst",
"BlobReceiver",
",",
"br",
"blob",
".",
"Ref",
",",
"src",
"io",
".",
"Reader",
")",
"(",
"blob",
".",
"SizedRef",
",",
"error",
")",
"{",
"return",
"receive",
"(",
"ctx",
",",
"dst",
",",
"br",
",",
"src",
",",
"true",
")",
"\n",
"}"
] |
// Receive wraps calling a BlobReceiver's ReceiveBlob method,
// additionally providing verification of the src digest, and also
// notifying the blob hub on success.
// The error will be ErrCorruptBlob if the blobref didn't match.
|
[
"Receive",
"wraps",
"calling",
"a",
"BlobReceiver",
"s",
"ReceiveBlob",
"method",
"additionally",
"providing",
"verification",
"of",
"the",
"src",
"digest",
"and",
"also",
"notifying",
"the",
"blob",
"hub",
"on",
"success",
".",
"The",
"error",
"will",
"be",
"ErrCorruptBlob",
"if",
"the",
"blobref",
"didn",
"t",
"match",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/receive.go#L43-L45
|
train
|
perkeep/perkeep
|
pkg/importer/importer.go
|
Register
|
func Register(name string, im Importer) {
if _, dup := importers[name]; dup {
panic("Dup registration of importer " + name)
}
if _, dup := reservedImporterKey[name]; dup {
panic("Dup registration of importer " + name)
}
if pt := im.Properties().PermanodeImporterType; pt != "" {
if _, dup := importers[pt]; dup {
panic("Dup registration of importer " + pt)
}
if _, dup := reservedImporterKey[pt]; dup {
panic("Dup registration of importer " + pt)
}
reservedImporterKey[pt] = true
}
importers[name] = im
}
|
go
|
func Register(name string, im Importer) {
if _, dup := importers[name]; dup {
panic("Dup registration of importer " + name)
}
if _, dup := reservedImporterKey[name]; dup {
panic("Dup registration of importer " + name)
}
if pt := im.Properties().PermanodeImporterType; pt != "" {
if _, dup := importers[pt]; dup {
panic("Dup registration of importer " + pt)
}
if _, dup := reservedImporterKey[pt]; dup {
panic("Dup registration of importer " + pt)
}
reservedImporterKey[pt] = true
}
importers[name] = im
}
|
[
"func",
"Register",
"(",
"name",
"string",
",",
"im",
"Importer",
")",
"{",
"if",
"_",
",",
"dup",
":=",
"importers",
"[",
"name",
"]",
";",
"dup",
"{",
"panic",
"(",
"\"",
"\"",
"+",
"name",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"dup",
":=",
"reservedImporterKey",
"[",
"name",
"]",
";",
"dup",
"{",
"panic",
"(",
"\"",
"\"",
"+",
"name",
")",
"\n",
"}",
"\n",
"if",
"pt",
":=",
"im",
".",
"Properties",
"(",
")",
".",
"PermanodeImporterType",
";",
"pt",
"!=",
"\"",
"\"",
"{",
"if",
"_",
",",
"dup",
":=",
"importers",
"[",
"pt",
"]",
";",
"dup",
"{",
"panic",
"(",
"\"",
"\"",
"+",
"pt",
")",
"\n",
"}",
"\n",
"if",
"_",
",",
"dup",
":=",
"reservedImporterKey",
"[",
"pt",
"]",
";",
"dup",
"{",
"panic",
"(",
"\"",
"\"",
"+",
"pt",
")",
"\n",
"}",
"\n",
"reservedImporterKey",
"[",
"pt",
"]",
"=",
"true",
"\n",
"}",
"\n",
"importers",
"[",
"name",
"]",
"=",
"im",
"\n",
"}"
] |
// Register registers a site-specific importer. It should only be called from init,
// and not from concurrent goroutines.
|
[
"Register",
"registers",
"a",
"site",
"-",
"specific",
"importer",
".",
"It",
"should",
"only",
"be",
"called",
"from",
"init",
"and",
"not",
"from",
"concurrent",
"goroutines",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/importer.go#L171-L188
|
train
|
perkeep/perkeep
|
pkg/importer/importer.go
|
Context
|
func (rc *RunContext) Context() context.Context {
if rc.ctx != nil {
return rc.ctx
}
return context.Background()
}
|
go
|
func (rc *RunContext) Context() context.Context {
if rc.ctx != nil {
return rc.ctx
}
return context.Background()
}
|
[
"func",
"(",
"rc",
"*",
"RunContext",
")",
"Context",
"(",
")",
"context",
".",
"Context",
"{",
"if",
"rc",
".",
"ctx",
"!=",
"nil",
"{",
"return",
"rc",
".",
"ctx",
"\n",
"}",
"\n",
"return",
"context",
".",
"Background",
"(",
")",
"\n",
"}"
] |
// Context returns the run's context. It is always non-nil.
|
[
"Context",
"returns",
"the",
"run",
"s",
"context",
".",
"It",
"is",
"always",
"non",
"-",
"nil",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/importer.go#L345-L350
|
train
|
perkeep/perkeep
|
pkg/importer/importer.go
|
CreateAccount
|
func CreateAccount(h *Host, impl string) (*RunContext, error) {
imp, ok := h.imp[impl]
if !ok {
return nil, fmt.Errorf("host does not have a %v importer", impl)
}
ia, err := imp.newAccount()
if err != nil {
return nil, fmt.Errorf("could not create new account for importer %v: %v", impl, err)
}
rc := &RunContext{
Host: ia.im.host,
ia: ia,
}
rc.ctx, rc.cancel = context.WithCancel(context.WithValue(context.Background(), ctxutil.HTTPClient, ia.im.host.HTTPClient()))
return rc, nil
}
|
go
|
func CreateAccount(h *Host, impl string) (*RunContext, error) {
imp, ok := h.imp[impl]
if !ok {
return nil, fmt.Errorf("host does not have a %v importer", impl)
}
ia, err := imp.newAccount()
if err != nil {
return nil, fmt.Errorf("could not create new account for importer %v: %v", impl, err)
}
rc := &RunContext{
Host: ia.im.host,
ia: ia,
}
rc.ctx, rc.cancel = context.WithCancel(context.WithValue(context.Background(), ctxutil.HTTPClient, ia.im.host.HTTPClient()))
return rc, nil
}
|
[
"func",
"CreateAccount",
"(",
"h",
"*",
"Host",
",",
"impl",
"string",
")",
"(",
"*",
"RunContext",
",",
"error",
")",
"{",
"imp",
",",
"ok",
":=",
"h",
".",
"imp",
"[",
"impl",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"impl",
")",
"\n",
"}",
"\n",
"ia",
",",
"err",
":=",
"imp",
".",
"newAccount",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"impl",
",",
"err",
")",
"\n",
"}",
"\n",
"rc",
":=",
"&",
"RunContext",
"{",
"Host",
":",
"ia",
".",
"im",
".",
"host",
",",
"ia",
":",
"ia",
",",
"}",
"\n",
"rc",
".",
"ctx",
",",
"rc",
".",
"cancel",
"=",
"context",
".",
"WithCancel",
"(",
"context",
".",
"WithValue",
"(",
"context",
".",
"Background",
"(",
")",
",",
"ctxutil",
".",
"HTTPClient",
",",
"ia",
".",
"im",
".",
"host",
".",
"HTTPClient",
"(",
")",
")",
")",
"\n",
"return",
"rc",
",",
"nil",
"\n\n",
"}"
] |
// CreateAccount creates a new importer account for the Host h, and the importer
// implementation named impl. It returns a RunContext setup with that account.
|
[
"CreateAccount",
"creates",
"a",
"new",
"importer",
"account",
"for",
"the",
"Host",
"h",
"and",
"the",
"importer",
"implementation",
"named",
"impl",
".",
"It",
"returns",
"a",
"RunContext",
"setup",
"with",
"that",
"account",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/importer.go#L354-L370
|
train
|
perkeep/perkeep
|
pkg/importer/importer.go
|
AccountsStatus
|
func (h *Host) AccountsStatus() (interface{}, []camtypes.StatusError) {
h.didInit.Wait()
var s []accountStatus
var errs []camtypes.StatusError
for _, impName := range h.importers {
imp := h.imp[impName]
accts, _ := imp.Accounts()
for _, ia := range accts {
as := accountStatus{
Type: impName,
Href: ia.AccountURL(),
Name: ia.AccountLinkSummary(),
}
ia.mu.Lock()
if ia.current != nil {
as.StartedUnixSec = ia.lastRunStart.Unix()
}
if !ia.lastRunDone.IsZero() {
as.LastFinishedUnixSec = ia.lastRunDone.Unix()
}
if ia.lastRunErr != nil {
as.LastError = ia.lastRunErr.Error()
errs = append(errs, camtypes.StatusError{
Error: ia.lastRunErr.Error(),
URL: ia.AccountURL(),
})
}
ia.mu.Unlock()
s = append(s, as)
}
}
return s, errs
}
|
go
|
func (h *Host) AccountsStatus() (interface{}, []camtypes.StatusError) {
h.didInit.Wait()
var s []accountStatus
var errs []camtypes.StatusError
for _, impName := range h.importers {
imp := h.imp[impName]
accts, _ := imp.Accounts()
for _, ia := range accts {
as := accountStatus{
Type: impName,
Href: ia.AccountURL(),
Name: ia.AccountLinkSummary(),
}
ia.mu.Lock()
if ia.current != nil {
as.StartedUnixSec = ia.lastRunStart.Unix()
}
if !ia.lastRunDone.IsZero() {
as.LastFinishedUnixSec = ia.lastRunDone.Unix()
}
if ia.lastRunErr != nil {
as.LastError = ia.lastRunErr.Error()
errs = append(errs, camtypes.StatusError{
Error: ia.lastRunErr.Error(),
URL: ia.AccountURL(),
})
}
ia.mu.Unlock()
s = append(s, as)
}
}
return s, errs
}
|
[
"func",
"(",
"h",
"*",
"Host",
")",
"AccountsStatus",
"(",
")",
"(",
"interface",
"{",
"}",
",",
"[",
"]",
"camtypes",
".",
"StatusError",
")",
"{",
"h",
".",
"didInit",
".",
"Wait",
"(",
")",
"\n",
"var",
"s",
"[",
"]",
"accountStatus",
"\n",
"var",
"errs",
"[",
"]",
"camtypes",
".",
"StatusError",
"\n",
"for",
"_",
",",
"impName",
":=",
"range",
"h",
".",
"importers",
"{",
"imp",
":=",
"h",
".",
"imp",
"[",
"impName",
"]",
"\n",
"accts",
",",
"_",
":=",
"imp",
".",
"Accounts",
"(",
")",
"\n",
"for",
"_",
",",
"ia",
":=",
"range",
"accts",
"{",
"as",
":=",
"accountStatus",
"{",
"Type",
":",
"impName",
",",
"Href",
":",
"ia",
".",
"AccountURL",
"(",
")",
",",
"Name",
":",
"ia",
".",
"AccountLinkSummary",
"(",
")",
",",
"}",
"\n",
"ia",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"ia",
".",
"current",
"!=",
"nil",
"{",
"as",
".",
"StartedUnixSec",
"=",
"ia",
".",
"lastRunStart",
".",
"Unix",
"(",
")",
"\n",
"}",
"\n",
"if",
"!",
"ia",
".",
"lastRunDone",
".",
"IsZero",
"(",
")",
"{",
"as",
".",
"LastFinishedUnixSec",
"=",
"ia",
".",
"lastRunDone",
".",
"Unix",
"(",
")",
"\n",
"}",
"\n",
"if",
"ia",
".",
"lastRunErr",
"!=",
"nil",
"{",
"as",
".",
"LastError",
"=",
"ia",
".",
"lastRunErr",
".",
"Error",
"(",
")",
"\n",
"errs",
"=",
"append",
"(",
"errs",
",",
"camtypes",
".",
"StatusError",
"{",
"Error",
":",
"ia",
".",
"lastRunErr",
".",
"Error",
"(",
")",
",",
"URL",
":",
"ia",
".",
"AccountURL",
"(",
")",
",",
"}",
")",
"\n",
"}",
"\n",
"ia",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"s",
"=",
"append",
"(",
"s",
",",
"as",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"s",
",",
"errs",
"\n",
"}"
] |
// AccountsStatus returns the currently configured accounts and their status for
// inclusion in the status.json document, as rendered by the web UI.
|
[
"AccountsStatus",
"returns",
"the",
"currently",
"configured",
"accounts",
"and",
"their",
"status",
"for",
"inclusion",
"in",
"the",
"status",
".",
"json",
"document",
"as",
"rendered",
"by",
"the",
"web",
"UI",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/importer.go#L439-L471
|
train
|
perkeep/perkeep
|
pkg/importer/importer.go
|
RunImporterAccount
|
func (h *Host) RunImporterAccount(importerType string, accountNode blob.Ref) error {
h.didInit.Wait()
imp, ok := h.imp[importerType]
if !ok {
return fmt.Errorf("no %q importer for this account", importerType)
}
accounts, err := imp.Accounts()
if err != nil {
return err
}
for _, ia := range accounts {
if ia.acct.pn != accountNode {
continue
}
return ia.run()
}
return fmt.Errorf("no %v account matching account in node %v", importerType, accountNode)
}
|
go
|
func (h *Host) RunImporterAccount(importerType string, accountNode blob.Ref) error {
h.didInit.Wait()
imp, ok := h.imp[importerType]
if !ok {
return fmt.Errorf("no %q importer for this account", importerType)
}
accounts, err := imp.Accounts()
if err != nil {
return err
}
for _, ia := range accounts {
if ia.acct.pn != accountNode {
continue
}
return ia.run()
}
return fmt.Errorf("no %v account matching account in node %v", importerType, accountNode)
}
|
[
"func",
"(",
"h",
"*",
"Host",
")",
"RunImporterAccount",
"(",
"importerType",
"string",
",",
"accountNode",
"blob",
".",
"Ref",
")",
"error",
"{",
"h",
".",
"didInit",
".",
"Wait",
"(",
")",
"\n",
"imp",
",",
"ok",
":=",
"h",
".",
"imp",
"[",
"importerType",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"importerType",
")",
"\n",
"}",
"\n",
"accounts",
",",
"err",
":=",
"imp",
".",
"Accounts",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"for",
"_",
",",
"ia",
":=",
"range",
"accounts",
"{",
"if",
"ia",
".",
"acct",
".",
"pn",
"!=",
"accountNode",
"{",
"continue",
"\n",
"}",
"\n",
"return",
"ia",
".",
"run",
"(",
")",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"importerType",
",",
"accountNode",
")",
"\n",
"}"
] |
// RunImporterAccount runs the importerType importer on the account described in
// accountNode.
|
[
"RunImporterAccount",
"runs",
"the",
"importerType",
"importer",
"on",
"the",
"account",
"described",
"in",
"accountNode",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/importer.go#L475-L492
|
train
|
perkeep/perkeep
|
pkg/importer/importer.go
|
HTTPClient
|
func (h *Host) HTTPClient() *http.Client {
if h.client == nil {
return http.DefaultClient
}
return h.client
}
|
go
|
func (h *Host) HTTPClient() *http.Client {
if h.client == nil {
return http.DefaultClient
}
return h.client
}
|
[
"func",
"(",
"h",
"*",
"Host",
")",
"HTTPClient",
"(",
")",
"*",
"http",
".",
"Client",
"{",
"if",
"h",
".",
"client",
"==",
"nil",
"{",
"return",
"http",
".",
"DefaultClient",
"\n",
"}",
"\n",
"return",
"h",
".",
"client",
"\n",
"}"
] |
// HTTPClient returns the HTTP client to use.
|
[
"HTTPClient",
"returns",
"the",
"HTTP",
"client",
"to",
"use",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/importer.go#L1333-L1338
|
train
|
perkeep/perkeep
|
pkg/importer/importer.go
|
HTTPTransport
|
func (h *Host) HTTPTransport() http.RoundTripper {
if h.transport == nil {
return http.DefaultTransport
}
return h.transport
}
|
go
|
func (h *Host) HTTPTransport() http.RoundTripper {
if h.transport == nil {
return http.DefaultTransport
}
return h.transport
}
|
[
"func",
"(",
"h",
"*",
"Host",
")",
"HTTPTransport",
"(",
")",
"http",
".",
"RoundTripper",
"{",
"if",
"h",
".",
"transport",
"==",
"nil",
"{",
"return",
"http",
".",
"DefaultTransport",
"\n",
"}",
"\n",
"return",
"h",
".",
"transport",
"\n",
"}"
] |
// HTTPTransport returns the HTTP transport to use.
|
[
"HTTPTransport",
"returns",
"the",
"HTTP",
"transport",
"to",
"use",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/importer.go#L1341-L1346
|
train
|
perkeep/perkeep
|
pkg/importer/importer.go
|
NewObject
|
func (h *Host) NewObject() (*Object, error) {
ctx := context.TODO() // TODO: move the NewObject method to some "ImportRun" type with a context field?
pn, err := h.upload(ctx, schema.NewUnsignedPermanode())
if err != nil {
return nil, err
}
// No need to do a describe query against it: we know it's
// empty (has no claims against it yet).
return &Object{h: h, pn: pn}, nil
}
|
go
|
func (h *Host) NewObject() (*Object, error) {
ctx := context.TODO() // TODO: move the NewObject method to some "ImportRun" type with a context field?
pn, err := h.upload(ctx, schema.NewUnsignedPermanode())
if err != nil {
return nil, err
}
// No need to do a describe query against it: we know it's
// empty (has no claims against it yet).
return &Object{h: h, pn: pn}, nil
}
|
[
"func",
"(",
"h",
"*",
"Host",
")",
"NewObject",
"(",
")",
"(",
"*",
"Object",
",",
"error",
")",
"{",
"ctx",
":=",
"context",
".",
"TODO",
"(",
")",
"// TODO: move the NewObject method to some \"ImportRun\" type with a context field?",
"\n",
"pn",
",",
"err",
":=",
"h",
".",
"upload",
"(",
"ctx",
",",
"schema",
".",
"NewUnsignedPermanode",
"(",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"// No need to do a describe query against it: we know it's",
"// empty (has no claims against it yet).",
"return",
"&",
"Object",
"{",
"h",
":",
"h",
",",
"pn",
":",
"pn",
"}",
",",
"nil",
"\n",
"}"
] |
// NewObject creates a new permanode and returns its Object wrapper.
|
[
"NewObject",
"creates",
"a",
"new",
"permanode",
"and",
"returns",
"its",
"Object",
"wrapper",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/importer.go#L1366-L1375
|
train
|
perkeep/perkeep
|
pkg/importer/importer.go
|
Attr
|
func (o *Object) Attr(attr string) string {
o.mu.RLock()
defer o.mu.RUnlock()
if v := o.attr[attr]; len(v) > 0 {
return v[0]
}
return ""
}
|
go
|
func (o *Object) Attr(attr string) string {
o.mu.RLock()
defer o.mu.RUnlock()
if v := o.attr[attr]; len(v) > 0 {
return v[0]
}
return ""
}
|
[
"func",
"(",
"o",
"*",
"Object",
")",
"Attr",
"(",
"attr",
"string",
")",
"string",
"{",
"o",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"o",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"if",
"v",
":=",
"o",
".",
"attr",
"[",
"attr",
"]",
";",
"len",
"(",
"v",
")",
">",
"0",
"{",
"return",
"v",
"[",
"0",
"]",
"\n",
"}",
"\n",
"return",
"\"",
"\"",
"\n",
"}"
] |
// Attr returns the object's attribute value for the provided attr,
// or the empty string if unset. To distinguish between unset,
// an empty string, or multiple attribute values, use Attrs.
|
[
"Attr",
"returns",
"the",
"object",
"s",
"attribute",
"value",
"for",
"the",
"provided",
"attr",
"or",
"the",
"empty",
"string",
"if",
"unset",
".",
"To",
"distinguish",
"between",
"unset",
"an",
"empty",
"string",
"or",
"multiple",
"attribute",
"values",
"use",
"Attrs",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/importer.go#L1396-L1403
|
train
|
perkeep/perkeep
|
pkg/importer/importer.go
|
Attrs
|
func (o *Object) Attrs(attr string) []string {
o.mu.RLock()
defer o.mu.RUnlock()
return o.attr[attr]
}
|
go
|
func (o *Object) Attrs(attr string) []string {
o.mu.RLock()
defer o.mu.RUnlock()
return o.attr[attr]
}
|
[
"func",
"(",
"o",
"*",
"Object",
")",
"Attrs",
"(",
"attr",
"string",
")",
"[",
"]",
"string",
"{",
"o",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"o",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"o",
".",
"attr",
"[",
"attr",
"]",
"\n",
"}"
] |
// Attrs returns the attribute values for the provided attr.
|
[
"Attrs",
"returns",
"the",
"attribute",
"values",
"for",
"the",
"provided",
"attr",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/importer.go#L1406-L1410
|
train
|
perkeep/perkeep
|
pkg/importer/importer.go
|
ForeachAttr
|
func (o *Object) ForeachAttr(fn func(key, value string)) {
o.mu.RLock()
defer o.mu.RUnlock()
for k, vv := range o.attr {
for _, v := range vv {
fn(k, v)
}
}
}
|
go
|
func (o *Object) ForeachAttr(fn func(key, value string)) {
o.mu.RLock()
defer o.mu.RUnlock()
for k, vv := range o.attr {
for _, v := range vv {
fn(k, v)
}
}
}
|
[
"func",
"(",
"o",
"*",
"Object",
")",
"ForeachAttr",
"(",
"fn",
"func",
"(",
"key",
",",
"value",
"string",
")",
")",
"{",
"o",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"o",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"for",
"k",
",",
"vv",
":=",
"range",
"o",
".",
"attr",
"{",
"for",
"_",
",",
"v",
":=",
"range",
"vv",
"{",
"fn",
"(",
"k",
",",
"v",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// ForeachAttr runs fn for each of the object's attributes & values.
// There might be multiple values for the same attribute.
// The internal lock is held while running, so no mutations should be
// made or it will deadlock.
|
[
"ForeachAttr",
"runs",
"fn",
"for",
"each",
"of",
"the",
"object",
"s",
"attributes",
"&",
"values",
".",
"There",
"might",
"be",
"multiple",
"values",
"for",
"the",
"same",
"attribute",
".",
"The",
"internal",
"lock",
"is",
"held",
"while",
"running",
"so",
"no",
"mutations",
"should",
"be",
"made",
"or",
"it",
"will",
"deadlock",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/importer.go#L1416-L1424
|
train
|
perkeep/perkeep
|
pkg/importer/importer.go
|
DelAttr
|
func (o *Object) DelAttr(key, value string) error {
ctx := context.TODO()
o.mu.Lock()
defer o.mu.Unlock()
_, err := o.h.upload(ctx, schema.NewDelAttributeClaim(o.pn, key, value))
if err != nil {
return err
}
if o.attr == nil {
o.attr = make(map[string][]string)
return nil
}
if value == "" {
delete(o.attr, key)
return nil
}
var values []string
for _, v := range o.attr[key] {
if v != value {
values = append(values, v)
}
}
o.attr[key] = values
return nil
}
|
go
|
func (o *Object) DelAttr(key, value string) error {
ctx := context.TODO()
o.mu.Lock()
defer o.mu.Unlock()
_, err := o.h.upload(ctx, schema.NewDelAttributeClaim(o.pn, key, value))
if err != nil {
return err
}
if o.attr == nil {
o.attr = make(map[string][]string)
return nil
}
if value == "" {
delete(o.attr, key)
return nil
}
var values []string
for _, v := range o.attr[key] {
if v != value {
values = append(values, v)
}
}
o.attr[key] = values
return nil
}
|
[
"func",
"(",
"o",
"*",
"Object",
")",
"DelAttr",
"(",
"key",
",",
"value",
"string",
")",
"error",
"{",
"ctx",
":=",
"context",
".",
"TODO",
"(",
")",
"\n",
"o",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"o",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"_",
",",
"err",
":=",
"o",
".",
"h",
".",
"upload",
"(",
"ctx",
",",
"schema",
".",
"NewDelAttributeClaim",
"(",
"o",
".",
"pn",
",",
"key",
",",
"value",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"o",
".",
"attr",
"==",
"nil",
"{",
"o",
".",
"attr",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"if",
"value",
"==",
"\"",
"\"",
"{",
"delete",
"(",
"o",
".",
"attr",
",",
"key",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"var",
"values",
"[",
"]",
"string",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"o",
".",
"attr",
"[",
"key",
"]",
"{",
"if",
"v",
"!=",
"value",
"{",
"values",
"=",
"append",
"(",
"values",
",",
"v",
")",
"\n",
"}",
"\n",
"}",
"\n",
"o",
".",
"attr",
"[",
"key",
"]",
"=",
"values",
"\n",
"return",
"nil",
"\n",
"}"
] |
// DelAttr removes value from the values set for the attribute attr of
// permaNode. If value is empty then all the values for attribute are cleared.
|
[
"DelAttr",
"removes",
"value",
"from",
"the",
"values",
"set",
"for",
"the",
"attribute",
"attr",
"of",
"permaNode",
".",
"If",
"value",
"is",
"empty",
"then",
"all",
"the",
"values",
"for",
"attribute",
"are",
"cleared",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/importer.go#L1428-L1452
|
train
|
perkeep/perkeep
|
pkg/importer/importer.go
|
SetAttr
|
func (o *Object) SetAttr(key, value string) error {
ctx := context.TODO() // TODO: make it possible to get a context via Object; either new context field, or via some "ImportRun" field?
if o.Attr(key) == value {
return nil
}
_, err := o.h.upload(ctx, schema.NewSetAttributeClaim(o.pn, key, value))
if err != nil {
return err
}
o.mu.Lock()
defer o.mu.Unlock()
if o.attr == nil {
o.attr = make(map[string][]string)
}
o.attr[key] = []string{value}
return nil
}
|
go
|
func (o *Object) SetAttr(key, value string) error {
ctx := context.TODO() // TODO: make it possible to get a context via Object; either new context field, or via some "ImportRun" field?
if o.Attr(key) == value {
return nil
}
_, err := o.h.upload(ctx, schema.NewSetAttributeClaim(o.pn, key, value))
if err != nil {
return err
}
o.mu.Lock()
defer o.mu.Unlock()
if o.attr == nil {
o.attr = make(map[string][]string)
}
o.attr[key] = []string{value}
return nil
}
|
[
"func",
"(",
"o",
"*",
"Object",
")",
"SetAttr",
"(",
"key",
",",
"value",
"string",
")",
"error",
"{",
"ctx",
":=",
"context",
".",
"TODO",
"(",
")",
"// TODO: make it possible to get a context via Object; either new context field, or via some \"ImportRun\" field?",
"\n",
"if",
"o",
".",
"Attr",
"(",
"key",
")",
"==",
"value",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"o",
".",
"h",
".",
"upload",
"(",
"ctx",
",",
"schema",
".",
"NewSetAttributeClaim",
"(",
"o",
".",
"pn",
",",
"key",
",",
"value",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"o",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"o",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"if",
"o",
".",
"attr",
"==",
"nil",
"{",
"o",
".",
"attr",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
")",
"\n",
"}",
"\n",
"o",
".",
"attr",
"[",
"key",
"]",
"=",
"[",
"]",
"string",
"{",
"value",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// SetAttr sets the attribute key to value.
|
[
"SetAttr",
"sets",
"the",
"attribute",
"key",
"to",
"value",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/importer.go#L1455-L1471
|
train
|
perkeep/perkeep
|
pkg/importer/importer.go
|
SetAttrValues
|
func (o *Object) SetAttrValues(key string, attrs []string) error {
ctx := context.TODO() // TODO: make it possible to get a context via Object; either new context field, or via some "ImportRun" field?
exists := asSet(o.Attrs(key))
actual := asSet(attrs)
o.mu.Lock()
defer o.mu.Unlock()
// add new values
for v := range actual {
if exists[v] {
delete(exists, v)
continue
}
_, err := o.h.upload(ctx, schema.NewAddAttributeClaim(o.pn, key, v))
if err != nil {
return err
}
}
// delete unneeded values
for v := range exists {
_, err := o.h.upload(ctx, schema.NewDelAttributeClaim(o.pn, key, v))
if err != nil {
return err
}
}
if o.attr == nil {
o.attr = make(map[string][]string)
}
o.attr[key] = attrs
return nil
}
|
go
|
func (o *Object) SetAttrValues(key string, attrs []string) error {
ctx := context.TODO() // TODO: make it possible to get a context via Object; either new context field, or via some "ImportRun" field?
exists := asSet(o.Attrs(key))
actual := asSet(attrs)
o.mu.Lock()
defer o.mu.Unlock()
// add new values
for v := range actual {
if exists[v] {
delete(exists, v)
continue
}
_, err := o.h.upload(ctx, schema.NewAddAttributeClaim(o.pn, key, v))
if err != nil {
return err
}
}
// delete unneeded values
for v := range exists {
_, err := o.h.upload(ctx, schema.NewDelAttributeClaim(o.pn, key, v))
if err != nil {
return err
}
}
if o.attr == nil {
o.attr = make(map[string][]string)
}
o.attr[key] = attrs
return nil
}
|
[
"func",
"(",
"o",
"*",
"Object",
")",
"SetAttrValues",
"(",
"key",
"string",
",",
"attrs",
"[",
"]",
"string",
")",
"error",
"{",
"ctx",
":=",
"context",
".",
"TODO",
"(",
")",
"// TODO: make it possible to get a context via Object; either new context field, or via some \"ImportRun\" field?",
"\n\n",
"exists",
":=",
"asSet",
"(",
"o",
".",
"Attrs",
"(",
"key",
")",
")",
"\n",
"actual",
":=",
"asSet",
"(",
"attrs",
")",
"\n",
"o",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"o",
".",
"mu",
".",
"Unlock",
"(",
")",
"\n",
"// add new values",
"for",
"v",
":=",
"range",
"actual",
"{",
"if",
"exists",
"[",
"v",
"]",
"{",
"delete",
"(",
"exists",
",",
"v",
")",
"\n",
"continue",
"\n",
"}",
"\n",
"_",
",",
"err",
":=",
"o",
".",
"h",
".",
"upload",
"(",
"ctx",
",",
"schema",
".",
"NewAddAttributeClaim",
"(",
"o",
".",
"pn",
",",
"key",
",",
"v",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"// delete unneeded values",
"for",
"v",
":=",
"range",
"exists",
"{",
"_",
",",
"err",
":=",
"o",
".",
"h",
".",
"upload",
"(",
"ctx",
",",
"schema",
".",
"NewDelAttributeClaim",
"(",
"o",
".",
"pn",
",",
"key",
",",
"v",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"o",
".",
"attr",
"==",
"nil",
"{",
"o",
".",
"attr",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
")",
"\n",
"}",
"\n",
"o",
".",
"attr",
"[",
"key",
"]",
"=",
"attrs",
"\n",
"return",
"nil",
"\n",
"}"
] |
// SetAttrValues sets multi-valued attribute.
|
[
"SetAttrValues",
"sets",
"multi",
"-",
"valued",
"attribute",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/importer.go#L1502-L1532
|
train
|
perkeep/perkeep
|
pkg/importer/importer.go
|
ObjectFromRef
|
func (h *Host) ObjectFromRef(permanodeRef blob.Ref) (*Object, error) {
ctx := context.TODO()
res, err := h.search.Describe(ctx, &search.DescribeRequest{
BlobRef: permanodeRef,
Depth: 1,
})
if err != nil {
return nil, err
}
db, ok := res.Meta[permanodeRef.String()]
if !ok {
return nil, fmt.Errorf("permanode %v wasn't in Describe response", permanodeRef)
}
if db.Permanode == nil {
return nil, fmt.Errorf("permanode %v had no DescribedPermanode in Describe response", permanodeRef)
}
return &Object{
h: h,
pn: permanodeRef,
attr: map[string][]string(db.Permanode.Attr),
modtime: db.Permanode.ModTime,
}, nil
}
|
go
|
func (h *Host) ObjectFromRef(permanodeRef blob.Ref) (*Object, error) {
ctx := context.TODO()
res, err := h.search.Describe(ctx, &search.DescribeRequest{
BlobRef: permanodeRef,
Depth: 1,
})
if err != nil {
return nil, err
}
db, ok := res.Meta[permanodeRef.String()]
if !ok {
return nil, fmt.Errorf("permanode %v wasn't in Describe response", permanodeRef)
}
if db.Permanode == nil {
return nil, fmt.Errorf("permanode %v had no DescribedPermanode in Describe response", permanodeRef)
}
return &Object{
h: h,
pn: permanodeRef,
attr: map[string][]string(db.Permanode.Attr),
modtime: db.Permanode.ModTime,
}, nil
}
|
[
"func",
"(",
"h",
"*",
"Host",
")",
"ObjectFromRef",
"(",
"permanodeRef",
"blob",
".",
"Ref",
")",
"(",
"*",
"Object",
",",
"error",
")",
"{",
"ctx",
":=",
"context",
".",
"TODO",
"(",
")",
"\n",
"res",
",",
"err",
":=",
"h",
".",
"search",
".",
"Describe",
"(",
"ctx",
",",
"&",
"search",
".",
"DescribeRequest",
"{",
"BlobRef",
":",
"permanodeRef",
",",
"Depth",
":",
"1",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"db",
",",
"ok",
":=",
"res",
".",
"Meta",
"[",
"permanodeRef",
".",
"String",
"(",
")",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"permanodeRef",
")",
"\n",
"}",
"\n",
"if",
"db",
".",
"Permanode",
"==",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"permanodeRef",
")",
"\n",
"}",
"\n",
"return",
"&",
"Object",
"{",
"h",
":",
"h",
",",
"pn",
":",
"permanodeRef",
",",
"attr",
":",
"map",
"[",
"string",
"]",
"[",
"]",
"string",
"(",
"db",
".",
"Permanode",
".",
"Attr",
")",
",",
"modtime",
":",
"db",
".",
"Permanode",
".",
"ModTime",
",",
"}",
",",
"nil",
"\n",
"}"
] |
// ObjectFromRef returns the object given by the named permanode
|
[
"ObjectFromRef",
"returns",
"the",
"object",
"given",
"by",
"the",
"named",
"permanode"
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/importer.go#L1577-L1599
|
train
|
perkeep/perkeep
|
pkg/blobserver/memory/mem.go
|
NewCache
|
func NewCache(size int64) *Storage {
return &Storage{
maxSize: size,
lru: lru.New(0), // infinite items; we evict by size, not count
}
}
|
go
|
func NewCache(size int64) *Storage {
return &Storage{
maxSize: size,
lru: lru.New(0), // infinite items; we evict by size, not count
}
}
|
[
"func",
"NewCache",
"(",
"size",
"int64",
")",
"*",
"Storage",
"{",
"return",
"&",
"Storage",
"{",
"maxSize",
":",
"size",
",",
"lru",
":",
"lru",
".",
"New",
"(",
"0",
")",
",",
"// infinite items; we evict by size, not count",
"}",
"\n",
"}"
] |
// NewCache returns a cache that won't store more than size bytes.
// Blobs are evicted in LRU order.
|
[
"NewCache",
"returns",
"a",
"cache",
"that",
"won",
"t",
"store",
"more",
"than",
"size",
"bytes",
".",
"Blobs",
"are",
"evicted",
"in",
"LRU",
"order",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/memory/mem.go#L75-L80
|
train
|
perkeep/perkeep
|
pkg/blobserver/memory/mem.go
|
NumBlobs
|
func (s *Storage) NumBlobs() int {
s.mu.RLock()
defer s.mu.RUnlock()
return len(s.m)
}
|
go
|
func (s *Storage) NumBlobs() int {
s.mu.RLock()
defer s.mu.RUnlock()
return len(s.m)
}
|
[
"func",
"(",
"s",
"*",
"Storage",
")",
"NumBlobs",
"(",
")",
"int",
"{",
"s",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"len",
"(",
"s",
".",
"m",
")",
"\n",
"}"
] |
// NumBlobs returns the number of blobs stored in s.
|
[
"NumBlobs",
"returns",
"the",
"number",
"of",
"blobs",
"stored",
"in",
"s",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/memory/mem.go#L287-L291
|
train
|
perkeep/perkeep
|
pkg/blobserver/memory/mem.go
|
SumBlobSize
|
func (s *Storage) SumBlobSize() int64 {
s.mu.RLock()
defer s.mu.RUnlock()
return s.size
}
|
go
|
func (s *Storage) SumBlobSize() int64 {
s.mu.RLock()
defer s.mu.RUnlock()
return s.size
}
|
[
"func",
"(",
"s",
"*",
"Storage",
")",
"SumBlobSize",
"(",
")",
"int64",
"{",
"s",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"return",
"s",
".",
"size",
"\n",
"}"
] |
// SumBlobSize returns the total size in bytes of all the blobs in s.
|
[
"SumBlobSize",
"returns",
"the",
"total",
"size",
"in",
"bytes",
"of",
"all",
"the",
"blobs",
"in",
"s",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/memory/mem.go#L294-L298
|
train
|
perkeep/perkeep
|
pkg/blobserver/memory/mem.go
|
BlobrefStrings
|
func (s *Storage) BlobrefStrings() []string {
s.mu.RLock()
defer s.mu.RUnlock()
sorted := make([]string, 0, len(s.m))
for br := range s.m {
sorted = append(sorted, br.String())
}
sort.Strings(sorted)
return sorted
}
|
go
|
func (s *Storage) BlobrefStrings() []string {
s.mu.RLock()
defer s.mu.RUnlock()
sorted := make([]string, 0, len(s.m))
for br := range s.m {
sorted = append(sorted, br.String())
}
sort.Strings(sorted)
return sorted
}
|
[
"func",
"(",
"s",
"*",
"Storage",
")",
"BlobrefStrings",
"(",
")",
"[",
"]",
"string",
"{",
"s",
".",
"mu",
".",
"RLock",
"(",
")",
"\n",
"defer",
"s",
".",
"mu",
".",
"RUnlock",
"(",
")",
"\n",
"sorted",
":=",
"make",
"(",
"[",
"]",
"string",
",",
"0",
",",
"len",
"(",
"s",
".",
"m",
")",
")",
"\n",
"for",
"br",
":=",
"range",
"s",
".",
"m",
"{",
"sorted",
"=",
"append",
"(",
"sorted",
",",
"br",
".",
"String",
"(",
")",
")",
"\n",
"}",
"\n",
"sort",
".",
"Strings",
"(",
"sorted",
")",
"\n",
"return",
"sorted",
"\n",
"}"
] |
// BlobrefStrings returns the sorted stringified blobrefs stored in s.
|
[
"BlobrefStrings",
"returns",
"the",
"sorted",
"stringified",
"blobrefs",
"stored",
"in",
"s",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/memory/mem.go#L301-L310
|
train
|
perkeep/perkeep
|
pkg/blobserver/memory/mem.go
|
Stats
|
func (s *Storage) Stats() (blobsFetched, bytesFetched int64) {
return atomic.LoadInt64(&s.blobsFetched), atomic.LoadInt64(&s.bytesFetched)
}
|
go
|
func (s *Storage) Stats() (blobsFetched, bytesFetched int64) {
return atomic.LoadInt64(&s.blobsFetched), atomic.LoadInt64(&s.bytesFetched)
}
|
[
"func",
"(",
"s",
"*",
"Storage",
")",
"Stats",
"(",
")",
"(",
"blobsFetched",
",",
"bytesFetched",
"int64",
")",
"{",
"return",
"atomic",
".",
"LoadInt64",
"(",
"&",
"s",
".",
"blobsFetched",
")",
",",
"atomic",
".",
"LoadInt64",
"(",
"&",
"s",
".",
"bytesFetched",
")",
"\n",
"}"
] |
// Stats returns the number of blobs and number of bytes that were fetched from s.
|
[
"Stats",
"returns",
"the",
"number",
"of",
"blobs",
"and",
"number",
"of",
"bytes",
"that",
"were",
"fetched",
"from",
"s",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/memory/mem.go#L313-L315
|
train
|
perkeep/perkeep
|
internal/netutil/ident.go
|
ConnUserid
|
func ConnUserid(conn net.Conn) (uid int, err error) {
return AddrPairUserid(conn.LocalAddr(), conn.RemoteAddr())
}
|
go
|
func ConnUserid(conn net.Conn) (uid int, err error) {
return AddrPairUserid(conn.LocalAddr(), conn.RemoteAddr())
}
|
[
"func",
"ConnUserid",
"(",
"conn",
"net",
".",
"Conn",
")",
"(",
"uid",
"int",
",",
"err",
"error",
")",
"{",
"return",
"AddrPairUserid",
"(",
"conn",
".",
"LocalAddr",
"(",
")",
",",
"conn",
".",
"RemoteAddr",
"(",
")",
")",
"\n",
"}"
] |
// ConnUserid returns the uid that owns the given localhost connection.
// The returned error is ErrNotFound if the connection wasn't found.
|
[
"ConnUserid",
"returns",
"the",
"uid",
"that",
"owns",
"the",
"given",
"localhost",
"connection",
".",
"The",
"returned",
"error",
"is",
"ErrNotFound",
"if",
"the",
"connection",
"wasn",
"t",
"found",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/netutil/ident.go#L44-L46
|
train
|
perkeep/perkeep
|
website/pk-web/godoc.go
|
writeNode
|
func writeNode(w io.Writer, fset *token.FileSet, x interface{}) {
// convert trailing tabs into spaces using a tconv filter
// to ensure a good outcome in most browsers (there may still
// be tabs in comments and strings, but converting those into
// the right number of spaces is much harder)
//
// TODO(gri) rethink printer flags - perhaps tconv can be eliminated
// with an another printer mode (which is more efficiently
// implemented in the printer than here with another layer)
mode := printer.TabIndent | printer.UseSpaces
err := (&printer.Config{Mode: mode, Tabwidth: tabwidth}).Fprint(&tconv{output: w}, fset, x)
if err != nil {
log.Print(err)
}
}
|
go
|
func writeNode(w io.Writer, fset *token.FileSet, x interface{}) {
// convert trailing tabs into spaces using a tconv filter
// to ensure a good outcome in most browsers (there may still
// be tabs in comments and strings, but converting those into
// the right number of spaces is much harder)
//
// TODO(gri) rethink printer flags - perhaps tconv can be eliminated
// with an another printer mode (which is more efficiently
// implemented in the printer than here with another layer)
mode := printer.TabIndent | printer.UseSpaces
err := (&printer.Config{Mode: mode, Tabwidth: tabwidth}).Fprint(&tconv{output: w}, fset, x)
if err != nil {
log.Print(err)
}
}
|
[
"func",
"writeNode",
"(",
"w",
"io",
".",
"Writer",
",",
"fset",
"*",
"token",
".",
"FileSet",
",",
"x",
"interface",
"{",
"}",
")",
"{",
"// convert trailing tabs into spaces using a tconv filter",
"// to ensure a good outcome in most browsers (there may still",
"// be tabs in comments and strings, but converting those into",
"// the right number of spaces is much harder)",
"//",
"// TODO(gri) rethink printer flags - perhaps tconv can be eliminated",
"// with an another printer mode (which is more efficiently",
"// implemented in the printer than here with another layer)",
"mode",
":=",
"printer",
".",
"TabIndent",
"|",
"printer",
".",
"UseSpaces",
"\n",
"err",
":=",
"(",
"&",
"printer",
".",
"Config",
"{",
"Mode",
":",
"mode",
",",
"Tabwidth",
":",
"tabwidth",
"}",
")",
".",
"Fprint",
"(",
"&",
"tconv",
"{",
"output",
":",
"w",
"}",
",",
"fset",
",",
"x",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Print",
"(",
"err",
")",
"\n",
"}",
"\n",
"}"
] |
// Write an AST node to w.
|
[
"Write",
"an",
"AST",
"node",
"to",
"w",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/website/pk-web/godoc.go#L138-L152
|
train
|
perkeep/perkeep
|
server/perkeepd/ui/goui/selectallbutton/selectall.go
|
getQuery
|
func (d SelectAllBtnDef) getQuery() *search.SearchQuery {
predicate := d.Props().callbacks.GetQuery()
if !strings.HasPrefix(predicate, "ref:") {
return &search.SearchQuery{
Limit: -1,
Expression: predicate,
}
}
// If we've got a ref: predicate, assume the given blobRef is a container, and
// find its children.
blobRef := strings.TrimPrefix(predicate, "ref:")
br, ok := blob.Parse(blobRef)
if !ok {
println(`Invalid blobRef in "ref:" predicate: ` + blobRef)
return nil
}
return &search.SearchQuery{
Limit: -1,
Constraint: &search.Constraint{Permanode: &search.PermanodeConstraint{
Relation: &search.RelationConstraint{
Relation: "parent",
Any: &search.Constraint{
BlobRefPrefix: br.String(),
},
},
}},
}
}
|
go
|
func (d SelectAllBtnDef) getQuery() *search.SearchQuery {
predicate := d.Props().callbacks.GetQuery()
if !strings.HasPrefix(predicate, "ref:") {
return &search.SearchQuery{
Limit: -1,
Expression: predicate,
}
}
// If we've got a ref: predicate, assume the given blobRef is a container, and
// find its children.
blobRef := strings.TrimPrefix(predicate, "ref:")
br, ok := blob.Parse(blobRef)
if !ok {
println(`Invalid blobRef in "ref:" predicate: ` + blobRef)
return nil
}
return &search.SearchQuery{
Limit: -1,
Constraint: &search.Constraint{Permanode: &search.PermanodeConstraint{
Relation: &search.RelationConstraint{
Relation: "parent",
Any: &search.Constraint{
BlobRefPrefix: br.String(),
},
},
}},
}
}
|
[
"func",
"(",
"d",
"SelectAllBtnDef",
")",
"getQuery",
"(",
")",
"*",
"search",
".",
"SearchQuery",
"{",
"predicate",
":=",
"d",
".",
"Props",
"(",
")",
".",
"callbacks",
".",
"GetQuery",
"(",
")",
"\n",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"predicate",
",",
"\"",
"\"",
")",
"{",
"return",
"&",
"search",
".",
"SearchQuery",
"{",
"Limit",
":",
"-",
"1",
",",
"Expression",
":",
"predicate",
",",
"}",
"\n",
"}",
"\n\n",
"// If we've got a ref: predicate, assume the given blobRef is a container, and",
"// find its children.",
"blobRef",
":=",
"strings",
".",
"TrimPrefix",
"(",
"predicate",
",",
"\"",
"\"",
")",
"\n",
"br",
",",
"ok",
":=",
"blob",
".",
"Parse",
"(",
"blobRef",
")",
"\n",
"if",
"!",
"ok",
"{",
"println",
"(",
"`Invalid blobRef in \"ref:\" predicate: `",
"+",
"blobRef",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"&",
"search",
".",
"SearchQuery",
"{",
"Limit",
":",
"-",
"1",
",",
"Constraint",
":",
"&",
"search",
".",
"Constraint",
"{",
"Permanode",
":",
"&",
"search",
".",
"PermanodeConstraint",
"{",
"Relation",
":",
"&",
"search",
".",
"RelationConstraint",
"{",
"Relation",
":",
"\"",
"\"",
",",
"Any",
":",
"&",
"search",
".",
"Constraint",
"{",
"BlobRefPrefix",
":",
"br",
".",
"String",
"(",
")",
",",
"}",
",",
"}",
",",
"}",
"}",
",",
"}",
"\n",
"}"
] |
// getQuery returns the query corresponding to the current search in the web UI.
|
[
"getQuery",
"returns",
"the",
"query",
"corresponding",
"to",
"the",
"current",
"search",
"in",
"the",
"web",
"UI",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/server/perkeepd/ui/goui/selectallbutton/selectall.go#L145-L173
|
train
|
perkeep/perkeep
|
server/perkeepd/ui/goui/selectallbutton/selectall.go
|
findAll
|
func (d SelectAllBtnDef) findAll() (map[string]bool, error) {
query := d.getQuery()
if query == nil {
return nil, nil
}
authToken := d.Props().authToken
am, err := auth.TokenOrNone(authToken)
if err != nil {
return nil, fmt.Errorf("Error setting up auth: %v", err)
}
cl, err := client.New(client.OptionAuthMode(am))
if err != nil {
return nil, err
}
res, err := cl.Query(context.TODO(), query)
if err != nil {
return nil, err
}
blobs := make(map[string]bool, len(res.Blobs))
for _, v := range res.Blobs {
blobs[v.Blob.String()] = true
}
return blobs, nil
}
|
go
|
func (d SelectAllBtnDef) findAll() (map[string]bool, error) {
query := d.getQuery()
if query == nil {
return nil, nil
}
authToken := d.Props().authToken
am, err := auth.TokenOrNone(authToken)
if err != nil {
return nil, fmt.Errorf("Error setting up auth: %v", err)
}
cl, err := client.New(client.OptionAuthMode(am))
if err != nil {
return nil, err
}
res, err := cl.Query(context.TODO(), query)
if err != nil {
return nil, err
}
blobs := make(map[string]bool, len(res.Blobs))
for _, v := range res.Blobs {
blobs[v.Blob.String()] = true
}
return blobs, nil
}
|
[
"func",
"(",
"d",
"SelectAllBtnDef",
")",
"findAll",
"(",
")",
"(",
"map",
"[",
"string",
"]",
"bool",
",",
"error",
")",
"{",
"query",
":=",
"d",
".",
"getQuery",
"(",
")",
"\n",
"if",
"query",
"==",
"nil",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"authToken",
":=",
"d",
".",
"Props",
"(",
")",
".",
"authToken",
"\n",
"am",
",",
"err",
":=",
"auth",
".",
"TokenOrNone",
"(",
"authToken",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"cl",
",",
"err",
":=",
"client",
".",
"New",
"(",
"client",
".",
"OptionAuthMode",
"(",
"am",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"res",
",",
"err",
":=",
"cl",
".",
"Query",
"(",
"context",
".",
"TODO",
"(",
")",
",",
"query",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"blobs",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"bool",
",",
"len",
"(",
"res",
".",
"Blobs",
")",
")",
"\n",
"for",
"_",
",",
"v",
":=",
"range",
"res",
".",
"Blobs",
"{",
"blobs",
"[",
"v",
".",
"Blob",
".",
"String",
"(",
")",
"]",
"=",
"true",
"\n",
"}",
"\n",
"return",
"blobs",
",",
"nil",
"\n",
"}"
] |
// findAll returns all the permanodes matching the current web UI search
// session. The javascript UI code uses a javascript object with blobRefs as
// properties to represent a user's selection of permanodes. Since gopherjs
// converts a Go map to a javascript object, findAll returns such a map so it
// matches directly what the UI code wants as a selection object.
|
[
"findAll",
"returns",
"all",
"the",
"permanodes",
"matching",
"the",
"current",
"web",
"UI",
"search",
"session",
".",
"The",
"javascript",
"UI",
"code",
"uses",
"a",
"javascript",
"object",
"with",
"blobRefs",
"as",
"properties",
"to",
"represent",
"a",
"user",
"s",
"selection",
"of",
"permanodes",
".",
"Since",
"gopherjs",
"converts",
"a",
"Go",
"map",
"to",
"a",
"javascript",
"object",
"findAll",
"returns",
"such",
"a",
"map",
"so",
"it",
"matches",
"directly",
"what",
"the",
"UI",
"code",
"wants",
"as",
"a",
"selection",
"object",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/server/perkeepd/ui/goui/selectallbutton/selectall.go#L180-L203
|
train
|
perkeep/perkeep
|
pkg/app/app.go
|
Client
|
func Client() (*client.Client, error) {
server := os.Getenv("CAMLI_API_HOST")
if server == "" {
return nil, errors.New("CAMLI_API_HOST var not set")
}
am, err := basicAuth()
if err != nil {
return nil, err
}
return client.New(
client.OptionNoExternalConfig(),
client.OptionServer(server),
client.OptionAuthMode(am),
)
}
|
go
|
func Client() (*client.Client, error) {
server := os.Getenv("CAMLI_API_HOST")
if server == "" {
return nil, errors.New("CAMLI_API_HOST var not set")
}
am, err := basicAuth()
if err != nil {
return nil, err
}
return client.New(
client.OptionNoExternalConfig(),
client.OptionServer(server),
client.OptionAuthMode(am),
)
}
|
[
"func",
"Client",
"(",
")",
"(",
"*",
"client",
".",
"Client",
",",
"error",
")",
"{",
"server",
":=",
"os",
".",
"Getenv",
"(",
"\"",
"\"",
")",
"\n",
"if",
"server",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"am",
",",
"err",
":=",
"basicAuth",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"client",
".",
"New",
"(",
"client",
".",
"OptionNoExternalConfig",
"(",
")",
",",
"client",
".",
"OptionServer",
"(",
"server",
")",
",",
"client",
".",
"OptionAuthMode",
"(",
"am",
")",
",",
")",
"\n",
"}"
] |
// Client returns a Perkeep client as defined by environment variables
// automatically supplied by the Perkeep server host.
|
[
"Client",
"returns",
"a",
"Perkeep",
"client",
"as",
"defined",
"by",
"environment",
"variables",
"automatically",
"supplied",
"by",
"the",
"Perkeep",
"server",
"host",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/app/app.go#L55-L69
|
train
|
perkeep/perkeep
|
cmd/pk/sync.go
|
storageFromParam
|
func (c *syncCmd) storageFromParam(which storageType, val string) (blobserver.Storage, error) {
var httpClient *http.Client
if val == "" {
switch which {
case storageThird:
return nil, nil
case storageSource:
discl := c.discoClient()
src, err := discl.BlobRoot()
if err != nil {
return nil, fmt.Errorf("Failed to discover source server's blob path: %v", err)
}
val = src
httpClient = discl.HTTPClient()
}
if val == "" {
return nil, cmdmain.UsageError("No --" + string(which) + " flag value specified")
}
}
if which == storageDest && val == "stdout" {
return nil, nil
}
if looksLikePath(val) {
disk, err := localdisk.New(val)
if err != nil {
return nil, fmt.Errorf("Interpreted --%v=%q as a local disk path, but got error: %v", which, val, err)
}
c.oneIsDisk = true
return disk, nil
}
cl, err := client.New(client.OptionServer(val), client.OptionInsecure(c.insecureTLS))
if err != nil {
return nil, fmt.Errorf("creating client for %q: %v", val, err)
}
if httpClient != nil {
cl.SetHTTPClient(httpClient)
}
if err := cl.SetupAuth(); err != nil {
return nil, fmt.Errorf("could not setup auth for connecting to %v: %v", val, err)
}
cl.Verbose = *cmdmain.FlagVerbose
cl.Logger = log.New(cmdmain.Stderr, "", log.LstdFlags)
serverKeyID, err := cl.ServerKeyID()
if err != nil && err != client.ErrNoSigning {
fmt.Fprintf(cmdmain.Stderr, "Failed to discover keyId for server %v: %v", val, err)
} else {
if which == storageSource {
c.srcKeyID = serverKeyID
} else if which == storageDest {
c.destKeyID = serverKeyID
}
}
return cl, nil
}
|
go
|
func (c *syncCmd) storageFromParam(which storageType, val string) (blobserver.Storage, error) {
var httpClient *http.Client
if val == "" {
switch which {
case storageThird:
return nil, nil
case storageSource:
discl := c.discoClient()
src, err := discl.BlobRoot()
if err != nil {
return nil, fmt.Errorf("Failed to discover source server's blob path: %v", err)
}
val = src
httpClient = discl.HTTPClient()
}
if val == "" {
return nil, cmdmain.UsageError("No --" + string(which) + " flag value specified")
}
}
if which == storageDest && val == "stdout" {
return nil, nil
}
if looksLikePath(val) {
disk, err := localdisk.New(val)
if err != nil {
return nil, fmt.Errorf("Interpreted --%v=%q as a local disk path, but got error: %v", which, val, err)
}
c.oneIsDisk = true
return disk, nil
}
cl, err := client.New(client.OptionServer(val), client.OptionInsecure(c.insecureTLS))
if err != nil {
return nil, fmt.Errorf("creating client for %q: %v", val, err)
}
if httpClient != nil {
cl.SetHTTPClient(httpClient)
}
if err := cl.SetupAuth(); err != nil {
return nil, fmt.Errorf("could not setup auth for connecting to %v: %v", val, err)
}
cl.Verbose = *cmdmain.FlagVerbose
cl.Logger = log.New(cmdmain.Stderr, "", log.LstdFlags)
serverKeyID, err := cl.ServerKeyID()
if err != nil && err != client.ErrNoSigning {
fmt.Fprintf(cmdmain.Stderr, "Failed to discover keyId for server %v: %v", val, err)
} else {
if which == storageSource {
c.srcKeyID = serverKeyID
} else if which == storageDest {
c.destKeyID = serverKeyID
}
}
return cl, nil
}
|
[
"func",
"(",
"c",
"*",
"syncCmd",
")",
"storageFromParam",
"(",
"which",
"storageType",
",",
"val",
"string",
")",
"(",
"blobserver",
".",
"Storage",
",",
"error",
")",
"{",
"var",
"httpClient",
"*",
"http",
".",
"Client",
"\n\n",
"if",
"val",
"==",
"\"",
"\"",
"{",
"switch",
"which",
"{",
"case",
"storageThird",
":",
"return",
"nil",
",",
"nil",
"\n",
"case",
"storageSource",
":",
"discl",
":=",
"c",
".",
"discoClient",
"(",
")",
"\n",
"src",
",",
"err",
":=",
"discl",
".",
"BlobRoot",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"val",
"=",
"src",
"\n",
"httpClient",
"=",
"discl",
".",
"HTTPClient",
"(",
")",
"\n",
"}",
"\n",
"if",
"val",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"cmdmain",
".",
"UsageError",
"(",
"\"",
"\"",
"+",
"string",
"(",
"which",
")",
"+",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"which",
"==",
"storageDest",
"&&",
"val",
"==",
"\"",
"\"",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"if",
"looksLikePath",
"(",
"val",
")",
"{",
"disk",
",",
"err",
":=",
"localdisk",
".",
"New",
"(",
"val",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"which",
",",
"val",
",",
"err",
")",
"\n",
"}",
"\n",
"c",
".",
"oneIsDisk",
"=",
"true",
"\n",
"return",
"disk",
",",
"nil",
"\n",
"}",
"\n",
"cl",
",",
"err",
":=",
"client",
".",
"New",
"(",
"client",
".",
"OptionServer",
"(",
"val",
")",
",",
"client",
".",
"OptionInsecure",
"(",
"c",
".",
"insecureTLS",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"val",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"httpClient",
"!=",
"nil",
"{",
"cl",
".",
"SetHTTPClient",
"(",
"httpClient",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"cl",
".",
"SetupAuth",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"val",
",",
"err",
")",
"\n",
"}",
"\n",
"cl",
".",
"Verbose",
"=",
"*",
"cmdmain",
".",
"FlagVerbose",
"\n",
"cl",
".",
"Logger",
"=",
"log",
".",
"New",
"(",
"cmdmain",
".",
"Stderr",
",",
"\"",
"\"",
",",
"log",
".",
"LstdFlags",
")",
"\n",
"serverKeyID",
",",
"err",
":=",
"cl",
".",
"ServerKeyID",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"&&",
"err",
"!=",
"client",
".",
"ErrNoSigning",
"{",
"fmt",
".",
"Fprintf",
"(",
"cmdmain",
".",
"Stderr",
",",
"\"",
"\"",
",",
"val",
",",
"err",
")",
"\n",
"}",
"else",
"{",
"if",
"which",
"==",
"storageSource",
"{",
"c",
".",
"srcKeyID",
"=",
"serverKeyID",
"\n",
"}",
"else",
"if",
"which",
"==",
"storageDest",
"{",
"c",
".",
"destKeyID",
"=",
"serverKeyID",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"cl",
",",
"nil",
"\n",
"}"
] |
// which is one of "src", "dest", or "thirdleg"
|
[
"which",
"is",
"one",
"of",
"src",
"dest",
"or",
"thirdleg"
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/cmd/pk/sync.go#L160-L214
|
train
|
perkeep/perkeep
|
pkg/client/remove.go
|
RemoveBlobs
|
func (c *Client) RemoveBlobs(ctx context.Context, blobs []blob.Ref) error {
if c.sto != nil {
return c.sto.RemoveBlobs(ctx, blobs)
}
pfx, err := c.prefix()
if err != nil {
return err
}
url_ := fmt.Sprintf("%s/camli/remove", pfx)
params := make(url.Values) // "blobN" -> BlobRefStr
needsDelete := make(map[blob.Ref]bool) // BlobRefStr -> true
for n, b := range blobs {
if !b.Valid() {
return errors.New("Cannot delete invalid blobref")
}
key := fmt.Sprintf("blob%v", n+1)
params.Add(key, b.String())
needsDelete[b] = true
}
req, err := http.NewRequest("POST", url_, strings.NewReader(params.Encode()))
if err != nil {
return fmt.Errorf("Error creating RemoveBlobs POST request: %v", err)
}
req = req.WithContext(ctx)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
c.authMode.AddAuthHeader(req)
resp, err := c.httpClient.Do(req)
if err != nil {
resp.Body.Close()
return fmt.Errorf("Got status code %d from blobserver for remove %s", resp.StatusCode, params.Encode())
}
var remResp handlers.RemoveResponse
decodeErr := httputil.DecodeJSON(resp, &remResp)
if resp.StatusCode != 200 {
resp.Body.Close()
if decodeErr == nil {
return fmt.Errorf("invalid http response %d in remove response: %v", resp.StatusCode, remResp.Error)
} else {
return fmt.Errorf("invalid http response %d in remove response", resp.StatusCode)
}
}
if decodeErr != nil {
return fmt.Errorf("failed to parse remove response: %v", err)
}
for _, br := range remResp.Removed {
delete(needsDelete, br)
}
if len(needsDelete) > 0 {
return fmt.Errorf("failed to remove blobs %s", strings.Join(stringKeys(needsDelete), ", "))
}
return nil
}
|
go
|
func (c *Client) RemoveBlobs(ctx context.Context, blobs []blob.Ref) error {
if c.sto != nil {
return c.sto.RemoveBlobs(ctx, blobs)
}
pfx, err := c.prefix()
if err != nil {
return err
}
url_ := fmt.Sprintf("%s/camli/remove", pfx)
params := make(url.Values) // "blobN" -> BlobRefStr
needsDelete := make(map[blob.Ref]bool) // BlobRefStr -> true
for n, b := range blobs {
if !b.Valid() {
return errors.New("Cannot delete invalid blobref")
}
key := fmt.Sprintf("blob%v", n+1)
params.Add(key, b.String())
needsDelete[b] = true
}
req, err := http.NewRequest("POST", url_, strings.NewReader(params.Encode()))
if err != nil {
return fmt.Errorf("Error creating RemoveBlobs POST request: %v", err)
}
req = req.WithContext(ctx)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
c.authMode.AddAuthHeader(req)
resp, err := c.httpClient.Do(req)
if err != nil {
resp.Body.Close()
return fmt.Errorf("Got status code %d from blobserver for remove %s", resp.StatusCode, params.Encode())
}
var remResp handlers.RemoveResponse
decodeErr := httputil.DecodeJSON(resp, &remResp)
if resp.StatusCode != 200 {
resp.Body.Close()
if decodeErr == nil {
return fmt.Errorf("invalid http response %d in remove response: %v", resp.StatusCode, remResp.Error)
} else {
return fmt.Errorf("invalid http response %d in remove response", resp.StatusCode)
}
}
if decodeErr != nil {
return fmt.Errorf("failed to parse remove response: %v", err)
}
for _, br := range remResp.Removed {
delete(needsDelete, br)
}
if len(needsDelete) > 0 {
return fmt.Errorf("failed to remove blobs %s", strings.Join(stringKeys(needsDelete), ", "))
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"RemoveBlobs",
"(",
"ctx",
"context",
".",
"Context",
",",
"blobs",
"[",
"]",
"blob",
".",
"Ref",
")",
"error",
"{",
"if",
"c",
".",
"sto",
"!=",
"nil",
"{",
"return",
"c",
".",
"sto",
".",
"RemoveBlobs",
"(",
"ctx",
",",
"blobs",
")",
"\n",
"}",
"\n",
"pfx",
",",
"err",
":=",
"c",
".",
"prefix",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"url_",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"pfx",
")",
"\n",
"params",
":=",
"make",
"(",
"url",
".",
"Values",
")",
"// \"blobN\" -> BlobRefStr",
"\n",
"needsDelete",
":=",
"make",
"(",
"map",
"[",
"blob",
".",
"Ref",
"]",
"bool",
")",
"// BlobRefStr -> true",
"\n",
"for",
"n",
",",
"b",
":=",
"range",
"blobs",
"{",
"if",
"!",
"b",
".",
"Valid",
"(",
")",
"{",
"return",
"errors",
".",
"New",
"(",
"\"",
"\"",
")",
"\n",
"}",
"\n",
"key",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"",
"\"",
",",
"n",
"+",
"1",
")",
"\n",
"params",
".",
"Add",
"(",
"key",
",",
"b",
".",
"String",
"(",
")",
")",
"\n",
"needsDelete",
"[",
"b",
"]",
"=",
"true",
"\n",
"}",
"\n\n",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"\"",
"\"",
",",
"url_",
",",
"strings",
".",
"NewReader",
"(",
"params",
".",
"Encode",
"(",
")",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"req",
"=",
"req",
".",
"WithContext",
"(",
"ctx",
")",
"\n",
"req",
".",
"Header",
".",
"Add",
"(",
"\"",
"\"",
",",
"\"",
"\"",
")",
"\n",
"c",
".",
"authMode",
".",
"AddAuthHeader",
"(",
"req",
")",
"\n",
"resp",
",",
"err",
":=",
"c",
".",
"httpClient",
".",
"Do",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"resp",
".",
"StatusCode",
",",
"params",
".",
"Encode",
"(",
")",
")",
"\n",
"}",
"\n",
"var",
"remResp",
"handlers",
".",
"RemoveResponse",
"\n",
"decodeErr",
":=",
"httputil",
".",
"DecodeJSON",
"(",
"resp",
",",
"&",
"remResp",
")",
"\n",
"if",
"resp",
".",
"StatusCode",
"!=",
"200",
"{",
"resp",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"if",
"decodeErr",
"==",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"resp",
".",
"StatusCode",
",",
"remResp",
".",
"Error",
")",
"\n",
"}",
"else",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"resp",
".",
"StatusCode",
")",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"decodeErr",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"for",
"_",
",",
"br",
":=",
"range",
"remResp",
".",
"Removed",
"{",
"delete",
"(",
"needsDelete",
",",
"br",
")",
"\n",
"}",
"\n",
"if",
"len",
"(",
"needsDelete",
")",
">",
"0",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"strings",
".",
"Join",
"(",
"stringKeys",
"(",
"needsDelete",
")",
",",
"\"",
"\"",
")",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// RemoveBlobs removes the list of blobs. An error is returned if the
// server failed to remove a blob. Removing a non-existent blob isn't
// an error.
|
[
"RemoveBlobs",
"removes",
"the",
"list",
"of",
"blobs",
".",
"An",
"error",
"is",
"returned",
"if",
"the",
"server",
"failed",
"to",
"remove",
"a",
"blob",
".",
"Removing",
"a",
"non",
"-",
"existent",
"blob",
"isn",
"t",
"an",
"error",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/remove.go#L35-L87
|
train
|
perkeep/perkeep
|
pkg/client/remove.go
|
RemoveBlob
|
func (c *Client) RemoveBlob(ctx context.Context, b blob.Ref) error {
return c.RemoveBlobs(ctx, []blob.Ref{b})
}
|
go
|
func (c *Client) RemoveBlob(ctx context.Context, b blob.Ref) error {
return c.RemoveBlobs(ctx, []blob.Ref{b})
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"RemoveBlob",
"(",
"ctx",
"context",
".",
"Context",
",",
"b",
"blob",
".",
"Ref",
")",
"error",
"{",
"return",
"c",
".",
"RemoveBlobs",
"(",
"ctx",
",",
"[",
"]",
"blob",
".",
"Ref",
"{",
"b",
"}",
")",
"\n",
"}"
] |
// RemoveBlob removes the provided blob. An error is returned if the server failed to remove
// the blob. Removing a non-existent blob isn't an error.
|
[
"RemoveBlob",
"removes",
"the",
"provided",
"blob",
".",
"An",
"error",
"is",
"returned",
"if",
"the",
"server",
"failed",
"to",
"remove",
"the",
"blob",
".",
"Removing",
"a",
"non",
"-",
"existent",
"blob",
"isn",
"t",
"an",
"error",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/remove.go#L91-L93
|
train
|
perkeep/perkeep
|
cmd/pk/list.go
|
setClient
|
func (c *listCmd) setClient() error {
ss, err := c.syncCmd.storageFromParam("src", c.syncCmd.src)
if err != nil {
fmt.Errorf("Could not set client for describe requests: %v", err)
}
var ok bool
c.cl, ok = ss.(*client.Client)
if !ok {
return fmt.Errorf("storageFromParam returned a %T, was expecting a *client.Client", ss)
}
return nil
}
|
go
|
func (c *listCmd) setClient() error {
ss, err := c.syncCmd.storageFromParam("src", c.syncCmd.src)
if err != nil {
fmt.Errorf("Could not set client for describe requests: %v", err)
}
var ok bool
c.cl, ok = ss.(*client.Client)
if !ok {
return fmt.Errorf("storageFromParam returned a %T, was expecting a *client.Client", ss)
}
return nil
}
|
[
"func",
"(",
"c",
"*",
"listCmd",
")",
"setClient",
"(",
")",
"error",
"{",
"ss",
",",
"err",
":=",
"c",
".",
"syncCmd",
".",
"storageFromParam",
"(",
"\"",
"\"",
",",
"c",
".",
"syncCmd",
".",
"src",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"err",
")",
"\n",
"}",
"\n",
"var",
"ok",
"bool",
"\n",
"c",
".",
"cl",
",",
"ok",
"=",
"ss",
".",
"(",
"*",
"client",
".",
"Client",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"",
"\"",
",",
"ss",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// setClient configures a client for c, for the describe requests.
|
[
"setClient",
"configures",
"a",
"client",
"for",
"c",
"for",
"the",
"describe",
"requests",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/cmd/pk/list.go#L147-L158
|
train
|
perkeep/perkeep
|
internal/httputil/faketransport.go
|
NewRegexpFakeTransport
|
func NewRegexpFakeTransport(allMatchers []*Matcher) (http.RoundTripper, error) {
var result regexpFakeTransport = []*regexPair{}
for _, matcher := range allMatchers {
r, err := regexp.Compile(matcher.URLRegex)
if err != nil {
return nil, err
}
pair := regexPair{r, matcher.Fn}
result = append(result, &pair)
}
return result, nil
}
|
go
|
func NewRegexpFakeTransport(allMatchers []*Matcher) (http.RoundTripper, error) {
var result regexpFakeTransport = []*regexPair{}
for _, matcher := range allMatchers {
r, err := regexp.Compile(matcher.URLRegex)
if err != nil {
return nil, err
}
pair := regexPair{r, matcher.Fn}
result = append(result, &pair)
}
return result, nil
}
|
[
"func",
"NewRegexpFakeTransport",
"(",
"allMatchers",
"[",
"]",
"*",
"Matcher",
")",
"(",
"http",
".",
"RoundTripper",
",",
"error",
")",
"{",
"var",
"result",
"regexpFakeTransport",
"=",
"[",
"]",
"*",
"regexPair",
"{",
"}",
"\n",
"for",
"_",
",",
"matcher",
":=",
"range",
"allMatchers",
"{",
"r",
",",
"err",
":=",
"regexp",
".",
"Compile",
"(",
"matcher",
".",
"URLRegex",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"pair",
":=",
"regexPair",
"{",
"r",
",",
"matcher",
".",
"Fn",
"}",
"\n",
"result",
"=",
"append",
"(",
"result",
",",
"&",
"pair",
")",
"\n",
"}",
"\n",
"return",
"result",
",",
"nil",
"\n",
"}"
] |
// NewRegexpFakeTransport takes a slice of Matchers and returns an
// http.RoundTripper that will apply the function associated with the
// first UrlRegex that matches.
|
[
"NewRegexpFakeTransport",
"takes",
"a",
"slice",
"of",
"Matchers",
"and",
"returns",
"an",
"http",
".",
"RoundTripper",
"that",
"will",
"apply",
"the",
"function",
"associated",
"with",
"the",
"first",
"UrlRegex",
"that",
"matches",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/httputil/faketransport.go#L57-L68
|
train
|
perkeep/perkeep
|
internal/httputil/faketransport.go
|
FileResponder
|
func FileResponder(filename string) func() *http.Response {
return func() *http.Response {
f, err := os.Open(filename)
if err != nil {
return &http.Response{StatusCode: 404, Status: "404 Not Found", Body: types.EmptyBody}
}
return &http.Response{StatusCode: 200, Status: "200 OK", Body: f}
}
}
|
go
|
func FileResponder(filename string) func() *http.Response {
return func() *http.Response {
f, err := os.Open(filename)
if err != nil {
return &http.Response{StatusCode: 404, Status: "404 Not Found", Body: types.EmptyBody}
}
return &http.Response{StatusCode: 200, Status: "200 OK", Body: f}
}
}
|
[
"func",
"FileResponder",
"(",
"filename",
"string",
")",
"func",
"(",
")",
"*",
"http",
".",
"Response",
"{",
"return",
"func",
"(",
")",
"*",
"http",
".",
"Response",
"{",
"f",
",",
"err",
":=",
"os",
".",
"Open",
"(",
"filename",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"&",
"http",
".",
"Response",
"{",
"StatusCode",
":",
"404",
",",
"Status",
":",
"\"",
"\"",
",",
"Body",
":",
"types",
".",
"EmptyBody",
"}",
"\n",
"}",
"\n",
"return",
"&",
"http",
".",
"Response",
"{",
"StatusCode",
":",
"200",
",",
"Status",
":",
"\"",
"\"",
",",
"Body",
":",
"f",
"}",
"\n",
"}",
"\n",
"}"
] |
// FileResponder returns an HTTP response generator that returns the
// contents of the named file.
|
[
"FileResponder",
"returns",
"an",
"HTTP",
"response",
"generator",
"that",
"returns",
"the",
"contents",
"of",
"the",
"named",
"file",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/httputil/faketransport.go#L89-L97
|
train
|
perkeep/perkeep
|
internal/httputil/faketransport.go
|
StaticResponder
|
func StaticResponder(res string) func() *http.Response {
_, err := http.ReadResponse(bufio.NewReader(strings.NewReader(res)), nil)
if err != nil {
panic("Invalid response given to StaticResponder: " + err.Error())
}
return func() *http.Response {
res, _ := http.ReadResponse(bufio.NewReader(strings.NewReader(res)), nil)
return res
}
}
|
go
|
func StaticResponder(res string) func() *http.Response {
_, err := http.ReadResponse(bufio.NewReader(strings.NewReader(res)), nil)
if err != nil {
panic("Invalid response given to StaticResponder: " + err.Error())
}
return func() *http.Response {
res, _ := http.ReadResponse(bufio.NewReader(strings.NewReader(res)), nil)
return res
}
}
|
[
"func",
"StaticResponder",
"(",
"res",
"string",
")",
"func",
"(",
")",
"*",
"http",
".",
"Response",
"{",
"_",
",",
"err",
":=",
"http",
".",
"ReadResponse",
"(",
"bufio",
".",
"NewReader",
"(",
"strings",
".",
"NewReader",
"(",
"res",
")",
")",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"\"",
"\"",
"+",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"}",
"\n",
"return",
"func",
"(",
")",
"*",
"http",
".",
"Response",
"{",
"res",
",",
"_",
":=",
"http",
".",
"ReadResponse",
"(",
"bufio",
".",
"NewReader",
"(",
"strings",
".",
"NewReader",
"(",
"res",
")",
")",
",",
"nil",
")",
"\n",
"return",
"res",
"\n",
"}",
"\n",
"}"
] |
// StaticResponder returns an HTTP response generator that parses res
// for an entire HTTP response, including headers and body.
|
[
"StaticResponder",
"returns",
"an",
"HTTP",
"response",
"generator",
"that",
"parses",
"res",
"for",
"an",
"entire",
"HTTP",
"response",
"including",
"headers",
"and",
"body",
"."
] |
e28bbbd1588d64df8ab7a82393afd39d64c061f7
|
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/httputil/faketransport.go#L101-L110
|
train
|
Subsets and Splits
SQL Console for semeru/code-text-go
Retrieves a limited set of code samples with their languages, with a specific case adjustment for 'Go' language.