repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
perkeep/perkeep
internal/video/thumbnail/thumbnailer.go
Command
func (f FFmpegThumbnailer) Command(uri *url.URL) (string, []string) { return "ffmpeg", []string{ "-seekable", "1", "-i", uri.String(), "-vf", "thumbnail", "-frames:v", "1", "-f", "image2pipe", "-c:v", "png", "pipe:1", } }
go
func (f FFmpegThumbnailer) Command(uri *url.URL) (string, []string) { return "ffmpeg", []string{ "-seekable", "1", "-i", uri.String(), "-vf", "thumbnail", "-frames:v", "1", "-f", "image2pipe", "-c:v", "png", "pipe:1", } }
[ "func", "(", "f", "FFmpegThumbnailer", ")", "Command", "(", "uri", "*", "url", ".", "URL", ")", "(", "string", ",", "[", "]", "string", ")", "{", "return", "\"", "\"", ",", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "uri", ".", "String", "(", ")", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "}", "\n", "}" ]
// Command implements the Command method for the Thumbnailer interface.
[ "Command", "implements", "the", "Command", "method", "for", "the", "Thumbnailer", "interface", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/video/thumbnail/thumbnailer.go#L48-L58
train
perkeep/perkeep
pkg/sorted/kv.go
NewKeyValue
func NewKeyValue(cfg jsonconfig.Obj) (KeyValue, error) { var s KeyValue var err error typ := cfg.RequiredString("type") ctor, ok := ctors[typ] if typ != "" && !ok { return nil, fmt.Errorf("Invalid sorted.KeyValue type %q", typ) } if ok { s, err = ctor(cfg) if err != nil { we, ok := err.(NeedWipeError) if !ok { return nil, fmt.Errorf("error from %q KeyValue: %v", typ, err) } if err := cfg.Validate(); err != nil { return nil, err } we.Msg = fmt.Sprintf("error from %q KeyValue: %v", typ, err) return s, we } } return s, cfg.Validate() }
go
func NewKeyValue(cfg jsonconfig.Obj) (KeyValue, error) { var s KeyValue var err error typ := cfg.RequiredString("type") ctor, ok := ctors[typ] if typ != "" && !ok { return nil, fmt.Errorf("Invalid sorted.KeyValue type %q", typ) } if ok { s, err = ctor(cfg) if err != nil { we, ok := err.(NeedWipeError) if !ok { return nil, fmt.Errorf("error from %q KeyValue: %v", typ, err) } if err := cfg.Validate(); err != nil { return nil, err } we.Msg = fmt.Sprintf("error from %q KeyValue: %v", typ, err) return s, we } } return s, cfg.Validate() }
[ "func", "NewKeyValue", "(", "cfg", "jsonconfig", ".", "Obj", ")", "(", "KeyValue", ",", "error", ")", "{", "var", "s", "KeyValue", "\n", "var", "err", "error", "\n", "typ", ":=", "cfg", ".", "RequiredString", "(", "\"", "\"", ")", "\n", "ctor", ",", "ok", ":=", "ctors", "[", "typ", "]", "\n", "if", "typ", "!=", "\"", "\"", "&&", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "typ", ")", "\n", "}", "\n", "if", "ok", "{", "s", ",", "err", "=", "ctor", "(", "cfg", ")", "\n", "if", "err", "!=", "nil", "{", "we", ",", "ok", ":=", "err", ".", "(", "NeedWipeError", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "typ", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "cfg", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "we", ".", "Msg", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "typ", ",", "err", ")", "\n", "return", "s", ",", "we", "\n", "}", "\n", "}", "\n", "return", "s", ",", "cfg", ".", "Validate", "(", ")", "\n", "}" ]
// NewKeyValue returns a KeyValue as defined by cfg. // It returns an error of type NeedWipeError when the returned KeyValue should // be fixed with Wipe.
[ "NewKeyValue", "returns", "a", "KeyValue", "as", "defined", "by", "cfg", ".", "It", "returns", "an", "error", "of", "type", "NeedWipeError", "when", "the", "returned", "KeyValue", "should", "be", "fixed", "with", "Wipe", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/sorted/kv.go#L204-L227
train
perkeep/perkeep
pkg/sorted/kv.go
NewKeyValueMaybeWipe
func NewKeyValueMaybeWipe(cfg jsonconfig.Obj) (KeyValue, error) { kv, err := NewKeyValue(cfg) if err == nil { return kv, nil } if _, ok := err.(NeedWipeError); !ok { return nil, err } wiper, ok := kv.(Wiper) if !ok { return nil, fmt.Errorf("storage type %T needs wiping because %v. But it doesn't support sorted.Wiper", err, kv) } we := err if err := wiper.Wipe(); err != nil { return nil, fmt.Errorf("sorted key/value type %T needed wiping because %v. But could not wipe: %v", kv, we, err) } return kv, nil }
go
func NewKeyValueMaybeWipe(cfg jsonconfig.Obj) (KeyValue, error) { kv, err := NewKeyValue(cfg) if err == nil { return kv, nil } if _, ok := err.(NeedWipeError); !ok { return nil, err } wiper, ok := kv.(Wiper) if !ok { return nil, fmt.Errorf("storage type %T needs wiping because %v. But it doesn't support sorted.Wiper", err, kv) } we := err if err := wiper.Wipe(); err != nil { return nil, fmt.Errorf("sorted key/value type %T needed wiping because %v. But could not wipe: %v", kv, we, err) } return kv, nil }
[ "func", "NewKeyValueMaybeWipe", "(", "cfg", "jsonconfig", ".", "Obj", ")", "(", "KeyValue", ",", "error", ")", "{", "kv", ",", "err", ":=", "NewKeyValue", "(", "cfg", ")", "\n", "if", "err", "==", "nil", "{", "return", "kv", ",", "nil", "\n", "}", "\n", "if", "_", ",", "ok", ":=", "err", ".", "(", "NeedWipeError", ")", ";", "!", "ok", "{", "return", "nil", ",", "err", "\n", "}", "\n", "wiper", ",", "ok", ":=", "kv", ".", "(", "Wiper", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ",", "kv", ")", "\n", "}", "\n", "we", ":=", "err", "\n", "if", "err", ":=", "wiper", ".", "Wipe", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "kv", ",", "we", ",", "err", ")", "\n", "}", "\n", "return", "kv", ",", "nil", "\n", "}" ]
// NewKeyValueMaybeWipe calls NewKeyValue and wipes the KeyValue if, and only // if, NewKeyValue has returned a NeedWipeError.
[ "NewKeyValueMaybeWipe", "calls", "NewKeyValue", "and", "wipes", "the", "KeyValue", "if", "and", "only", "if", "NewKeyValue", "has", "returned", "a", "NeedWipeError", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/sorted/kv.go#L231-L248
train
perkeep/perkeep
pkg/sorted/kv.go
CheckSizes
func CheckSizes(key, value string) error { if len(key) > MaxKeySize { return ErrKeyTooLarge } if len(value) > MaxValueSize { return ErrValueTooLarge } return nil }
go
func CheckSizes(key, value string) error { if len(key) > MaxKeySize { return ErrKeyTooLarge } if len(value) > MaxValueSize { return ErrValueTooLarge } return nil }
[ "func", "CheckSizes", "(", "key", ",", "value", "string", ")", "error", "{", "if", "len", "(", "key", ")", ">", "MaxKeySize", "{", "return", "ErrKeyTooLarge", "\n", "}", "\n", "if", "len", "(", "value", ")", ">", "MaxValueSize", "{", "return", "ErrValueTooLarge", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CheckSizes returns ErrKeyTooLarge if key does not respect KeyMaxSize or // ErrValueTooLarge if value does not respect ValueMaxSize
[ "CheckSizes", "returns", "ErrKeyTooLarge", "if", "key", "does", "not", "respect", "KeyMaxSize", "or", "ErrValueTooLarge", "if", "value", "does", "not", "respect", "ValueMaxSize" ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/sorted/kv.go#L273-L281
train
perkeep/perkeep
pkg/search/query.go
addContinueConstraint
func (q *SearchQuery) addContinueConstraint() error { cont := q.Continue if cont == "" { return nil } if q.Constraint.onlyMatchesPermanode() { tokent, lastbr, ok := parsePermanodeContinueToken(cont) if !ok { return errors.New("Unexpected continue token") } if q.Sort == LastModifiedDesc || q.Sort == CreatedDesc { var lastMod, lastCreated time.Time switch q.Sort { case LastModifiedDesc: lastMod = tokent case CreatedDesc: lastCreated = tokent } baseConstraint := q.Constraint q.Constraint = &Constraint{ Logical: &LogicalConstraint{ Op: "and", A: &Constraint{ Permanode: &PermanodeConstraint{ Continue: &PermanodeContinueConstraint{ LastCreated: lastCreated, LastMod: lastMod, Last: lastbr, }, }, }, B: baseConstraint, }, } } return nil } return errors.New("token not valid for query type") }
go
func (q *SearchQuery) addContinueConstraint() error { cont := q.Continue if cont == "" { return nil } if q.Constraint.onlyMatchesPermanode() { tokent, lastbr, ok := parsePermanodeContinueToken(cont) if !ok { return errors.New("Unexpected continue token") } if q.Sort == LastModifiedDesc || q.Sort == CreatedDesc { var lastMod, lastCreated time.Time switch q.Sort { case LastModifiedDesc: lastMod = tokent case CreatedDesc: lastCreated = tokent } baseConstraint := q.Constraint q.Constraint = &Constraint{ Logical: &LogicalConstraint{ Op: "and", A: &Constraint{ Permanode: &PermanodeConstraint{ Continue: &PermanodeContinueConstraint{ LastCreated: lastCreated, LastMod: lastMod, Last: lastbr, }, }, }, B: baseConstraint, }, } } return nil } return errors.New("token not valid for query type") }
[ "func", "(", "q", "*", "SearchQuery", ")", "addContinueConstraint", "(", ")", "error", "{", "cont", ":=", "q", ".", "Continue", "\n", "if", "cont", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n", "if", "q", ".", "Constraint", ".", "onlyMatchesPermanode", "(", ")", "{", "tokent", ",", "lastbr", ",", "ok", ":=", "parsePermanodeContinueToken", "(", "cont", ")", "\n", "if", "!", "ok", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "q", ".", "Sort", "==", "LastModifiedDesc", "||", "q", ".", "Sort", "==", "CreatedDesc", "{", "var", "lastMod", ",", "lastCreated", "time", ".", "Time", "\n", "switch", "q", ".", "Sort", "{", "case", "LastModifiedDesc", ":", "lastMod", "=", "tokent", "\n", "case", "CreatedDesc", ":", "lastCreated", "=", "tokent", "\n", "}", "\n", "baseConstraint", ":=", "q", ".", "Constraint", "\n", "q", ".", "Constraint", "=", "&", "Constraint", "{", "Logical", ":", "&", "LogicalConstraint", "{", "Op", ":", "\"", "\"", ",", "A", ":", "&", "Constraint", "{", "Permanode", ":", "&", "PermanodeConstraint", "{", "Continue", ":", "&", "PermanodeContinueConstraint", "{", "LastCreated", ":", "lastCreated", ",", "LastMod", ":", "lastMod", ",", "Last", ":", "lastbr", ",", "}", ",", "}", ",", "}", ",", "B", ":", "baseConstraint", ",", "}", ",", "}", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// addContinueConstraint conditionally modifies q.Constraint to scroll // past the results as indicated by q.Continue.
[ "addContinueConstraint", "conditionally", "modifies", "q", ".", "Constraint", "to", "scroll", "past", "the", "results", "as", "indicated", "by", "q", ".", "Continue", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/search/query.go#L195-L233
train
perkeep/perkeep
pkg/search/query.go
matchesPermanodeTypes
func (c *Constraint) matchesPermanodeTypes() []string { if c == nil { return nil } if pc := c.Permanode; pc != nil && pc.Attr == "camliNodeType" && pc.Value != "" { return []string{pc.Value} } if lc := c.Logical; lc != nil { sa := lc.A.matchesPermanodeTypes() sb := lc.B.matchesPermanodeTypes() switch lc.Op { case "and": if len(sa) != 0 { return sa } return sb case "or": return append(sa, sb...) } } return nil }
go
func (c *Constraint) matchesPermanodeTypes() []string { if c == nil { return nil } if pc := c.Permanode; pc != nil && pc.Attr == "camliNodeType" && pc.Value != "" { return []string{pc.Value} } if lc := c.Logical; lc != nil { sa := lc.A.matchesPermanodeTypes() sb := lc.B.matchesPermanodeTypes() switch lc.Op { case "and": if len(sa) != 0 { return sa } return sb case "or": return append(sa, sb...) } } return nil }
[ "func", "(", "c", "*", "Constraint", ")", "matchesPermanodeTypes", "(", ")", "[", "]", "string", "{", "if", "c", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "if", "pc", ":=", "c", ".", "Permanode", ";", "pc", "!=", "nil", "&&", "pc", ".", "Attr", "==", "\"", "\"", "&&", "pc", ".", "Value", "!=", "\"", "\"", "{", "return", "[", "]", "string", "{", "pc", ".", "Value", "}", "\n", "}", "\n", "if", "lc", ":=", "c", ".", "Logical", ";", "lc", "!=", "nil", "{", "sa", ":=", "lc", ".", "A", ".", "matchesPermanodeTypes", "(", ")", "\n", "sb", ":=", "lc", ".", "B", ".", "matchesPermanodeTypes", "(", ")", "\n", "switch", "lc", ".", "Op", "{", "case", "\"", "\"", ":", "if", "len", "(", "sa", ")", "!=", "0", "{", "return", "sa", "\n", "}", "\n", "return", "sb", "\n", "case", "\"", "\"", ":", "return", "append", "(", "sa", ",", "sb", "...", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n\n", "}" ]
// matchesPermanodeTypes returns a set of valid permanode types that a matching // permanode must have as its "camliNodeType" attribute. // It returns a zero-length slice if this constraint might include things other // things.
[ "matchesPermanodeTypes", "returns", "a", "set", "of", "valid", "permanode", "types", "that", "a", "matching", "permanode", "must", "have", "as", "its", "camliNodeType", "attribute", ".", "It", "returns", "a", "zero", "-", "length", "slice", "if", "this", "constraint", "might", "include", "things", "other", "things", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/search/query.go#L338-L360
train
perkeep/perkeep
pkg/search/query.go
matchesAtMostOneBlob
func (c *Constraint) matchesAtMostOneBlob() blob.Ref { if c == nil { return blob.Ref{} } if c.BlobRefPrefix != "" { br, ok := blob.Parse(c.BlobRefPrefix) if ok { return br } } if c.Logical != nil && c.Logical.Op == "and" { if br := c.Logical.A.matchesAtMostOneBlob(); br.Valid() { return br } if br := c.Logical.B.matchesAtMostOneBlob(); br.Valid() { return br } } return blob.Ref{} }
go
func (c *Constraint) matchesAtMostOneBlob() blob.Ref { if c == nil { return blob.Ref{} } if c.BlobRefPrefix != "" { br, ok := blob.Parse(c.BlobRefPrefix) if ok { return br } } if c.Logical != nil && c.Logical.Op == "and" { if br := c.Logical.A.matchesAtMostOneBlob(); br.Valid() { return br } if br := c.Logical.B.matchesAtMostOneBlob(); br.Valid() { return br } } return blob.Ref{} }
[ "func", "(", "c", "*", "Constraint", ")", "matchesAtMostOneBlob", "(", ")", "blob", ".", "Ref", "{", "if", "c", "==", "nil", "{", "return", "blob", ".", "Ref", "{", "}", "\n", "}", "\n", "if", "c", ".", "BlobRefPrefix", "!=", "\"", "\"", "{", "br", ",", "ok", ":=", "blob", ".", "Parse", "(", "c", ".", "BlobRefPrefix", ")", "\n", "if", "ok", "{", "return", "br", "\n", "}", "\n", "}", "\n", "if", "c", ".", "Logical", "!=", "nil", "&&", "c", ".", "Logical", ".", "Op", "==", "\"", "\"", "{", "if", "br", ":=", "c", ".", "Logical", ".", "A", ".", "matchesAtMostOneBlob", "(", ")", ";", "br", ".", "Valid", "(", ")", "{", "return", "br", "\n", "}", "\n", "if", "br", ":=", "c", ".", "Logical", ".", "B", ".", "matchesAtMostOneBlob", "(", ")", ";", "br", ".", "Valid", "(", ")", "{", "return", "br", "\n", "}", "\n", "}", "\n", "return", "blob", ".", "Ref", "{", "}", "\n", "}" ]
// matchesAtMostOneBlob reports whether this constraint matches at most a single blob. // If so, it returns that blob. Otherwise it returns a zero, invalid blob.Ref.
[ "matchesAtMostOneBlob", "reports", "whether", "this", "constraint", "matches", "at", "most", "a", "single", "blob", ".", "If", "so", "it", "returns", "that", "blob", ".", "Otherwise", "it", "returns", "a", "zero", "invalid", "blob", ".", "Ref", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/search/query.go#L364-L383
train
perkeep/perkeep
pkg/search/query.go
setResultContinue
func (q *SearchQuery) setResultContinue(corpus *index.Corpus, res *SearchResult) { if !q.Constraint.onlyMatchesPermanode() { return } var pnTimeFunc func(blob.Ref) (t time.Time, ok bool) switch q.Sort { case LastModifiedDesc: pnTimeFunc = corpus.PermanodeModtime case CreatedDesc: pnTimeFunc = corpus.PermanodeAnyTime default: return } if q.Limit <= 0 || len(res.Blobs) != q.Limit { return } lastpn := res.Blobs[len(res.Blobs)-1].Blob t, ok := pnTimeFunc(lastpn) if !ok { return } res.Continue = fmt.Sprintf("pn:%d:%v", t.UnixNano(), lastpn) }
go
func (q *SearchQuery) setResultContinue(corpus *index.Corpus, res *SearchResult) { if !q.Constraint.onlyMatchesPermanode() { return } var pnTimeFunc func(blob.Ref) (t time.Time, ok bool) switch q.Sort { case LastModifiedDesc: pnTimeFunc = corpus.PermanodeModtime case CreatedDesc: pnTimeFunc = corpus.PermanodeAnyTime default: return } if q.Limit <= 0 || len(res.Blobs) != q.Limit { return } lastpn := res.Blobs[len(res.Blobs)-1].Blob t, ok := pnTimeFunc(lastpn) if !ok { return } res.Continue = fmt.Sprintf("pn:%d:%v", t.UnixNano(), lastpn) }
[ "func", "(", "q", "*", "SearchQuery", ")", "setResultContinue", "(", "corpus", "*", "index", ".", "Corpus", ",", "res", "*", "SearchResult", ")", "{", "if", "!", "q", ".", "Constraint", ".", "onlyMatchesPermanode", "(", ")", "{", "return", "\n", "}", "\n", "var", "pnTimeFunc", "func", "(", "blob", ".", "Ref", ")", "(", "t", "time", ".", "Time", ",", "ok", "bool", ")", "\n", "switch", "q", ".", "Sort", "{", "case", "LastModifiedDesc", ":", "pnTimeFunc", "=", "corpus", ".", "PermanodeModtime", "\n", "case", "CreatedDesc", ":", "pnTimeFunc", "=", "corpus", ".", "PermanodeAnyTime", "\n", "default", ":", "return", "\n", "}", "\n\n", "if", "q", ".", "Limit", "<=", "0", "||", "len", "(", "res", ".", "Blobs", ")", "!=", "q", ".", "Limit", "{", "return", "\n", "}", "\n", "lastpn", ":=", "res", ".", "Blobs", "[", "len", "(", "res", ".", "Blobs", ")", "-", "1", "]", ".", "Blob", "\n", "t", ",", "ok", ":=", "pnTimeFunc", "(", "lastpn", ")", "\n", "if", "!", "ok", "{", "return", "\n", "}", "\n", "res", ".", "Continue", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "t", ".", "UnixNano", "(", ")", ",", "lastpn", ")", "\n", "}" ]
// setResultContinue sets res.Continue if q is suitable for having a continue token. // The corpus is locked for reads.
[ "setResultContinue", "sets", "res", ".", "Continue", "if", "q", "is", "suitable", "for", "having", "a", "continue", "token", ".", "The", "corpus", "is", "locked", "for", "reads", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/search/query.go#L1359-L1382
train
perkeep/perkeep
pkg/search/query.go
hasValueConstraint
func (c *PermanodeConstraint) hasValueConstraint() bool { // If a field has been added or removed, update this after adding the new field to the return statement if necessary. const expectedFields = 15 if numPermanodeFields != expectedFields { panic(fmt.Sprintf("PermanodeConstraint field count changed (now %v rather than %v)", numPermanodeFields, expectedFields)) } return c.Value != "" || c.ValueMatches != nil || c.ValueMatchesInt != nil || c.ValueMatchesFloat != nil || c.ValueInSet != nil }
go
func (c *PermanodeConstraint) hasValueConstraint() bool { // If a field has been added or removed, update this after adding the new field to the return statement if necessary. const expectedFields = 15 if numPermanodeFields != expectedFields { panic(fmt.Sprintf("PermanodeConstraint field count changed (now %v rather than %v)", numPermanodeFields, expectedFields)) } return c.Value != "" || c.ValueMatches != nil || c.ValueMatchesInt != nil || c.ValueMatchesFloat != nil || c.ValueInSet != nil }
[ "func", "(", "c", "*", "PermanodeConstraint", ")", "hasValueConstraint", "(", ")", "bool", "{", "// If a field has been added or removed, update this after adding the new field to the return statement if necessary.", "const", "expectedFields", "=", "15", "\n", "if", "numPermanodeFields", "!=", "expectedFields", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "numPermanodeFields", ",", "expectedFields", ")", ")", "\n", "}", "\n", "return", "c", ".", "Value", "!=", "\"", "\"", "||", "c", ".", "ValueMatches", "!=", "nil", "||", "c", ".", "ValueMatchesInt", "!=", "nil", "||", "c", ".", "ValueMatchesFloat", "!=", "nil", "||", "c", ".", "ValueInSet", "!=", "nil", "\n", "}" ]
// hasValueConstraint returns true if one or more constraints that check an attribute's value are set.
[ "hasValueConstraint", "returns", "true", "if", "one", "or", "more", "constraints", "that", "check", "an", "attribute", "s", "value", "are", "set", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/search/query.go#L1668-L1679
train
perkeep/perkeep
pkg/search/query.go
permanodeMatchesAttrVals
func (c *PermanodeConstraint) permanodeMatchesAttrVals(ctx context.Context, s *search, vals []string) (bool, error) { if c.NumValue != nil && !c.NumValue.intMatches(int64(len(vals))) { return false, nil } if c.hasValueConstraint() { nmatch := 0 for _, val := range vals { match, err := c.permanodeMatchesAttrVal(ctx, s, val) if err != nil { return false, err } if match { nmatch++ } } if nmatch == 0 { return false, nil } if c.ValueAll { return nmatch == len(vals), nil } } return true, nil }
go
func (c *PermanodeConstraint) permanodeMatchesAttrVals(ctx context.Context, s *search, vals []string) (bool, error) { if c.NumValue != nil && !c.NumValue.intMatches(int64(len(vals))) { return false, nil } if c.hasValueConstraint() { nmatch := 0 for _, val := range vals { match, err := c.permanodeMatchesAttrVal(ctx, s, val) if err != nil { return false, err } if match { nmatch++ } } if nmatch == 0 { return false, nil } if c.ValueAll { return nmatch == len(vals), nil } } return true, nil }
[ "func", "(", "c", "*", "PermanodeConstraint", ")", "permanodeMatchesAttrVals", "(", "ctx", "context", ".", "Context", ",", "s", "*", "search", ",", "vals", "[", "]", "string", ")", "(", "bool", ",", "error", ")", "{", "if", "c", ".", "NumValue", "!=", "nil", "&&", "!", "c", ".", "NumValue", ".", "intMatches", "(", "int64", "(", "len", "(", "vals", ")", ")", ")", "{", "return", "false", ",", "nil", "\n", "}", "\n", "if", "c", ".", "hasValueConstraint", "(", ")", "{", "nmatch", ":=", "0", "\n", "for", "_", ",", "val", ":=", "range", "vals", "{", "match", ",", "err", ":=", "c", ".", "permanodeMatchesAttrVal", "(", "ctx", ",", "s", ",", "val", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "if", "match", "{", "nmatch", "++", "\n", "}", "\n", "}", "\n", "if", "nmatch", "==", "0", "{", "return", "false", ",", "nil", "\n", "}", "\n", "if", "c", ".", "ValueAll", "{", "return", "nmatch", "==", "len", "(", "vals", ")", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "true", ",", "nil", "\n", "}" ]
// permanodeMatchesAttrVals checks that the values in vals - all of them, if c.ValueAll is set - // match the values for c.Attr. // vals are the current permanode values of c.Attr.
[ "permanodeMatchesAttrVals", "checks", "that", "the", "values", "in", "vals", "-", "all", "of", "them", "if", "c", ".", "ValueAll", "is", "set", "-", "match", "the", "values", "for", "c", ".", "Attr", ".", "vals", "are", "the", "current", "permanode", "values", "of", "c", ".", "Attr", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/search/query.go#L1822-L1845
train
perkeep/perkeep
pkg/search/query.go
hasMatchingParent
func (c *DirConstraint) hasMatchingParent(ctx context.Context, s *search, parents map[blob.Ref]struct{}) (bool, error) { for parent := range parents { meta, err := s.blobMeta(ctx, parent) if err != nil { if os.IsNotExist(err) { continue } return false, err } ok, err := c.blobMatches(ctx, s, parent, meta) if err != nil { return false, err } if ok { return true, nil } } return false, nil }
go
func (c *DirConstraint) hasMatchingParent(ctx context.Context, s *search, parents map[blob.Ref]struct{}) (bool, error) { for parent := range parents { meta, err := s.blobMeta(ctx, parent) if err != nil { if os.IsNotExist(err) { continue } return false, err } ok, err := c.blobMatches(ctx, s, parent, meta) if err != nil { return false, err } if ok { return true, nil } } return false, nil }
[ "func", "(", "c", "*", "DirConstraint", ")", "hasMatchingParent", "(", "ctx", "context", ".", "Context", ",", "s", "*", "search", ",", "parents", "map", "[", "blob", ".", "Ref", "]", "struct", "{", "}", ")", "(", "bool", ",", "error", ")", "{", "for", "parent", ":=", "range", "parents", "{", "meta", ",", "err", ":=", "s", ".", "blobMeta", "(", "ctx", ",", "parent", ")", "\n", "if", "err", "!=", "nil", "{", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "continue", "\n", "}", "\n", "return", "false", ",", "err", "\n", "}", "\n", "ok", ",", "err", ":=", "c", ".", "blobMatches", "(", "ctx", ",", "s", ",", "parent", ",", "meta", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "if", "ok", "{", "return", "true", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "false", ",", "nil", "\n", "}" ]
// hasMatchingParent checks all parents against c and returns true as soon as one of // them matches, or returns false if none of them is a match.
[ "hasMatchingParent", "checks", "all", "parents", "against", "c", "and", "returns", "true", "as", "soon", "as", "one", "of", "them", "matches", "or", "returns", "false", "if", "none", "of", "them", "is", "a", "match", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/search/query.go#L2185-L2203
train
perkeep/perkeep
pkg/search/query.go
hasMatchingChild
func (c *DirConstraint) hasMatchingChild(ctx context.Context, s *search, children map[blob.Ref]struct{}, matcher func(context.Context, *search, blob.Ref, camtypes.BlobMeta) (bool, error)) (bool, error) { // TODO(mpl): See if we're guaranteed to be CPU-bound (i.e. all resources are in // corpus), and if not, add some concurrency to spread costly index lookups. for child, _ := range children { meta, err := s.blobMeta(ctx, child) if err != nil { if os.IsNotExist(err) { continue } return false, err } ok, err := matcher(ctx, s, child, meta) if err != nil { return false, err } if ok { return true, nil } } return false, nil }
go
func (c *DirConstraint) hasMatchingChild(ctx context.Context, s *search, children map[blob.Ref]struct{}, matcher func(context.Context, *search, blob.Ref, camtypes.BlobMeta) (bool, error)) (bool, error) { // TODO(mpl): See if we're guaranteed to be CPU-bound (i.e. all resources are in // corpus), and if not, add some concurrency to spread costly index lookups. for child, _ := range children { meta, err := s.blobMeta(ctx, child) if err != nil { if os.IsNotExist(err) { continue } return false, err } ok, err := matcher(ctx, s, child, meta) if err != nil { return false, err } if ok { return true, nil } } return false, nil }
[ "func", "(", "c", "*", "DirConstraint", ")", "hasMatchingChild", "(", "ctx", "context", ".", "Context", ",", "s", "*", "search", ",", "children", "map", "[", "blob", ".", "Ref", "]", "struct", "{", "}", ",", "matcher", "func", "(", "context", ".", "Context", ",", "*", "search", ",", "blob", ".", "Ref", ",", "camtypes", ".", "BlobMeta", ")", "(", "bool", ",", "error", ")", ")", "(", "bool", ",", "error", ")", "{", "// TODO(mpl): See if we're guaranteed to be CPU-bound (i.e. all resources are in", "// corpus), and if not, add some concurrency to spread costly index lookups.", "for", "child", ",", "_", ":=", "range", "children", "{", "meta", ",", "err", ":=", "s", ".", "blobMeta", "(", "ctx", ",", "child", ")", "\n", "if", "err", "!=", "nil", "{", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "continue", "\n", "}", "\n", "return", "false", ",", "err", "\n", "}", "\n", "ok", ",", "err", ":=", "matcher", "(", "ctx", ",", "s", ",", "child", ",", "meta", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "if", "ok", "{", "return", "true", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "false", ",", "nil", "\n", "}" ]
// hasMatchingChild runs matcher against each child and returns true as soon as // there is a match, of false if none of them is a match.
[ "hasMatchingChild", "runs", "matcher", "against", "each", "child", "and", "returns", "true", "as", "soon", "as", "there", "is", "a", "match", "of", "false", "if", "none", "of", "them", "is", "a", "match", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/search/query.go#L2207-L2228
train
perkeep/perkeep
pkg/blobserver/localdisk/generation.go
StorageGeneration
func (ds *DiskStorage) StorageGeneration() (initTime time.Time, random string, err error) { return ds.gen.StorageGeneration() }
go
func (ds *DiskStorage) StorageGeneration() (initTime time.Time, random string, err error) { return ds.gen.StorageGeneration() }
[ "func", "(", "ds", "*", "DiskStorage", ")", "StorageGeneration", "(", ")", "(", "initTime", "time", ".", "Time", ",", "random", "string", ",", "err", "error", ")", "{", "return", "ds", ".", "gen", ".", "StorageGeneration", "(", ")", "\n", "}" ]
// StorageGeneration returns the generation's initialization time, // and the random string.
[ "StorageGeneration", "returns", "the", "generation", "s", "initialization", "time", "and", "the", "random", "string", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/localdisk/generation.go#L30-L32
train
perkeep/perkeep
internal/osutil/gce/gce.go
LogWriter
func LogWriter() (w io.WriteCloser, err error) { w = multiWriteCloser{ w: os.Stderr, // Because we don't actually want to close os.Stderr (which we could). closer: types.NopCloser, } if !env.OnGCE() { return } projID, err := metadata.ProjectID() if projID == "" { log.Printf("Error getting project ID: %v", err) return } scopes, _ := metadata.Scopes("default") haveScope := func(scope string) bool { for _, x := range scopes { if x == scope { return true } } return false } if !haveScope(logging.WriteScope) { return nil, fmt.Errorf("when this Google Compute Engine VM instance was created, it wasn't granted enough access to use Google Cloud Logging (Scope URL: %v)", logging.WriteScope) } ctx := context.Background() logc, err := logging.NewClient(ctx, projID) if err != nil { return nil, fmt.Errorf("error creating Google logging client: %v", err) } if err := logc.Ping(ctx); err != nil { return nil, fmt.Errorf("Google logging client not ready (ping failed): %v", err) } logw := writer{ severity: logging.Debug, logger: logc.Logger("perkeepd-stderr"), } return multiWriteCloser{ w: io.MultiWriter(w, logw), closer: logc, }, nil }
go
func LogWriter() (w io.WriteCloser, err error) { w = multiWriteCloser{ w: os.Stderr, // Because we don't actually want to close os.Stderr (which we could). closer: types.NopCloser, } if !env.OnGCE() { return } projID, err := metadata.ProjectID() if projID == "" { log.Printf("Error getting project ID: %v", err) return } scopes, _ := metadata.Scopes("default") haveScope := func(scope string) bool { for _, x := range scopes { if x == scope { return true } } return false } if !haveScope(logging.WriteScope) { return nil, fmt.Errorf("when this Google Compute Engine VM instance was created, it wasn't granted enough access to use Google Cloud Logging (Scope URL: %v)", logging.WriteScope) } ctx := context.Background() logc, err := logging.NewClient(ctx, projID) if err != nil { return nil, fmt.Errorf("error creating Google logging client: %v", err) } if err := logc.Ping(ctx); err != nil { return nil, fmt.Errorf("Google logging client not ready (ping failed): %v", err) } logw := writer{ severity: logging.Debug, logger: logc.Logger("perkeepd-stderr"), } return multiWriteCloser{ w: io.MultiWriter(w, logw), closer: logc, }, nil }
[ "func", "LogWriter", "(", ")", "(", "w", "io", ".", "WriteCloser", ",", "err", "error", ")", "{", "w", "=", "multiWriteCloser", "{", "w", ":", "os", ".", "Stderr", ",", "// Because we don't actually want to close os.Stderr (which we could).", "closer", ":", "types", ".", "NopCloser", ",", "}", "\n", "if", "!", "env", ".", "OnGCE", "(", ")", "{", "return", "\n", "}", "\n", "projID", ",", "err", ":=", "metadata", ".", "ProjectID", "(", ")", "\n", "if", "projID", "==", "\"", "\"", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "scopes", ",", "_", ":=", "metadata", ".", "Scopes", "(", "\"", "\"", ")", "\n", "haveScope", ":=", "func", "(", "scope", "string", ")", "bool", "{", "for", "_", ",", "x", ":=", "range", "scopes", "{", "if", "x", "==", "scope", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}", "\n", "if", "!", "haveScope", "(", "logging", ".", "WriteScope", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "logging", ".", "WriteScope", ")", "\n", "}", "\n\n", "ctx", ":=", "context", ".", "Background", "(", ")", "\n", "logc", ",", "err", ":=", "logging", ".", "NewClient", "(", "ctx", ",", "projID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "logc", ".", "Ping", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "logw", ":=", "writer", "{", "severity", ":", "logging", ".", "Debug", ",", "logger", ":", "logc", ".", "Logger", "(", "\"", "\"", ")", ",", "}", "\n", "return", "multiWriteCloser", "{", "w", ":", "io", ".", "MultiWriter", "(", "w", ",", "logw", ")", ",", "closer", ":", "logc", ",", "}", ",", "nil", "\n", "}" ]
// LogWriter returns an environment-specific io.WriteCloser suitable for passing // to log.SetOutput. It will also include writing to os.Stderr as well. // Since it might be writing to a Google Cloud Logger, it is the responsibility // of the caller to Close it when needed, to flush the last log entries.
[ "LogWriter", "returns", "an", "environment", "-", "specific", "io", ".", "WriteCloser", "suitable", "for", "passing", "to", "log", ".", "SetOutput", ".", "It", "will", "also", "include", "writing", "to", "os", ".", "Stderr", "as", "well", ".", "Since", "it", "might", "be", "writing", "to", "a", "Google", "Cloud", "Logger", "it", "is", "the", "responsibility", "of", "the", "caller", "to", "Close", "it", "when", "needed", "to", "flush", "the", "last", "log", "entries", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/osutil/gce/gce.go#L102-L145
train
perkeep/perkeep
internal/osutil/gce/gce.go
resetInstance
func resetInstance() error { if !env.OnGCE() { return errors.New("cannot reset instance if not on GCE") } ctx := context.Background() inst, err := gceInstance() if err != nil { return err } cs, projectID, zone, name := inst.cis, inst.projectID, inst.zone, inst.name call := cs.Reset(projectID, zone, name).Context(ctx) op, err := call.Do() if err != nil { if googleapi.IsNotModified(err) { return nil } return fmt.Errorf("error resetting instance: %v", err) } // TODO(mpl): refactor this whole pattern below into a func opName := op.Name for { select { case <-ctx.Done(): return ctx.Err() case <-time.After(500 * time.Millisecond): } op, err := inst.cs.ZoneOperations.Get(projectID, zone, opName).Context(ctx).Do() if err != nil { return fmt.Errorf("failed to get op %s: %v", opName, err) } switch op.Status { case "PENDING", "RUNNING": continue case "DONE": if op.Error != nil { for _, operr := range op.Error.Errors { log.Printf("operation error: %+v", operr) } return fmt.Errorf("operation error: %v", op.Error.Errors[0]) } log.Print("Successfully reset instance") return nil default: return fmt.Errorf("unknown operation status %q: %+v", op.Status, op) } } }
go
func resetInstance() error { if !env.OnGCE() { return errors.New("cannot reset instance if not on GCE") } ctx := context.Background() inst, err := gceInstance() if err != nil { return err } cs, projectID, zone, name := inst.cis, inst.projectID, inst.zone, inst.name call := cs.Reset(projectID, zone, name).Context(ctx) op, err := call.Do() if err != nil { if googleapi.IsNotModified(err) { return nil } return fmt.Errorf("error resetting instance: %v", err) } // TODO(mpl): refactor this whole pattern below into a func opName := op.Name for { select { case <-ctx.Done(): return ctx.Err() case <-time.After(500 * time.Millisecond): } op, err := inst.cs.ZoneOperations.Get(projectID, zone, opName).Context(ctx).Do() if err != nil { return fmt.Errorf("failed to get op %s: %v", opName, err) } switch op.Status { case "PENDING", "RUNNING": continue case "DONE": if op.Error != nil { for _, operr := range op.Error.Errors { log.Printf("operation error: %+v", operr) } return fmt.Errorf("operation error: %v", op.Error.Errors[0]) } log.Print("Successfully reset instance") return nil default: return fmt.Errorf("unknown operation status %q: %+v", op.Status, op) } } }
[ "func", "resetInstance", "(", ")", "error", "{", "if", "!", "env", ".", "OnGCE", "(", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "ctx", ":=", "context", ".", "Background", "(", ")", "\n\n", "inst", ",", "err", ":=", "gceInstance", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cs", ",", "projectID", ",", "zone", ",", "name", ":=", "inst", ".", "cis", ",", "inst", ".", "projectID", ",", "inst", ".", "zone", ",", "inst", ".", "name", "\n\n", "call", ":=", "cs", ".", "Reset", "(", "projectID", ",", "zone", ",", "name", ")", ".", "Context", "(", "ctx", ")", "\n", "op", ",", "err", ":=", "call", ".", "Do", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "googleapi", ".", "IsNotModified", "(", "err", ")", "{", "return", "nil", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "// TODO(mpl): refactor this whole pattern below into a func", "opName", ":=", "op", ".", "Name", "\n", "for", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "ctx", ".", "Err", "(", ")", "\n", "case", "<-", "time", ".", "After", "(", "500", "*", "time", ".", "Millisecond", ")", ":", "}", "\n", "op", ",", "err", ":=", "inst", ".", "cs", ".", "ZoneOperations", ".", "Get", "(", "projectID", ",", "zone", ",", "opName", ")", ".", "Context", "(", "ctx", ")", ".", "Do", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "opName", ",", "err", ")", "\n", "}", "\n", "switch", "op", ".", "Status", "{", "case", "\"", "\"", ",", "\"", "\"", ":", "continue", "\n", "case", "\"", "\"", ":", "if", "op", ".", "Error", "!=", "nil", "{", "for", "_", ",", "operr", ":=", "range", "op", ".", "Error", ".", "Errors", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "operr", ")", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "op", ".", "Error", ".", "Errors", "[", "0", "]", ")", "\n", "}", "\n", "log", ".", "Print", "(", "\"", "\"", ")", "\n", "return", "nil", "\n", "default", ":", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "op", ".", "Status", ",", "op", ")", "\n", "}", "\n", "}", "\n", "}" ]
// resetInstance reboots the GCE VM that this process is running in.
[ "resetInstance", "reboots", "the", "GCE", "VM", "that", "this", "process", "is", "running", "in", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/osutil/gce/gce.go#L188-L237
train
perkeep/perkeep
server/perkeepd/ui/goui/sharebutton/sharebutton.go
OnClick
func (d ShareItemsBtnDef) OnClick(e *react.SyntheticMouseEvent) { go func() { sharedURL, err := d.shareSelection() if err != nil { dom.GetWindow().Alert(fmt.Sprintf("%v", err)) return } prefix, err := d.urlPrefix() if err != nil { dom.GetWindow().Alert(fmt.Sprintf("Cannot display full share URL: %v", err)) return } sharedURL = prefix + sharedURL anchorText := sharedURL[:20] + "..." + sharedURL[len(sharedURL)-20:] // TODO(mpl): move some of the Dialog code to Go. d.Props().callbacks.ShowSharedURL(sharedURL, anchorText) }() }
go
func (d ShareItemsBtnDef) OnClick(e *react.SyntheticMouseEvent) { go func() { sharedURL, err := d.shareSelection() if err != nil { dom.GetWindow().Alert(fmt.Sprintf("%v", err)) return } prefix, err := d.urlPrefix() if err != nil { dom.GetWindow().Alert(fmt.Sprintf("Cannot display full share URL: %v", err)) return } sharedURL = prefix + sharedURL anchorText := sharedURL[:20] + "..." + sharedURL[len(sharedURL)-20:] // TODO(mpl): move some of the Dialog code to Go. d.Props().callbacks.ShowSharedURL(sharedURL, anchorText) }() }
[ "func", "(", "d", "ShareItemsBtnDef", ")", "OnClick", "(", "e", "*", "react", ".", "SyntheticMouseEvent", ")", "{", "go", "func", "(", ")", "{", "sharedURL", ",", "err", ":=", "d", ".", "shareSelection", "(", ")", "\n", "if", "err", "!=", "nil", "{", "dom", ".", "GetWindow", "(", ")", ".", "Alert", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "return", "\n", "}", "\n", "prefix", ",", "err", ":=", "d", ".", "urlPrefix", "(", ")", "\n", "if", "err", "!=", "nil", "{", "dom", ".", "GetWindow", "(", ")", ".", "Alert", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "return", "\n", "}", "\n", "sharedURL", "=", "prefix", "+", "sharedURL", "\n", "anchorText", ":=", "sharedURL", "[", ":", "20", "]", "+", "\"", "\"", "+", "sharedURL", "[", "len", "(", "sharedURL", ")", "-", "20", ":", "]", "\n", "// TODO(mpl): move some of the Dialog code to Go.", "d", ".", "Props", "(", ")", ".", "callbacks", ".", "ShowSharedURL", "(", "sharedURL", ",", "anchorText", ")", "\n", "}", "(", ")", "\n", "}" ]
// On success, handleShareSelection calls d.showSharedURL with the URL that can // be used to share the item. If the item is a file, the URL can be used directly // to fetch the file. If the item is a directory, the URL should be used with // pk-get -shared.
[ "On", "success", "handleShareSelection", "calls", "d", ".", "showSharedURL", "with", "the", "URL", "that", "can", "be", "used", "to", "share", "the", "item", ".", "If", "the", "item", "is", "a", "file", "the", "URL", "can", "be", "used", "directly", "to", "fetch", "the", "file", ".", "If", "the", "item", "is", "a", "directory", "the", "URL", "should", "be", "used", "with", "pk", "-", "get", "-", "shared", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/server/perkeepd/ui/goui/sharebutton/sharebutton.go#L166-L183
train
perkeep/perkeep
server/perkeepd/ui/goui/sharebutton/sharebutton.go
mkdir
func mkdir(am auth.AuthMode, children []blob.Ref) (blob.Ref, error) { cl, err := client.New(client.OptionAuthMode(am)) if err != nil { return blob.Ref{}, err } var newdir blob.Ref ss := schema.NewStaticSet() subsets := ss.SetStaticSetMembers(children) for _, v := range subsets { // TODO(mpl): make them concurrent if _, err := cl.UploadBlob(context.TODO(), v); err != nil { return newdir, err } } ssb := ss.Blob() if _, err := cl.UploadBlob(context.TODO(), ssb); err != nil { return newdir, err } const fileNameLayout = "20060102150405" fileName := "shared-" + time.Now().Format(fileNameLayout) dir := schema.NewDirMap(fileName).PopulateDirectoryMap(ssb.BlobRef()) dirBlob := dir.Blob() if _, err := cl.UploadBlob(context.TODO(), dirBlob); err != nil { return newdir, err } return dirBlob.BlobRef(), nil }
go
func mkdir(am auth.AuthMode, children []blob.Ref) (blob.Ref, error) { cl, err := client.New(client.OptionAuthMode(am)) if err != nil { return blob.Ref{}, err } var newdir blob.Ref ss := schema.NewStaticSet() subsets := ss.SetStaticSetMembers(children) for _, v := range subsets { // TODO(mpl): make them concurrent if _, err := cl.UploadBlob(context.TODO(), v); err != nil { return newdir, err } } ssb := ss.Blob() if _, err := cl.UploadBlob(context.TODO(), ssb); err != nil { return newdir, err } const fileNameLayout = "20060102150405" fileName := "shared-" + time.Now().Format(fileNameLayout) dir := schema.NewDirMap(fileName).PopulateDirectoryMap(ssb.BlobRef()) dirBlob := dir.Blob() if _, err := cl.UploadBlob(context.TODO(), dirBlob); err != nil { return newdir, err } return dirBlob.BlobRef(), nil }
[ "func", "mkdir", "(", "am", "auth", ".", "AuthMode", ",", "children", "[", "]", "blob", ".", "Ref", ")", "(", "blob", ".", "Ref", ",", "error", ")", "{", "cl", ",", "err", ":=", "client", ".", "New", "(", "client", ".", "OptionAuthMode", "(", "am", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "blob", ".", "Ref", "{", "}", ",", "err", "\n", "}", "\n", "var", "newdir", "blob", ".", "Ref", "\n", "ss", ":=", "schema", ".", "NewStaticSet", "(", ")", "\n", "subsets", ":=", "ss", ".", "SetStaticSetMembers", "(", "children", ")", "\n", "for", "_", ",", "v", ":=", "range", "subsets", "{", "// TODO(mpl): make them concurrent", "if", "_", ",", "err", ":=", "cl", ".", "UploadBlob", "(", "context", ".", "TODO", "(", ")", ",", "v", ")", ";", "err", "!=", "nil", "{", "return", "newdir", ",", "err", "\n", "}", "\n", "}", "\n", "ssb", ":=", "ss", ".", "Blob", "(", ")", "\n", "if", "_", ",", "err", ":=", "cl", ".", "UploadBlob", "(", "context", ".", "TODO", "(", ")", ",", "ssb", ")", ";", "err", "!=", "nil", "{", "return", "newdir", ",", "err", "\n", "}", "\n", "const", "fileNameLayout", "=", "\"", "\"", "\n", "fileName", ":=", "\"", "\"", "+", "time", ".", "Now", "(", ")", ".", "Format", "(", "fileNameLayout", ")", "\n", "dir", ":=", "schema", ".", "NewDirMap", "(", "fileName", ")", ".", "PopulateDirectoryMap", "(", "ssb", ".", "BlobRef", "(", ")", ")", "\n", "dirBlob", ":=", "dir", ".", "Blob", "(", ")", "\n", "if", "_", ",", "err", ":=", "cl", ".", "UploadBlob", "(", "context", ".", "TODO", "(", ")", ",", "dirBlob", ")", ";", "err", "!=", "nil", "{", "return", "newdir", ",", "err", "\n", "}", "\n\n", "return", "dirBlob", ".", "BlobRef", "(", ")", ",", "nil", "\n", "}" ]
// mkdir creates a new directory blob, with children composing its static-set, // and uploads it. It returns the blobRef of the new directory.
[ "mkdir", "creates", "a", "new", "directory", "blob", "with", "children", "composing", "its", "static", "-", "set", "and", "uploads", "it", ".", "It", "returns", "the", "blobRef", "of", "the", "new", "directory", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/server/perkeepd/ui/goui/sharebutton/sharebutton.go#L225-L252
train
perkeep/perkeep
server/perkeepd/ui/goui/sharebutton/sharebutton.go
shareFile
func shareFile(am auth.AuthMode, target blob.Ref, isDir bool) (string, error) { cl, err := client.New(client.OptionAuthMode(am)) if err != nil { return "", err } claim, err := newShareClaim(cl, target) if err != nil { return "", err } shareRoot, err := cl.ShareRoot() if err != nil { return "", err } if isDir { return fmt.Sprintf("%s%s", shareRoot, claim), nil } return fmt.Sprintf("%s%s?via=%s&assemble=1", shareRoot, target, claim), nil }
go
func shareFile(am auth.AuthMode, target blob.Ref, isDir bool) (string, error) { cl, err := client.New(client.OptionAuthMode(am)) if err != nil { return "", err } claim, err := newShareClaim(cl, target) if err != nil { return "", err } shareRoot, err := cl.ShareRoot() if err != nil { return "", err } if isDir { return fmt.Sprintf("%s%s", shareRoot, claim), nil } return fmt.Sprintf("%s%s?via=%s&assemble=1", shareRoot, target, claim), nil }
[ "func", "shareFile", "(", "am", "auth", ".", "AuthMode", ",", "target", "blob", ".", "Ref", ",", "isDir", "bool", ")", "(", "string", ",", "error", ")", "{", "cl", ",", "err", ":=", "client", ".", "New", "(", "client", ".", "OptionAuthMode", "(", "am", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "claim", ",", "err", ":=", "newShareClaim", "(", "cl", ",", "target", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "shareRoot", ",", "err", ":=", "cl", ".", "ShareRoot", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "if", "isDir", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "shareRoot", ",", "claim", ")", ",", "nil", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "shareRoot", ",", "target", ",", "claim", ")", ",", "nil", "\n", "}" ]
// shareFile returns the URL that can be used to share the target item. If the // item is a file, the URL can be used directly to fetch the file. If the item is a // directory, the URL should be used with pk-get -shared.
[ "shareFile", "returns", "the", "URL", "that", "can", "be", "used", "to", "share", "the", "target", "item", ".", "If", "the", "item", "is", "a", "file", "the", "URL", "can", "be", "used", "directly", "to", "fetch", "the", "file", ".", "If", "the", "item", "is", "a", "directory", "the", "URL", "should", "be", "used", "with", "pk", "-", "get", "-", "shared", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/server/perkeepd/ui/goui/sharebutton/sharebutton.go#L257-L274
train
perkeep/perkeep
server/perkeepd/ui/goui/sharebutton/sharebutton.go
newShareClaim
func newShareClaim(cl *client.Client, target blob.Ref) (blob.Ref, error) { var claim blob.Ref signer, err := cl.ServerPublicKeyBlobRef() if err != nil { return claim, fmt.Errorf("could not get signer: %v", err) } shareSchema := schema.NewShareRef(schema.ShareHaveRef, true) shareSchema.SetShareTarget(target) unsignedClaim, err := shareSchema.SetSigner(signer).JSON() if err != nil { return claim, fmt.Errorf("could not create unsigned share claim: %v", err) } signedClaim, err := cl.Sign(context.TODO(), "", strings.NewReader("json="+unsignedClaim)) if err != nil { return claim, fmt.Errorf("could not get signed share claim: %v", err) } sbr, err := cl.Upload(context.TODO(), client.NewUploadHandleFromString(string(signedClaim))) if err != nil { return claim, fmt.Errorf("could not upload share claim: %v", err) } return sbr.BlobRef, nil }
go
func newShareClaim(cl *client.Client, target blob.Ref) (blob.Ref, error) { var claim blob.Ref signer, err := cl.ServerPublicKeyBlobRef() if err != nil { return claim, fmt.Errorf("could not get signer: %v", err) } shareSchema := schema.NewShareRef(schema.ShareHaveRef, true) shareSchema.SetShareTarget(target) unsignedClaim, err := shareSchema.SetSigner(signer).JSON() if err != nil { return claim, fmt.Errorf("could not create unsigned share claim: %v", err) } signedClaim, err := cl.Sign(context.TODO(), "", strings.NewReader("json="+unsignedClaim)) if err != nil { return claim, fmt.Errorf("could not get signed share claim: %v", err) } sbr, err := cl.Upload(context.TODO(), client.NewUploadHandleFromString(string(signedClaim))) if err != nil { return claim, fmt.Errorf("could not upload share claim: %v", err) } return sbr.BlobRef, nil }
[ "func", "newShareClaim", "(", "cl", "*", "client", ".", "Client", ",", "target", "blob", ".", "Ref", ")", "(", "blob", ".", "Ref", ",", "error", ")", "{", "var", "claim", "blob", ".", "Ref", "\n", "signer", ",", "err", ":=", "cl", ".", "ServerPublicKeyBlobRef", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "claim", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "shareSchema", ":=", "schema", ".", "NewShareRef", "(", "schema", ".", "ShareHaveRef", ",", "true", ")", "\n", "shareSchema", ".", "SetShareTarget", "(", "target", ")", "\n", "unsignedClaim", ",", "err", ":=", "shareSchema", ".", "SetSigner", "(", "signer", ")", ".", "JSON", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "claim", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "signedClaim", ",", "err", ":=", "cl", ".", "Sign", "(", "context", ".", "TODO", "(", ")", ",", "\"", "\"", ",", "strings", ".", "NewReader", "(", "\"", "\"", "+", "unsignedClaim", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "claim", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "sbr", ",", "err", ":=", "cl", ".", "Upload", "(", "context", ".", "TODO", "(", ")", ",", "client", ".", "NewUploadHandleFromString", "(", "string", "(", "signedClaim", ")", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "claim", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "sbr", ".", "BlobRef", ",", "nil", "\n", "}" ]
// newShareClaim creates, signs, and uploads a transitive haveref share claim // for sharing the target item. It returns the ref of the claim.
[ "newShareClaim", "creates", "signs", "and", "uploads", "a", "transitive", "haveref", "share", "claim", "for", "sharing", "the", "target", "item", ".", "It", "returns", "the", "ref", "of", "the", "claim", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/server/perkeepd/ui/goui/sharebutton/sharebutton.go#L278-L299
train
perkeep/perkeep
pkg/importer/gphotos/download.go
fileAsPhoto
func (dl *downloader) fileAsPhoto(f *drive.File) *photo { if f == nil { return nil } if f.Size == 0 { // anything non-binary can't be a photo, so skip it. return nil } if !inPhotoSpace(f) { // not a photo return nil } p := &photo{ ID: f.Id, Name: f.Name, Starred: f.Starred, Version: f.Version, MimeType: f.MimeType, Properties: f.Properties, Description: f.Description, WebContentLink: f.WebContentLink, OriginalFilename: f.OriginalFilename, } if f.ImageMediaMetadata != nil { p.FileImageMediaMetadata = *f.ImageMediaMetadata } if f.CreatedTime != "" { p.CreatedTime, _ = time.Parse(time.RFC3339, f.CreatedTime) } if f.ModifiedTime != "" { p.ModifiedTime, _ = time.Parse(time.RFC3339, f.ModifiedTime) } return p }
go
func (dl *downloader) fileAsPhoto(f *drive.File) *photo { if f == nil { return nil } if f.Size == 0 { // anything non-binary can't be a photo, so skip it. return nil } if !inPhotoSpace(f) { // not a photo return nil } p := &photo{ ID: f.Id, Name: f.Name, Starred: f.Starred, Version: f.Version, MimeType: f.MimeType, Properties: f.Properties, Description: f.Description, WebContentLink: f.WebContentLink, OriginalFilename: f.OriginalFilename, } if f.ImageMediaMetadata != nil { p.FileImageMediaMetadata = *f.ImageMediaMetadata } if f.CreatedTime != "" { p.CreatedTime, _ = time.Parse(time.RFC3339, f.CreatedTime) } if f.ModifiedTime != "" { p.ModifiedTime, _ = time.Parse(time.RFC3339, f.ModifiedTime) } return p }
[ "func", "(", "dl", "*", "downloader", ")", "fileAsPhoto", "(", "f", "*", "drive", ".", "File", ")", "*", "photo", "{", "if", "f", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "if", "f", ".", "Size", "==", "0", "{", "// anything non-binary can't be a photo, so skip it.", "return", "nil", "\n", "}", "\n", "if", "!", "inPhotoSpace", "(", "f", ")", "{", "// not a photo", "return", "nil", "\n", "}", "\n", "p", ":=", "&", "photo", "{", "ID", ":", "f", ".", "Id", ",", "Name", ":", "f", ".", "Name", ",", "Starred", ":", "f", ".", "Starred", ",", "Version", ":", "f", ".", "Version", ",", "MimeType", ":", "f", ".", "MimeType", ",", "Properties", ":", "f", ".", "Properties", ",", "Description", ":", "f", ".", "Description", ",", "WebContentLink", ":", "f", ".", "WebContentLink", ",", "OriginalFilename", ":", "f", ".", "OriginalFilename", ",", "}", "\n", "if", "f", ".", "ImageMediaMetadata", "!=", "nil", "{", "p", ".", "FileImageMediaMetadata", "=", "*", "f", ".", "ImageMediaMetadata", "\n", "}", "\n", "if", "f", ".", "CreatedTime", "!=", "\"", "\"", "{", "p", ".", "CreatedTime", ",", "_", "=", "time", ".", "Parse", "(", "time", ".", "RFC3339", ",", "f", ".", "CreatedTime", ")", "\n", "}", "\n", "if", "f", ".", "ModifiedTime", "!=", "\"", "\"", "{", "p", ".", "ModifiedTime", ",", "_", "=", "time", ".", "Parse", "(", "time", ".", "RFC3339", ",", "f", ".", "ModifiedTime", ")", "\n", "}", "\n\n", "return", "p", "\n", "}" ]
// fileAsPhoto returns a photo populated with the information found about f, // or nil if f is not actually a photo from Google Photos. // // The returned photo contains only the metadata; // the content of the photo can be downloaded with dl.openPhoto.
[ "fileAsPhoto", "returns", "a", "photo", "populated", "with", "the", "information", "found", "about", "f", "or", "nil", "if", "f", "is", "not", "actually", "a", "photo", "from", "Google", "Photos", ".", "The", "returned", "photo", "contains", "only", "the", "metadata", ";", "the", "content", "of", "the", "photo", "can", "be", "downloaded", "with", "dl", ".", "openPhoto", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/gphotos/download.go#L281-L315
train
perkeep/perkeep
pkg/importer/gphotos/download.go
rateLimit
func (dl *downloader) rateLimit(ctx context.Context, f func() error) error { const ( msgRateLimitExceeded = "Rate Limit Exceeded" msgUserRateLimitExceeded = "User Rate Limit Exceeded" msgUserRateLimitExceededShort = "userRateLimitExceeded" ) // Ensure a 1 minute try limit. ctx, cancel := context.WithTimeout(ctx, time.Minute) defer cancel() for { if err := dl.rate.Wait(ctx); err != nil { log.Printf("gphotos: rate limit failure: %v", err) return err } err := f() if err == nil { return nil } ge, ok := err.(*googleapi.Error) if !ok || ge.Code != 403 { return err } if ge.Message == "" { var ok bool for _, e := range ge.Errors { if ok = e.Reason == msgUserRateLimitExceededShort; ok { break } } // For some cases, googleapi does not parse the returned JSON // properly, so we have to fall back to check the original text. // // Usually this is a "User Rate Limit Exceeded", but that's // also a "Rate Limit Exceeded", and we're interested just in the // fact, not the cause. if !ok && !strings.Contains(ge.Body, msgRateLimitExceeded) { return err } } // Some arbitrary sleep. log.Printf("gphotos: sleeping for 5s after 403 error, presumably due to a rate limit") time.Sleep(5 * time.Second) log.Printf("gphotos: retrying after sleep...") } }
go
func (dl *downloader) rateLimit(ctx context.Context, f func() error) error { const ( msgRateLimitExceeded = "Rate Limit Exceeded" msgUserRateLimitExceeded = "User Rate Limit Exceeded" msgUserRateLimitExceededShort = "userRateLimitExceeded" ) // Ensure a 1 minute try limit. ctx, cancel := context.WithTimeout(ctx, time.Minute) defer cancel() for { if err := dl.rate.Wait(ctx); err != nil { log.Printf("gphotos: rate limit failure: %v", err) return err } err := f() if err == nil { return nil } ge, ok := err.(*googleapi.Error) if !ok || ge.Code != 403 { return err } if ge.Message == "" { var ok bool for _, e := range ge.Errors { if ok = e.Reason == msgUserRateLimitExceededShort; ok { break } } // For some cases, googleapi does not parse the returned JSON // properly, so we have to fall back to check the original text. // // Usually this is a "User Rate Limit Exceeded", but that's // also a "Rate Limit Exceeded", and we're interested just in the // fact, not the cause. if !ok && !strings.Contains(ge.Body, msgRateLimitExceeded) { return err } } // Some arbitrary sleep. log.Printf("gphotos: sleeping for 5s after 403 error, presumably due to a rate limit") time.Sleep(5 * time.Second) log.Printf("gphotos: retrying after sleep...") } }
[ "func", "(", "dl", "*", "downloader", ")", "rateLimit", "(", "ctx", "context", ".", "Context", ",", "f", "func", "(", ")", "error", ")", "error", "{", "const", "(", "msgRateLimitExceeded", "=", "\"", "\"", "\n", "msgUserRateLimitExceeded", "=", "\"", "\"", "\n", "msgUserRateLimitExceededShort", "=", "\"", "\"", "\n", ")", "\n\n", "// Ensure a 1 minute try limit.", "ctx", ",", "cancel", ":=", "context", ".", "WithTimeout", "(", "ctx", ",", "time", ".", "Minute", ")", "\n", "defer", "cancel", "(", ")", "\n", "for", "{", "if", "err", ":=", "dl", ".", "rate", ".", "Wait", "(", "ctx", ")", ";", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n", "err", ":=", "f", "(", ")", "\n", "if", "err", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "ge", ",", "ok", ":=", "err", ".", "(", "*", "googleapi", ".", "Error", ")", "\n", "if", "!", "ok", "||", "ge", ".", "Code", "!=", "403", "{", "return", "err", "\n", "}", "\n", "if", "ge", ".", "Message", "==", "\"", "\"", "{", "var", "ok", "bool", "\n", "for", "_", ",", "e", ":=", "range", "ge", ".", "Errors", "{", "if", "ok", "=", "e", ".", "Reason", "==", "msgUserRateLimitExceededShort", ";", "ok", "{", "break", "\n", "}", "\n", "}", "\n", "// For some cases, googleapi does not parse the returned JSON", "// properly, so we have to fall back to check the original text.", "//", "// Usually this is a \"User Rate Limit Exceeded\", but that's", "// also a \"Rate Limit Exceeded\", and we're interested just in the", "// fact, not the cause.", "if", "!", "ok", "&&", "!", "strings", ".", "Contains", "(", "ge", ".", "Body", ",", "msgRateLimitExceeded", ")", "{", "return", "err", "\n", "}", "\n", "}", "\n", "// Some arbitrary sleep.", "log", ".", "Printf", "(", "\"", "\"", ")", "\n", "time", ".", "Sleep", "(", "5", "*", "time", ".", "Second", ")", "\n", "log", ".", "Printf", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// rateLimit calls f obeying the global Rate limit. // On "Rate Limit Exceeded" error, it sleeps and tries later.
[ "rateLimit", "calls", "f", "obeying", "the", "global", "Rate", "limit", ".", "On", "Rate", "Limit", "Exceeded", "error", "it", "sleeps", "and", "tries", "later", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/gphotos/download.go#L319-L364
train
perkeep/perkeep
internal/magic/magic.go
MIMEType
func MIMEType(hdr []byte) string { hlen := len(hdr) for _, pte := range matchTable { if pte.fn != nil { if pte.fn(hdr) { return pte.mtype } continue } plen := pte.offset + len(pte.prefix) if hlen > plen && bytes.Equal(hdr[pte.offset:plen], pte.prefix) { return pte.mtype } } t := http.DetectContentType(hdr) t = strings.Replace(t, "; charset=utf-8", "", 1) if t != "application/octet-stream" && t != "text/plain" { return t } return "" }
go
func MIMEType(hdr []byte) string { hlen := len(hdr) for _, pte := range matchTable { if pte.fn != nil { if pte.fn(hdr) { return pte.mtype } continue } plen := pte.offset + len(pte.prefix) if hlen > plen && bytes.Equal(hdr[pte.offset:plen], pte.prefix) { return pte.mtype } } t := http.DetectContentType(hdr) t = strings.Replace(t, "; charset=utf-8", "", 1) if t != "application/octet-stream" && t != "text/plain" { return t } return "" }
[ "func", "MIMEType", "(", "hdr", "[", "]", "byte", ")", "string", "{", "hlen", ":=", "len", "(", "hdr", ")", "\n", "for", "_", ",", "pte", ":=", "range", "matchTable", "{", "if", "pte", ".", "fn", "!=", "nil", "{", "if", "pte", ".", "fn", "(", "hdr", ")", "{", "return", "pte", ".", "mtype", "\n", "}", "\n", "continue", "\n", "}", "\n", "plen", ":=", "pte", ".", "offset", "+", "len", "(", "pte", ".", "prefix", ")", "\n", "if", "hlen", ">", "plen", "&&", "bytes", ".", "Equal", "(", "hdr", "[", "pte", ".", "offset", ":", "plen", "]", ",", "pte", ".", "prefix", ")", "{", "return", "pte", ".", "mtype", "\n", "}", "\n", "}", "\n", "t", ":=", "http", ".", "DetectContentType", "(", "hdr", ")", "\n", "t", "=", "strings", ".", "Replace", "(", "t", ",", "\"", "\"", ",", "\"", "\"", ",", "1", ")", "\n", "if", "t", "!=", "\"", "\"", "&&", "t", "!=", "\"", "\"", "{", "return", "t", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// MIMEType returns the MIME type from the data in the provided header // of the data. // It returns the empty string if the MIME type can't be determined.
[ "MIMEType", "returns", "the", "MIME", "type", "from", "the", "data", "in", "the", "provided", "header", "of", "the", "data", ".", "It", "returns", "the", "empty", "string", "if", "the", "MIME", "type", "can", "t", "be", "determined", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/magic/magic.go#L173-L193
train
perkeep/perkeep
internal/magic/magic.go
MIMETypeFromReaderAt
func MIMETypeFromReaderAt(ra io.ReaderAt) (mime string) { var buf [1024]byte n, _ := ra.ReadAt(buf[:], 0) return MIMEType(buf[:n]) }
go
func MIMETypeFromReaderAt(ra io.ReaderAt) (mime string) { var buf [1024]byte n, _ := ra.ReadAt(buf[:], 0) return MIMEType(buf[:n]) }
[ "func", "MIMETypeFromReaderAt", "(", "ra", "io", ".", "ReaderAt", ")", "(", "mime", "string", ")", "{", "var", "buf", "[", "1024", "]", "byte", "\n", "n", ",", "_", ":=", "ra", ".", "ReadAt", "(", "buf", "[", ":", "]", ",", "0", ")", "\n", "return", "MIMEType", "(", "buf", "[", ":", "n", "]", ")", "\n", "}" ]
// MIMETypeFromReaderAt takes a ReaderAt, sniffs the beginning of it, // and returns the MIME type if sniffed, else the empty string.
[ "MIMETypeFromReaderAt", "takes", "a", "ReaderAt", "sniffs", "the", "beginning", "of", "it", "and", "returns", "the", "MIME", "type", "if", "sniffed", "else", "the", "empty", "string", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/magic/magic.go#L211-L215
train
perkeep/perkeep
internal/magic/magic.go
HasExtension
func HasExtension(filename string, extensions map[string]bool) bool { var ext string if e := filepath.Ext(filename); strings.HasPrefix(e, ".") { ext = e[1:] } else { return false } // Case-insensitive lookup. // Optimistically assume a short ASCII extension and be // allocation-free in that case. var buf [10]byte lower := buf[:0] const utf8RuneSelf = 0x80 // from utf8 package, but not importing it. for i := 0; i < len(ext); i++ { c := ext[i] if c >= utf8RuneSelf { // Slow path. return extensions[strings.ToLower(ext)] } if 'A' <= c && c <= 'Z' { lower = append(lower, c+('a'-'A')) } else { lower = append(lower, c) } } // The conversion from []byte to string doesn't allocate in // a map lookup. return extensions[string(lower)] }
go
func HasExtension(filename string, extensions map[string]bool) bool { var ext string if e := filepath.Ext(filename); strings.HasPrefix(e, ".") { ext = e[1:] } else { return false } // Case-insensitive lookup. // Optimistically assume a short ASCII extension and be // allocation-free in that case. var buf [10]byte lower := buf[:0] const utf8RuneSelf = 0x80 // from utf8 package, but not importing it. for i := 0; i < len(ext); i++ { c := ext[i] if c >= utf8RuneSelf { // Slow path. return extensions[strings.ToLower(ext)] } if 'A' <= c && c <= 'Z' { lower = append(lower, c+('a'-'A')) } else { lower = append(lower, c) } } // The conversion from []byte to string doesn't allocate in // a map lookup. return extensions[string(lower)] }
[ "func", "HasExtension", "(", "filename", "string", ",", "extensions", "map", "[", "string", "]", "bool", ")", "bool", "{", "var", "ext", "string", "\n", "if", "e", ":=", "filepath", ".", "Ext", "(", "filename", ")", ";", "strings", ".", "HasPrefix", "(", "e", ",", "\"", "\"", ")", "{", "ext", "=", "e", "[", "1", ":", "]", "\n", "}", "else", "{", "return", "false", "\n", "}", "\n\n", "// Case-insensitive lookup.", "// Optimistically assume a short ASCII extension and be", "// allocation-free in that case.", "var", "buf", "[", "10", "]", "byte", "\n", "lower", ":=", "buf", "[", ":", "0", "]", "\n", "const", "utf8RuneSelf", "=", "0x80", "// from utf8 package, but not importing it.", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "ext", ")", ";", "i", "++", "{", "c", ":=", "ext", "[", "i", "]", "\n", "if", "c", ">=", "utf8RuneSelf", "{", "// Slow path.", "return", "extensions", "[", "strings", ".", "ToLower", "(", "ext", ")", "]", "\n", "}", "\n", "if", "'A'", "<=", "c", "&&", "c", "<=", "'Z'", "{", "lower", "=", "append", "(", "lower", ",", "c", "+", "(", "'a'", "-", "'A'", ")", ")", "\n", "}", "else", "{", "lower", "=", "append", "(", "lower", ",", "c", ")", "\n", "}", "\n", "}", "\n", "// The conversion from []byte to string doesn't allocate in", "// a map lookup.", "return", "extensions", "[", "string", "(", "lower", ")", "]", "\n", "}" ]
// HasExtension returns whether the file extension of filename is among // extensions. It is a case-insensitive lookup, optimized for the ASCII case.
[ "HasExtension", "returns", "whether", "the", "file", "extension", "of", "filename", "is", "among", "extensions", ".", "It", "is", "a", "case", "-", "insensitive", "lookup", "optimized", "for", "the", "ASCII", "case", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/magic/magic.go#L235-L264
train
perkeep/perkeep
internal/magic/magic.go
MIMETypeByExtension
func MIMETypeByExtension(ext string) string { mimeParts := strings.SplitN(mime.TypeByExtension(ext), ";", 2) return strings.TrimSpace(mimeParts[0]) }
go
func MIMETypeByExtension(ext string) string { mimeParts := strings.SplitN(mime.TypeByExtension(ext), ";", 2) return strings.TrimSpace(mimeParts[0]) }
[ "func", "MIMETypeByExtension", "(", "ext", "string", ")", "string", "{", "mimeParts", ":=", "strings", ".", "SplitN", "(", "mime", ".", "TypeByExtension", "(", "ext", ")", ",", "\"", "\"", ",", "2", ")", "\n", "return", "strings", ".", "TrimSpace", "(", "mimeParts", "[", "0", "]", ")", "\n", "}" ]
// MIMETypeByExtension calls mime.TypeByExtension, and removes optional parameters, // to keep only the type and subtype.
[ "MIMETypeByExtension", "calls", "mime", ".", "TypeByExtension", "and", "removes", "optional", "parameters", "to", "keep", "only", "the", "type", "and", "subtype", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/magic/magic.go#L268-L271
train
perkeep/perkeep
pkg/blobserver/blobpacked/blobpacked.go
checkLargeIntegrity
func (s *storage) checkLargeIntegrity() (RecoveryMode, error) { inLarge := 0 var missing []blob.Ref // blobs in large but not in meta var extra []blob.Ref // blobs in meta but not in large t := s.meta.Find(zipMetaPrefix, zipMetaPrefixLimit) defer t.Close() iterate := true var enumFunc func(sb blob.SizedRef) error enumFunc = func(sb blob.SizedRef) error { if iterate && !t.Next() { // all of the yet to be enumerated are missing from meta missing = append(missing, sb.Ref) return nil } iterate = true wantMetaKey := zipMetaPrefix + sb.Ref.String() metaKey := t.Key() if metaKey != wantMetaKey { if metaKey > wantMetaKey { // zipRef missing from meta missing = append(missing, sb.Ref) iterate = false return nil } // zipRef in meta that actually does not exist in s.large. xbr, ok := blob.Parse(strings.TrimPrefix(metaKey, zipMetaPrefix)) if !ok { return fmt.Errorf("boggus key in z: row: %q", metaKey) } extra = append(extra, xbr) // iterate meta once more at the same storage enumeration point return enumFunc(sb) } if _, err := parseZipMetaRow(t.ValueBytes()); err != nil { return fmt.Errorf("error parsing row from meta: %v", err) } inLarge++ return nil } log.Printf("blobpacked: checking integrity of packed blobs against index...") if err := blobserver.EnumerateAllFrom(context.Background(), s.large, "", enumFunc); err != nil { return FullRecovery, err } log.Printf("blobpacked: %d large blobs found in index, %d missing from index", inLarge, len(missing)) if len(missing) > 0 { printSample(missing, "missing") } if len(extra) > 0 { printSample(extra, "extra") return FullRecovery, fmt.Errorf("%d large blobs in index but not actually in storage", len(extra)) } if err := t.Close(); err != nil { return FullRecovery, fmt.Errorf("error reading or closing index: %v", err) } if len(missing) > 0 { return FastRecovery, fmt.Errorf("%d large blobs missing from index", len(missing)) } return NoRecovery, nil }
go
func (s *storage) checkLargeIntegrity() (RecoveryMode, error) { inLarge := 0 var missing []blob.Ref // blobs in large but not in meta var extra []blob.Ref // blobs in meta but not in large t := s.meta.Find(zipMetaPrefix, zipMetaPrefixLimit) defer t.Close() iterate := true var enumFunc func(sb blob.SizedRef) error enumFunc = func(sb blob.SizedRef) error { if iterate && !t.Next() { // all of the yet to be enumerated are missing from meta missing = append(missing, sb.Ref) return nil } iterate = true wantMetaKey := zipMetaPrefix + sb.Ref.String() metaKey := t.Key() if metaKey != wantMetaKey { if metaKey > wantMetaKey { // zipRef missing from meta missing = append(missing, sb.Ref) iterate = false return nil } // zipRef in meta that actually does not exist in s.large. xbr, ok := blob.Parse(strings.TrimPrefix(metaKey, zipMetaPrefix)) if !ok { return fmt.Errorf("boggus key in z: row: %q", metaKey) } extra = append(extra, xbr) // iterate meta once more at the same storage enumeration point return enumFunc(sb) } if _, err := parseZipMetaRow(t.ValueBytes()); err != nil { return fmt.Errorf("error parsing row from meta: %v", err) } inLarge++ return nil } log.Printf("blobpacked: checking integrity of packed blobs against index...") if err := blobserver.EnumerateAllFrom(context.Background(), s.large, "", enumFunc); err != nil { return FullRecovery, err } log.Printf("blobpacked: %d large blobs found in index, %d missing from index", inLarge, len(missing)) if len(missing) > 0 { printSample(missing, "missing") } if len(extra) > 0 { printSample(extra, "extra") return FullRecovery, fmt.Errorf("%d large blobs in index but not actually in storage", len(extra)) } if err := t.Close(); err != nil { return FullRecovery, fmt.Errorf("error reading or closing index: %v", err) } if len(missing) > 0 { return FastRecovery, fmt.Errorf("%d large blobs missing from index", len(missing)) } return NoRecovery, nil }
[ "func", "(", "s", "*", "storage", ")", "checkLargeIntegrity", "(", ")", "(", "RecoveryMode", ",", "error", ")", "{", "inLarge", ":=", "0", "\n", "var", "missing", "[", "]", "blob", ".", "Ref", "// blobs in large but not in meta", "\n", "var", "extra", "[", "]", "blob", ".", "Ref", "// blobs in meta but not in large", "\n", "t", ":=", "s", ".", "meta", ".", "Find", "(", "zipMetaPrefix", ",", "zipMetaPrefixLimit", ")", "\n", "defer", "t", ".", "Close", "(", ")", "\n", "iterate", ":=", "true", "\n", "var", "enumFunc", "func", "(", "sb", "blob", ".", "SizedRef", ")", "error", "\n", "enumFunc", "=", "func", "(", "sb", "blob", ".", "SizedRef", ")", "error", "{", "if", "iterate", "&&", "!", "t", ".", "Next", "(", ")", "{", "// all of the yet to be enumerated are missing from meta", "missing", "=", "append", "(", "missing", ",", "sb", ".", "Ref", ")", "\n", "return", "nil", "\n", "}", "\n", "iterate", "=", "true", "\n", "wantMetaKey", ":=", "zipMetaPrefix", "+", "sb", ".", "Ref", ".", "String", "(", ")", "\n", "metaKey", ":=", "t", ".", "Key", "(", ")", "\n", "if", "metaKey", "!=", "wantMetaKey", "{", "if", "metaKey", ">", "wantMetaKey", "{", "// zipRef missing from meta", "missing", "=", "append", "(", "missing", ",", "sb", ".", "Ref", ")", "\n", "iterate", "=", "false", "\n", "return", "nil", "\n", "}", "\n", "// zipRef in meta that actually does not exist in s.large.", "xbr", ",", "ok", ":=", "blob", ".", "Parse", "(", "strings", ".", "TrimPrefix", "(", "metaKey", ",", "zipMetaPrefix", ")", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "metaKey", ")", "\n", "}", "\n", "extra", "=", "append", "(", "extra", ",", "xbr", ")", "\n", "// iterate meta once more at the same storage enumeration point", "return", "enumFunc", "(", "sb", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "parseZipMetaRow", "(", "t", ".", "ValueBytes", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "inLarge", "++", "\n", "return", "nil", "\n", "}", "\n", "log", ".", "Printf", "(", "\"", "\"", ")", "\n", "if", "err", ":=", "blobserver", ".", "EnumerateAllFrom", "(", "context", ".", "Background", "(", ")", ",", "s", ".", "large", ",", "\"", "\"", ",", "enumFunc", ")", ";", "err", "!=", "nil", "{", "return", "FullRecovery", ",", "err", "\n", "}", "\n", "log", ".", "Printf", "(", "\"", "\"", ",", "inLarge", ",", "len", "(", "missing", ")", ")", "\n", "if", "len", "(", "missing", ")", ">", "0", "{", "printSample", "(", "missing", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "extra", ")", ">", "0", "{", "printSample", "(", "extra", ",", "\"", "\"", ")", "\n", "return", "FullRecovery", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "extra", ")", ")", "\n", "}", "\n", "if", "err", ":=", "t", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "FullRecovery", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "len", "(", "missing", ")", ">", "0", "{", "return", "FastRecovery", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "missing", ")", ")", "\n", "}", "\n", "return", "NoRecovery", ",", "nil", "\n", "}" ]
// checkLargeIntegrity verifies that all large blobs in the large storage are // indexed in meta, and vice-versa, that all rows in meta referring to a large blob // correspond to an existing large blob in the large storage. If any of the above // is not true, it returns the recovery mode that should be used to fix the // problem, as well as the error detailing the problem. It does not perform any // check about the contents of the large blobs themselves.
[ "checkLargeIntegrity", "verifies", "that", "all", "large", "blobs", "in", "the", "large", "storage", "are", "indexed", "in", "meta", "and", "vice", "-", "versa", "that", "all", "rows", "in", "meta", "referring", "to", "a", "large", "blob", "correspond", "to", "an", "existing", "large", "blob", "in", "the", "large", "storage", ".", "If", "any", "of", "the", "above", "is", "not", "true", "it", "returns", "the", "recovery", "mode", "that", "should", "be", "used", "to", "fix", "the", "problem", "as", "well", "as", "the", "error", "detailing", "the", "problem", ".", "It", "does", "not", "perform", "any", "check", "about", "the", "contents", "of", "the", "large", "blobs", "themselves", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/blobpacked/blobpacked.go#L383-L441
train
perkeep/perkeep
pkg/blobserver/blobpacked/blobpacked.go
getMetaRow
func (s *storage) getMetaRow(br blob.Ref) (meta, error) { v, err := s.meta.Get(blobMetaPrefix + br.String()) if err == sorted.ErrNotFound { return meta{}, nil } if err != nil { return meta{}, fmt.Errorf("blobpacked.getMetaRow(%v) = %v", br, err) } return parseMetaRow([]byte(v)) }
go
func (s *storage) getMetaRow(br blob.Ref) (meta, error) { v, err := s.meta.Get(blobMetaPrefix + br.String()) if err == sorted.ErrNotFound { return meta{}, nil } if err != nil { return meta{}, fmt.Errorf("blobpacked.getMetaRow(%v) = %v", br, err) } return parseMetaRow([]byte(v)) }
[ "func", "(", "s", "*", "storage", ")", "getMetaRow", "(", "br", "blob", ".", "Ref", ")", "(", "meta", ",", "error", ")", "{", "v", ",", "err", ":=", "s", ".", "meta", ".", "Get", "(", "blobMetaPrefix", "+", "br", ".", "String", "(", ")", ")", "\n", "if", "err", "==", "sorted", ".", "ErrNotFound", "{", "return", "meta", "{", "}", ",", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "meta", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "br", ",", "err", ")", "\n", "}", "\n", "return", "parseMetaRow", "(", "[", "]", "byte", "(", "v", ")", ")", "\n", "}" ]
// if not found, err == nil.
[ "if", "not", "found", "err", "==", "nil", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/blobpacked/blobpacked.go#L841-L850
train
perkeep/perkeep
pkg/blobserver/blobpacked/blobpacked.go
check
func check(err error) { if err != nil { b := make([]byte, 2<<10) b = b[:runtime.Stack(b, false)] log.Printf("Unlikely error condition triggered: %v at %s", err, b) panic(err) } }
go
func check(err error) { if err != nil { b := make([]byte, 2<<10) b = b[:runtime.Stack(b, false)] log.Printf("Unlikely error condition triggered: %v at %s", err, b) panic(err) } }
[ "func", "check", "(", "err", "error", ")", "{", "if", "err", "!=", "nil", "{", "b", ":=", "make", "(", "[", "]", "byte", ",", "2", "<<", "10", ")", "\n", "b", "=", "b", "[", ":", "runtime", ".", "Stack", "(", "b", ",", "false", ")", "]", "\n", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ",", "b", ")", "\n", "panic", "(", "err", ")", "\n", "}", "\n", "}" ]
// check should only be used for things which really shouldn't ever happen, but should // still be checked. If there is interesting logic in the 'else', then don't use this.
[ "check", "should", "only", "be", "used", "for", "things", "which", "really", "shouldn", "t", "ever", "happen", "but", "should", "still", "be", "checked", ".", "If", "there", "is", "interesting", "logic", "in", "the", "else", "then", "don", "t", "use", "this", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/blobpacked/blobpacked.go#L1297-L1304
train
perkeep/perkeep
pkg/blobserver/blobpacked/blobpacked.go
foreachZipBlob
func (s *storage) foreachZipBlob(ctx context.Context, zipRef blob.Ref, fn func(BlobAndPos) error) error { sb, err := blobserver.StatBlob(ctx, s.large, zipRef) if err != nil { return err } zr, err := zip.NewReader(blob.ReaderAt(ctx, s.large, zipRef), int64(sb.Size)) if err != nil { return zipOpenError{zipRef, err} } var maniFile *zip.File // or nil if not found var firstOff int64 // offset of first file (the packed data chunks) for i, f := range zr.File { if i == 0 { firstOff, err = f.DataOffset() if err != nil { return err } } if f.Name == zipManifestPath { maniFile = f break } } if maniFile == nil { return errors.New("no camlistore manifest file found in zip") } // apply fn to all the schema blobs for _, f := range zr.File { if !strings.HasPrefix(f.Name, "camlistore/") || f.Name == zipManifestPath || !strings.HasSuffix(f.Name, ".json") { continue } brStr := strings.TrimSuffix(strings.TrimPrefix(f.Name, "camlistore/"), ".json") br, ok := blob.Parse(brStr) if ok { off, err := f.DataOffset() if err != nil { return err } if err := fn(BlobAndPos{ SizedRef: blob.SizedRef{Ref: br, Size: uint32(f.UncompressedSize64)}, Offset: off, }); err != nil { return err } } } maniRC, err := maniFile.Open() if err != nil { return err } defer maniRC.Close() var mf Manifest if err := json.NewDecoder(maniRC).Decode(&mf); err != nil { return err } if !mf.WholeRef.Valid() || mf.WholeSize == 0 || !mf.DataBlobsOrigin.Valid() { return errors.New("incomplete blobpack manifest JSON") } // apply fn to all the data blobs for _, bap := range mf.DataBlobs { bap.Offset += firstOff if err := fn(bap); err != nil { return err } } return nil }
go
func (s *storage) foreachZipBlob(ctx context.Context, zipRef blob.Ref, fn func(BlobAndPos) error) error { sb, err := blobserver.StatBlob(ctx, s.large, zipRef) if err != nil { return err } zr, err := zip.NewReader(blob.ReaderAt(ctx, s.large, zipRef), int64(sb.Size)) if err != nil { return zipOpenError{zipRef, err} } var maniFile *zip.File // or nil if not found var firstOff int64 // offset of first file (the packed data chunks) for i, f := range zr.File { if i == 0 { firstOff, err = f.DataOffset() if err != nil { return err } } if f.Name == zipManifestPath { maniFile = f break } } if maniFile == nil { return errors.New("no camlistore manifest file found in zip") } // apply fn to all the schema blobs for _, f := range zr.File { if !strings.HasPrefix(f.Name, "camlistore/") || f.Name == zipManifestPath || !strings.HasSuffix(f.Name, ".json") { continue } brStr := strings.TrimSuffix(strings.TrimPrefix(f.Name, "camlistore/"), ".json") br, ok := blob.Parse(brStr) if ok { off, err := f.DataOffset() if err != nil { return err } if err := fn(BlobAndPos{ SizedRef: blob.SizedRef{Ref: br, Size: uint32(f.UncompressedSize64)}, Offset: off, }); err != nil { return err } } } maniRC, err := maniFile.Open() if err != nil { return err } defer maniRC.Close() var mf Manifest if err := json.NewDecoder(maniRC).Decode(&mf); err != nil { return err } if !mf.WholeRef.Valid() || mf.WholeSize == 0 || !mf.DataBlobsOrigin.Valid() { return errors.New("incomplete blobpack manifest JSON") } // apply fn to all the data blobs for _, bap := range mf.DataBlobs { bap.Offset += firstOff if err := fn(bap); err != nil { return err } } return nil }
[ "func", "(", "s", "*", "storage", ")", "foreachZipBlob", "(", "ctx", "context", ".", "Context", ",", "zipRef", "blob", ".", "Ref", ",", "fn", "func", "(", "BlobAndPos", ")", "error", ")", "error", "{", "sb", ",", "err", ":=", "blobserver", ".", "StatBlob", "(", "ctx", ",", "s", ".", "large", ",", "zipRef", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "zr", ",", "err", ":=", "zip", ".", "NewReader", "(", "blob", ".", "ReaderAt", "(", "ctx", ",", "s", ".", "large", ",", "zipRef", ")", ",", "int64", "(", "sb", ".", "Size", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "zipOpenError", "{", "zipRef", ",", "err", "}", "\n", "}", "\n", "var", "maniFile", "*", "zip", ".", "File", "// or nil if not found", "\n", "var", "firstOff", "int64", "// offset of first file (the packed data chunks)", "\n", "for", "i", ",", "f", ":=", "range", "zr", ".", "File", "{", "if", "i", "==", "0", "{", "firstOff", ",", "err", "=", "f", ".", "DataOffset", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "if", "f", ".", "Name", "==", "zipManifestPath", "{", "maniFile", "=", "f", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "maniFile", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "// apply fn to all the schema blobs", "for", "_", ",", "f", ":=", "range", "zr", ".", "File", "{", "if", "!", "strings", ".", "HasPrefix", "(", "f", ".", "Name", ",", "\"", "\"", ")", "||", "f", ".", "Name", "==", "zipManifestPath", "||", "!", "strings", ".", "HasSuffix", "(", "f", ".", "Name", ",", "\"", "\"", ")", "{", "continue", "\n", "}", "\n", "brStr", ":=", "strings", ".", "TrimSuffix", "(", "strings", ".", "TrimPrefix", "(", "f", ".", "Name", ",", "\"", "\"", ")", ",", "\"", "\"", ")", "\n", "br", ",", "ok", ":=", "blob", ".", "Parse", "(", "brStr", ")", "\n", "if", "ok", "{", "off", ",", "err", ":=", "f", ".", "DataOffset", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "fn", "(", "BlobAndPos", "{", "SizedRef", ":", "blob", ".", "SizedRef", "{", "Ref", ":", "br", ",", "Size", ":", "uint32", "(", "f", ".", "UncompressedSize64", ")", "}", ",", "Offset", ":", "off", ",", "}", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "maniRC", ",", "err", ":=", "maniFile", ".", "Open", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "maniRC", ".", "Close", "(", ")", "\n\n", "var", "mf", "Manifest", "\n", "if", "err", ":=", "json", ".", "NewDecoder", "(", "maniRC", ")", ".", "Decode", "(", "&", "mf", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "!", "mf", ".", "WholeRef", ".", "Valid", "(", ")", "||", "mf", ".", "WholeSize", "==", "0", "||", "!", "mf", ".", "DataBlobsOrigin", ".", "Valid", "(", ")", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "// apply fn to all the data blobs", "for", "_", ",", "bap", ":=", "range", "mf", ".", "DataBlobs", "{", "bap", ".", "Offset", "+=", "firstOff", "\n", "if", "err", ":=", "fn", "(", "bap", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// foreachZipBlob calls fn for each blob in the zip pack blob // identified by zipRef. If fn returns a non-nil error, // foreachZipBlob stops enumerating with that error.
[ "foreachZipBlob", "calls", "fn", "for", "each", "blob", "in", "the", "zip", "pack", "blob", "identified", "by", "zipRef", ".", "If", "fn", "returns", "a", "non", "-", "nil", "error", "foreachZipBlob", "stops", "enumerating", "with", "that", "error", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/blobpacked/blobpacked.go#L1522-L1590
train
perkeep/perkeep
pkg/blobserver/blobpacked/blobpacked.go
deleteZipPack
func (s *storage) deleteZipPack(ctx context.Context, br blob.Ref) error { inUse, err := s.zipPartsInUse(ctx, br) if err != nil { return err } if len(inUse) > 0 { return fmt.Errorf("can't delete zip pack %v: %d parts in use: %v", br, len(inUse), inUse) } if err := s.large.RemoveBlobs(ctx, []blob.Ref{br}); err != nil { return err } return s.meta.Delete("d:" + br.String()) }
go
func (s *storage) deleteZipPack(ctx context.Context, br blob.Ref) error { inUse, err := s.zipPartsInUse(ctx, br) if err != nil { return err } if len(inUse) > 0 { return fmt.Errorf("can't delete zip pack %v: %d parts in use: %v", br, len(inUse), inUse) } if err := s.large.RemoveBlobs(ctx, []blob.Ref{br}); err != nil { return err } return s.meta.Delete("d:" + br.String()) }
[ "func", "(", "s", "*", "storage", ")", "deleteZipPack", "(", "ctx", "context", ".", "Context", ",", "br", "blob", ".", "Ref", ")", "error", "{", "inUse", ",", "err", ":=", "s", ".", "zipPartsInUse", "(", "ctx", ",", "br", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "len", "(", "inUse", ")", ">", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "br", ",", "len", "(", "inUse", ")", ",", "inUse", ")", "\n", "}", "\n", "if", "err", ":=", "s", ".", "large", ".", "RemoveBlobs", "(", "ctx", ",", "[", "]", "blob", ".", "Ref", "{", "br", "}", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "s", ".", "meta", ".", "Delete", "(", "\"", "\"", "+", "br", ".", "String", "(", ")", ")", "\n", "}" ]
// deleteZipPack deletes the zip pack file br, but only if that zip // file's parts are deleted already from the meta index.
[ "deleteZipPack", "deletes", "the", "zip", "pack", "file", "br", "but", "only", "if", "that", "zip", "file", "s", "parts", "are", "deleted", "already", "from", "the", "meta", "index", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/blobpacked/blobpacked.go#L1594-L1606
train
perkeep/perkeep
internal/video/thumbnail/service.go
NewService
func NewService(th Thumbnailer, timeout time.Duration, maxProcs int) *Service { var g *syncutil.Gate if maxProcs > 0 { g = syncutil.NewGate(maxProcs) } return &Service{ thumbnailer: th, timeout: timeout, gate: g, } }
go
func NewService(th Thumbnailer, timeout time.Duration, maxProcs int) *Service { var g *syncutil.Gate if maxProcs > 0 { g = syncutil.NewGate(maxProcs) } return &Service{ thumbnailer: th, timeout: timeout, gate: g, } }
[ "func", "NewService", "(", "th", "Thumbnailer", ",", "timeout", "time", ".", "Duration", ",", "maxProcs", "int", ")", "*", "Service", "{", "var", "g", "*", "syncutil", ".", "Gate", "\n", "if", "maxProcs", ">", "0", "{", "g", "=", "syncutil", ".", "NewGate", "(", "maxProcs", ")", "\n", "}", "\n\n", "return", "&", "Service", "{", "thumbnailer", ":", "th", ",", "timeout", ":", "timeout", ",", "gate", ":", "g", ",", "}", "\n", "}" ]
// NewService builds a new Service. Zero timeout or maxProcs means no limit.
[ "NewService", "builds", "a", "new", "Service", ".", "Zero", "timeout", "or", "maxProcs", "means", "no", "limit", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/video/thumbnail/service.go#L82-L94
train
perkeep/perkeep
internal/video/thumbnail/service.go
Generate
func (s *Service) Generate(videoRef blob.Ref, w io.Writer, src blob.Fetcher) error { if s.gate != nil { s.gate.Start() defer s.gate.Done() } ln, err := netutil.ListenOnLocalRandomPort() if err != nil { return err } defer ln.Close() videoURI := &url.URL{ Scheme: "http", Host: ln.Addr().String(), Path: videoRef.String(), } cmdErrc := make(chan error, 1) cmd := buildCmd(s.thumbnailer, videoURI, w) cmdErrOut, err := cmd.StderrPipe() if err != nil { return err } if err := cmd.Start(); err != nil { return err } defer cmd.Process.Kill() go func() { out, err := ioutil.ReadAll(cmdErrOut) if err != nil { cmdErrc <- err return } cmd.Wait() if cmd.ProcessState.Success() { cmdErrc <- nil return } cmdErrc <- fmt.Errorf("thumbnail subprocess failed:\n%s", out) }() servErrc := make(chan error, 1) go func() { servErrc <- http.Serve(ln, createVideothumbnailHandler(videoRef, src)) }() select { case err := <-cmdErrc: return err case err := <-servErrc: return err case <-s.timer(): return errTimeout } }
go
func (s *Service) Generate(videoRef blob.Ref, w io.Writer, src blob.Fetcher) error { if s.gate != nil { s.gate.Start() defer s.gate.Done() } ln, err := netutil.ListenOnLocalRandomPort() if err != nil { return err } defer ln.Close() videoURI := &url.URL{ Scheme: "http", Host: ln.Addr().String(), Path: videoRef.String(), } cmdErrc := make(chan error, 1) cmd := buildCmd(s.thumbnailer, videoURI, w) cmdErrOut, err := cmd.StderrPipe() if err != nil { return err } if err := cmd.Start(); err != nil { return err } defer cmd.Process.Kill() go func() { out, err := ioutil.ReadAll(cmdErrOut) if err != nil { cmdErrc <- err return } cmd.Wait() if cmd.ProcessState.Success() { cmdErrc <- nil return } cmdErrc <- fmt.Errorf("thumbnail subprocess failed:\n%s", out) }() servErrc := make(chan error, 1) go func() { servErrc <- http.Serve(ln, createVideothumbnailHandler(videoRef, src)) }() select { case err := <-cmdErrc: return err case err := <-servErrc: return err case <-s.timer(): return errTimeout } }
[ "func", "(", "s", "*", "Service", ")", "Generate", "(", "videoRef", "blob", ".", "Ref", ",", "w", "io", ".", "Writer", ",", "src", "blob", ".", "Fetcher", ")", "error", "{", "if", "s", ".", "gate", "!=", "nil", "{", "s", ".", "gate", ".", "Start", "(", ")", "\n", "defer", "s", ".", "gate", ".", "Done", "(", ")", "\n", "}", "\n\n", "ln", ",", "err", ":=", "netutil", ".", "ListenOnLocalRandomPort", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "ln", ".", "Close", "(", ")", "\n\n", "videoURI", ":=", "&", "url", ".", "URL", "{", "Scheme", ":", "\"", "\"", ",", "Host", ":", "ln", ".", "Addr", "(", ")", ".", "String", "(", ")", ",", "Path", ":", "videoRef", ".", "String", "(", ")", ",", "}", "\n\n", "cmdErrc", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n", "cmd", ":=", "buildCmd", "(", "s", ".", "thumbnailer", ",", "videoURI", ",", "w", ")", "\n", "cmdErrOut", ",", "err", ":=", "cmd", ".", "StderrPipe", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "cmd", ".", "Start", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "cmd", ".", "Process", ".", "Kill", "(", ")", "\n", "go", "func", "(", ")", "{", "out", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "cmdErrOut", ")", "\n", "if", "err", "!=", "nil", "{", "cmdErrc", "<-", "err", "\n", "return", "\n", "}", "\n", "cmd", ".", "Wait", "(", ")", "\n", "if", "cmd", ".", "ProcessState", ".", "Success", "(", ")", "{", "cmdErrc", "<-", "nil", "\n", "return", "\n", "}", "\n", "cmdErrc", "<-", "fmt", ".", "Errorf", "(", "\"", "\\n", "\"", ",", "out", ")", "\n", "}", "(", ")", "\n\n", "servErrc", ":=", "make", "(", "chan", "error", ",", "1", ")", "\n", "go", "func", "(", ")", "{", "servErrc", "<-", "http", ".", "Serve", "(", "ln", ",", "createVideothumbnailHandler", "(", "videoRef", ",", "src", ")", ")", "\n", "}", "(", ")", "\n\n", "select", "{", "case", "err", ":=", "<-", "cmdErrc", ":", "return", "err", "\n", "case", "err", ":=", "<-", "servErrc", ":", "return", "err", "\n", "case", "<-", "s", ".", "timer", "(", ")", ":", "return", "errTimeout", "\n", "}", "\n", "}" ]
// Generate reads the video given by videoRef from src and writes its thumbnail image to w.
[ "Generate", "reads", "the", "video", "given", "by", "videoRef", "from", "src", "and", "writes", "its", "thumbnail", "image", "to", "w", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/video/thumbnail/service.go#L99-L155
train
perkeep/perkeep
server/perkeepd/ui/goui/downloadbutton/gen_DownloadItemsBtn_reactGen.go
Props
func (d DownloadItemsBtnDef) Props() DownloadItemsBtnProps { uprops := d.ComponentDef.Props() return uprops.(DownloadItemsBtnProps) }
go
func (d DownloadItemsBtnDef) Props() DownloadItemsBtnProps { uprops := d.ComponentDef.Props() return uprops.(DownloadItemsBtnProps) }
[ "func", "(", "d", "DownloadItemsBtnDef", ")", "Props", "(", ")", "DownloadItemsBtnProps", "{", "uprops", ":=", "d", ".", "ComponentDef", ".", "Props", "(", ")", "\n", "return", "uprops", ".", "(", "DownloadItemsBtnProps", ")", "\n", "}" ]
// Props is an auto-generated proxy to the current props of DownloadItemsBtn
[ "Props", "is", "an", "auto", "-", "generated", "proxy", "to", "the", "current", "props", "of", "DownloadItemsBtn" ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/server/perkeepd/ui/goui/downloadbutton/gen_DownloadItemsBtn_reactGen.go#L30-L33
train
perkeep/perkeep
pkg/server/import_share.go
importAll
func (si *shareImporter) importAll(ctx context.Context) error { src, shared, err := client.NewFromShareRoot(ctx, si.shareURL, client.OptionNoExternalConfig()) if err != nil { return err } si.src = src si.br = shared si.workc = make(chan work, 2*numWorkers) defer close(si.workc) // fan out over a pool of numWorkers workers overall for i := 0; i < numWorkers; i++ { go func() { for wi := range si.workc { wi.errc <- si.imprt(ctx, wi.br) } }() } // work assignment is done asynchronously, so imprt returns before all the work is finished. err = si.imprt(ctx, shared) si.wg.Wait() if err == nil { si.mu.RLock() err = si.err si.mu.RUnlock() } log.Print("share importer: all workers done") if err != nil { return err } return nil }
go
func (si *shareImporter) importAll(ctx context.Context) error { src, shared, err := client.NewFromShareRoot(ctx, si.shareURL, client.OptionNoExternalConfig()) if err != nil { return err } si.src = src si.br = shared si.workc = make(chan work, 2*numWorkers) defer close(si.workc) // fan out over a pool of numWorkers workers overall for i := 0; i < numWorkers; i++ { go func() { for wi := range si.workc { wi.errc <- si.imprt(ctx, wi.br) } }() } // work assignment is done asynchronously, so imprt returns before all the work is finished. err = si.imprt(ctx, shared) si.wg.Wait() if err == nil { si.mu.RLock() err = si.err si.mu.RUnlock() } log.Print("share importer: all workers done") if err != nil { return err } return nil }
[ "func", "(", "si", "*", "shareImporter", ")", "importAll", "(", "ctx", "context", ".", "Context", ")", "error", "{", "src", ",", "shared", ",", "err", ":=", "client", ".", "NewFromShareRoot", "(", "ctx", ",", "si", ".", "shareURL", ",", "client", ".", "OptionNoExternalConfig", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "si", ".", "src", "=", "src", "\n", "si", ".", "br", "=", "shared", "\n", "si", ".", "workc", "=", "make", "(", "chan", "work", ",", "2", "*", "numWorkers", ")", "\n", "defer", "close", "(", "si", ".", "workc", ")", "\n\n", "// fan out over a pool of numWorkers workers overall", "for", "i", ":=", "0", ";", "i", "<", "numWorkers", ";", "i", "++", "{", "go", "func", "(", ")", "{", "for", "wi", ":=", "range", "si", ".", "workc", "{", "wi", ".", "errc", "<-", "si", ".", "imprt", "(", "ctx", ",", "wi", ".", "br", ")", "\n", "}", "\n", "}", "(", ")", "\n", "}", "\n", "// work assignment is done asynchronously, so imprt returns before all the work is finished.", "err", "=", "si", ".", "imprt", "(", "ctx", ",", "shared", ")", "\n", "si", ".", "wg", ".", "Wait", "(", ")", "\n", "if", "err", "==", "nil", "{", "si", ".", "mu", ".", "RLock", "(", ")", "\n", "err", "=", "si", ".", "err", "\n", "si", ".", "mu", ".", "RUnlock", "(", ")", "\n", "}", "\n", "log", ".", "Print", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// importAll imports all the shared contents transitively reachable under // si.shareURL.
[ "importAll", "imports", "all", "the", "shared", "contents", "transitively", "reachable", "under", "si", ".", "shareURL", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/server/import_share.go#L176-L207
train
perkeep/perkeep
pkg/server/import_share.go
importAssembled
func (si *shareImporter) importAssembled(ctx context.Context) { res, err := http.Get(si.shareURL) if err != nil { return } defer res.Body.Close() br, err := schema.WriteFileFromReader(ctx, si.dest, "", res.Body) if err != nil { return } si.mu.Lock() si.br = br si.mu.Unlock() return }
go
func (si *shareImporter) importAssembled(ctx context.Context) { res, err := http.Get(si.shareURL) if err != nil { return } defer res.Body.Close() br, err := schema.WriteFileFromReader(ctx, si.dest, "", res.Body) if err != nil { return } si.mu.Lock() si.br = br si.mu.Unlock() return }
[ "func", "(", "si", "*", "shareImporter", ")", "importAssembled", "(", "ctx", "context", ".", "Context", ")", "{", "res", ",", "err", ":=", "http", ".", "Get", "(", "si", ".", "shareURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "defer", "res", ".", "Body", ".", "Close", "(", ")", "\n", "br", ",", "err", ":=", "schema", ".", "WriteFileFromReader", "(", "ctx", ",", "si", ".", "dest", ",", "\"", "\"", ",", "res", ".", "Body", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "si", ".", "mu", ".", "Lock", "(", ")", "\n", "si", ".", "br", "=", "br", "\n", "si", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "\n", "}" ]
// importAssembled imports the assembled file shared at si.shareURL.
[ "importAssembled", "imports", "the", "assembled", "file", "shared", "at", "si", ".", "shareURL", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/server/import_share.go#L210-L224
train
perkeep/perkeep
pkg/server/import_share.go
isAssembled
func (si *shareImporter) isAssembled() (bool, error) { u, err := url.Parse(si.shareURL) if err != nil { return false, err } isAs, _ := strconv.ParseBool(u.Query().Get("assemble")) return isAs, nil }
go
func (si *shareImporter) isAssembled() (bool, error) { u, err := url.Parse(si.shareURL) if err != nil { return false, err } isAs, _ := strconv.ParseBool(u.Query().Get("assemble")) return isAs, nil }
[ "func", "(", "si", "*", "shareImporter", ")", "isAssembled", "(", ")", "(", "bool", ",", "error", ")", "{", "u", ",", "err", ":=", "url", ".", "Parse", "(", "si", ".", "shareURL", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "isAs", ",", "_", ":=", "strconv", ".", "ParseBool", "(", "u", ".", "Query", "(", ")", ".", "Get", "(", "\"", "\"", ")", ")", "\n", "return", "isAs", ",", "nil", "\n", "}" ]
// isAssembled reports whether si.shareURL is of a shared assembled file.
[ "isAssembled", "reports", "whether", "si", ".", "shareURL", "is", "of", "a", "shared", "assembled", "file", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/server/import_share.go#L227-L234
train
perkeep/perkeep
pkg/server/import_share.go
serveProgress
func (si *shareImporter) serveProgress(w http.ResponseWriter, r *http.Request) { si.mu.RLock() defer si.mu.RUnlock() httputil.ReturnJSON(w, camtypes.ShareImportProgress{ FilesSeen: si.seen, FilesCopied: si.copied, Running: si.running, Assembled: si.assembled, BlobRef: si.br, }) }
go
func (si *shareImporter) serveProgress(w http.ResponseWriter, r *http.Request) { si.mu.RLock() defer si.mu.RUnlock() httputil.ReturnJSON(w, camtypes.ShareImportProgress{ FilesSeen: si.seen, FilesCopied: si.copied, Running: si.running, Assembled: si.assembled, BlobRef: si.br, }) }
[ "func", "(", "si", "*", "shareImporter", ")", "serveProgress", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "si", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "si", ".", "mu", ".", "RUnlock", "(", ")", "\n", "httputil", ".", "ReturnJSON", "(", "w", ",", "camtypes", ".", "ShareImportProgress", "{", "FilesSeen", ":", "si", ".", "seen", ",", "FilesCopied", ":", "si", ".", "copied", ",", "Running", ":", "si", ".", "running", ",", "Assembled", ":", "si", ".", "assembled", ",", "BlobRef", ":", "si", ".", "br", ",", "}", ")", "\n", "}" ]
// serveProgress serves the state of the currently running importing process
[ "serveProgress", "serves", "the", "state", "of", "the", "currently", "running", "importing", "process" ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/server/import_share.go#L304-L314
train
perkeep/perkeep
internal/httputil/certs.go
GenSelfTLS
func GenSelfTLS(hostname string) (certPEM, keyPEM []byte, err error) { priv, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { return certPEM, keyPEM, fmt.Errorf("failed to generate private key: %s", err) } now := time.Now() if hostname == "" { hostname = "localhost" } serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { log.Fatalf("failed to generate serial number: %s", err) } template := x509.Certificate{ SerialNumber: serialNumber, Subject: pkix.Name{ CommonName: hostname, Organization: []string{hostname}, }, NotBefore: now.Add(-5 * time.Minute).UTC(), NotAfter: now.AddDate(1, 0, 0).UTC(), SubjectKeyId: []byte{1, 2, 3, 4}, KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, IsCA: true, BasicConstraintsValid: true, } derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv) if err != nil { return certPEM, keyPEM, fmt.Errorf("failed to create certificate: %s", err) } var buf bytes.Buffer if err := pem.Encode(&buf, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil { return certPEM, keyPEM, fmt.Errorf("error writing self-signed HTTPS cert: %v", err) } certPEM = []byte(buf.String()) buf.Reset() if err := pem.Encode(&buf, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}); err != nil { return certPEM, keyPEM, fmt.Errorf("error writing self-signed HTTPS private key: %v", err) } keyPEM = buf.Bytes() return certPEM, keyPEM, nil }
go
func GenSelfTLS(hostname string) (certPEM, keyPEM []byte, err error) { priv, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { return certPEM, keyPEM, fmt.Errorf("failed to generate private key: %s", err) } now := time.Now() if hostname == "" { hostname = "localhost" } serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { log.Fatalf("failed to generate serial number: %s", err) } template := x509.Certificate{ SerialNumber: serialNumber, Subject: pkix.Name{ CommonName: hostname, Organization: []string{hostname}, }, NotBefore: now.Add(-5 * time.Minute).UTC(), NotAfter: now.AddDate(1, 0, 0).UTC(), SubjectKeyId: []byte{1, 2, 3, 4}, KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, IsCA: true, BasicConstraintsValid: true, } derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv) if err != nil { return certPEM, keyPEM, fmt.Errorf("failed to create certificate: %s", err) } var buf bytes.Buffer if err := pem.Encode(&buf, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil { return certPEM, keyPEM, fmt.Errorf("error writing self-signed HTTPS cert: %v", err) } certPEM = []byte(buf.String()) buf.Reset() if err := pem.Encode(&buf, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}); err != nil { return certPEM, keyPEM, fmt.Errorf("error writing self-signed HTTPS private key: %v", err) } keyPEM = buf.Bytes() return certPEM, keyPEM, nil }
[ "func", "GenSelfTLS", "(", "hostname", "string", ")", "(", "certPEM", ",", "keyPEM", "[", "]", "byte", ",", "err", "error", ")", "{", "priv", ",", "err", ":=", "rsa", ".", "GenerateKey", "(", "rand", ".", "Reader", ",", "2048", ")", "\n", "if", "err", "!=", "nil", "{", "return", "certPEM", ",", "keyPEM", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "now", ":=", "time", ".", "Now", "(", ")", "\n\n", "if", "hostname", "==", "\"", "\"", "{", "hostname", "=", "\"", "\"", "\n", "}", "\n", "serialNumberLimit", ":=", "new", "(", "big", ".", "Int", ")", ".", "Lsh", "(", "big", ".", "NewInt", "(", "1", ")", ",", "128", ")", "\n", "serialNumber", ",", "err", ":=", "rand", ".", "Int", "(", "rand", ".", "Reader", ",", "serialNumberLimit", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "template", ":=", "x509", ".", "Certificate", "{", "SerialNumber", ":", "serialNumber", ",", "Subject", ":", "pkix", ".", "Name", "{", "CommonName", ":", "hostname", ",", "Organization", ":", "[", "]", "string", "{", "hostname", "}", ",", "}", ",", "NotBefore", ":", "now", ".", "Add", "(", "-", "5", "*", "time", ".", "Minute", ")", ".", "UTC", "(", ")", ",", "NotAfter", ":", "now", ".", "AddDate", "(", "1", ",", "0", ",", "0", ")", ".", "UTC", "(", ")", ",", "SubjectKeyId", ":", "[", "]", "byte", "{", "1", ",", "2", ",", "3", ",", "4", "}", ",", "KeyUsage", ":", "x509", ".", "KeyUsageKeyEncipherment", "|", "x509", ".", "KeyUsageDigitalSignature", "|", "x509", ".", "KeyUsageCertSign", ",", "IsCA", ":", "true", ",", "BasicConstraintsValid", ":", "true", ",", "}", "\n\n", "derBytes", ",", "err", ":=", "x509", ".", "CreateCertificate", "(", "rand", ".", "Reader", ",", "&", "template", ",", "&", "template", ",", "&", "priv", ".", "PublicKey", ",", "priv", ")", "\n", "if", "err", "!=", "nil", "{", "return", "certPEM", ",", "keyPEM", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "var", "buf", "bytes", ".", "Buffer", "\n", "if", "err", ":=", "pem", ".", "Encode", "(", "&", "buf", ",", "&", "pem", ".", "Block", "{", "Type", ":", "\"", "\"", ",", "Bytes", ":", "derBytes", "}", ")", ";", "err", "!=", "nil", "{", "return", "certPEM", ",", "keyPEM", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "certPEM", "=", "[", "]", "byte", "(", "buf", ".", "String", "(", ")", ")", "\n\n", "buf", ".", "Reset", "(", ")", "\n", "if", "err", ":=", "pem", ".", "Encode", "(", "&", "buf", ",", "&", "pem", ".", "Block", "{", "Type", ":", "\"", "\"", ",", "Bytes", ":", "x509", ".", "MarshalPKCS1PrivateKey", "(", "priv", ")", "}", ")", ";", "err", "!=", "nil", "{", "return", "certPEM", ",", "keyPEM", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "keyPEM", "=", "buf", ".", "Bytes", "(", ")", "\n", "return", "certPEM", ",", "keyPEM", ",", "nil", "\n", "}" ]
// GenSelfTLS generates a self-signed certificate and key for hostname.
[ "GenSelfTLS", "generates", "a", "self", "-", "signed", "certificate", "and", "key", "for", "hostname", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/httputil/certs.go#L54-L100
train
perkeep/perkeep
internal/httputil/certs.go
CertFingerprint
func CertFingerprint(certPEM []byte) (string, error) { p, _ := pem.Decode(certPEM) if p == nil { return "", errors.New("no valid PEM data found") } cert, err := x509.ParseCertificate(p.Bytes) if err != nil { return "", fmt.Errorf("failed to parse certificate: %v", err) } return hashutil.SHA256Prefix(cert.Raw), nil }
go
func CertFingerprint(certPEM []byte) (string, error) { p, _ := pem.Decode(certPEM) if p == nil { return "", errors.New("no valid PEM data found") } cert, err := x509.ParseCertificate(p.Bytes) if err != nil { return "", fmt.Errorf("failed to parse certificate: %v", err) } return hashutil.SHA256Prefix(cert.Raw), nil }
[ "func", "CertFingerprint", "(", "certPEM", "[", "]", "byte", ")", "(", "string", ",", "error", ")", "{", "p", ",", "_", ":=", "pem", ".", "Decode", "(", "certPEM", ")", "\n", "if", "p", "==", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "cert", ",", "err", ":=", "x509", ".", "ParseCertificate", "(", "p", ".", "Bytes", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "hashutil", ".", "SHA256Prefix", "(", "cert", ".", "Raw", ")", ",", "nil", "\n", "}" ]
// CertFingerprint returns the SHA-256 prefix of the x509 certificate encoded in certPEM.
[ "CertFingerprint", "returns", "the", "SHA", "-", "256", "prefix", "of", "the", "x509", "certificate", "encoded", "in", "certPEM", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/httputil/certs.go#L103-L113
train
perkeep/perkeep
internal/httputil/certs.go
GenSelfTLSFiles
func GenSelfTLSFiles(hostname, certPath, keyPath string) (fingerprint string, err error) { cert, key, err := GenSelfTLS(hostname) if err != nil { return "", err } sig, err := CertFingerprint(cert) if err != nil { return "", fmt.Errorf("could not get SHA-256 fingerprint of certificate: %v", err) } if err := wkfs.WriteFile(certPath, cert, 0666); err != nil { return "", fmt.Errorf("failed to write self-signed TLS cert: %v", err) } if err := wkfs.WriteFile(keyPath, key, 0600); err != nil { return "", fmt.Errorf("failed to write self-signed TLS key: %v", err) } return sig, nil }
go
func GenSelfTLSFiles(hostname, certPath, keyPath string) (fingerprint string, err error) { cert, key, err := GenSelfTLS(hostname) if err != nil { return "", err } sig, err := CertFingerprint(cert) if err != nil { return "", fmt.Errorf("could not get SHA-256 fingerprint of certificate: %v", err) } if err := wkfs.WriteFile(certPath, cert, 0666); err != nil { return "", fmt.Errorf("failed to write self-signed TLS cert: %v", err) } if err := wkfs.WriteFile(keyPath, key, 0600); err != nil { return "", fmt.Errorf("failed to write self-signed TLS key: %v", err) } return sig, nil }
[ "func", "GenSelfTLSFiles", "(", "hostname", ",", "certPath", ",", "keyPath", "string", ")", "(", "fingerprint", "string", ",", "err", "error", ")", "{", "cert", ",", "key", ",", "err", ":=", "GenSelfTLS", "(", "hostname", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "sig", ",", "err", ":=", "CertFingerprint", "(", "cert", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "wkfs", ".", "WriteFile", "(", "certPath", ",", "cert", ",", "0666", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "wkfs", ".", "WriteFile", "(", "keyPath", ",", "key", ",", "0600", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "sig", ",", "nil", "\n", "}" ]
// GenSelfTLSFiles generates a self-signed certificate and key for hostname, // and writes them to the given paths. If it succeeds it also returns // the SHA256 prefix of the new cert.
[ "GenSelfTLSFiles", "generates", "a", "self", "-", "signed", "certificate", "and", "key", "for", "hostname", "and", "writes", "them", "to", "the", "given", "paths", ".", "If", "it", "succeeds", "it", "also", "returns", "the", "SHA256", "prefix", "of", "the", "new", "cert", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/httputil/certs.go#L118-L134
train
perkeep/perkeep
pkg/types/camtypes/search.go
Contains
func (b LocationBounds) Contains(loc Location) bool { if b.SpansDateLine() { return loc.Longitude >= b.West || loc.Longitude <= b.East } return loc.Longitude >= b.West && loc.Longitude <= b.East }
go
func (b LocationBounds) Contains(loc Location) bool { if b.SpansDateLine() { return loc.Longitude >= b.West || loc.Longitude <= b.East } return loc.Longitude >= b.West && loc.Longitude <= b.East }
[ "func", "(", "b", "LocationBounds", ")", "Contains", "(", "loc", "Location", ")", "bool", "{", "if", "b", ".", "SpansDateLine", "(", ")", "{", "return", "loc", ".", "Longitude", ">=", "b", ".", "West", "||", "loc", ".", "Longitude", "<=", "b", ".", "East", "\n", "}", "\n", "return", "loc", ".", "Longitude", ">=", "b", ".", "West", "&&", "loc", ".", "Longitude", "<=", "b", ".", "East", "\n", "}" ]
// Contains reports whether loc is in the bounds b.
[ "Contains", "reports", "whether", "loc", "is", "in", "the", "bounds", "b", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/types/camtypes/search.go#L285-L290
train
perkeep/perkeep
pkg/types/camtypes/search.go
Expand
func (b LocationBounds) Expand(loc Location) LocationBounds { if b == (LocationBounds{}) { return LocationBounds{ North: loc.Latitude, South: loc.Latitude, West: loc.Longitude, East: loc.Longitude, } } nb := LocationBounds{ North: b.North, South: b.South, West: b.West, East: b.East, } if loc.Latitude > nb.North { nb.North = loc.Latitude } else if loc.Latitude < nb.South { nb.South = loc.Latitude } if nb.Contains(loc) { return nb } center := nb.center() dToCenter := center.Longitude - loc.Longitude if math.Abs(dToCenter) <= 180 { if dToCenter > 0 { // expand Westwards nb.West = loc.Longitude } else { // expand Eastwards nb.East = loc.Longitude } return nb } if dToCenter > 0 { // expand Eastwards nb.East = loc.Longitude } else { // expand Westwards nb.West = loc.Longitude } return nb }
go
func (b LocationBounds) Expand(loc Location) LocationBounds { if b == (LocationBounds{}) { return LocationBounds{ North: loc.Latitude, South: loc.Latitude, West: loc.Longitude, East: loc.Longitude, } } nb := LocationBounds{ North: b.North, South: b.South, West: b.West, East: b.East, } if loc.Latitude > nb.North { nb.North = loc.Latitude } else if loc.Latitude < nb.South { nb.South = loc.Latitude } if nb.Contains(loc) { return nb } center := nb.center() dToCenter := center.Longitude - loc.Longitude if math.Abs(dToCenter) <= 180 { if dToCenter > 0 { // expand Westwards nb.West = loc.Longitude } else { // expand Eastwards nb.East = loc.Longitude } return nb } if dToCenter > 0 { // expand Eastwards nb.East = loc.Longitude } else { // expand Westwards nb.West = loc.Longitude } return nb }
[ "func", "(", "b", "LocationBounds", ")", "Expand", "(", "loc", "Location", ")", "LocationBounds", "{", "if", "b", "==", "(", "LocationBounds", "{", "}", ")", "{", "return", "LocationBounds", "{", "North", ":", "loc", ".", "Latitude", ",", "South", ":", "loc", ".", "Latitude", ",", "West", ":", "loc", ".", "Longitude", ",", "East", ":", "loc", ".", "Longitude", ",", "}", "\n", "}", "\n", "nb", ":=", "LocationBounds", "{", "North", ":", "b", ".", "North", ",", "South", ":", "b", ".", "South", ",", "West", ":", "b", ".", "West", ",", "East", ":", "b", ".", "East", ",", "}", "\n", "if", "loc", ".", "Latitude", ">", "nb", ".", "North", "{", "nb", ".", "North", "=", "loc", ".", "Latitude", "\n", "}", "else", "if", "loc", ".", "Latitude", "<", "nb", ".", "South", "{", "nb", ".", "South", "=", "loc", ".", "Latitude", "\n", "}", "\n", "if", "nb", ".", "Contains", "(", "loc", ")", "{", "return", "nb", "\n", "}", "\n", "center", ":=", "nb", ".", "center", "(", ")", "\n", "dToCenter", ":=", "center", ".", "Longitude", "-", "loc", ".", "Longitude", "\n", "if", "math", ".", "Abs", "(", "dToCenter", ")", "<=", "180", "{", "if", "dToCenter", ">", "0", "{", "// expand Westwards", "nb", ".", "West", "=", "loc", ".", "Longitude", "\n", "}", "else", "{", "// expand Eastwards", "nb", ".", "East", "=", "loc", ".", "Longitude", "\n", "}", "\n", "return", "nb", "\n", "}", "\n", "if", "dToCenter", ">", "0", "{", "// expand Eastwards", "nb", ".", "East", "=", "loc", ".", "Longitude", "\n", "}", "else", "{", "// expand Westwards", "nb", ".", "West", "=", "loc", ".", "Longitude", "\n", "}", "\n", "return", "nb", "\n", "}" ]
// Expand returns a new LocationBounds nb. If either of loc coordinates is // outside of b, nb is the dimensions of b expanded as little as possible in // order to include loc. Otherwise, nb is just a copy of b.
[ "Expand", "returns", "a", "new", "LocationBounds", "nb", ".", "If", "either", "of", "loc", "coordinates", "is", "outside", "of", "b", "nb", "is", "the", "dimensions", "of", "b", "expanded", "as", "little", "as", "possible", "in", "order", "to", "include", "loc", ".", "Otherwise", "nb", "is", "just", "a", "copy", "of", "b", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/types/camtypes/search.go#L302-L345
train
perkeep/perkeep
internal/osutil/restart_windows.go
SelfPath
func SelfPath() (string, error) { kernel32, err := syscall.LoadDLL("kernel32.dll") if err != nil { return "", err } sysproc, err := kernel32.FindProc("GetModuleFileNameW") if err != nil { return "", err } b := make([]uint16, syscall.MAX_PATH) r, _, err := sysproc.Call(0, uintptr(unsafe.Pointer(&b[0])), uintptr(len(b))) n := uint32(r) if n == 0 { return "", err } return string(utf16.Decode(b[0:n])), nil }
go
func SelfPath() (string, error) { kernel32, err := syscall.LoadDLL("kernel32.dll") if err != nil { return "", err } sysproc, err := kernel32.FindProc("GetModuleFileNameW") if err != nil { return "", err } b := make([]uint16, syscall.MAX_PATH) r, _, err := sysproc.Call(0, uintptr(unsafe.Pointer(&b[0])), uintptr(len(b))) n := uint32(r) if n == 0 { return "", err } return string(utf16.Decode(b[0:n])), nil }
[ "func", "SelfPath", "(", ")", "(", "string", ",", "error", ")", "{", "kernel32", ",", "err", ":=", "syscall", ".", "LoadDLL", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "sysproc", ",", "err", ":=", "kernel32", ".", "FindProc", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "b", ":=", "make", "(", "[", "]", "uint16", ",", "syscall", ".", "MAX_PATH", ")", "\n", "r", ",", "_", ",", "err", ":=", "sysproc", ".", "Call", "(", "0", ",", "uintptr", "(", "unsafe", ".", "Pointer", "(", "&", "b", "[", "0", "]", ")", ")", ",", "uintptr", "(", "len", "(", "b", ")", ")", ")", "\n", "n", ":=", "uint32", "(", "r", ")", "\n", "if", "n", "==", "0", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "string", "(", "utf16", ".", "Decode", "(", "b", "[", "0", ":", "n", "]", ")", ")", ",", "nil", "\n", "}" ]
// SelfPath returns the path of the executable for the currently running // process.
[ "SelfPath", "returns", "the", "path", "of", "the", "executable", "for", "the", "currently", "running", "process", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/osutil/restart_windows.go#L30-L46
train
perkeep/perkeep
cmd/pk/googinit.go
prompt
func prompt(promptText string) string { fmt.Fprint(cmdmain.Stdout, promptText) sc := bufio.NewScanner(cmdmain.Stdin) sc.Scan() return strings.TrimSpace(sc.Text()) }
go
func prompt(promptText string) string { fmt.Fprint(cmdmain.Stdout, promptText) sc := bufio.NewScanner(cmdmain.Stdin) sc.Scan() return strings.TrimSpace(sc.Text()) }
[ "func", "prompt", "(", "promptText", "string", ")", "string", "{", "fmt", ".", "Fprint", "(", "cmdmain", ".", "Stdout", ",", "promptText", ")", "\n", "sc", ":=", "bufio", ".", "NewScanner", "(", "cmdmain", ".", "Stdin", ")", "\n", "sc", ".", "Scan", "(", ")", "\n", "return", "strings", ".", "TrimSpace", "(", "sc", ".", "Text", "(", ")", ")", "\n", "}" ]
// Prompt the user for an input line. Return the given input.
[ "Prompt", "the", "user", "for", "an", "input", "line", ".", "Return", "the", "given", "input", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/cmd/pk/googinit.go#L116-L121
train
perkeep/perkeep
pkg/fs/xattr.go
load
func (x *xattr) load(p *search.DescribedPermanode) { x.mu.Lock() defer x.mu.Unlock() *x.xattrs = map[string][]byte{} for k, v := range p.Attr { if strings.HasPrefix(k, xattrPrefix) { name := k[len(xattrPrefix):] val, err := base64.StdEncoding.DecodeString(v[0]) if err != nil { Logger.Printf("Base64 decoding error on attribute %v: %v", name, err) continue } (*x.xattrs)[name] = val } } }
go
func (x *xattr) load(p *search.DescribedPermanode) { x.mu.Lock() defer x.mu.Unlock() *x.xattrs = map[string][]byte{} for k, v := range p.Attr { if strings.HasPrefix(k, xattrPrefix) { name := k[len(xattrPrefix):] val, err := base64.StdEncoding.DecodeString(v[0]) if err != nil { Logger.Printf("Base64 decoding error on attribute %v: %v", name, err) continue } (*x.xattrs)[name] = val } } }
[ "func", "(", "x", "*", "xattr", ")", "load", "(", "p", "*", "search", ".", "DescribedPermanode", ")", "{", "x", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "x", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "*", "x", ".", "xattrs", "=", "map", "[", "string", "]", "[", "]", "byte", "{", "}", "\n", "for", "k", ",", "v", ":=", "range", "p", ".", "Attr", "{", "if", "strings", ".", "HasPrefix", "(", "k", ",", "xattrPrefix", ")", "{", "name", ":=", "k", "[", "len", "(", "xattrPrefix", ")", ":", "]", "\n", "val", ",", "err", ":=", "base64", ".", "StdEncoding", ".", "DecodeString", "(", "v", "[", "0", "]", ")", "\n", "if", "err", "!=", "nil", "{", "Logger", ".", "Printf", "(", "\"", "\"", ",", "name", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "(", "*", "x", ".", "xattrs", ")", "[", "name", "]", "=", "val", "\n", "}", "\n", "}", "\n", "}" ]
// load is invoked after the creation of a fuse.Node that may contain extended // attributes. This creates the node's xattr map as well as fills it with any // extended attributes found in the permanode's claims.
[ "load", "is", "invoked", "after", "the", "creation", "of", "a", "fuse", ".", "Node", "that", "may", "contain", "extended", "attributes", ".", "This", "creates", "the", "node", "s", "xattr", "map", "as", "well", "as", "fills", "it", "with", "any", "extended", "attributes", "found", "in", "the", "permanode", "s", "claims", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/fs/xattr.go#L58-L74
train
perkeep/perkeep
pkg/blobserver/stat.go
StatBlob
func StatBlob(ctx context.Context, bs BlobStatter, br blob.Ref) (blob.SizedRef, error) { var ret blob.SizedRef err := bs.StatBlobs(ctx, []blob.Ref{br}, func(sb blob.SizedRef) error { ret = sb return nil }) if err == nil && !ret.Ref.Valid() { err = os.ErrNotExist } return ret, err }
go
func StatBlob(ctx context.Context, bs BlobStatter, br blob.Ref) (blob.SizedRef, error) { var ret blob.SizedRef err := bs.StatBlobs(ctx, []blob.Ref{br}, func(sb blob.SizedRef) error { ret = sb return nil }) if err == nil && !ret.Ref.Valid() { err = os.ErrNotExist } return ret, err }
[ "func", "StatBlob", "(", "ctx", "context", ".", "Context", ",", "bs", "BlobStatter", ",", "br", "blob", ".", "Ref", ")", "(", "blob", ".", "SizedRef", ",", "error", ")", "{", "var", "ret", "blob", ".", "SizedRef", "\n", "err", ":=", "bs", ".", "StatBlobs", "(", "ctx", ",", "[", "]", "blob", ".", "Ref", "{", "br", "}", ",", "func", "(", "sb", "blob", ".", "SizedRef", ")", "error", "{", "ret", "=", "sb", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "==", "nil", "&&", "!", "ret", ".", "Ref", ".", "Valid", "(", ")", "{", "err", "=", "os", ".", "ErrNotExist", "\n", "}", "\n", "return", "ret", ",", "err", "\n", "}" ]
// StatBlob calls bs.StatBlobs to stat a single blob. // If the blob is not found, the error is os.ErrNotExist.
[ "StatBlob", "calls", "bs", ".", "StatBlobs", "to", "stat", "a", "single", "blob", ".", "If", "the", "blob", "is", "not", "found", "the", "error", "is", "os", ".", "ErrNotExist", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/stat.go#L31-L41
train
perkeep/perkeep
pkg/blobserver/stat.go
StatBlobs
func StatBlobs(ctx context.Context, bs BlobStatter, blobs []blob.Ref) (map[blob.Ref]blob.SizedRef, error) { var m map[blob.Ref]blob.SizedRef err := bs.StatBlobs(ctx, blobs, func(sb blob.SizedRef) error { if m == nil { m = make(map[blob.Ref]blob.SizedRef) } m[sb.Ref] = sb return nil }) return m, err }
go
func StatBlobs(ctx context.Context, bs BlobStatter, blobs []blob.Ref) (map[blob.Ref]blob.SizedRef, error) { var m map[blob.Ref]blob.SizedRef err := bs.StatBlobs(ctx, blobs, func(sb blob.SizedRef) error { if m == nil { m = make(map[blob.Ref]blob.SizedRef) } m[sb.Ref] = sb return nil }) return m, err }
[ "func", "StatBlobs", "(", "ctx", "context", ".", "Context", ",", "bs", "BlobStatter", ",", "blobs", "[", "]", "blob", ".", "Ref", ")", "(", "map", "[", "blob", ".", "Ref", "]", "blob", ".", "SizedRef", ",", "error", ")", "{", "var", "m", "map", "[", "blob", ".", "Ref", "]", "blob", ".", "SizedRef", "\n", "err", ":=", "bs", ".", "StatBlobs", "(", "ctx", ",", "blobs", ",", "func", "(", "sb", "blob", ".", "SizedRef", ")", "error", "{", "if", "m", "==", "nil", "{", "m", "=", "make", "(", "map", "[", "blob", ".", "Ref", "]", "blob", ".", "SizedRef", ")", "\n", "}", "\n", "m", "[", "sb", ".", "Ref", "]", "=", "sb", "\n", "return", "nil", "\n", "}", ")", "\n", "return", "m", ",", "err", "\n", "}" ]
// StatBlobs stats multiple blobs and returns a map // of the found refs to their sizes.
[ "StatBlobs", "stats", "multiple", "blobs", "and", "returns", "a", "map", "of", "the", "found", "refs", "to", "their", "sizes", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/stat.go#L45-L55
train
perkeep/perkeep
website/pk-web/contributors.go
add
func (a *author) add(src *author) { if src == nil { return } a.Emails = append(a.Emails, src.Emails...) a.Names = append(a.Names, src.Names...) a.Commits += src.Commits if src.Role != "" { a.Role = src.Role } if src.URL != "" { a.URL = src.URL } }
go
func (a *author) add(src *author) { if src == nil { return } a.Emails = append(a.Emails, src.Emails...) a.Names = append(a.Names, src.Names...) a.Commits += src.Commits if src.Role != "" { a.Role = src.Role } if src.URL != "" { a.URL = src.URL } }
[ "func", "(", "a", "*", "author", ")", "add", "(", "src", "*", "author", ")", "{", "if", "src", "==", "nil", "{", "return", "\n", "}", "\n", "a", ".", "Emails", "=", "append", "(", "a", ".", "Emails", ",", "src", ".", "Emails", "...", ")", "\n", "a", ".", "Names", "=", "append", "(", "a", ".", "Names", ",", "src", ".", "Names", "...", ")", "\n", "a", ".", "Commits", "+=", "src", ".", "Commits", "\n", "if", "src", ".", "Role", "!=", "\"", "\"", "{", "a", ".", "Role", "=", "src", ".", "Role", "\n", "}", "\n", "if", "src", ".", "URL", "!=", "\"", "\"", "{", "a", ".", "URL", "=", "src", ".", "URL", "\n", "}", "\n", "}" ]
// add merges src's fields into a's.
[ "add", "merges", "src", "s", "fields", "into", "a", "s", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/website/pk-web/contributors.go#L45-L58
train
perkeep/perkeep
website/pk-web/contributors.go
contribHandler
func contribHandler() http.HandlerFunc { c, err := genContribPage() if err != nil { log.Printf("Couldn't generate contributors page: %v", err) log.Printf("Using static contributors page") return mainHandler } title := "" if m := h1TitlePattern.FindSubmatch(c); len(m) > 1 { title = string(m[1]) } return func(w http.ResponseWriter, r *http.Request) { servePage(w, r, pageParams{ title: title, content: c, }) } }
go
func contribHandler() http.HandlerFunc { c, err := genContribPage() if err != nil { log.Printf("Couldn't generate contributors page: %v", err) log.Printf("Using static contributors page") return mainHandler } title := "" if m := h1TitlePattern.FindSubmatch(c); len(m) > 1 { title = string(m[1]) } return func(w http.ResponseWriter, r *http.Request) { servePage(w, r, pageParams{ title: title, content: c, }) } }
[ "func", "contribHandler", "(", ")", "http", ".", "HandlerFunc", "{", "c", ",", "err", ":=", "genContribPage", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "log", ".", "Printf", "(", "\"", "\"", ")", "\n", "return", "mainHandler", "\n", "}", "\n\n", "title", ":=", "\"", "\"", "\n", "if", "m", ":=", "h1TitlePattern", ".", "FindSubmatch", "(", "c", ")", ";", "len", "(", "m", ")", ">", "1", "{", "title", "=", "string", "(", "m", "[", "1", "]", ")", "\n", "}", "\n", "return", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "servePage", "(", "w", ",", "r", ",", "pageParams", "{", "title", ":", "title", ",", "content", ":", "c", ",", "}", ")", "\n", "}", "\n", "}" ]
// contribHandler returns a handler that serves the generated contributors page, // or the static file handler if it couldn't run git for any reason.
[ "contribHandler", "returns", "a", "handler", "that", "serves", "the", "generated", "contributors", "page", "or", "the", "static", "file", "handler", "if", "it", "couldn", "t", "run", "git", "for", "any", "reason", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/website/pk-web/contributors.go#L184-L202
train
perkeep/perkeep
pkg/schema/sign.go
SignJSON
func (s *Signer) SignJSON(ctx context.Context, json string, t time.Time) (string, error) { sr := s.baseSigReq sr.UnsignedJSON = json sr.SignatureTime = t return sr.Sign(ctx) }
go
func (s *Signer) SignJSON(ctx context.Context, json string, t time.Time) (string, error) { sr := s.baseSigReq sr.UnsignedJSON = json sr.SignatureTime = t return sr.Sign(ctx) }
[ "func", "(", "s", "*", "Signer", ")", "SignJSON", "(", "ctx", "context", ".", "Context", ",", "json", "string", ",", "t", "time", ".", "Time", ")", "(", "string", ",", "error", ")", "{", "sr", ":=", "s", ".", "baseSigReq", "\n", "sr", ".", "UnsignedJSON", "=", "json", "\n", "sr", ".", "SignatureTime", "=", "t", "\n", "return", "sr", ".", "Sign", "(", "ctx", ")", "\n", "}" ]
// SignJSON signs the provided json at the optional time t. // If t is the zero Time, the current time is used.
[ "SignJSON", "signs", "the", "provided", "json", "at", "the", "optional", "time", "t", ".", "If", "t", "is", "the", "zero", "Time", "the", "current", "time", "is", "used", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/schema/sign.go#L120-L125
train
perkeep/perkeep
pkg/server/ui.go
InitHandler
func (ui *UIHandler) InitHandler(hl blobserver.FindHandlerByTyper) error { // InitHandler is called after all handlers have been setup, so the bootstrap // of the camliRoot node for publishers in dev-mode is already done. searchPrefix, _, err := hl.FindHandlerByType("search") if err != nil { return errors.New("No search handler configured, which is necessary for the ui handler") } var sh *search.Handler htype, hi := hl.AllHandlers() if h, ok := hi[searchPrefix]; !ok { return errors.New("failed to find the \"search\" handler") } else { sh = h.(*search.Handler) ui.search = sh } camliRootQuery := func(camliRoot string) (*search.SearchResult, error) { return sh.Query(context.TODO(), &search.SearchQuery{ Limit: 1, Constraint: &search.Constraint{ Permanode: &search.PermanodeConstraint{ Attr: "camliRoot", Value: camliRoot, }, }, }) } for prefix, typ := range htype { if typ != "app" { continue } ah, ok := hi[prefix].(*app.Handler) if !ok { panic(fmt.Sprintf("UI: handler for %v has type \"app\" but is not app.Handler", prefix)) } // TODO(mpl): this check is weak, as the user could very well // use another binary name for the publisher app. We should // introduce/use another identifier. if ah.ProgramName() != "publisher" { continue } appConfig := ah.AppConfig() if appConfig == nil { log.Printf("UI: app handler for %v has no appConfig", prefix) continue } camliRoot, ok := appConfig["camliRoot"].(string) if !ok { log.Printf("UI: camliRoot in appConfig is %T, want string", appConfig["camliRoot"]) continue } result, err := camliRootQuery(camliRoot) if err != nil { log.Printf("UI: could not find permanode for camliRoot %v: %v", camliRoot, err) continue } if len(result.Blobs) == 0 || !result.Blobs[0].Blob.Valid() { log.Printf("UI: no valid permanode for camliRoot %v", camliRoot) continue } if ui.publishRoots == nil { ui.publishRoots = make(map[string]*publishRoot) } ui.publishRoots[prefix] = &publishRoot{ Name: camliRoot, Prefix: prefix, Permanode: result.Blobs[0].Blob, } } return nil }
go
func (ui *UIHandler) InitHandler(hl blobserver.FindHandlerByTyper) error { // InitHandler is called after all handlers have been setup, so the bootstrap // of the camliRoot node for publishers in dev-mode is already done. searchPrefix, _, err := hl.FindHandlerByType("search") if err != nil { return errors.New("No search handler configured, which is necessary for the ui handler") } var sh *search.Handler htype, hi := hl.AllHandlers() if h, ok := hi[searchPrefix]; !ok { return errors.New("failed to find the \"search\" handler") } else { sh = h.(*search.Handler) ui.search = sh } camliRootQuery := func(camliRoot string) (*search.SearchResult, error) { return sh.Query(context.TODO(), &search.SearchQuery{ Limit: 1, Constraint: &search.Constraint{ Permanode: &search.PermanodeConstraint{ Attr: "camliRoot", Value: camliRoot, }, }, }) } for prefix, typ := range htype { if typ != "app" { continue } ah, ok := hi[prefix].(*app.Handler) if !ok { panic(fmt.Sprintf("UI: handler for %v has type \"app\" but is not app.Handler", prefix)) } // TODO(mpl): this check is weak, as the user could very well // use another binary name for the publisher app. We should // introduce/use another identifier. if ah.ProgramName() != "publisher" { continue } appConfig := ah.AppConfig() if appConfig == nil { log.Printf("UI: app handler for %v has no appConfig", prefix) continue } camliRoot, ok := appConfig["camliRoot"].(string) if !ok { log.Printf("UI: camliRoot in appConfig is %T, want string", appConfig["camliRoot"]) continue } result, err := camliRootQuery(camliRoot) if err != nil { log.Printf("UI: could not find permanode for camliRoot %v: %v", camliRoot, err) continue } if len(result.Blobs) == 0 || !result.Blobs[0].Blob.Valid() { log.Printf("UI: no valid permanode for camliRoot %v", camliRoot) continue } if ui.publishRoots == nil { ui.publishRoots = make(map[string]*publishRoot) } ui.publishRoots[prefix] = &publishRoot{ Name: camliRoot, Prefix: prefix, Permanode: result.Blobs[0].Blob, } } return nil }
[ "func", "(", "ui", "*", "UIHandler", ")", "InitHandler", "(", "hl", "blobserver", ".", "FindHandlerByTyper", ")", "error", "{", "// InitHandler is called after all handlers have been setup, so the bootstrap", "// of the camliRoot node for publishers in dev-mode is already done.", "searchPrefix", ",", "_", ",", "err", ":=", "hl", ".", "FindHandlerByType", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "sh", "*", "search", ".", "Handler", "\n", "htype", ",", "hi", ":=", "hl", ".", "AllHandlers", "(", ")", "\n", "if", "h", ",", "ok", ":=", "hi", "[", "searchPrefix", "]", ";", "!", "ok", "{", "return", "errors", ".", "New", "(", "\"", "\\\"", "\\\"", "\"", ")", "\n", "}", "else", "{", "sh", "=", "h", ".", "(", "*", "search", ".", "Handler", ")", "\n", "ui", ".", "search", "=", "sh", "\n", "}", "\n", "camliRootQuery", ":=", "func", "(", "camliRoot", "string", ")", "(", "*", "search", ".", "SearchResult", ",", "error", ")", "{", "return", "sh", ".", "Query", "(", "context", ".", "TODO", "(", ")", ",", "&", "search", ".", "SearchQuery", "{", "Limit", ":", "1", ",", "Constraint", ":", "&", "search", ".", "Constraint", "{", "Permanode", ":", "&", "search", ".", "PermanodeConstraint", "{", "Attr", ":", "\"", "\"", ",", "Value", ":", "camliRoot", ",", "}", ",", "}", ",", "}", ")", "\n", "}", "\n", "for", "prefix", ",", "typ", ":=", "range", "htype", "{", "if", "typ", "!=", "\"", "\"", "{", "continue", "\n", "}", "\n", "ah", ",", "ok", ":=", "hi", "[", "prefix", "]", ".", "(", "*", "app", ".", "Handler", ")", "\n", "if", "!", "ok", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\\\"", "\\\"", "\"", ",", "prefix", ")", ")", "\n", "}", "\n", "// TODO(mpl): this check is weak, as the user could very well", "// use another binary name for the publisher app. We should", "// introduce/use another identifier.", "if", "ah", ".", "ProgramName", "(", ")", "!=", "\"", "\"", "{", "continue", "\n", "}", "\n", "appConfig", ":=", "ah", ".", "AppConfig", "(", ")", "\n", "if", "appConfig", "==", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "prefix", ")", "\n", "continue", "\n", "}", "\n", "camliRoot", ",", "ok", ":=", "appConfig", "[", "\"", "\"", "]", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "appConfig", "[", "\"", "\"", "]", ")", "\n", "continue", "\n", "}", "\n", "result", ",", "err", ":=", "camliRootQuery", "(", "camliRoot", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "camliRoot", ",", "err", ")", "\n", "continue", "\n", "}", "\n", "if", "len", "(", "result", ".", "Blobs", ")", "==", "0", "||", "!", "result", ".", "Blobs", "[", "0", "]", ".", "Blob", ".", "Valid", "(", ")", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "camliRoot", ")", "\n", "continue", "\n", "}", "\n", "if", "ui", ".", "publishRoots", "==", "nil", "{", "ui", ".", "publishRoots", "=", "make", "(", "map", "[", "string", "]", "*", "publishRoot", ")", "\n", "}", "\n", "ui", ".", "publishRoots", "[", "prefix", "]", "=", "&", "publishRoot", "{", "Name", ":", "camliRoot", ",", "Prefix", ":", "prefix", ",", "Permanode", ":", "result", ".", "Blobs", "[", "0", "]", ".", "Blob", ",", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// InitHandler goes through all the other configured handlers to discover // the publisher ones, and uses them to populate ui.publishRoots.
[ "InitHandler", "goes", "through", "all", "the", "other", "configured", "handlers", "to", "discover", "the", "publisher", "ones", "and", "uses", "them", "to", "populate", "ui", ".", "publishRoots", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/server/ui.go#L253-L322
train
perkeep/perkeep
pkg/server/ui.go
ServeStaticFile
func ServeStaticFile(rw http.ResponseWriter, req *http.Request, root http.FileSystem, file string) { f, err := root.Open("/" + file) if err != nil { http.NotFound(rw, req) log.Printf("Failed to open file %q from embedded resources: %v", file, err) return } defer f.Close() var modTime time.Time if fi, err := f.Stat(); err == nil { modTime = fi.ModTime() } // TODO(wathiede): should pkg/magic be leveraged here somehow? It has a // slightly different purpose. if strings.HasSuffix(file, ".svg") { rw.Header().Set("Content-Type", "image/svg+xml") } http.ServeContent(rw, req, file, modTime, f) }
go
func ServeStaticFile(rw http.ResponseWriter, req *http.Request, root http.FileSystem, file string) { f, err := root.Open("/" + file) if err != nil { http.NotFound(rw, req) log.Printf("Failed to open file %q from embedded resources: %v", file, err) return } defer f.Close() var modTime time.Time if fi, err := f.Stat(); err == nil { modTime = fi.ModTime() } // TODO(wathiede): should pkg/magic be leveraged here somehow? It has a // slightly different purpose. if strings.HasSuffix(file, ".svg") { rw.Header().Set("Content-Type", "image/svg+xml") } http.ServeContent(rw, req, file, modTime, f) }
[ "func", "ServeStaticFile", "(", "rw", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ",", "root", "http", ".", "FileSystem", ",", "file", "string", ")", "{", "f", ",", "err", ":=", "root", ".", "Open", "(", "\"", "\"", "+", "file", ")", "\n", "if", "err", "!=", "nil", "{", "http", ".", "NotFound", "(", "rw", ",", "req", ")", "\n", "log", ".", "Printf", "(", "\"", "\"", ",", "file", ",", "err", ")", "\n", "return", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "var", "modTime", "time", ".", "Time", "\n", "if", "fi", ",", "err", ":=", "f", ".", "Stat", "(", ")", ";", "err", "==", "nil", "{", "modTime", "=", "fi", ".", "ModTime", "(", ")", "\n", "}", "\n", "// TODO(wathiede): should pkg/magic be leveraged here somehow? It has a", "// slightly different purpose.", "if", "strings", ".", "HasSuffix", "(", "file", ",", "\"", "\"", ")", "{", "rw", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n", "http", ".", "ServeContent", "(", "rw", ",", "req", ",", "file", ",", "modTime", ",", "f", ")", "\n", "}" ]
// ServeStaticFile serves file from the root virtual filesystem.
[ "ServeStaticFile", "serves", "file", "from", "the", "root", "virtual", "filesystem", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/server/ui.go#L488-L506
train
perkeep/perkeep
pkg/server/ui.go
serveDepsJS
func serveDepsJS(rw http.ResponseWriter, req *http.Request, dir string) { var root http.FileSystem if dir == "" { root = uistatic.Files } else { root = http.Dir(dir) } b, err := closure.GenDeps(root) if err != nil { log.Print(err) http.Error(rw, "Server error", 500) return } rw.Header().Set("Content-Type", "text/javascript; charset=utf-8") rw.Write([]byte("// auto-generated from perkeepd\n")) rw.Write(b) }
go
func serveDepsJS(rw http.ResponseWriter, req *http.Request, dir string) { var root http.FileSystem if dir == "" { root = uistatic.Files } else { root = http.Dir(dir) } b, err := closure.GenDeps(root) if err != nil { log.Print(err) http.Error(rw, "Server error", 500) return } rw.Header().Set("Content-Type", "text/javascript; charset=utf-8") rw.Write([]byte("// auto-generated from perkeepd\n")) rw.Write(b) }
[ "func", "serveDepsJS", "(", "rw", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ",", "dir", "string", ")", "{", "var", "root", "http", ".", "FileSystem", "\n", "if", "dir", "==", "\"", "\"", "{", "root", "=", "uistatic", ".", "Files", "\n", "}", "else", "{", "root", "=", "http", ".", "Dir", "(", "dir", ")", "\n", "}", "\n\n", "b", ",", "err", ":=", "closure", ".", "GenDeps", "(", "root", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Print", "(", "err", ")", "\n", "http", ".", "Error", "(", "rw", ",", "\"", "\"", ",", "500", ")", "\n", "return", "\n", "}", "\n", "rw", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "rw", ".", "Write", "(", "[", "]", "byte", "(", "\"", "\\n", "\"", ")", ")", "\n", "rw", ".", "Write", "(", "b", ")", "\n", "}" ]
// serveDepsJS serves an auto-generated Closure deps.js file.
[ "serveDepsJS", "serves", "an", "auto", "-", "generated", "Closure", "deps", ".", "js", "file", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/server/ui.go#L672-L689
train
perkeep/perkeep
pkg/sorted/kvfile/kvfile.go
NewStorage
func NewStorage(file string) (sorted.KeyValue, error) { return newKeyValueFromJSONConfig(jsonconfig.Obj{"file": file}) }
go
func NewStorage(file string) (sorted.KeyValue, error) { return newKeyValueFromJSONConfig(jsonconfig.Obj{"file": file}) }
[ "func", "NewStorage", "(", "file", "string", ")", "(", "sorted", ".", "KeyValue", ",", "error", ")", "{", "return", "newKeyValueFromJSONConfig", "(", "jsonconfig", ".", "Obj", "{", "\"", "\"", ":", "file", "}", ")", "\n", "}" ]
// NewStorage is a convenience that calls newKeyValueFromJSONConfig // with file as the kv storage file.
[ "NewStorage", "is", "a", "convenience", "that", "calls", "newKeyValueFromJSONConfig", "with", "file", "as", "the", "kv", "storage", "file", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/sorted/kvfile/kvfile.go#L46-L48
train
perkeep/perkeep
pkg/client/upload.go
NewUploadHandleFromString
func NewUploadHandleFromString(data string) *UploadHandle { bref := blob.RefFromString(data) r := strings.NewReader(data) return &UploadHandle{BlobRef: bref, Size: uint32(len(data)), Contents: r} }
go
func NewUploadHandleFromString(data string) *UploadHandle { bref := blob.RefFromString(data) r := strings.NewReader(data) return &UploadHandle{BlobRef: bref, Size: uint32(len(data)), Contents: r} }
[ "func", "NewUploadHandleFromString", "(", "data", "string", ")", "*", "UploadHandle", "{", "bref", ":=", "blob", ".", "RefFromString", "(", "data", ")", "\n", "r", ":=", "strings", ".", "NewReader", "(", "data", ")", "\n", "return", "&", "UploadHandle", "{", "BlobRef", ":", "bref", ",", "Size", ":", "uint32", "(", "len", "(", "data", ")", ")", ",", "Contents", ":", "r", "}", "\n", "}" ]
// NewUploadHandleFromString returns an upload handle
[ "NewUploadHandleFromString", "returns", "an", "upload", "handle" ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/upload.go#L132-L136
train
perkeep/perkeep
pkg/client/upload.go
doStat
func (c *Client) doStat(ctx context.Context, blobs []blob.Ref, wait time.Duration, gated bool, fn func(blob.SizedRef) error) error { var buf bytes.Buffer fmt.Fprintf(&buf, "camliversion=1") if wait > 0 { secs := int(wait.Seconds()) if secs == 0 { secs = 1 } fmt.Fprintf(&buf, "&maxwaitsec=%d", secs) } for i, blob := range blobs { fmt.Fprintf(&buf, "&blob%d=%s", i+1, blob) } pfx, err := c.prefix() if err != nil { return err } req := c.newRequest(ctx, "POST", fmt.Sprintf("%s/camli/stat", pfx), &buf) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") var resp *http.Response if gated { resp, err = c.doReqGated(req) } else { resp, err = c.httpClient.Do(req) } if err != nil { return fmt.Errorf("stat HTTP error: %v", err) } if resp.Body != nil { defer resp.Body.Close() } if resp.StatusCode != 200 { return fmt.Errorf("stat response had http status %d", resp.StatusCode) } stat, err := parseStatResponse(resp) if err != nil { return err } for _, sb := range stat.HaveMap { if err := fn(sb); err != nil { return err } } return nil }
go
func (c *Client) doStat(ctx context.Context, blobs []blob.Ref, wait time.Duration, gated bool, fn func(blob.SizedRef) error) error { var buf bytes.Buffer fmt.Fprintf(&buf, "camliversion=1") if wait > 0 { secs := int(wait.Seconds()) if secs == 0 { secs = 1 } fmt.Fprintf(&buf, "&maxwaitsec=%d", secs) } for i, blob := range blobs { fmt.Fprintf(&buf, "&blob%d=%s", i+1, blob) } pfx, err := c.prefix() if err != nil { return err } req := c.newRequest(ctx, "POST", fmt.Sprintf("%s/camli/stat", pfx), &buf) req.Header.Set("Content-Type", "application/x-www-form-urlencoded") var resp *http.Response if gated { resp, err = c.doReqGated(req) } else { resp, err = c.httpClient.Do(req) } if err != nil { return fmt.Errorf("stat HTTP error: %v", err) } if resp.Body != nil { defer resp.Body.Close() } if resp.StatusCode != 200 { return fmt.Errorf("stat response had http status %d", resp.StatusCode) } stat, err := parseStatResponse(resp) if err != nil { return err } for _, sb := range stat.HaveMap { if err := fn(sb); err != nil { return err } } return nil }
[ "func", "(", "c", "*", "Client", ")", "doStat", "(", "ctx", "context", ".", "Context", ",", "blobs", "[", "]", "blob", ".", "Ref", ",", "wait", "time", ".", "Duration", ",", "gated", "bool", ",", "fn", "func", "(", "blob", ".", "SizedRef", ")", "error", ")", "error", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "fmt", ".", "Fprintf", "(", "&", "buf", ",", "\"", "\"", ")", "\n", "if", "wait", ">", "0", "{", "secs", ":=", "int", "(", "wait", ".", "Seconds", "(", ")", ")", "\n", "if", "secs", "==", "0", "{", "secs", "=", "1", "\n", "}", "\n", "fmt", ".", "Fprintf", "(", "&", "buf", ",", "\"", "\"", ",", "secs", ")", "\n", "}", "\n", "for", "i", ",", "blob", ":=", "range", "blobs", "{", "fmt", ".", "Fprintf", "(", "&", "buf", ",", "\"", "\"", ",", "i", "+", "1", ",", "blob", ")", "\n", "}", "\n\n", "pfx", ",", "err", ":=", "c", ".", "prefix", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "req", ":=", "c", ".", "newRequest", "(", "ctx", ",", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "pfx", ")", ",", "&", "buf", ")", "\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "var", "resp", "*", "http", ".", "Response", "\n", "if", "gated", "{", "resp", ",", "err", "=", "c", ".", "doReqGated", "(", "req", ")", "\n", "}", "else", "{", "resp", ",", "err", "=", "c", ".", "httpClient", ".", "Do", "(", "req", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "resp", ".", "Body", "!=", "nil", "{", "defer", "resp", ".", "Body", ".", "Close", "(", ")", "\n", "}", "\n\n", "if", "resp", ".", "StatusCode", "!=", "200", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "resp", ".", "StatusCode", ")", "\n", "}", "\n\n", "stat", ",", "err", ":=", "parseStatResponse", "(", "resp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "_", ",", "sb", ":=", "range", "stat", ".", "HaveMap", "{", "if", "err", ":=", "fn", "(", "sb", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// doStat does an HTTP request for the stat. the number of blobs is used verbatim. No extra splitting // or batching is done at this layer. // The semantics are the same as blobserver.BlobStatter. // gate controls whether it uses httpGate to pause on requests.
[ "doStat", "does", "an", "HTTP", "request", "for", "the", "stat", ".", "the", "number", "of", "blobs", "is", "used", "verbatim", ".", "No", "extra", "splitting", "or", "batching", "is", "done", "at", "this", "layer", ".", "The", "semantics", "are", "the", "same", "as", "blobserver", ".", "BlobStatter", ".", "gate", "controls", "whether", "it", "uses", "httpGate", "to", "pause", "on", "requests", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/upload.go#L194-L242
train
perkeep/perkeep
pkg/client/upload.go
readerAndSize
func (h *UploadHandle) readerAndSize() (io.Reader, int64, error) { if h.Size > 0 { return h.Contents, int64(h.Size), nil } var b bytes.Buffer n, err := io.Copy(&b, h.Contents) if err != nil { return nil, 0, err } return &b, n, nil }
go
func (h *UploadHandle) readerAndSize() (io.Reader, int64, error) { if h.Size > 0 { return h.Contents, int64(h.Size), nil } var b bytes.Buffer n, err := io.Copy(&b, h.Contents) if err != nil { return nil, 0, err } return &b, n, nil }
[ "func", "(", "h", "*", "UploadHandle", ")", "readerAndSize", "(", ")", "(", "io", ".", "Reader", ",", "int64", ",", "error", ")", "{", "if", "h", ".", "Size", ">", "0", "{", "return", "h", ".", "Contents", ",", "int64", "(", "h", ".", "Size", ")", ",", "nil", "\n", "}", "\n", "var", "b", "bytes", ".", "Buffer", "\n", "n", ",", "err", ":=", "io", ".", "Copy", "(", "&", "b", ",", "h", ".", "Contents", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "0", ",", "err", "\n", "}", "\n", "return", "&", "b", ",", "n", ",", "nil", "\n", "}" ]
// Figure out the size of the contents. // If the size was provided, trust it.
[ "Figure", "out", "the", "size", "of", "the", "contents", ".", "If", "the", "size", "was", "provided", "trust", "it", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/upload.go#L246-L256
train
perkeep/perkeep
pkg/search/expr.go
readInternal
func (p *parser) readInternal() *token { for t := range p.tokens { return &t } return &token{tokenEOF, "", -1} }
go
func (p *parser) readInternal() *token { for t := range p.tokens { return &t } return &token{tokenEOF, "", -1} }
[ "func", "(", "p", "*", "parser", ")", "readInternal", "(", ")", "*", "token", "{", "for", "t", ":=", "range", "p", ".", "tokens", "{", "return", "&", "t", "\n", "}", "\n", "return", "&", "token", "{", "tokenEOF", ",", "\"", "\"", ",", "-", "1", "}", "\n", "}" ]
// ReadInternal should not be called directly, use 'next' or 'peek'
[ "ReadInternal", "should", "not", "be", "called", "directly", "use", "next", "or", "peek" ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/search/expr.go#L109-L114
train
perkeep/perkeep
pkg/search/expr.go
atomWords
func (p *parser) atomWords() (a atom, start int, err error) { i := p.peek() start = i.start a = atom{} switch i.typ { case tokenLiteral: err = newParseExpError(noLiteralSupport, *i) return case tokenQuotedLiteral: err = newParseExpError(noQuotedLiteralSupport, *i) return case tokenColon: err = newParseExpError(predicateError, *i) return case tokenPredicate: i := p.next() a.predicate = i.val } for { switch p.peek().typ { case tokenColon: p.next() continue case tokenArg: i := p.next() a.args = append(a.args, i.val) continue case tokenQuotedArg: i := p.next() var uq string uq, err = strconv.Unquote(i.val) if err != nil { return } a.args = append(a.args, uq) continue } return } }
go
func (p *parser) atomWords() (a atom, start int, err error) { i := p.peek() start = i.start a = atom{} switch i.typ { case tokenLiteral: err = newParseExpError(noLiteralSupport, *i) return case tokenQuotedLiteral: err = newParseExpError(noQuotedLiteralSupport, *i) return case tokenColon: err = newParseExpError(predicateError, *i) return case tokenPredicate: i := p.next() a.predicate = i.val } for { switch p.peek().typ { case tokenColon: p.next() continue case tokenArg: i := p.next() a.args = append(a.args, i.val) continue case tokenQuotedArg: i := p.next() var uq string uq, err = strconv.Unquote(i.val) if err != nil { return } a.args = append(a.args, uq) continue } return } }
[ "func", "(", "p", "*", "parser", ")", "atomWords", "(", ")", "(", "a", "atom", ",", "start", "int", ",", "err", "error", ")", "{", "i", ":=", "p", ".", "peek", "(", ")", "\n", "start", "=", "i", ".", "start", "\n", "a", "=", "atom", "{", "}", "\n", "switch", "i", ".", "typ", "{", "case", "tokenLiteral", ":", "err", "=", "newParseExpError", "(", "noLiteralSupport", ",", "*", "i", ")", "\n", "return", "\n", "case", "tokenQuotedLiteral", ":", "err", "=", "newParseExpError", "(", "noQuotedLiteralSupport", ",", "*", "i", ")", "\n", "return", "\n", "case", "tokenColon", ":", "err", "=", "newParseExpError", "(", "predicateError", ",", "*", "i", ")", "\n", "return", "\n", "case", "tokenPredicate", ":", "i", ":=", "p", ".", "next", "(", ")", "\n", "a", ".", "predicate", "=", "i", ".", "val", "\n", "}", "\n", "for", "{", "switch", "p", ".", "peek", "(", ")", ".", "typ", "{", "case", "tokenColon", ":", "p", ".", "next", "(", ")", "\n", "continue", "\n", "case", "tokenArg", ":", "i", ":=", "p", ".", "next", "(", ")", "\n", "a", ".", "args", "=", "append", "(", "a", ".", "args", ",", "i", ".", "val", ")", "\n", "continue", "\n", "case", "tokenQuotedArg", ":", "i", ":=", "p", ".", "next", "(", ")", "\n", "var", "uq", "string", "\n", "uq", ",", "err", "=", "strconv", ".", "Unquote", "(", "i", ".", "val", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "a", ".", "args", "=", "append", "(", "a", ".", "args", ",", "uq", ")", "\n", "continue", "\n", "}", "\n", "return", "\n", "}", "\n", "}" ]
// AtomWords returns the parsed atom, the starting position of this // atom and an error.
[ "AtomWords", "returns", "the", "parsed", "atom", "the", "starting", "position", "of", "this", "atom", "and", "an", "error", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/search/expr.go#L256-L295
train
perkeep/perkeep
pkg/blobserver/mongo/mongo.go
configFromJSON
func configFromJSON(cfg jsonconfig.Obj) (config, error) { conf := config{ server: cfg.OptionalString("host", "localhost"), database: cfg.RequiredString("database"), collection: cfg.OptionalString("collection", "blobs"), user: cfg.OptionalString("user", ""), password: cfg.OptionalString("password", ""), } if err := cfg.Validate(); err != nil { return config{}, err } return conf, nil }
go
func configFromJSON(cfg jsonconfig.Obj) (config, error) { conf := config{ server: cfg.OptionalString("host", "localhost"), database: cfg.RequiredString("database"), collection: cfg.OptionalString("collection", "blobs"), user: cfg.OptionalString("user", ""), password: cfg.OptionalString("password", ""), } if err := cfg.Validate(); err != nil { return config{}, err } return conf, nil }
[ "func", "configFromJSON", "(", "cfg", "jsonconfig", ".", "Obj", ")", "(", "config", ",", "error", ")", "{", "conf", ":=", "config", "{", "server", ":", "cfg", ".", "OptionalString", "(", "\"", "\"", ",", "\"", "\"", ")", ",", "database", ":", "cfg", ".", "RequiredString", "(", "\"", "\"", ")", ",", "collection", ":", "cfg", ".", "OptionalString", "(", "\"", "\"", ",", "\"", "\"", ")", ",", "user", ":", "cfg", ".", "OptionalString", "(", "\"", "\"", ",", "\"", "\"", ")", ",", "password", ":", "cfg", ".", "OptionalString", "(", "\"", "\"", ",", "\"", "\"", ")", ",", "}", "\n", "if", "err", ":=", "cfg", ".", "Validate", "(", ")", ";", "err", "!=", "nil", "{", "return", "config", "{", "}", ",", "err", "\n", "}", "\n", "return", "conf", ",", "nil", "\n", "}" ]
// ConfigFromJSON populates Config from cfg, and validates // cfg. It returns an error if cfg fails to validate.
[ "ConfigFromJSON", "populates", "Config", "from", "cfg", "and", "validates", "cfg", ".", "It", "returns", "an", "error", "if", "cfg", "fails", "to", "validate", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/mongo/mongo.go#L119-L131
train
perkeep/perkeep
server/perkeepd/perkeepd.go
certHostname
func certHostname(listen, baseURL string) (string, error) { hostPort, err := netutil.HostPort(baseURL) if err != nil { hostPort = listen } hostname, _, err := net.SplitHostPort(hostPort) if err != nil { return "", fmt.Errorf("failed to find hostname for cert from address %q: %v", hostPort, err) } return hostname, nil }
go
func certHostname(listen, baseURL string) (string, error) { hostPort, err := netutil.HostPort(baseURL) if err != nil { hostPort = listen } hostname, _, err := net.SplitHostPort(hostPort) if err != nil { return "", fmt.Errorf("failed to find hostname for cert from address %q: %v", hostPort, err) } return hostname, nil }
[ "func", "certHostname", "(", "listen", ",", "baseURL", "string", ")", "(", "string", ",", "error", ")", "{", "hostPort", ",", "err", ":=", "netutil", ".", "HostPort", "(", "baseURL", ")", "\n", "if", "err", "!=", "nil", "{", "hostPort", "=", "listen", "\n", "}", "\n", "hostname", ",", "_", ",", "err", ":=", "net", ".", "SplitHostPort", "(", "hostPort", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "hostPort", ",", "err", ")", "\n", "}", "\n", "return", "hostname", ",", "nil", "\n", "}" ]
// certHostname figures out the name to use for the TLS certificates, using baseURL // and falling back to the listen address if baseURL is empty or invalid.
[ "certHostname", "figures", "out", "the", "name", "to", "use", "for", "the", "TLS", "certificates", "using", "baseURL", "and", "falling", "back", "to", "the", "listen", "address", "if", "baseURL", "is", "empty", "or", "invalid", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/server/perkeepd/perkeepd.go#L352-L362
train
perkeep/perkeep
server/perkeepd/perkeepd.go
checkGeoKey
func checkGeoKey() error { if _, err := geocode.GetAPIKey(); err == nil { return nil } keyPath, err := geocode.GetAPIKeyPath() if err != nil { return fmt.Errorf("error getting Geocoding API key path: %v", err) } if env.OnGCE() { keyPath = strings.TrimPrefix(keyPath, "/gcs/") return fmt.Errorf("for location related requests to properly work, you need to create a Google Geocoding API Key (see https://developers.google.com/maps/documentation/geocoding/get-api-key ), and save it in your VM's configuration bucket as: %v", keyPath) } return fmt.Errorf("for location related requests to properly work, you need to create a Google Geocoding API Key (see https://developers.google.com/maps/documentation/geocoding/get-api-key ), and save it in Perkeep's configuration directory as: %v", keyPath) }
go
func checkGeoKey() error { if _, err := geocode.GetAPIKey(); err == nil { return nil } keyPath, err := geocode.GetAPIKeyPath() if err != nil { return fmt.Errorf("error getting Geocoding API key path: %v", err) } if env.OnGCE() { keyPath = strings.TrimPrefix(keyPath, "/gcs/") return fmt.Errorf("for location related requests to properly work, you need to create a Google Geocoding API Key (see https://developers.google.com/maps/documentation/geocoding/get-api-key ), and save it in your VM's configuration bucket as: %v", keyPath) } return fmt.Errorf("for location related requests to properly work, you need to create a Google Geocoding API Key (see https://developers.google.com/maps/documentation/geocoding/get-api-key ), and save it in Perkeep's configuration directory as: %v", keyPath) }
[ "func", "checkGeoKey", "(", ")", "error", "{", "if", "_", ",", "err", ":=", "geocode", ".", "GetAPIKey", "(", ")", ";", "err", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "keyPath", ",", "err", ":=", "geocode", ".", "GetAPIKeyPath", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "if", "env", ".", "OnGCE", "(", ")", "{", "keyPath", "=", "strings", ".", "TrimPrefix", "(", "keyPath", ",", "\"", "\"", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "keyPath", ")", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "keyPath", ")", "\n", "}" ]
// checkGeoKey returns nil if we have a Google Geocoding API key file stored // in the config dir. Otherwise it returns instruction about it as the error.
[ "checkGeoKey", "returns", "nil", "if", "we", "have", "a", "Google", "Geocoding", "API", "key", "file", "stored", "in", "the", "config", "dir", ".", "Otherwise", "it", "returns", "instruction", "about", "it", "as", "the", "error", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/server/perkeepd/perkeepd.go#L375-L388
train
perkeep/perkeep
pkg/index/util.go
Dup
func (s *dupSkipper) Dup(v string) bool { if s.m == nil { s.m = make(map[string]bool) } if s.m[v] { return true } s.m[v] = true return false }
go
func (s *dupSkipper) Dup(v string) bool { if s.m == nil { s.m = make(map[string]bool) } if s.m[v] { return true } s.m[v] = true return false }
[ "func", "(", "s", "*", "dupSkipper", ")", "Dup", "(", "v", "string", ")", "bool", "{", "if", "s", ".", "m", "==", "nil", "{", "s", ".", "m", "=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "}", "\n", "if", "s", ".", "m", "[", "v", "]", "{", "return", "true", "\n", "}", "\n", "s", ".", "m", "[", "v", "]", "=", "true", "\n", "return", "false", "\n", "}" ]
// not thread safe.
[ "not", "thread", "safe", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/util.go#L39-L48
train
perkeep/perkeep
pkg/index/util.go
claimPtrsAttrValue
func claimPtrsAttrValue(claims []*camtypes.Claim, attr string, at time.Time, signerFilter SignerRefSet) string { return claimsIntfAttrValue(claimPtrSlice(claims), attr, at, signerFilter) }
go
func claimPtrsAttrValue(claims []*camtypes.Claim, attr string, at time.Time, signerFilter SignerRefSet) string { return claimsIntfAttrValue(claimPtrSlice(claims), attr, at, signerFilter) }
[ "func", "claimPtrsAttrValue", "(", "claims", "[", "]", "*", "camtypes", ".", "Claim", ",", "attr", "string", ",", "at", "time", ".", "Time", ",", "signerFilter", "SignerRefSet", ")", "string", "{", "return", "claimsIntfAttrValue", "(", "claimPtrSlice", "(", "claims", ")", ",", "attr", ",", "at", ",", "signerFilter", ")", "\n", "}" ]
// claimPtrsAttrValue returns the value of attr from claims, // or the empty string if not found. // Claims should be sorted by claim.Date.
[ "claimPtrsAttrValue", "returns", "the", "value", "of", "attr", "from", "claims", "or", "the", "empty", "string", "if", "not", "found", ".", "Claims", "should", "be", "sorted", "by", "claim", ".", "Date", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/util.go#L53-L55
train
perkeep/perkeep
pkg/index/util.go
claimsIntfAttrValue
func claimsIntfAttrValue(claims claimsIntf, attr string, at time.Time, signerFilter SignerRefSet) string { if claims == nil { panic("nil claims argument in claimsIntfAttrValue") } if at.IsZero() { at = time.Now() } // use a small static buffer as it speeds up // search.BenchmarkQueryPermanodeLocation by 6-7% // with go 1.7.1 var buf [8]string v := buf[:][:0] for i := 0; i < claims.Len(); i++ { cl := claims.Claim(i) if cl.Attr != attr || cl.Date.After(at) { continue } if len(signerFilter) > 0 { if !signerFilter.blobMatches(cl.Signer) { continue } } switch cl.Type { case string(schema.DelAttributeClaim): if cl.Value == "" { v = v[:0] } else { i := 0 for _, w := range v { if w != cl.Value { v[i] = w i++ } } v = v[:i] } case string(schema.SetAttributeClaim): v = append(v[:0], cl.Value) case string(schema.AddAttributeClaim): v = append(v, cl.Value) } } if len(v) != 0 { return v[0] } return "" }
go
func claimsIntfAttrValue(claims claimsIntf, attr string, at time.Time, signerFilter SignerRefSet) string { if claims == nil { panic("nil claims argument in claimsIntfAttrValue") } if at.IsZero() { at = time.Now() } // use a small static buffer as it speeds up // search.BenchmarkQueryPermanodeLocation by 6-7% // with go 1.7.1 var buf [8]string v := buf[:][:0] for i := 0; i < claims.Len(); i++ { cl := claims.Claim(i) if cl.Attr != attr || cl.Date.After(at) { continue } if len(signerFilter) > 0 { if !signerFilter.blobMatches(cl.Signer) { continue } } switch cl.Type { case string(schema.DelAttributeClaim): if cl.Value == "" { v = v[:0] } else { i := 0 for _, w := range v { if w != cl.Value { v[i] = w i++ } } v = v[:i] } case string(schema.SetAttributeClaim): v = append(v[:0], cl.Value) case string(schema.AddAttributeClaim): v = append(v, cl.Value) } } if len(v) != 0 { return v[0] } return "" }
[ "func", "claimsIntfAttrValue", "(", "claims", "claimsIntf", ",", "attr", "string", ",", "at", "time", ".", "Time", ",", "signerFilter", "SignerRefSet", ")", "string", "{", "if", "claims", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "at", ".", "IsZero", "(", ")", "{", "at", "=", "time", ".", "Now", "(", ")", "\n", "}", "\n\n", "// use a small static buffer as it speeds up", "// search.BenchmarkQueryPermanodeLocation by 6-7%", "// with go 1.7.1", "var", "buf", "[", "8", "]", "string", "\n", "v", ":=", "buf", "[", ":", "]", "[", ":", "0", "]", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "claims", ".", "Len", "(", ")", ";", "i", "++", "{", "cl", ":=", "claims", ".", "Claim", "(", "i", ")", "\n", "if", "cl", ".", "Attr", "!=", "attr", "||", "cl", ".", "Date", ".", "After", "(", "at", ")", "{", "continue", "\n", "}", "\n\n", "if", "len", "(", "signerFilter", ")", ">", "0", "{", "if", "!", "signerFilter", ".", "blobMatches", "(", "cl", ".", "Signer", ")", "{", "continue", "\n", "}", "\n", "}", "\n\n", "switch", "cl", ".", "Type", "{", "case", "string", "(", "schema", ".", "DelAttributeClaim", ")", ":", "if", "cl", ".", "Value", "==", "\"", "\"", "{", "v", "=", "v", "[", ":", "0", "]", "\n", "}", "else", "{", "i", ":=", "0", "\n", "for", "_", ",", "w", ":=", "range", "v", "{", "if", "w", "!=", "cl", ".", "Value", "{", "v", "[", "i", "]", "=", "w", "\n", "i", "++", "\n", "}", "\n", "}", "\n", "v", "=", "v", "[", ":", "i", "]", "\n", "}", "\n", "case", "string", "(", "schema", ".", "SetAttributeClaim", ")", ":", "v", "=", "append", "(", "v", "[", ":", "0", "]", ",", "cl", ".", "Value", ")", "\n", "case", "string", "(", "schema", ".", "AddAttributeClaim", ")", ":", "v", "=", "append", "(", "v", ",", "cl", ".", "Value", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "v", ")", "!=", "0", "{", "return", "v", "[", "0", "]", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// claimsIntfAttrValue finds the value of an attribute in a list of claims // or empty string if not found. claims must be non-nil. // If signerFilter contains any refs, a claim is only taken into account if it // has been signed by one of the given signer refs.
[ "claimsIntfAttrValue", "finds", "the", "value", "of", "an", "attribute", "in", "a", "list", "of", "claims", "or", "empty", "string", "if", "not", "found", ".", "claims", "must", "be", "non", "-", "nil", ".", "If", "signerFilter", "contains", "any", "refs", "a", "claim", "is", "only", "taken", "into", "account", "if", "it", "has", "been", "signed", "by", "one", "of", "the", "given", "signer", "refs", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/util.go#L76-L127
train
perkeep/perkeep
pkg/blobserver/blobhub.go
GetHub
func GetHub(storage interface{}) BlobHub { if h, ok := getHub(storage); ok { return h } hubmu.Lock() defer hubmu.Unlock() h, ok := stohub[storage] if ok { return h } h = new(memHub) stohub[storage] = h return h }
go
func GetHub(storage interface{}) BlobHub { if h, ok := getHub(storage); ok { return h } hubmu.Lock() defer hubmu.Unlock() h, ok := stohub[storage] if ok { return h } h = new(memHub) stohub[storage] = h return h }
[ "func", "GetHub", "(", "storage", "interface", "{", "}", ")", "BlobHub", "{", "if", "h", ",", "ok", ":=", "getHub", "(", "storage", ")", ";", "ok", "{", "return", "h", "\n", "}", "\n", "hubmu", ".", "Lock", "(", ")", "\n", "defer", "hubmu", ".", "Unlock", "(", ")", "\n", "h", ",", "ok", ":=", "stohub", "[", "storage", "]", "\n", "if", "ok", "{", "return", "h", "\n", "}", "\n", "h", "=", "new", "(", "memHub", ")", "\n", "stohub", "[", "storage", "]", "=", "h", "\n", "return", "h", "\n", "}" ]
// GetHub return a BlobHub for the given storage implementation.
[ "GetHub", "return", "a", "BlobHub", "for", "the", "given", "storage", "implementation", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/blobhub.go#L59-L72
train
perkeep/perkeep
pkg/blobserver/blobhub.go
WaitForBlob
func WaitForBlob(storage interface{}, deadline time.Time, blobs []blob.Ref) { hub := GetHub(storage) ch := make(chan blob.Ref, 1) if len(blobs) == 0 { hub.RegisterListener(ch) defer hub.UnregisterListener(ch) } for _, br := range blobs { hub.RegisterBlobListener(br, ch) defer hub.UnregisterBlobListener(br, ch) } var tc <-chan time.Time if !canLongPoll { tc = time.After(2 * time.Second) } t := time.NewTimer(time.Until(deadline)) defer t.Stop() select { case <-ch: case <-tc: case <-t.C: } }
go
func WaitForBlob(storage interface{}, deadline time.Time, blobs []blob.Ref) { hub := GetHub(storage) ch := make(chan blob.Ref, 1) if len(blobs) == 0 { hub.RegisterListener(ch) defer hub.UnregisterListener(ch) } for _, br := range blobs { hub.RegisterBlobListener(br, ch) defer hub.UnregisterBlobListener(br, ch) } var tc <-chan time.Time if !canLongPoll { tc = time.After(2 * time.Second) } t := time.NewTimer(time.Until(deadline)) defer t.Stop() select { case <-ch: case <-tc: case <-t.C: } }
[ "func", "WaitForBlob", "(", "storage", "interface", "{", "}", ",", "deadline", "time", ".", "Time", ",", "blobs", "[", "]", "blob", ".", "Ref", ")", "{", "hub", ":=", "GetHub", "(", "storage", ")", "\n", "ch", ":=", "make", "(", "chan", "blob", ".", "Ref", ",", "1", ")", "\n", "if", "len", "(", "blobs", ")", "==", "0", "{", "hub", ".", "RegisterListener", "(", "ch", ")", "\n", "defer", "hub", ".", "UnregisterListener", "(", "ch", ")", "\n", "}", "\n", "for", "_", ",", "br", ":=", "range", "blobs", "{", "hub", ".", "RegisterBlobListener", "(", "br", ",", "ch", ")", "\n", "defer", "hub", ".", "UnregisterBlobListener", "(", "br", ",", "ch", ")", "\n", "}", "\n", "var", "tc", "<-", "chan", "time", ".", "Time", "\n", "if", "!", "canLongPoll", "{", "tc", "=", "time", ".", "After", "(", "2", "*", "time", ".", "Second", ")", "\n", "}", "\n\n", "t", ":=", "time", ".", "NewTimer", "(", "time", ".", "Until", "(", "deadline", ")", ")", "\n", "defer", "t", ".", "Stop", "(", ")", "\n\n", "select", "{", "case", "<-", "ch", ":", "case", "<-", "tc", ":", "case", "<-", "t", ".", "C", ":", "}", "\n", "}" ]
// WaitForBlob waits until deadline for blobs to arrive. If blobs is empty, any // blobs are waited on. Otherwise, those specific blobs are waited on. // When WaitForBlob returns, nothing may have happened.
[ "WaitForBlob", "waits", "until", "deadline", "for", "blobs", "to", "arrive", ".", "If", "blobs", "is", "empty", "any", "blobs", "are", "waited", "on", ".", "Otherwise", "those", "specific", "blobs", "are", "waited", "on", ".", "When", "WaitForBlob", "returns", "nothing", "may", "have", "happened", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/blobhub.go#L87-L111
train
perkeep/perkeep
pkg/index/receive.go
indexReadyBlobs
func (ix *Index) indexReadyBlobs(ctx context.Context) { defer ix.reindexWg.Done() ix.RLock() // For tests if ix.oooDisabled { ix.RUnlock() return } ix.RUnlock() failed := make(map[blob.Ref]bool) for { ix.Lock() if len(ix.readyReindex) == 0 { ix.Unlock() return } var br blob.Ref for br = range ix.readyReindex { break } delete(ix.readyReindex, br) ix.Unlock() if err := ix.indexBlob(ctx, br); err != nil { log.Printf("out-of-order indexBlob(%v) = %v", br, err) failed[br] = true } } ix.Lock() defer ix.Unlock() for br := range failed { ix.readyReindex[br] = true } }
go
func (ix *Index) indexReadyBlobs(ctx context.Context) { defer ix.reindexWg.Done() ix.RLock() // For tests if ix.oooDisabled { ix.RUnlock() return } ix.RUnlock() failed := make(map[blob.Ref]bool) for { ix.Lock() if len(ix.readyReindex) == 0 { ix.Unlock() return } var br blob.Ref for br = range ix.readyReindex { break } delete(ix.readyReindex, br) ix.Unlock() if err := ix.indexBlob(ctx, br); err != nil { log.Printf("out-of-order indexBlob(%v) = %v", br, err) failed[br] = true } } ix.Lock() defer ix.Unlock() for br := range failed { ix.readyReindex[br] = true } }
[ "func", "(", "ix", "*", "Index", ")", "indexReadyBlobs", "(", "ctx", "context", ".", "Context", ")", "{", "defer", "ix", ".", "reindexWg", ".", "Done", "(", ")", "\n", "ix", ".", "RLock", "(", ")", "\n", "// For tests", "if", "ix", ".", "oooDisabled", "{", "ix", ".", "RUnlock", "(", ")", "\n", "return", "\n", "}", "\n", "ix", ".", "RUnlock", "(", ")", "\n", "failed", ":=", "make", "(", "map", "[", "blob", ".", "Ref", "]", "bool", ")", "\n", "for", "{", "ix", ".", "Lock", "(", ")", "\n", "if", "len", "(", "ix", ".", "readyReindex", ")", "==", "0", "{", "ix", ".", "Unlock", "(", ")", "\n", "return", "\n", "}", "\n", "var", "br", "blob", ".", "Ref", "\n", "for", "br", "=", "range", "ix", ".", "readyReindex", "{", "break", "\n", "}", "\n", "delete", "(", "ix", ".", "readyReindex", ",", "br", ")", "\n", "ix", ".", "Unlock", "(", ")", "\n", "if", "err", ":=", "ix", ".", "indexBlob", "(", "ctx", ",", "br", ")", ";", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "br", ",", "err", ")", "\n", "failed", "[", "br", "]", "=", "true", "\n", "}", "\n", "}", "\n", "ix", ".", "Lock", "(", ")", "\n", "defer", "ix", ".", "Unlock", "(", ")", "\n", "for", "br", ":=", "range", "failed", "{", "ix", ".", "readyReindex", "[", "br", "]", "=", "true", "\n", "}", "\n", "}" ]
// indexReadyBlobs indexes blobs that have been recently marked as ready to be // reindexed, after the blobs they depend on eventually were indexed.
[ "indexReadyBlobs", "indexes", "blobs", "that", "have", "been", "recently", "marked", "as", "ready", "to", "be", "reindexed", "after", "the", "blobs", "they", "depend", "on", "eventually", "were", "indexed", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/receive.go#L132-L164
train
perkeep/perkeep
pkg/index/receive.go
noteBlobIndexed
func (ix *Index) noteBlobIndexed(br blob.Ref) { for _, needer := range ix.neededBy[br] { newNeeds := blobsFilteringOut(ix.needs[needer], br) if len(newNeeds) == 0 { ix.readyReindex[needer] = true delete(ix.needs, needer) ix.reindexWg.Add(1) go ix.indexReadyBlobs(context.Background()) } else { ix.needs[needer] = newNeeds } } delete(ix.neededBy, br) }
go
func (ix *Index) noteBlobIndexed(br blob.Ref) { for _, needer := range ix.neededBy[br] { newNeeds := blobsFilteringOut(ix.needs[needer], br) if len(newNeeds) == 0 { ix.readyReindex[needer] = true delete(ix.needs, needer) ix.reindexWg.Add(1) go ix.indexReadyBlobs(context.Background()) } else { ix.needs[needer] = newNeeds } } delete(ix.neededBy, br) }
[ "func", "(", "ix", "*", "Index", ")", "noteBlobIndexed", "(", "br", "blob", ".", "Ref", ")", "{", "for", "_", ",", "needer", ":=", "range", "ix", ".", "neededBy", "[", "br", "]", "{", "newNeeds", ":=", "blobsFilteringOut", "(", "ix", ".", "needs", "[", "needer", "]", ",", "br", ")", "\n", "if", "len", "(", "newNeeds", ")", "==", "0", "{", "ix", ".", "readyReindex", "[", "needer", "]", "=", "true", "\n", "delete", "(", "ix", ".", "needs", ",", "needer", ")", "\n", "ix", ".", "reindexWg", ".", "Add", "(", "1", ")", "\n", "go", "ix", ".", "indexReadyBlobs", "(", "context", ".", "Background", "(", ")", ")", "\n", "}", "else", "{", "ix", ".", "needs", "[", "needer", "]", "=", "newNeeds", "\n", "}", "\n", "}", "\n", "delete", "(", "ix", ".", "neededBy", ",", "br", ")", "\n", "}" ]
// noteBlobIndexed checks if the recent indexing of br now allows the blobs that // were depending on br, to be indexed in turn. If yes, they're reindexed // asynchronously by indexReadyBlobs.
[ "noteBlobIndexed", "checks", "if", "the", "recent", "indexing", "of", "br", "now", "allows", "the", "blobs", "that", "were", "depending", "on", "br", "to", "be", "indexed", "in", "turn", ".", "If", "yes", "they", "re", "reindexed", "asynchronously", "by", "indexReadyBlobs", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/receive.go#L169-L182
train
perkeep/perkeep
pkg/index/receive.go
commit
func (ix *Index) commit(mm *mutationMap) error { // We want the update of the deletes cache to be atomic // with the transaction commit, so we lock here instead // of within updateDeletesCache. ix.deletes.Lock() defer ix.deletes.Unlock() bm := ix.s.BeginBatch() for k, v := range mm.kv { bm.Set(k, v) } err := ix.s.CommitBatch(bm) if err != nil { return err } for _, cl := range mm.deletes { if err := ix.updateDeletesCache(cl); err != nil { return fmt.Errorf("Could not update the deletes cache after deletion from %v: %v", cl, err) } } return nil }
go
func (ix *Index) commit(mm *mutationMap) error { // We want the update of the deletes cache to be atomic // with the transaction commit, so we lock here instead // of within updateDeletesCache. ix.deletes.Lock() defer ix.deletes.Unlock() bm := ix.s.BeginBatch() for k, v := range mm.kv { bm.Set(k, v) } err := ix.s.CommitBatch(bm) if err != nil { return err } for _, cl := range mm.deletes { if err := ix.updateDeletesCache(cl); err != nil { return fmt.Errorf("Could not update the deletes cache after deletion from %v: %v", cl, err) } } return nil }
[ "func", "(", "ix", "*", "Index", ")", "commit", "(", "mm", "*", "mutationMap", ")", "error", "{", "// We want the update of the deletes cache to be atomic", "// with the transaction commit, so we lock here instead", "// of within updateDeletesCache.", "ix", ".", "deletes", ".", "Lock", "(", ")", "\n", "defer", "ix", ".", "deletes", ".", "Unlock", "(", ")", "\n", "bm", ":=", "ix", ".", "s", ".", "BeginBatch", "(", ")", "\n", "for", "k", ",", "v", ":=", "range", "mm", ".", "kv", "{", "bm", ".", "Set", "(", "k", ",", "v", ")", "\n", "}", "\n", "err", ":=", "ix", ".", "s", ".", "CommitBatch", "(", "bm", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "_", ",", "cl", ":=", "range", "mm", ".", "deletes", "{", "if", "err", ":=", "ix", ".", "updateDeletesCache", "(", "cl", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "cl", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// commit writes the contents of the mutationMap on a batch // mutation and commits that batch. It also updates the deletes // cache.
[ "commit", "writes", "the", "contents", "of", "the", "mutationMap", "on", "a", "batch", "mutation", "and", "commits", "that", "batch", ".", "It", "also", "updates", "the", "deletes", "cache", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/receive.go#L303-L323
train
perkeep/perkeep
pkg/index/receive.go
hasErrNotExist
func (tf *trackErrorsFetcher) hasErrNotExist() bool { tf.mu.RLock() defer tf.mu.RUnlock() if len(tf.errs) == 0 { return false } for _, v := range tf.errs { if v != os.ErrNotExist { return false } } return true }
go
func (tf *trackErrorsFetcher) hasErrNotExist() bool { tf.mu.RLock() defer tf.mu.RUnlock() if len(tf.errs) == 0 { return false } for _, v := range tf.errs { if v != os.ErrNotExist { return false } } return true }
[ "func", "(", "tf", "*", "trackErrorsFetcher", ")", "hasErrNotExist", "(", ")", "bool", "{", "tf", ".", "mu", ".", "RLock", "(", ")", "\n", "defer", "tf", ".", "mu", ".", "RUnlock", "(", ")", "\n", "if", "len", "(", "tf", ".", "errs", ")", "==", "0", "{", "return", "false", "\n", "}", "\n", "for", "_", ",", "v", ":=", "range", "tf", ".", "errs", "{", "if", "v", "!=", "os", ".", "ErrNotExist", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// hasErrNotExist reports whether tf recorded any error and if all of them are // os.ErrNotExist errors.
[ "hasErrNotExist", "reports", "whether", "tf", "recorded", "any", "error", "and", "if", "all", "of", "them", "are", "os", ".", "ErrNotExist", "errors", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/receive.go#L423-L435
train
perkeep/perkeep
pkg/index/receive.go
readPrefixOrFile
func readPrefixOrFile(prefix []byte, fetcher blob.Fetcher, b *schema.Blob, fn func(filePrefixReader) error) (err error) { pr := bytes.NewReader(prefix) err = fn(pr) if err == io.EOF || err == io.ErrUnexpectedEOF { var fr *schema.FileReader fr, err = b.NewFileReader(fetcher) if err == nil { err = fn(fr) fr.Close() } } return err }
go
func readPrefixOrFile(prefix []byte, fetcher blob.Fetcher, b *schema.Blob, fn func(filePrefixReader) error) (err error) { pr := bytes.NewReader(prefix) err = fn(pr) if err == io.EOF || err == io.ErrUnexpectedEOF { var fr *schema.FileReader fr, err = b.NewFileReader(fetcher) if err == nil { err = fn(fr) fr.Close() } } return err }
[ "func", "readPrefixOrFile", "(", "prefix", "[", "]", "byte", ",", "fetcher", "blob", ".", "Fetcher", ",", "b", "*", "schema", ".", "Blob", ",", "fn", "func", "(", "filePrefixReader", ")", "error", ")", "(", "err", "error", ")", "{", "pr", ":=", "bytes", ".", "NewReader", "(", "prefix", ")", "\n", "err", "=", "fn", "(", "pr", ")", "\n", "if", "err", "==", "io", ".", "EOF", "||", "err", "==", "io", ".", "ErrUnexpectedEOF", "{", "var", "fr", "*", "schema", ".", "FileReader", "\n", "fr", ",", "err", "=", "b", ".", "NewFileReader", "(", "fetcher", ")", "\n", "if", "err", "==", "nil", "{", "err", "=", "fn", "(", "fr", ")", "\n", "fr", ".", "Close", "(", ")", "\n", "}", "\n", "}", "\n", "return", "err", "\n", "}" ]
// readPrefixOrFile executes a given func with a reader on the passed prefix and // falls back to passing a reader on the whole file if the func returns an error.
[ "readPrefixOrFile", "executes", "a", "given", "func", "with", "a", "reader", "on", "the", "passed", "prefix", "and", "falls", "back", "to", "passing", "a", "reader", "on", "the", "whole", "file", "if", "the", "func", "returns", "an", "error", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/receive.go#L445-L457
train
perkeep/perkeep
pkg/index/receive.go
indexMusic
func indexMusic(r readerutil.SizeReaderAt, wholeRef blob.Ref, mm *mutationMap) { tag, err := taglib.Decode(r, r.Size()) if err != nil { log.Print("index: error parsing tag: ", err) return } var footerLength int64 = 0 if hasTag, err := media.HasID3v1Tag(r); err != nil { log.Print("index: unable to check for ID3v1 tag: ", err) return } else if hasTag { footerLength = media.ID3v1TagLength } // Generate a hash of the audio portion of the file (i.e. excluding ID3v1 and v2 tags). audioStart := int64(tag.TagSize()) audioSize := r.Size() - audioStart - footerLength hash := blob.NewHash() if _, err := io.Copy(hash, io.NewSectionReader(r, audioStart, audioSize)); err != nil { log.Print("index: error generating hash of audio data: ", err) return } mediaRef := blob.RefFromHash(hash) duration, err := media.GetMPEGAudioDuration(io.NewSectionReader(r, audioStart, audioSize)) if err != nil { log.Print("index: unable to calculate audio duration: ", err) duration = 0 } var yearStr, trackStr, discStr, durationStr string if !tag.Year().IsZero() { const justYearLayout = "2006" yearStr = tag.Year().Format(justYearLayout) } if tag.Track() != 0 { trackStr = fmt.Sprintf("%d", tag.Track()) } if tag.Disc() != 0 { discStr = fmt.Sprintf("%d", tag.Disc()) } if duration != 0 { durationStr = fmt.Sprintf("%d", duration/time.Millisecond) } // Note: if you add to this map, please update // pkg/search/query.go's MediaTagConstraint Tag docs. tags := map[string]string{ "title": tag.Title(), "artist": tag.Artist(), "album": tag.Album(), "genre": tag.Genre(), "musicbrainzalbumid": tag.CustomFrames()["MusicBrainz Album Id"], "year": yearStr, "track": trackStr, "disc": discStr, "mediaref": mediaRef.String(), "durationms": durationStr, } for tag, value := range tags { if value != "" { mm.Set(keyMediaTag.Key(wholeRef, tag), keyMediaTag.Val(value)) } } }
go
func indexMusic(r readerutil.SizeReaderAt, wholeRef blob.Ref, mm *mutationMap) { tag, err := taglib.Decode(r, r.Size()) if err != nil { log.Print("index: error parsing tag: ", err) return } var footerLength int64 = 0 if hasTag, err := media.HasID3v1Tag(r); err != nil { log.Print("index: unable to check for ID3v1 tag: ", err) return } else if hasTag { footerLength = media.ID3v1TagLength } // Generate a hash of the audio portion of the file (i.e. excluding ID3v1 and v2 tags). audioStart := int64(tag.TagSize()) audioSize := r.Size() - audioStart - footerLength hash := blob.NewHash() if _, err := io.Copy(hash, io.NewSectionReader(r, audioStart, audioSize)); err != nil { log.Print("index: error generating hash of audio data: ", err) return } mediaRef := blob.RefFromHash(hash) duration, err := media.GetMPEGAudioDuration(io.NewSectionReader(r, audioStart, audioSize)) if err != nil { log.Print("index: unable to calculate audio duration: ", err) duration = 0 } var yearStr, trackStr, discStr, durationStr string if !tag.Year().IsZero() { const justYearLayout = "2006" yearStr = tag.Year().Format(justYearLayout) } if tag.Track() != 0 { trackStr = fmt.Sprintf("%d", tag.Track()) } if tag.Disc() != 0 { discStr = fmt.Sprintf("%d", tag.Disc()) } if duration != 0 { durationStr = fmt.Sprintf("%d", duration/time.Millisecond) } // Note: if you add to this map, please update // pkg/search/query.go's MediaTagConstraint Tag docs. tags := map[string]string{ "title": tag.Title(), "artist": tag.Artist(), "album": tag.Album(), "genre": tag.Genre(), "musicbrainzalbumid": tag.CustomFrames()["MusicBrainz Album Id"], "year": yearStr, "track": trackStr, "disc": discStr, "mediaref": mediaRef.String(), "durationms": durationStr, } for tag, value := range tags { if value != "" { mm.Set(keyMediaTag.Key(wholeRef, tag), keyMediaTag.Val(value)) } } }
[ "func", "indexMusic", "(", "r", "readerutil", ".", "SizeReaderAt", ",", "wholeRef", "blob", ".", "Ref", ",", "mm", "*", "mutationMap", ")", "{", "tag", ",", "err", ":=", "taglib", ".", "Decode", "(", "r", ",", "r", ".", "Size", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Print", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "var", "footerLength", "int64", "=", "0", "\n", "if", "hasTag", ",", "err", ":=", "media", ".", "HasID3v1Tag", "(", "r", ")", ";", "err", "!=", "nil", "{", "log", ".", "Print", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "else", "if", "hasTag", "{", "footerLength", "=", "media", ".", "ID3v1TagLength", "\n", "}", "\n\n", "// Generate a hash of the audio portion of the file (i.e. excluding ID3v1 and v2 tags).", "audioStart", ":=", "int64", "(", "tag", ".", "TagSize", "(", ")", ")", "\n", "audioSize", ":=", "r", ".", "Size", "(", ")", "-", "audioStart", "-", "footerLength", "\n", "hash", ":=", "blob", ".", "NewHash", "(", ")", "\n", "if", "_", ",", "err", ":=", "io", ".", "Copy", "(", "hash", ",", "io", ".", "NewSectionReader", "(", "r", ",", "audioStart", ",", "audioSize", ")", ")", ";", "err", "!=", "nil", "{", "log", ".", "Print", "(", "\"", "\"", ",", "err", ")", "\n", "return", "\n", "}", "\n", "mediaRef", ":=", "blob", ".", "RefFromHash", "(", "hash", ")", "\n\n", "duration", ",", "err", ":=", "media", ".", "GetMPEGAudioDuration", "(", "io", ".", "NewSectionReader", "(", "r", ",", "audioStart", ",", "audioSize", ")", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Print", "(", "\"", "\"", ",", "err", ")", "\n", "duration", "=", "0", "\n", "}", "\n\n", "var", "yearStr", ",", "trackStr", ",", "discStr", ",", "durationStr", "string", "\n", "if", "!", "tag", ".", "Year", "(", ")", ".", "IsZero", "(", ")", "{", "const", "justYearLayout", "=", "\"", "\"", "\n", "yearStr", "=", "tag", ".", "Year", "(", ")", ".", "Format", "(", "justYearLayout", ")", "\n", "}", "\n", "if", "tag", ".", "Track", "(", ")", "!=", "0", "{", "trackStr", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "tag", ".", "Track", "(", ")", ")", "\n", "}", "\n", "if", "tag", ".", "Disc", "(", ")", "!=", "0", "{", "discStr", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "tag", ".", "Disc", "(", ")", ")", "\n", "}", "\n", "if", "duration", "!=", "0", "{", "durationStr", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "duration", "/", "time", ".", "Millisecond", ")", "\n", "}", "\n\n", "// Note: if you add to this map, please update", "// pkg/search/query.go's MediaTagConstraint Tag docs.", "tags", ":=", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "tag", ".", "Title", "(", ")", ",", "\"", "\"", ":", "tag", ".", "Artist", "(", ")", ",", "\"", "\"", ":", "tag", ".", "Album", "(", ")", ",", "\"", "\"", ":", "tag", ".", "Genre", "(", ")", ",", "\"", "\"", ":", "tag", ".", "CustomFrames", "(", ")", "[", "\"", "\"", "]", ",", "\"", "\"", ":", "yearStr", ",", "\"", "\"", ":", "trackStr", ",", "\"", "\"", ":", "discStr", ",", "\"", "\"", ":", "mediaRef", ".", "String", "(", ")", ",", "\"", "\"", ":", "durationStr", ",", "}", "\n\n", "for", "tag", ",", "value", ":=", "range", "tags", "{", "if", "value", "!=", "\"", "\"", "{", "mm", ".", "Set", "(", "keyMediaTag", ".", "Key", "(", "wholeRef", ",", "tag", ")", ",", "keyMediaTag", ".", "Val", "(", "value", ")", ")", "\n", "}", "\n", "}", "\n", "}" ]
// indexMusic adds mutations to index the wholeRef by attached metadata and other properties.
[ "indexMusic", "adds", "mutations", "to", "index", "the", "wholeRef", "by", "attached", "metadata", "and", "other", "properties", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/receive.go#L707-L773
train
perkeep/perkeep
pkg/index/receive.go
populateDeleteClaim
func (ix *Index) populateDeleteClaim(ctx context.Context, cl schema.Claim, vr *jsonsign.VerifyRequest, mm *mutationMap) error { br := cl.Blob().BlobRef() target := cl.Target() if !target.Valid() { log.Print(fmt.Errorf("no valid target for delete claim %v", br)) return nil } meta, err := ix.GetBlobMeta(ctx, target) if err != nil { if err == os.ErrNotExist { if err := ix.noteNeeded(br, target); err != nil { return fmt.Errorf("could not note that delete claim %v depends on %v: %v", br, target, err) } return errMissingDep } log.Print(fmt.Errorf("Could not get mime type of target blob %v: %v", target, err)) return nil } // TODO(mpl): create consts somewhere for "claim" and "permanode" as camliTypes, and use them, // instead of hardcoding. Unless they already exist ? (didn't find them). if meta.CamliType != "permanode" && meta.CamliType != "claim" { log.Print(fmt.Errorf("delete claim target in %v is neither a permanode nor a claim: %v", br, meta.CamliType)) return nil } mm.Set(keyDeleted.Key(target, cl.ClaimDateString(), br), "") if meta.CamliType == "claim" { return nil } recentKey := keyRecentPermanode.Key(vr.SignerKeyId, cl.ClaimDateString(), br) mm.Set(recentKey, target.String()) attr, value := cl.Attribute(), cl.Value() claimKey := keyPermanodeClaim.Key(target, vr.SignerKeyId, cl.ClaimDateString(), br) mm.Set(claimKey, keyPermanodeClaim.Val(cl.ClaimType(), attr, value, vr.CamliSigner)) return nil }
go
func (ix *Index) populateDeleteClaim(ctx context.Context, cl schema.Claim, vr *jsonsign.VerifyRequest, mm *mutationMap) error { br := cl.Blob().BlobRef() target := cl.Target() if !target.Valid() { log.Print(fmt.Errorf("no valid target for delete claim %v", br)) return nil } meta, err := ix.GetBlobMeta(ctx, target) if err != nil { if err == os.ErrNotExist { if err := ix.noteNeeded(br, target); err != nil { return fmt.Errorf("could not note that delete claim %v depends on %v: %v", br, target, err) } return errMissingDep } log.Print(fmt.Errorf("Could not get mime type of target blob %v: %v", target, err)) return nil } // TODO(mpl): create consts somewhere for "claim" and "permanode" as camliTypes, and use them, // instead of hardcoding. Unless they already exist ? (didn't find them). if meta.CamliType != "permanode" && meta.CamliType != "claim" { log.Print(fmt.Errorf("delete claim target in %v is neither a permanode nor a claim: %v", br, meta.CamliType)) return nil } mm.Set(keyDeleted.Key(target, cl.ClaimDateString(), br), "") if meta.CamliType == "claim" { return nil } recentKey := keyRecentPermanode.Key(vr.SignerKeyId, cl.ClaimDateString(), br) mm.Set(recentKey, target.String()) attr, value := cl.Attribute(), cl.Value() claimKey := keyPermanodeClaim.Key(target, vr.SignerKeyId, cl.ClaimDateString(), br) mm.Set(claimKey, keyPermanodeClaim.Val(cl.ClaimType(), attr, value, vr.CamliSigner)) return nil }
[ "func", "(", "ix", "*", "Index", ")", "populateDeleteClaim", "(", "ctx", "context", ".", "Context", ",", "cl", "schema", ".", "Claim", ",", "vr", "*", "jsonsign", ".", "VerifyRequest", ",", "mm", "*", "mutationMap", ")", "error", "{", "br", ":=", "cl", ".", "Blob", "(", ")", ".", "BlobRef", "(", ")", "\n", "target", ":=", "cl", ".", "Target", "(", ")", "\n", "if", "!", "target", ".", "Valid", "(", ")", "{", "log", ".", "Print", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "br", ")", ")", "\n", "return", "nil", "\n", "}", "\n", "meta", ",", "err", ":=", "ix", ".", "GetBlobMeta", "(", "ctx", ",", "target", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "os", ".", "ErrNotExist", "{", "if", "err", ":=", "ix", ".", "noteNeeded", "(", "br", ",", "target", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "br", ",", "target", ",", "err", ")", "\n", "}", "\n", "return", "errMissingDep", "\n", "}", "\n", "log", ".", "Print", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "target", ",", "err", ")", ")", "\n", "return", "nil", "\n", "}", "\n\n", "// TODO(mpl): create consts somewhere for \"claim\" and \"permanode\" as camliTypes, and use them,", "// instead of hardcoding. Unless they already exist ? (didn't find them).", "if", "meta", ".", "CamliType", "!=", "\"", "\"", "&&", "meta", ".", "CamliType", "!=", "\"", "\"", "{", "log", ".", "Print", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "br", ",", "meta", ".", "CamliType", ")", ")", "\n", "return", "nil", "\n", "}", "\n", "mm", ".", "Set", "(", "keyDeleted", ".", "Key", "(", "target", ",", "cl", ".", "ClaimDateString", "(", ")", ",", "br", ")", ",", "\"", "\"", ")", "\n", "if", "meta", ".", "CamliType", "==", "\"", "\"", "{", "return", "nil", "\n", "}", "\n", "recentKey", ":=", "keyRecentPermanode", ".", "Key", "(", "vr", ".", "SignerKeyId", ",", "cl", ".", "ClaimDateString", "(", ")", ",", "br", ")", "\n", "mm", ".", "Set", "(", "recentKey", ",", "target", ".", "String", "(", ")", ")", "\n", "attr", ",", "value", ":=", "cl", ".", "Attribute", "(", ")", ",", "cl", ".", "Value", "(", ")", "\n", "claimKey", ":=", "keyPermanodeClaim", ".", "Key", "(", "target", ",", "vr", ".", "SignerKeyId", ",", "cl", ".", "ClaimDateString", "(", ")", ",", "br", ")", "\n", "mm", ".", "Set", "(", "claimKey", ",", "keyPermanodeClaim", ".", "Val", "(", "cl", ".", "ClaimType", "(", ")", ",", "attr", ",", "value", ",", "vr", ".", "CamliSigner", ")", ")", "\n", "return", "nil", "\n", "}" ]
// populateDeleteClaim adds to mm the entries resulting from the delete claim cl. // It is assumed cl is a valid claim, and vr has already been verified.
[ "populateDeleteClaim", "adds", "to", "mm", "the", "entries", "resulting", "from", "the", "delete", "claim", "cl", ".", "It", "is", "assumed", "cl", "is", "a", "valid", "claim", "and", "vr", "has", "already", "been", "verified", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/receive.go#L811-L846
train
perkeep/perkeep
pkg/index/receive.go
updateDeletesCache
func (ix *Index) updateDeletesCache(deleteClaim schema.Claim) error { target := deleteClaim.Target() deleter := deleteClaim.Blob() when, err := deleter.ClaimDate() if err != nil { return fmt.Errorf("Could not get date of delete claim %v: %v", deleteClaim, err) } targetDeletions := append(ix.deletes.m[target], deletion{ deleter: deleter.BlobRef(), when: when, }) sort.Sort(sort.Reverse(byDeletionDate(targetDeletions))) ix.deletes.m[target] = targetDeletions return nil }
go
func (ix *Index) updateDeletesCache(deleteClaim schema.Claim) error { target := deleteClaim.Target() deleter := deleteClaim.Blob() when, err := deleter.ClaimDate() if err != nil { return fmt.Errorf("Could not get date of delete claim %v: %v", deleteClaim, err) } targetDeletions := append(ix.deletes.m[target], deletion{ deleter: deleter.BlobRef(), when: when, }) sort.Sort(sort.Reverse(byDeletionDate(targetDeletions))) ix.deletes.m[target] = targetDeletions return nil }
[ "func", "(", "ix", "*", "Index", ")", "updateDeletesCache", "(", "deleteClaim", "schema", ".", "Claim", ")", "error", "{", "target", ":=", "deleteClaim", ".", "Target", "(", ")", "\n", "deleter", ":=", "deleteClaim", ".", "Blob", "(", ")", "\n", "when", ",", "err", ":=", "deleter", ".", "ClaimDate", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "deleteClaim", ",", "err", ")", "\n", "}", "\n", "targetDeletions", ":=", "append", "(", "ix", ".", "deletes", ".", "m", "[", "target", "]", ",", "deletion", "{", "deleter", ":", "deleter", ".", "BlobRef", "(", ")", ",", "when", ":", "when", ",", "}", ")", "\n", "sort", ".", "Sort", "(", "sort", ".", "Reverse", "(", "byDeletionDate", "(", "targetDeletions", ")", ")", ")", "\n", "ix", ".", "deletes", ".", "m", "[", "target", "]", "=", "targetDeletions", "\n", "return", "nil", "\n", "}" ]
// updateDeletesCache updates the index deletes cache with the cl delete claim. // deleteClaim is trusted to be a valid delete Claim.
[ "updateDeletesCache", "updates", "the", "index", "deletes", "cache", "with", "the", "cl", "delete", "claim", ".", "deleteClaim", "is", "trusted", "to", "be", "a", "valid", "delete", "Claim", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/receive.go#L937-L952
train
perkeep/perkeep
cmd/pk-devimport/devimport.go
getCredentials
func getCredentials(sh search.QueryDescriber, importerType string) (string, string, error) { var clientID, clientSecret string res, err := sh.Query(context.TODO(), &search.SearchQuery{ Expression: "attr:camliNodeType:importer and attr:importerType:" + importerType, Describe: &search.DescribeRequest{ Depth: 1, }, }) if err != nil { return clientID, clientSecret, err } if res.Describe == nil { return clientID, clientSecret, errors.New("no importer node found") } var attrs url.Values for _, resBlob := range res.Blobs { blob := resBlob.Blob desBlob, ok := res.Describe.Meta[blob.String()] if !ok || desBlob.Permanode == nil { continue } attrs = desBlob.Permanode.Attr if attrs.Get("camliNodeType") != "importer" { return clientID, clientSecret, errors.New("search result returned non importer node") } if t := attrs.Get("importerType"); t != importerType { return clientID, clientSecret, fmt.Errorf("search result returned importer node of the wrong type: %v", t) } break } attrClientID, attrClientSecret := "authClientID", "authClientSecret" attr := attrs[attrClientID] if len(attr) != 1 { return clientID, clientSecret, fmt.Errorf("no %v attribute", attrClientID) } clientID = attr[0] attr = attrs[attrClientSecret] if len(attr) != 1 { return clientID, clientSecret, fmt.Errorf("no %v attribute", attrClientSecret) } clientSecret = attr[0] return clientID, clientSecret, nil }
go
func getCredentials(sh search.QueryDescriber, importerType string) (string, string, error) { var clientID, clientSecret string res, err := sh.Query(context.TODO(), &search.SearchQuery{ Expression: "attr:camliNodeType:importer and attr:importerType:" + importerType, Describe: &search.DescribeRequest{ Depth: 1, }, }) if err != nil { return clientID, clientSecret, err } if res.Describe == nil { return clientID, clientSecret, errors.New("no importer node found") } var attrs url.Values for _, resBlob := range res.Blobs { blob := resBlob.Blob desBlob, ok := res.Describe.Meta[blob.String()] if !ok || desBlob.Permanode == nil { continue } attrs = desBlob.Permanode.Attr if attrs.Get("camliNodeType") != "importer" { return clientID, clientSecret, errors.New("search result returned non importer node") } if t := attrs.Get("importerType"); t != importerType { return clientID, clientSecret, fmt.Errorf("search result returned importer node of the wrong type: %v", t) } break } attrClientID, attrClientSecret := "authClientID", "authClientSecret" attr := attrs[attrClientID] if len(attr) != 1 { return clientID, clientSecret, fmt.Errorf("no %v attribute", attrClientID) } clientID = attr[0] attr = attrs[attrClientSecret] if len(attr) != 1 { return clientID, clientSecret, fmt.Errorf("no %v attribute", attrClientSecret) } clientSecret = attr[0] return clientID, clientSecret, nil }
[ "func", "getCredentials", "(", "sh", "search", ".", "QueryDescriber", ",", "importerType", "string", ")", "(", "string", ",", "string", ",", "error", ")", "{", "var", "clientID", ",", "clientSecret", "string", "\n", "res", ",", "err", ":=", "sh", ".", "Query", "(", "context", ".", "TODO", "(", ")", ",", "&", "search", ".", "SearchQuery", "{", "Expression", ":", "\"", "\"", "+", "importerType", ",", "Describe", ":", "&", "search", ".", "DescribeRequest", "{", "Depth", ":", "1", ",", "}", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "clientID", ",", "clientSecret", ",", "err", "\n", "}", "\n", "if", "res", ".", "Describe", "==", "nil", "{", "return", "clientID", ",", "clientSecret", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "var", "attrs", "url", ".", "Values", "\n", "for", "_", ",", "resBlob", ":=", "range", "res", ".", "Blobs", "{", "blob", ":=", "resBlob", ".", "Blob", "\n", "desBlob", ",", "ok", ":=", "res", ".", "Describe", ".", "Meta", "[", "blob", ".", "String", "(", ")", "]", "\n", "if", "!", "ok", "||", "desBlob", ".", "Permanode", "==", "nil", "{", "continue", "\n", "}", "\n", "attrs", "=", "desBlob", ".", "Permanode", ".", "Attr", "\n", "if", "attrs", ".", "Get", "(", "\"", "\"", ")", "!=", "\"", "\"", "{", "return", "clientID", ",", "clientSecret", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "t", ":=", "attrs", ".", "Get", "(", "\"", "\"", ")", ";", "t", "!=", "importerType", "{", "return", "clientID", ",", "clientSecret", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "t", ")", "\n", "}", "\n", "break", "\n", "}", "\n", "attrClientID", ",", "attrClientSecret", ":=", "\"", "\"", ",", "\"", "\"", "\n", "attr", ":=", "attrs", "[", "attrClientID", "]", "\n", "if", "len", "(", "attr", ")", "!=", "1", "{", "return", "clientID", ",", "clientSecret", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "attrClientID", ")", "\n", "}", "\n", "clientID", "=", "attr", "[", "0", "]", "\n", "attr", "=", "attrs", "[", "attrClientSecret", "]", "\n", "if", "len", "(", "attr", ")", "!=", "1", "{", "return", "clientID", ",", "clientSecret", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "attrClientSecret", ")", "\n", "}", "\n", "clientSecret", "=", "attr", "[", "0", "]", "\n", "return", "clientID", ",", "clientSecret", ",", "nil", "\n", "}" ]
// getCredentials returns the OAuth clientID and clientSecret found in the // importer node of the given importerType.
[ "getCredentials", "returns", "the", "OAuth", "clientID", "and", "clientSecret", "found", "in", "the", "importer", "node", "of", "the", "given", "importerType", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/cmd/pk-devimport/devimport.go#L112-L154
train
perkeep/perkeep
pkg/schema/filewriter.go
WriteFileFromReaderWithModTime
func WriteFileFromReaderWithModTime(ctx context.Context, bs blobserver.StatReceiver, filename string, modTime time.Time, r io.Reader) (blob.Ref, error) { if strings.Contains(filename, "/") { return blob.Ref{}, fmt.Errorf("schema.WriteFileFromReader: filename %q shouldn't contain a slash", filename) } m := NewFileMap(filename) if !modTime.IsZero() { m.SetModTime(modTime) } return WriteFileMap(ctx, bs, m, r) }
go
func WriteFileFromReaderWithModTime(ctx context.Context, bs blobserver.StatReceiver, filename string, modTime time.Time, r io.Reader) (blob.Ref, error) { if strings.Contains(filename, "/") { return blob.Ref{}, fmt.Errorf("schema.WriteFileFromReader: filename %q shouldn't contain a slash", filename) } m := NewFileMap(filename) if !modTime.IsZero() { m.SetModTime(modTime) } return WriteFileMap(ctx, bs, m, r) }
[ "func", "WriteFileFromReaderWithModTime", "(", "ctx", "context", ".", "Context", ",", "bs", "blobserver", ".", "StatReceiver", ",", "filename", "string", ",", "modTime", "time", ".", "Time", ",", "r", "io", ".", "Reader", ")", "(", "blob", ".", "Ref", ",", "error", ")", "{", "if", "strings", ".", "Contains", "(", "filename", ",", "\"", "\"", ")", "{", "return", "blob", ".", "Ref", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "filename", ")", "\n", "}", "\n\n", "m", ":=", "NewFileMap", "(", "filename", ")", "\n", "if", "!", "modTime", ".", "IsZero", "(", ")", "{", "m", ".", "SetModTime", "(", "modTime", ")", "\n", "}", "\n", "return", "WriteFileMap", "(", "ctx", ",", "bs", ",", "m", ",", "r", ")", "\n", "}" ]
// WriteFileFromReaderWithModTime creates and uploads a "file" JSON schema // composed of chunks of r, also uploading the chunks. The returned // BlobRef is of the JSON file schema blob. // Both filename and modTime are optional.
[ "WriteFileFromReaderWithModTime", "creates", "and", "uploads", "a", "file", "JSON", "schema", "composed", "of", "chunks", "of", "r", "also", "uploading", "the", "chunks", ".", "The", "returned", "BlobRef", "is", "of", "the", "JSON", "file", "schema", "blob", ".", "Both", "filename", "and", "modTime", "are", "optional", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/schema/filewriter.go#L69-L79
train
perkeep/perkeep
pkg/schema/filewriter.go
WriteFileFromReader
func WriteFileFromReader(ctx context.Context, bs blobserver.StatReceiver, filename string, r io.Reader) (blob.Ref, error) { return WriteFileFromReaderWithModTime(ctx, bs, filename, time.Time{}, r) }
go
func WriteFileFromReader(ctx context.Context, bs blobserver.StatReceiver, filename string, r io.Reader) (blob.Ref, error) { return WriteFileFromReaderWithModTime(ctx, bs, filename, time.Time{}, r) }
[ "func", "WriteFileFromReader", "(", "ctx", "context", ".", "Context", ",", "bs", "blobserver", ".", "StatReceiver", ",", "filename", "string", ",", "r", "io", ".", "Reader", ")", "(", "blob", ".", "Ref", ",", "error", ")", "{", "return", "WriteFileFromReaderWithModTime", "(", "ctx", ",", "bs", ",", "filename", ",", "time", ".", "Time", "{", "}", ",", "r", ")", "\n", "}" ]
// WriteFileFromReader creates and uploads a "file" JSON schema // composed of chunks of r, also uploading the chunks. The returned // BlobRef is of the JSON file schema blob. // The filename is optional.
[ "WriteFileFromReader", "creates", "and", "uploads", "a", "file", "JSON", "schema", "composed", "of", "chunks", "of", "r", "also", "uploading", "the", "chunks", ".", "The", "returned", "BlobRef", "is", "of", "the", "JSON", "file", "schema", "blob", ".", "The", "filename", "is", "optional", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/schema/filewriter.go#L85-L87
train
perkeep/perkeep
pkg/schema/filewriter.go
WriteFileMap
func WriteFileMap(ctx context.Context, bs blobserver.StatReceiver, file *Builder, r io.Reader) (blob.Ref, error) { return writeFileMapRolling(ctx, bs, file, r) }
go
func WriteFileMap(ctx context.Context, bs blobserver.StatReceiver, file *Builder, r io.Reader) (blob.Ref, error) { return writeFileMapRolling(ctx, bs, file, r) }
[ "func", "WriteFileMap", "(", "ctx", "context", ".", "Context", ",", "bs", "blobserver", ".", "StatReceiver", ",", "file", "*", "Builder", ",", "r", "io", ".", "Reader", ")", "(", "blob", ".", "Ref", ",", "error", ")", "{", "return", "writeFileMapRolling", "(", "ctx", ",", "bs", ",", "file", ",", "r", ")", "\n", "}" ]
// WriteFileMap uploads chunks of r to bs while populating file and // finally uploading file's Blob. The returned blobref is of file's // JSON blob.
[ "WriteFileMap", "uploads", "chunks", "of", "r", "to", "bs", "while", "populating", "file", "and", "finally", "uploading", "file", "s", "Blob", ".", "The", "returned", "blobref", "is", "of", "file", "s", "JSON", "blob", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/schema/filewriter.go#L92-L94
train
perkeep/perkeep
pkg/schema/filewriter.go
Get
func (f *uploadBytesFuture) Get() (blob.Ref, error) { for _, f := range f.children { if _, err := f.Get(); err != nil { return blob.Ref{}, err } } return f.br, <-f.errc }
go
func (f *uploadBytesFuture) Get() (blob.Ref, error) { for _, f := range f.children { if _, err := f.Get(); err != nil { return blob.Ref{}, err } } return f.br, <-f.errc }
[ "func", "(", "f", "*", "uploadBytesFuture", ")", "Get", "(", ")", "(", "blob", ".", "Ref", ",", "error", ")", "{", "for", "_", ",", "f", ":=", "range", "f", ".", "children", "{", "if", "_", ",", "err", ":=", "f", ".", "Get", "(", ")", ";", "err", "!=", "nil", "{", "return", "blob", ".", "Ref", "{", "}", ",", "err", "\n", "}", "\n", "}", "\n", "return", "f", ".", "br", ",", "<-", "f", ".", "errc", "\n", "}" ]
// Get blocks for all children and returns any final error.
[ "Get", "blocks", "for", "all", "children", "and", "returns", "any", "final", "error", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/schema/filewriter.go#L216-L223
train
perkeep/perkeep
pkg/schema/filewriter.go
writeFileMapRolling
func writeFileMapRolling(ctx context.Context, bs blobserver.StatReceiver, file *Builder, r io.Reader) (blob.Ref, error) { n, spans, err := writeFileChunks(ctx, bs, file, r) if err != nil { return blob.Ref{}, err } // The top-level content parts return uploadBytes(ctx, bs, file, n, spans).Get() }
go
func writeFileMapRolling(ctx context.Context, bs blobserver.StatReceiver, file *Builder, r io.Reader) (blob.Ref, error) { n, spans, err := writeFileChunks(ctx, bs, file, r) if err != nil { return blob.Ref{}, err } // The top-level content parts return uploadBytes(ctx, bs, file, n, spans).Get() }
[ "func", "writeFileMapRolling", "(", "ctx", "context", ".", "Context", ",", "bs", "blobserver", ".", "StatReceiver", ",", "file", "*", "Builder", ",", "r", "io", ".", "Reader", ")", "(", "blob", ".", "Ref", ",", "error", ")", "{", "n", ",", "spans", ",", "err", ":=", "writeFileChunks", "(", "ctx", ",", "bs", ",", "file", ",", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "blob", ".", "Ref", "{", "}", ",", "err", "\n", "}", "\n", "// The top-level content parts", "return", "uploadBytes", "(", "ctx", ",", "bs", ",", "file", ",", "n", ",", "spans", ")", ".", "Get", "(", ")", "\n", "}" ]
// writeFileMap uploads chunks of r to bs while populating fileMap and // finally uploading fileMap. The returned blobref is of fileMap's // JSON blob. It uses rolling checksum for the chunks sizes.
[ "writeFileMap", "uploads", "chunks", "of", "r", "to", "bs", "while", "populating", "fileMap", "and", "finally", "uploading", "fileMap", ".", "The", "returned", "blobref", "is", "of", "fileMap", "s", "JSON", "blob", ".", "It", "uses", "rolling", "checksum", "for", "the", "chunks", "sizes", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/schema/filewriter.go#L265-L272
train
perkeep/perkeep
pkg/schema/filewriter.go
WriteFileChunks
func WriteFileChunks(ctx context.Context, bs blobserver.StatReceiver, file *Builder, r io.Reader) error { size, spans, err := writeFileChunks(ctx, bs, file, r) if err != nil { return err } parts := []BytesPart{} future := newUploadBytesFuture() addBytesParts(ctx, bs, &parts, spans, future) future.errc <- nil // Get will still block on addBytesParts' children if _, err := future.Get(); err != nil { return err } return file.PopulateParts(size, parts) }
go
func WriteFileChunks(ctx context.Context, bs blobserver.StatReceiver, file *Builder, r io.Reader) error { size, spans, err := writeFileChunks(ctx, bs, file, r) if err != nil { return err } parts := []BytesPart{} future := newUploadBytesFuture() addBytesParts(ctx, bs, &parts, spans, future) future.errc <- nil // Get will still block on addBytesParts' children if _, err := future.Get(); err != nil { return err } return file.PopulateParts(size, parts) }
[ "func", "WriteFileChunks", "(", "ctx", "context", ".", "Context", ",", "bs", "blobserver", ".", "StatReceiver", ",", "file", "*", "Builder", ",", "r", "io", ".", "Reader", ")", "error", "{", "size", ",", "spans", ",", "err", ":=", "writeFileChunks", "(", "ctx", ",", "bs", ",", "file", ",", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "parts", ":=", "[", "]", "BytesPart", "{", "}", "\n", "future", ":=", "newUploadBytesFuture", "(", ")", "\n", "addBytesParts", "(", "ctx", ",", "bs", ",", "&", "parts", ",", "spans", ",", "future", ")", "\n", "future", ".", "errc", "<-", "nil", "// Get will still block on addBytesParts' children", "\n", "if", "_", ",", "err", ":=", "future", ".", "Get", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "file", ".", "PopulateParts", "(", "size", ",", "parts", ")", "\n", "}" ]
// WriteFileChunks uploads chunks of r to bs while populating file. // It does not upload file.
[ "WriteFileChunks", "uploads", "chunks", "of", "r", "to", "bs", "while", "populating", "file", ".", "It", "does", "not", "upload", "file", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/schema/filewriter.go#L276-L289
train
perkeep/perkeep
internal/pools/pools.go
BytesBuffer
func BytesBuffer() *bytes.Buffer { buf := bytesBuffer.Get().(*bytes.Buffer) buf.Reset() return buf }
go
func BytesBuffer() *bytes.Buffer { buf := bytesBuffer.Get().(*bytes.Buffer) buf.Reset() return buf }
[ "func", "BytesBuffer", "(", ")", "*", "bytes", ".", "Buffer", "{", "buf", ":=", "bytesBuffer", ".", "Get", "(", ")", ".", "(", "*", "bytes", ".", "Buffer", ")", "\n", "buf", ".", "Reset", "(", ")", "\n", "return", "buf", "\n", "}" ]
// BytesBuffer returns an empty bytes.Buffer. // It should be returned with PutBuffer.
[ "BytesBuffer", "returns", "an", "empty", "bytes", ".", "Buffer", ".", "It", "should", "be", "returned", "with", "PutBuffer", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/pools/pools.go#L32-L36
train
perkeep/perkeep
pkg/auth/auth.go
RegisterAuth
func RegisterAuth(name string, ctor AuthConfigParser) { if _, dup := authConstructor[name]; dup { panic("Dup registration of auth mode " + name) } authConstructor[name] = ctor }
go
func RegisterAuth(name string, ctor AuthConfigParser) { if _, dup := authConstructor[name]; dup { panic("Dup registration of auth mode " + name) } authConstructor[name] = ctor }
[ "func", "RegisterAuth", "(", "name", "string", ",", "ctor", "AuthConfigParser", ")", "{", "if", "_", ",", "dup", ":=", "authConstructor", "[", "name", "]", ";", "dup", "{", "panic", "(", "\"", "\"", "+", "name", ")", "\n", "}", "\n", "authConstructor", "[", "name", "]", "=", "ctor", "\n", "}" ]
// RegisterAuth registers a new authentication scheme.
[ "RegisterAuth", "registers", "a", "new", "authentication", "scheme", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/auth/auth.go#L100-L105
train
perkeep/perkeep
pkg/auth/auth.go
NewBasicAuth
func NewBasicAuth(username, password string) AuthMode { return &UserPass{ Username: username, Password: password, } }
go
func NewBasicAuth(username, password string) AuthMode { return &UserPass{ Username: username, Password: password, } }
[ "func", "NewBasicAuth", "(", "username", ",", "password", "string", ")", "AuthMode", "{", "return", "&", "UserPass", "{", "Username", ":", "username", ",", "Password", ":", "password", ",", "}", "\n", "}" ]
// NewBasicAuth returns a UserPass Authmode, adequate to support HTTP // basic authentication.
[ "NewBasicAuth", "returns", "a", "UserPass", "Authmode", "adequate", "to", "support", "HTTP", "basic", "authentication", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/auth/auth.go#L157-L162
train
perkeep/perkeep
pkg/auth/auth.go
AllowedWithAuth
func AllowedWithAuth(am AuthMode, req *http.Request, op Operation) bool { if op&OpUpload != 0 { // upload (at least from pk-put) requires stat and get too op = op | OpVivify } return am.AllowedAccess(req)&op == op }
go
func AllowedWithAuth(am AuthMode, req *http.Request, op Operation) bool { if op&OpUpload != 0 { // upload (at least from pk-put) requires stat and get too op = op | OpVivify } return am.AllowedAccess(req)&op == op }
[ "func", "AllowedWithAuth", "(", "am", "AuthMode", ",", "req", "*", "http", ".", "Request", ",", "op", "Operation", ")", "bool", "{", "if", "op", "&", "OpUpload", "!=", "0", "{", "// upload (at least from pk-put) requires stat and get too", "op", "=", "op", "|", "OpVivify", "\n", "}", "\n", "return", "am", ".", "AllowedAccess", "(", "req", ")", "&", "op", "==", "op", "\n", "}" ]
// AllowedWithAuth returns whether the given request // has access to perform all the operations in op // against am.
[ "AllowedWithAuth", "returns", "whether", "the", "given", "request", "has", "access", "to", "perform", "all", "the", "operations", "in", "op", "against", "am", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/auth/auth.go#L341-L347
train
perkeep/perkeep
pkg/auth/auth.go
Allowed
func Allowed(req *http.Request, op Operation) bool { for _, m := range modes { if AllowedWithAuth(m, req, op) { return true } } return false }
go
func Allowed(req *http.Request, op Operation) bool { for _, m := range modes { if AllowedWithAuth(m, req, op) { return true } } return false }
[ "func", "Allowed", "(", "req", "*", "http", ".", "Request", ",", "op", "Operation", ")", "bool", "{", "for", "_", ",", "m", ":=", "range", "modes", "{", "if", "AllowedWithAuth", "(", "m", ",", "req", ",", "op", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// Allowed returns whether the given request // has access to perform all the operations in op.
[ "Allowed", "returns", "whether", "the", "given", "request", "has", "access", "to", "perform", "all", "the", "operations", "in", "op", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/auth/auth.go#L351-L358
train
perkeep/perkeep
pkg/auth/auth.go
ServeHTTP
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { h.serveHTTPForOp(w, r, OpAll) }
go
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { h.serveHTTPForOp(w, r, OpAll) }
[ "func", "(", "h", "Handler", ")", "ServeHTTP", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "h", ".", "serveHTTPForOp", "(", "w", ",", "r", ",", "OpAll", ")", "\n", "}" ]
// ServeHTTP serves only if this request and auth mode are allowed all Operations.
[ "ServeHTTP", "serves", "only", "if", "this", "request", "and", "auth", "mode", "are", "allowed", "all", "Operations", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/auth/auth.go#L418-L420
train
perkeep/perkeep
pkg/auth/auth.go
serveHTTPForOp
func (h Handler) serveHTTPForOp(w http.ResponseWriter, r *http.Request, op Operation) { if Allowed(r, op) { h.Handler.ServeHTTP(w, r) } else { SendUnauthorized(w, r) } }
go
func (h Handler) serveHTTPForOp(w http.ResponseWriter, r *http.Request, op Operation) { if Allowed(r, op) { h.Handler.ServeHTTP(w, r) } else { SendUnauthorized(w, r) } }
[ "func", "(", "h", "Handler", ")", "serveHTTPForOp", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ",", "op", "Operation", ")", "{", "if", "Allowed", "(", "r", ",", "op", ")", "{", "h", ".", "Handler", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "}", "else", "{", "SendUnauthorized", "(", "w", ",", "r", ")", "\n", "}", "\n", "}" ]
// serveHTTPForOp serves only if op is allowed for this request and auth mode.
[ "serveHTTPForOp", "serves", "only", "if", "op", "is", "allowed", "for", "this", "request", "and", "auth", "mode", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/auth/auth.go#L423-L429
train
perkeep/perkeep
pkg/auth/auth.go
RequireAuth
func RequireAuth(h http.Handler, op Operation) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { if Allowed(req, op) { h.ServeHTTP(rw, req) } else { SendUnauthorized(rw, req) } }) }
go
func RequireAuth(h http.Handler, op Operation) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { if Allowed(req, op) { h.ServeHTTP(rw, req) } else { SendUnauthorized(rw, req) } }) }
[ "func", "RequireAuth", "(", "h", "http", ".", "Handler", ",", "op", "Operation", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "rw", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "if", "Allowed", "(", "req", ",", "op", ")", "{", "h", ".", "ServeHTTP", "(", "rw", ",", "req", ")", "\n", "}", "else", "{", "SendUnauthorized", "(", "rw", ",", "req", ")", "\n", "}", "\n", "}", ")", "\n", "}" ]
// RequireAuth wraps a function with another function that enforces // HTTP Basic Auth and checks if the operations in op are all permitted.
[ "RequireAuth", "wraps", "a", "function", "with", "another", "function", "that", "enforces", "HTTP", "Basic", "Auth", "and", "checks", "if", "the", "operations", "in", "op", "are", "all", "permitted", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/auth/auth.go#L433-L441
train
perkeep/perkeep
pkg/auth/auth.go
TokenOrNone
func TokenOrNone(token string) (AuthMode, error) { if token == OmitAuthToken { return None{}, nil } return NewTokenAuth(token) }
go
func TokenOrNone(token string) (AuthMode, error) { if token == OmitAuthToken { return None{}, nil } return NewTokenAuth(token) }
[ "func", "TokenOrNone", "(", "token", "string", ")", "(", "AuthMode", ",", "error", ")", "{", "if", "token", "==", "OmitAuthToken", "{", "return", "None", "{", "}", ",", "nil", "\n", "}", "\n", "return", "NewTokenAuth", "(", "token", ")", "\n", "}" ]
// TokenOrNone returns a token auth mode if token is not OmitAuthToken, and // otherwise a None auth mode.
[ "TokenOrNone", "returns", "a", "token", "auth", "mode", "if", "token", "is", "not", "OmitAuthToken", "and", "otherwise", "a", "None", "auth", "mode", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/auth/auth.go#L470-L475
train
perkeep/perkeep
pkg/index/corpus.go
blobMatches
func (srs SignerRefSet) blobMatches(br blob.Ref) bool { for _, v := range srs { if br.EqualString(v) { return true } } return false }
go
func (srs SignerRefSet) blobMatches(br blob.Ref) bool { for _, v := range srs { if br.EqualString(v) { return true } } return false }
[ "func", "(", "srs", "SignerRefSet", ")", "blobMatches", "(", "br", "blob", ".", "Ref", ")", "bool", "{", "for", "_", ",", "v", ":=", "range", "srs", "{", "if", "br", ".", "EqualString", "(", "v", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// blobMatches reports whether br is in the set.
[ "blobMatches", "reports", "whether", "br", "is", "in", "the", "set", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/corpus.go#L127-L134
train
perkeep/perkeep
pkg/index/corpus.go
cacheAttrClaim
func (m attrValues) cacheAttrClaim(cl *camtypes.Claim) { switch cl.Type { case string(schema.SetAttributeClaim): m[cl.Attr] = []string{cl.Value} case string(schema.AddAttributeClaim): m[cl.Attr] = append(m[cl.Attr], cl.Value) case string(schema.DelAttributeClaim): if cl.Value == "" { delete(m, cl.Attr) } else { a, i := m[cl.Attr], 0 for _, v := range a { if v != cl.Value { a[i] = v i++ } } m[cl.Attr] = a[:i] } } }
go
func (m attrValues) cacheAttrClaim(cl *camtypes.Claim) { switch cl.Type { case string(schema.SetAttributeClaim): m[cl.Attr] = []string{cl.Value} case string(schema.AddAttributeClaim): m[cl.Attr] = append(m[cl.Attr], cl.Value) case string(schema.DelAttributeClaim): if cl.Value == "" { delete(m, cl.Attr) } else { a, i := m[cl.Attr], 0 for _, v := range a { if v != cl.Value { a[i] = v i++ } } m[cl.Attr] = a[:i] } } }
[ "func", "(", "m", "attrValues", ")", "cacheAttrClaim", "(", "cl", "*", "camtypes", ".", "Claim", ")", "{", "switch", "cl", ".", "Type", "{", "case", "string", "(", "schema", ".", "SetAttributeClaim", ")", ":", "m", "[", "cl", ".", "Attr", "]", "=", "[", "]", "string", "{", "cl", ".", "Value", "}", "\n", "case", "string", "(", "schema", ".", "AddAttributeClaim", ")", ":", "m", "[", "cl", ".", "Attr", "]", "=", "append", "(", "m", "[", "cl", ".", "Attr", "]", ",", "cl", ".", "Value", ")", "\n", "case", "string", "(", "schema", ".", "DelAttributeClaim", ")", ":", "if", "cl", ".", "Value", "==", "\"", "\"", "{", "delete", "(", "m", ",", "cl", ".", "Attr", ")", "\n", "}", "else", "{", "a", ",", "i", ":=", "m", "[", "cl", ".", "Attr", "]", ",", "0", "\n", "for", "_", ",", "v", ":=", "range", "a", "{", "if", "v", "!=", "cl", ".", "Value", "{", "a", "[", "i", "]", "=", "v", "\n", "i", "++", "\n", "}", "\n", "}", "\n", "m", "[", "cl", ".", "Attr", "]", "=", "a", "[", ":", "i", "]", "\n", "}", "\n", "}", "\n", "}" ]
// cacheAttrClaim applies attribute changes from cl.
[ "cacheAttrClaim", "applies", "attribute", "changes", "from", "cl", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/corpus.go#L172-L192
train
perkeep/perkeep
pkg/index/corpus.go
restoreInvariants
func (pm *PermanodeMeta) restoreInvariants(signers signerFromBlobrefMap) error { sort.Sort(camtypes.ClaimPtrsByDate(pm.Claims)) pm.attr = make(attrValues) pm.signer = make(map[string]attrValues) for _, cl := range pm.Claims { if err := pm.appendAttrClaim(cl, signers); err != nil { return err } } return nil }
go
func (pm *PermanodeMeta) restoreInvariants(signers signerFromBlobrefMap) error { sort.Sort(camtypes.ClaimPtrsByDate(pm.Claims)) pm.attr = make(attrValues) pm.signer = make(map[string]attrValues) for _, cl := range pm.Claims { if err := pm.appendAttrClaim(cl, signers); err != nil { return err } } return nil }
[ "func", "(", "pm", "*", "PermanodeMeta", ")", "restoreInvariants", "(", "signers", "signerFromBlobrefMap", ")", "error", "{", "sort", ".", "Sort", "(", "camtypes", ".", "ClaimPtrsByDate", "(", "pm", ".", "Claims", ")", ")", "\n", "pm", ".", "attr", "=", "make", "(", "attrValues", ")", "\n", "pm", ".", "signer", "=", "make", "(", "map", "[", "string", "]", "attrValues", ")", "\n", "for", "_", ",", "cl", ":=", "range", "pm", ".", "Claims", "{", "if", "err", ":=", "pm", ".", "appendAttrClaim", "(", "cl", ",", "signers", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// restoreInvariants sorts claims by date and // recalculates latest attributes.
[ "restoreInvariants", "sorts", "claims", "by", "date", "and", "recalculates", "latest", "attributes", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/corpus.go#L196-L206
train
perkeep/perkeep
pkg/index/corpus.go
fixupLastClaim
func (pm *PermanodeMeta) fixupLastClaim(signers signerFromBlobrefMap) error { if pm.attr != nil { n := len(pm.Claims) if n < 2 || camtypes.ClaimPtrsByDate(pm.Claims).Less(n-2, n-1) { // already sorted, update Attrs from new Claim return pm.appendAttrClaim(pm.Claims[n-1], signers) } } return pm.restoreInvariants(signers) }
go
func (pm *PermanodeMeta) fixupLastClaim(signers signerFromBlobrefMap) error { if pm.attr != nil { n := len(pm.Claims) if n < 2 || camtypes.ClaimPtrsByDate(pm.Claims).Less(n-2, n-1) { // already sorted, update Attrs from new Claim return pm.appendAttrClaim(pm.Claims[n-1], signers) } } return pm.restoreInvariants(signers) }
[ "func", "(", "pm", "*", "PermanodeMeta", ")", "fixupLastClaim", "(", "signers", "signerFromBlobrefMap", ")", "error", "{", "if", "pm", ".", "attr", "!=", "nil", "{", "n", ":=", "len", "(", "pm", ".", "Claims", ")", "\n", "if", "n", "<", "2", "||", "camtypes", ".", "ClaimPtrsByDate", "(", "pm", ".", "Claims", ")", ".", "Less", "(", "n", "-", "2", ",", "n", "-", "1", ")", "{", "// already sorted, update Attrs from new Claim", "return", "pm", ".", "appendAttrClaim", "(", "pm", ".", "Claims", "[", "n", "-", "1", "]", ",", "signers", ")", "\n", "}", "\n", "}", "\n", "return", "pm", ".", "restoreInvariants", "(", "signers", ")", "\n", "}" ]
// fixupLastClaim fixes invariants on the assumption // that the all but the last element in Claims are sorted by date // and the last element is the only one not yet included in Attrs.
[ "fixupLastClaim", "fixes", "invariants", "on", "the", "assumption", "that", "the", "all", "but", "the", "last", "element", "in", "Claims", "are", "sorted", "by", "date", "and", "the", "last", "element", "is", "the", "only", "one", "not", "yet", "included", "in", "Attrs", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/corpus.go#L211-L220
train
perkeep/perkeep
pkg/index/corpus.go
initDeletes
func (c *Corpus) initDeletes(s sorted.KeyValue) (err error) { it := queryPrefix(s, keyDeleted) defer closeIterator(it, &err) for it.Next() { cl, ok := kvDeleted(it.Key()) if !ok { return fmt.Errorf("Bogus keyDeleted entry key: want |\"deleted\"|<deleted blobref>|<reverse claimdate>|<deleter claim>|, got %q", it.Key()) } targetDeletions := append(c.deletes[cl.Target], deletion{ deleter: cl.BlobRef, when: cl.Date, }) sort.Sort(sort.Reverse(byDeletionDate(targetDeletions))) c.deletes[cl.Target] = targetDeletions } return err }
go
func (c *Corpus) initDeletes(s sorted.KeyValue) (err error) { it := queryPrefix(s, keyDeleted) defer closeIterator(it, &err) for it.Next() { cl, ok := kvDeleted(it.Key()) if !ok { return fmt.Errorf("Bogus keyDeleted entry key: want |\"deleted\"|<deleted blobref>|<reverse claimdate>|<deleter claim>|, got %q", it.Key()) } targetDeletions := append(c.deletes[cl.Target], deletion{ deleter: cl.BlobRef, when: cl.Date, }) sort.Sort(sort.Reverse(byDeletionDate(targetDeletions))) c.deletes[cl.Target] = targetDeletions } return err }
[ "func", "(", "c", "*", "Corpus", ")", "initDeletes", "(", "s", "sorted", ".", "KeyValue", ")", "(", "err", "error", ")", "{", "it", ":=", "queryPrefix", "(", "s", ",", "keyDeleted", ")", "\n", "defer", "closeIterator", "(", "it", ",", "&", "err", ")", "\n", "for", "it", ".", "Next", "(", ")", "{", "cl", ",", "ok", ":=", "kvDeleted", "(", "it", ".", "Key", "(", ")", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\\\"", "\\\"", "\"", ",", "it", ".", "Key", "(", ")", ")", "\n", "}", "\n", "targetDeletions", ":=", "append", "(", "c", ".", "deletes", "[", "cl", ".", "Target", "]", ",", "deletion", "{", "deleter", ":", "cl", ".", "BlobRef", ",", "when", ":", "cl", ".", "Date", ",", "}", ")", "\n", "sort", ".", "Sort", "(", "sort", ".", "Reverse", "(", "byDeletionDate", "(", "targetDeletions", ")", ")", ")", "\n", "c", ".", "deletes", "[", "cl", ".", "Target", "]", "=", "targetDeletions", "\n", "}", "\n", "return", "err", "\n", "}" ]
// initDeletes populates the corpus deletes from the delete entries in s.
[ "initDeletes", "populates", "the", "corpus", "deletes", "from", "the", "delete", "entries", "in", "s", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/corpus.go#L528-L545
train
perkeep/perkeep
pkg/index/corpus.go
updateDeletes
func (c *Corpus) updateDeletes(deleteClaim schema.Claim) error { target := c.br(deleteClaim.Target()) deleter := deleteClaim.Blob() when, err := deleter.ClaimDate() if err != nil { return fmt.Errorf("Could not get date of delete claim %v: %v", deleteClaim, err) } del := deletion{ deleter: c.br(deleter.BlobRef()), when: when, } for _, v := range c.deletes[target] { if v == del { return nil } } targetDeletions := append(c.deletes[target], del) sort.Sort(sort.Reverse(byDeletionDate(targetDeletions))) c.deletes[target] = targetDeletions return nil }
go
func (c *Corpus) updateDeletes(deleteClaim schema.Claim) error { target := c.br(deleteClaim.Target()) deleter := deleteClaim.Blob() when, err := deleter.ClaimDate() if err != nil { return fmt.Errorf("Could not get date of delete claim %v: %v", deleteClaim, err) } del := deletion{ deleter: c.br(deleter.BlobRef()), when: when, } for _, v := range c.deletes[target] { if v == del { return nil } } targetDeletions := append(c.deletes[target], del) sort.Sort(sort.Reverse(byDeletionDate(targetDeletions))) c.deletes[target] = targetDeletions return nil }
[ "func", "(", "c", "*", "Corpus", ")", "updateDeletes", "(", "deleteClaim", "schema", ".", "Claim", ")", "error", "{", "target", ":=", "c", ".", "br", "(", "deleteClaim", ".", "Target", "(", ")", ")", "\n", "deleter", ":=", "deleteClaim", ".", "Blob", "(", ")", "\n", "when", ",", "err", ":=", "deleter", ".", "ClaimDate", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "deleteClaim", ",", "err", ")", "\n", "}", "\n", "del", ":=", "deletion", "{", "deleter", ":", "c", ".", "br", "(", "deleter", ".", "BlobRef", "(", ")", ")", ",", "when", ":", "when", ",", "}", "\n", "for", "_", ",", "v", ":=", "range", "c", ".", "deletes", "[", "target", "]", "{", "if", "v", "==", "del", "{", "return", "nil", "\n", "}", "\n", "}", "\n", "targetDeletions", ":=", "append", "(", "c", ".", "deletes", "[", "target", "]", ",", "del", ")", "\n", "sort", ".", "Sort", "(", "sort", ".", "Reverse", "(", "byDeletionDate", "(", "targetDeletions", ")", ")", ")", "\n", "c", ".", "deletes", "[", "target", "]", "=", "targetDeletions", "\n", "return", "nil", "\n", "}" ]
// updateDeletes updates the corpus deletes with the delete claim deleteClaim. // deleteClaim is trusted to be a valid delete Claim.
[ "updateDeletes", "updates", "the", "corpus", "deletes", "with", "the", "delete", "claim", "deleteClaim", ".", "deleteClaim", "is", "trusted", "to", "be", "a", "valid", "delete", "Claim", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/corpus.go#L644-L664
train
perkeep/perkeep
pkg/index/corpus.go
mergeWholeToFileRow
func (c *Corpus) mergeWholeToFileRow(k, v []byte) error { pair := k[len("wholetofile|"):] pipe := bytes.IndexByte(pair, '|') if pipe < 0 { return fmt.Errorf("bogus row %q = %q", k, v) } wholeRef, ok1 := blob.ParseBytes(pair[:pipe]) fileRef, ok2 := blob.ParseBytes(pair[pipe+1:]) if !ok1 || !ok2 { return fmt.Errorf("bogus row %q = %q", k, v) } c.fileWholeRef[fileRef] = wholeRef if c.building && !c.hasLegacySHA1 { if bytes.HasPrefix(pair, sha1Prefix) { c.hasLegacySHA1 = true } } return nil }
go
func (c *Corpus) mergeWholeToFileRow(k, v []byte) error { pair := k[len("wholetofile|"):] pipe := bytes.IndexByte(pair, '|') if pipe < 0 { return fmt.Errorf("bogus row %q = %q", k, v) } wholeRef, ok1 := blob.ParseBytes(pair[:pipe]) fileRef, ok2 := blob.ParseBytes(pair[pipe+1:]) if !ok1 || !ok2 { return fmt.Errorf("bogus row %q = %q", k, v) } c.fileWholeRef[fileRef] = wholeRef if c.building && !c.hasLegacySHA1 { if bytes.HasPrefix(pair, sha1Prefix) { c.hasLegacySHA1 = true } } return nil }
[ "func", "(", "c", "*", "Corpus", ")", "mergeWholeToFileRow", "(", "k", ",", "v", "[", "]", "byte", ")", "error", "{", "pair", ":=", "k", "[", "len", "(", "\"", "\"", ")", ":", "]", "\n", "pipe", ":=", "bytes", ".", "IndexByte", "(", "pair", ",", "'|'", ")", "\n", "if", "pipe", "<", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "k", ",", "v", ")", "\n", "}", "\n", "wholeRef", ",", "ok1", ":=", "blob", ".", "ParseBytes", "(", "pair", "[", ":", "pipe", "]", ")", "\n", "fileRef", ",", "ok2", ":=", "blob", ".", "ParseBytes", "(", "pair", "[", "pipe", "+", "1", ":", "]", ")", "\n", "if", "!", "ok1", "||", "!", "ok2", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "k", ",", "v", ")", "\n", "}", "\n", "c", ".", "fileWholeRef", "[", "fileRef", "]", "=", "wholeRef", "\n", "if", "c", ".", "building", "&&", "!", "c", ".", "hasLegacySHA1", "{", "if", "bytes", ".", "HasPrefix", "(", "pair", ",", "sha1Prefix", ")", "{", "c", ".", "hasLegacySHA1", "=", "true", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// "wholetofile|sha1-17b53c7c3e664d3613dfdce50ef1f2a09e8f04b5|sha1-fb88f3eab3acfcf3cfc8cd77ae4366f6f975d227" -> "1"
[ "wholetofile|sha1", "-", "17b53c7c3e664d3613dfdce50ef1f2a09e8f04b5|sha1", "-", "fb88f3eab3acfcf3cfc8cd77ae4366f6f975d227", "-", ">", "1" ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/corpus.go#L854-L872
train
perkeep/perkeep
pkg/index/corpus.go
mergeMediaTag
func (c *Corpus) mergeMediaTag(k, v []byte) error { f := strings.Split(string(k), "|") if len(f) != 3 { return fmt.Errorf("unexpected key %q", k) } wholeRef, ok := blob.Parse(f[1]) if !ok { return fmt.Errorf("failed to parse wholeref from key %q", k) } tm, ok := c.mediaTags[wholeRef] if !ok { tm = make(map[string]string) c.mediaTags[wholeRef] = tm } tm[c.str(f[2])] = c.str(urld(string(v))) return nil }
go
func (c *Corpus) mergeMediaTag(k, v []byte) error { f := strings.Split(string(k), "|") if len(f) != 3 { return fmt.Errorf("unexpected key %q", k) } wholeRef, ok := blob.Parse(f[1]) if !ok { return fmt.Errorf("failed to parse wholeref from key %q", k) } tm, ok := c.mediaTags[wholeRef] if !ok { tm = make(map[string]string) c.mediaTags[wholeRef] = tm } tm[c.str(f[2])] = c.str(urld(string(v))) return nil }
[ "func", "(", "c", "*", "Corpus", ")", "mergeMediaTag", "(", "k", ",", "v", "[", "]", "byte", ")", "error", "{", "f", ":=", "strings", ".", "Split", "(", "string", "(", "k", ")", ",", "\"", "\"", ")", "\n", "if", "len", "(", "f", ")", "!=", "3", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "k", ")", "\n", "}", "\n", "wholeRef", ",", "ok", ":=", "blob", ".", "Parse", "(", "f", "[", "1", "]", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "k", ")", "\n", "}", "\n", "tm", ",", "ok", ":=", "c", ".", "mediaTags", "[", "wholeRef", "]", "\n", "if", "!", "ok", "{", "tm", "=", "make", "(", "map", "[", "string", "]", "string", ")", "\n", "c", ".", "mediaTags", "[", "wholeRef", "]", "=", "tm", "\n", "}", "\n", "tm", "[", "c", ".", "str", "(", "f", "[", "2", "]", ")", "]", "=", "c", ".", "str", "(", "urld", "(", "string", "(", "v", ")", ")", ")", "\n", "return", "nil", "\n", "}" ]
// "mediatag|sha1-2b219be9d9691b4f8090e7ee2690098097f59566|album" = "Some+Album+Name"
[ "mediatag|sha1", "-", "2b219be9d9691b4f8090e7ee2690098097f59566|album", "=", "Some", "+", "Album", "+", "Name" ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/corpus.go#L875-L891
train
perkeep/perkeep
pkg/index/corpus.go
mergeEXIFGPSRow
func (c *Corpus) mergeEXIFGPSRow(k, v []byte) error { wholeRef, ok := blob.ParseBytes(k[len("exifgps|"):]) pipe := bytes.IndexByte(v, '|') if pipe < 0 || !ok { return fmt.Errorf("bogus row %q = %q", k, v) } lat, err := strconv.ParseFloat(string(v[:pipe]), 64) long, err1 := strconv.ParseFloat(string(v[pipe+1:]), 64) if err != nil || err1 != nil { if err != nil { log.Printf("index: bogus latitude in value of row %q = %q", k, v) } else { log.Printf("index: bogus longitude in value of row %q = %q", k, v) } return nil } c.gps[wholeRef] = latLong{lat, long} return nil }
go
func (c *Corpus) mergeEXIFGPSRow(k, v []byte) error { wholeRef, ok := blob.ParseBytes(k[len("exifgps|"):]) pipe := bytes.IndexByte(v, '|') if pipe < 0 || !ok { return fmt.Errorf("bogus row %q = %q", k, v) } lat, err := strconv.ParseFloat(string(v[:pipe]), 64) long, err1 := strconv.ParseFloat(string(v[pipe+1:]), 64) if err != nil || err1 != nil { if err != nil { log.Printf("index: bogus latitude in value of row %q = %q", k, v) } else { log.Printf("index: bogus longitude in value of row %q = %q", k, v) } return nil } c.gps[wholeRef] = latLong{lat, long} return nil }
[ "func", "(", "c", "*", "Corpus", ")", "mergeEXIFGPSRow", "(", "k", ",", "v", "[", "]", "byte", ")", "error", "{", "wholeRef", ",", "ok", ":=", "blob", ".", "ParseBytes", "(", "k", "[", "len", "(", "\"", "\"", ")", ":", "]", ")", "\n", "pipe", ":=", "bytes", ".", "IndexByte", "(", "v", ",", "'|'", ")", "\n", "if", "pipe", "<", "0", "||", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "k", ",", "v", ")", "\n", "}", "\n", "lat", ",", "err", ":=", "strconv", ".", "ParseFloat", "(", "string", "(", "v", "[", ":", "pipe", "]", ")", ",", "64", ")", "\n", "long", ",", "err1", ":=", "strconv", ".", "ParseFloat", "(", "string", "(", "v", "[", "pipe", "+", "1", ":", "]", ")", ",", "64", ")", "\n", "if", "err", "!=", "nil", "||", "err1", "!=", "nil", "{", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "k", ",", "v", ")", "\n", "}", "else", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "k", ",", "v", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "c", ".", "gps", "[", "wholeRef", "]", "=", "latLong", "{", "lat", ",", "long", "}", "\n", "return", "nil", "\n", "}" ]
// "exifgps|sha1-17b53c7c3e664d3613dfdce50ef1f2a09e8f04b5" -> "-122.39897155555556|37.61952208333334"
[ "exifgps|sha1", "-", "17b53c7c3e664d3613dfdce50ef1f2a09e8f04b5", "-", ">", "-", "122", ".", "39897155555556|37", ".", "61952208333334" ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/corpus.go#L894-L912
train