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
pkg/importer/flickr/flickr.go
updatePrimaryPhoto
func (r *run) updatePrimaryPhoto(photoNode *importer.Object) error { photoId := photoNode.Attr(attrFlickrId) for album, photo := range r.primaryPhoto { if photoId != photo { continue } setsNode, err := r.getTopLevelNode("sets", "Sets") if err != nil { return fmt.Errorf("could not set %v as primary photo of %v, no root sets: %v", photoId, album, err) } setNode, err := setsNode.ChildPathObject(album) if err != nil { return fmt.Errorf("could not set %v as primary photo of %v, no album: %v", photoId, album, err) } fileRef := photoNode.Attr(nodeattr.CamliContent) if fileRef == "" { return fmt.Errorf("could not set %v as primary photo of %v: fileRef of photo is unknown", photoId, album) } if err := setNode.SetAttr(nodeattr.CamliContentImage, fileRef); err != nil { return fmt.Errorf("could not set %v as primary photo of %v: %v", photoId, album, err) } delete(r.primaryPhoto, album) } return nil }
go
func (r *run) updatePrimaryPhoto(photoNode *importer.Object) error { photoId := photoNode.Attr(attrFlickrId) for album, photo := range r.primaryPhoto { if photoId != photo { continue } setsNode, err := r.getTopLevelNode("sets", "Sets") if err != nil { return fmt.Errorf("could not set %v as primary photo of %v, no root sets: %v", photoId, album, err) } setNode, err := setsNode.ChildPathObject(album) if err != nil { return fmt.Errorf("could not set %v as primary photo of %v, no album: %v", photoId, album, err) } fileRef := photoNode.Attr(nodeattr.CamliContent) if fileRef == "" { return fmt.Errorf("could not set %v as primary photo of %v: fileRef of photo is unknown", photoId, album) } if err := setNode.SetAttr(nodeattr.CamliContentImage, fileRef); err != nil { return fmt.Errorf("could not set %v as primary photo of %v: %v", photoId, album, err) } delete(r.primaryPhoto, album) } return nil }
[ "func", "(", "r", "*", "run", ")", "updatePrimaryPhoto", "(", "photoNode", "*", "importer", ".", "Object", ")", "error", "{", "photoId", ":=", "photoNode", ".", "Attr", "(", "attrFlickrId", ")", "\n", "for", "album", ",", "photo", ":=", "range", "r", ".", "primaryPhoto", "{", "if", "photoId", "!=", "photo", "{", "continue", "\n", "}", "\n", "setsNode", ",", "err", ":=", "r", ".", "getTopLevelNode", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "photoId", ",", "album", ",", "err", ")", "\n", "}", "\n", "setNode", ",", "err", ":=", "setsNode", ".", "ChildPathObject", "(", "album", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "photoId", ",", "album", ",", "err", ")", "\n", "}", "\n", "fileRef", ":=", "photoNode", ".", "Attr", "(", "nodeattr", ".", "CamliContent", ")", "\n", "if", "fileRef", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "photoId", ",", "album", ")", "\n", "}", "\n", "if", "err", ":=", "setNode", ".", "SetAttr", "(", "nodeattr", ".", "CamliContentImage", ",", "fileRef", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "photoId", ",", "album", ",", "err", ")", "\n", "}", "\n", "delete", "(", "r", ".", "primaryPhoto", ",", "album", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// updatePrimaryPhoto uses the camliContent of photoNode to set the // camliContentImage of any album for which photoNode is the primary photo.
[ "updatePrimaryPhoto", "uses", "the", "camliContent", "of", "photoNode", "to", "set", "the", "camliContentImage", "of", "any", "album", "for", "which", "photoNode", "is", "the", "primary", "photo", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/flickr/flickr.go#L455-L479
train
perkeep/perkeep
internal/images/docker.go
pull
func pull(image string) error { var stdout, stderr bytes.Buffer cmd := exec.Command("docker", "pull", image) cmd.Stdout = &stdout cmd.Stderr = &stderr err := cmd.Run() out := stdout.String() // TODO(mpl): if it turns out docker respects conventions and the // "Authentication is required" message does come from stderr, then quit // checking stdout. if err != nil || stderr.Len() != 0 || strings.Contains(out, "Authentication is required") { return fmt.Errorf("docker pull failed: stdout: %s, stderr: %s, err: %v", out, stderr.String(), err) } return nil }
go
func pull(image string) error { var stdout, stderr bytes.Buffer cmd := exec.Command("docker", "pull", image) cmd.Stdout = &stdout cmd.Stderr = &stderr err := cmd.Run() out := stdout.String() // TODO(mpl): if it turns out docker respects conventions and the // "Authentication is required" message does come from stderr, then quit // checking stdout. if err != nil || stderr.Len() != 0 || strings.Contains(out, "Authentication is required") { return fmt.Errorf("docker pull failed: stdout: %s, stderr: %s, err: %v", out, stderr.String(), err) } return nil }
[ "func", "pull", "(", "image", "string", ")", "error", "{", "var", "stdout", ",", "stderr", "bytes", ".", "Buffer", "\n", "cmd", ":=", "exec", ".", "Command", "(", "\"", "\"", ",", "\"", "\"", ",", "image", ")", "\n", "cmd", ".", "Stdout", "=", "&", "stdout", "\n", "cmd", ".", "Stderr", "=", "&", "stderr", "\n", "err", ":=", "cmd", ".", "Run", "(", ")", "\n", "out", ":=", "stdout", ".", "String", "(", ")", "\n", "// TODO(mpl): if it turns out docker respects conventions and the", "// \"Authentication is required\" message does come from stderr, then quit", "// checking stdout.", "if", "err", "!=", "nil", "||", "stderr", ".", "Len", "(", ")", "!=", "0", "||", "strings", ".", "Contains", "(", "out", ",", "\"", "\"", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "out", ",", "stderr", ".", "String", "(", ")", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Pull retrieves the docker image with 'docker pull'.
[ "Pull", "retrieves", "the", "docker", "image", "with", "docker", "pull", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/images/docker.go#L78-L92
train
perkeep/perkeep
app/scanningcabinet/datastore.go
updateScan
func (h *handler) updateScan(ctx context.Context, pn blob.Ref, new, old *mediaObject) error { if old == nil { mo, err := h.fetchScan(pn) if err != nil { return fmt.Errorf("scan %v not found: %v", pn, err) } old = &mo } if new.contentRef.Valid() && old.contentRef != new.contentRef { if err := h.setAttribute(ctx, pn, "camliContent", new.contentRef.String()); err != nil { return fmt.Errorf("could not set contentRef for scan %v: %v", pn, err) } } if new.documentRef.Valid() && old.documentRef != new.documentRef { if err := h.setAttribute(ctx, pn, "document", new.documentRef.String()); err != nil { return fmt.Errorf("could not set documentRef for scan %v: %v", pn, err) } } if !old.creation.Equal(new.creation) { if new.creation.IsZero() { if err := h.delAttribute(ctx, pn, nodeattr.DateCreated, ""); err != nil { return fmt.Errorf("could not delete creation date for scan %v: %v", pn, err) } } else { if err := h.setAttribute(ctx, pn, nodeattr.DateCreated, new.creation.UTC().Format(time.RFC3339)); err != nil { return fmt.Errorf("could not set creation date for scan %v: %v", pn, err) } } } return nil }
go
func (h *handler) updateScan(ctx context.Context, pn blob.Ref, new, old *mediaObject) error { if old == nil { mo, err := h.fetchScan(pn) if err != nil { return fmt.Errorf("scan %v not found: %v", pn, err) } old = &mo } if new.contentRef.Valid() && old.contentRef != new.contentRef { if err := h.setAttribute(ctx, pn, "camliContent", new.contentRef.String()); err != nil { return fmt.Errorf("could not set contentRef for scan %v: %v", pn, err) } } if new.documentRef.Valid() && old.documentRef != new.documentRef { if err := h.setAttribute(ctx, pn, "document", new.documentRef.String()); err != nil { return fmt.Errorf("could not set documentRef for scan %v: %v", pn, err) } } if !old.creation.Equal(new.creation) { if new.creation.IsZero() { if err := h.delAttribute(ctx, pn, nodeattr.DateCreated, ""); err != nil { return fmt.Errorf("could not delete creation date for scan %v: %v", pn, err) } } else { if err := h.setAttribute(ctx, pn, nodeattr.DateCreated, new.creation.UTC().Format(time.RFC3339)); err != nil { return fmt.Errorf("could not set creation date for scan %v: %v", pn, err) } } } return nil }
[ "func", "(", "h", "*", "handler", ")", "updateScan", "(", "ctx", "context", ".", "Context", ",", "pn", "blob", ".", "Ref", ",", "new", ",", "old", "*", "mediaObject", ")", "error", "{", "if", "old", "==", "nil", "{", "mo", ",", "err", ":=", "h", ".", "fetchScan", "(", "pn", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "pn", ",", "err", ")", "\n", "}", "\n", "old", "=", "&", "mo", "\n", "}", "\n", "if", "new", ".", "contentRef", ".", "Valid", "(", ")", "&&", "old", ".", "contentRef", "!=", "new", ".", "contentRef", "{", "if", "err", ":=", "h", ".", "setAttribute", "(", "ctx", ",", "pn", ",", "\"", "\"", ",", "new", ".", "contentRef", ".", "String", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "pn", ",", "err", ")", "\n", "}", "\n", "}", "\n", "if", "new", ".", "documentRef", ".", "Valid", "(", ")", "&&", "old", ".", "documentRef", "!=", "new", ".", "documentRef", "{", "if", "err", ":=", "h", ".", "setAttribute", "(", "ctx", ",", "pn", ",", "\"", "\"", ",", "new", ".", "documentRef", ".", "String", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "pn", ",", "err", ")", "\n", "}", "\n", "}", "\n", "if", "!", "old", ".", "creation", ".", "Equal", "(", "new", ".", "creation", ")", "{", "if", "new", ".", "creation", ".", "IsZero", "(", ")", "{", "if", "err", ":=", "h", ".", "delAttribute", "(", "ctx", ",", "pn", ",", "nodeattr", ".", "DateCreated", ",", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "pn", ",", "err", ")", "\n", "}", "\n", "}", "else", "{", "if", "err", ":=", "h", ".", "setAttribute", "(", "ctx", ",", "pn", ",", "nodeattr", ".", "DateCreated", ",", "new", ".", "creation", ".", "UTC", "(", ")", ".", "Format", "(", "time", ".", "RFC3339", ")", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "pn", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// old is an optimization, in case the caller already had fetched the old scan. // If nil, the current scan will be fetched for comparison with new.
[ "old", "is", "an", "optimization", "in", "case", "the", "caller", "already", "had", "fetched", "the", "old", "scan", ".", "If", "nil", "the", "current", "scan", "will", "be", "fetched", "for", "comparison", "with", "new", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/scanningcabinet/datastore.go#L331-L361
train
perkeep/perkeep
app/scanningcabinet/datastore.go
persistDocAndPages
func (h *handler) persistDocAndPages(ctx context.Context, newDoc document) (blob.Ref, error) { br := blob.Ref{} pn, err := h.createDocument(ctx, newDoc) if err != nil { return br, err } for _, page := range newDoc.pages { if err := h.setAttribute(ctx, page, "document", pn.String()); err != nil { return br, fmt.Errorf("could not update scan %v with %v:%v", page, "document", pn) } } return pn, nil }
go
func (h *handler) persistDocAndPages(ctx context.Context, newDoc document) (blob.Ref, error) { br := blob.Ref{} pn, err := h.createDocument(ctx, newDoc) if err != nil { return br, err } for _, page := range newDoc.pages { if err := h.setAttribute(ctx, page, "document", pn.String()); err != nil { return br, fmt.Errorf("could not update scan %v with %v:%v", page, "document", pn) } } return pn, nil }
[ "func", "(", "h", "*", "handler", ")", "persistDocAndPages", "(", "ctx", "context", ".", "Context", ",", "newDoc", "document", ")", "(", "blob", ".", "Ref", ",", "error", ")", "{", "br", ":=", "blob", ".", "Ref", "{", "}", "\n", "pn", ",", "err", ":=", "h", ".", "createDocument", "(", "ctx", ",", "newDoc", ")", "\n", "if", "err", "!=", "nil", "{", "return", "br", ",", "err", "\n", "}", "\n", "for", "_", ",", "page", ":=", "range", "newDoc", ".", "pages", "{", "if", "err", ":=", "h", ".", "setAttribute", "(", "ctx", ",", "page", ",", "\"", "\"", ",", "pn", ".", "String", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "br", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "page", ",", "\"", "\"", ",", "pn", ")", "\n\n", "}", "\n", "}", "\n", "return", "pn", ",", "nil", "\n", "}" ]
// persistDocAndPages creates a new Document struct that represents // the given mediaObject structs and stores it in the datastore, updates each of // these mediaObject in the datastore with references back to the new Document struct // and returns the key to the new document entity
[ "persistDocAndPages", "creates", "a", "new", "Document", "struct", "that", "represents", "the", "given", "mediaObject", "structs", "and", "stores", "it", "in", "the", "datastore", "updates", "each", "of", "these", "mediaObject", "in", "the", "datastore", "with", "references", "back", "to", "the", "new", "Document", "struct", "and", "returns", "the", "key", "to", "the", "new", "document", "entity" ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/scanningcabinet/datastore.go#L480-L493
train
perkeep/perkeep
app/scanningcabinet/datastore.go
dateOrZero
func dateOrZero(datestr, format string) (time.Time, error) { if datestr == "" { return time.Time{}, nil } if format == "" { format = time.RFC3339 } return time.Parse(format, datestr) }
go
func dateOrZero(datestr, format string) (time.Time, error) { if datestr == "" { return time.Time{}, nil } if format == "" { format = time.RFC3339 } return time.Parse(format, datestr) }
[ "func", "dateOrZero", "(", "datestr", ",", "format", "string", ")", "(", "time", ".", "Time", ",", "error", ")", "{", "if", "datestr", "==", "\"", "\"", "{", "return", "time", ".", "Time", "{", "}", ",", "nil", "\n", "}", "\n", "if", "format", "==", "\"", "\"", "{", "format", "=", "time", ".", "RFC3339", "\n", "}", "\n", "return", "time", ".", "Parse", "(", "format", ",", "datestr", ")", "\n", "}" ]
// dateOrZero parses datestr with the given format and returns the resulting // time and error. An empty datestr is not an error and yields a zero time. format // defaults to time.RFC3339 if empty.
[ "dateOrZero", "parses", "datestr", "with", "the", "given", "format", "and", "returns", "the", "resulting", "time", "and", "error", ".", "An", "empty", "datestr", "is", "not", "an", "error", "and", "yields", "a", "zero", "time", ".", "format", "defaults", "to", "time", ".", "RFC3339", "if", "empty", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/scanningcabinet/datastore.go#L769-L777
train
perkeep/perkeep
app/scanningcabinet/datastore.go
breakAndDeleteDoc
func (h *handler) breakAndDeleteDoc(ctx context.Context, docRef blob.Ref) error { doc, err := h.fetchDocument(docRef) if err != nil { return fmt.Errorf("document %v not found: %v", docRef, err) } if err := h.deleteNode(ctx, docRef); err != nil { return fmt.Errorf("could not delete document %v: %v", docRef, err) } for _, page := range doc.pages { if err := h.delAttribute(ctx, page, "document", ""); err != nil { return fmt.Errorf("could not unset document of scan %v: %v", page, err) } } return nil }
go
func (h *handler) breakAndDeleteDoc(ctx context.Context, docRef blob.Ref) error { doc, err := h.fetchDocument(docRef) if err != nil { return fmt.Errorf("document %v not found: %v", docRef, err) } if err := h.deleteNode(ctx, docRef); err != nil { return fmt.Errorf("could not delete document %v: %v", docRef, err) } for _, page := range doc.pages { if err := h.delAttribute(ctx, page, "document", ""); err != nil { return fmt.Errorf("could not unset document of scan %v: %v", page, err) } } return nil }
[ "func", "(", "h", "*", "handler", ")", "breakAndDeleteDoc", "(", "ctx", "context", ".", "Context", ",", "docRef", "blob", ".", "Ref", ")", "error", "{", "doc", ",", "err", ":=", "h", ".", "fetchDocument", "(", "docRef", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "docRef", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "h", ".", "deleteNode", "(", "ctx", ",", "docRef", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "docRef", ",", "err", ")", "\n", "}", "\n", "for", "_", ",", "page", ":=", "range", "doc", ".", "pages", "{", "if", "err", ":=", "h", ".", "delAttribute", "(", "ctx", ",", "page", ",", "\"", "\"", ",", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "page", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// breakAndDeleteDoc deletes the given document struct and marks all of its // associated mediaObject as not being part of a document
[ "breakAndDeleteDoc", "deletes", "the", "given", "document", "struct", "and", "marks", "all", "of", "its", "associated", "mediaObject", "as", "not", "being", "part", "of", "a", "document" ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/scanningcabinet/datastore.go#L840-L854
train
perkeep/perkeep
pkg/index/index.go
NewOwner
func NewOwner(keyID string, ref blob.Ref) *Owner { return &Owner{ keyID: []string{keyID}, blobByKeyID: map[string]SignerRefSet{keyID: SignerRefSet{ref.String()}}, } }
go
func NewOwner(keyID string, ref blob.Ref) *Owner { return &Owner{ keyID: []string{keyID}, blobByKeyID: map[string]SignerRefSet{keyID: SignerRefSet{ref.String()}}, } }
[ "func", "NewOwner", "(", "keyID", "string", ",", "ref", "blob", ".", "Ref", ")", "*", "Owner", "{", "return", "&", "Owner", "{", "keyID", ":", "[", "]", "string", "{", "keyID", "}", ",", "blobByKeyID", ":", "map", "[", "string", "]", "SignerRefSet", "{", "keyID", ":", "SignerRefSet", "{", "ref", ".", "String", "(", ")", "}", "}", ",", "}", "\n", "}" ]
// NewOwner returns an Owner that associates keyID with ref.
[ "NewOwner", "returns", "an", "Owner", "that", "associates", "keyID", "with", "ref", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/index.go#L124-L129
train
perkeep/perkeep
pkg/index/index.go
RefSet
func (o *Owner) RefSet(keyID string) SignerRefSet { if o == nil || len(o.blobByKeyID) == 0 { return nil } refs := o.blobByKeyID[keyID] if len(refs) == 0 { return nil } return refs }
go
func (o *Owner) RefSet(keyID string) SignerRefSet { if o == nil || len(o.blobByKeyID) == 0 { return nil } refs := o.blobByKeyID[keyID] if len(refs) == 0 { return nil } return refs }
[ "func", "(", "o", "*", "Owner", ")", "RefSet", "(", "keyID", "string", ")", "SignerRefSet", "{", "if", "o", "==", "nil", "||", "len", "(", "o", ".", "blobByKeyID", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "refs", ":=", "o", ".", "blobByKeyID", "[", "keyID", "]", "\n", "if", "len", "(", "refs", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n", "return", "refs", "\n", "}" ]
// RefSet returns the set of refs that represent the same owner as keyID.
[ "RefSet", "returns", "the", "set", "of", "refs", "that", "represent", "the", "same", "owner", "as", "keyID", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/index.go#L141-L150
train
perkeep/perkeep
pkg/index/index.go
SetReindexMaxProcs
func SetReindexMaxProcs(n int) { reindexMaxProcs.Lock() defer reindexMaxProcs.Unlock() reindexMaxProcs.v = n }
go
func SetReindexMaxProcs(n int) { reindexMaxProcs.Lock() defer reindexMaxProcs.Unlock() reindexMaxProcs.v = n }
[ "func", "SetReindexMaxProcs", "(", "n", "int", ")", "{", "reindexMaxProcs", ".", "Lock", "(", ")", "\n", "defer", "reindexMaxProcs", ".", "Unlock", "(", ")", "\n", "reindexMaxProcs", ".", "v", "=", "n", "\n", "}" ]
// SetReindexMaxProcs sets the maximum number of concurrent goroutines that are // used during reindexing.
[ "SetReindexMaxProcs", "sets", "the", "maximum", "number", "of", "concurrent", "goroutines", "that", "are", "used", "during", "reindexing", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/index.go#L435-L439
train
perkeep/perkeep
pkg/index/index.go
integrityCheck
func (x *Index) integrityCheck(timeout time.Duration) error { t0 := time.Now() x.logf("starting integrity check...") defer func() { x.logf("integrity check done (after %v)", time.Since(t0).Round(10*time.Millisecond)) }() if x.blobSource == nil { return errors.New("index: can't check sanity of index: no blobSource") } // we don't actually need seen atm, but I anticipate we'll return it at some // point, so we can display the blobs that were tested/seen/missed on the web UI. seen := make([]blob.Ref, 0) notFound := make([]blob.Ref, 0) enumCtx := context.TODO() stopTime := time.NewTimer(timeout) defer stopTime.Stop() var errEOT = errors.New("time's out") if err := blobserver.EnumerateAll(enumCtx, x.blobSource, func(sb blob.SizedRef) error { select { case <-stopTime.C: return errEOT default: } if _, err := x.GetBlobMeta(enumCtx, sb.Ref); err != nil { if !os.IsNotExist(err) { return err } notFound = append(notFound, sb.Ref) return nil } seen = append(seen, sb.Ref) return nil }); err != nil && err != errEOT { return err } if len(notFound) > 0 { // TODO(mpl): at least on GCE, display that message and maybe more on a web UI page as well. x.logf("WARNING: sanity checking of the index found %d non-indexed blobs out of %d tested blobs. Reindexing is advised.", len(notFound), len(notFound)+len(seen)) } return nil }
go
func (x *Index) integrityCheck(timeout time.Duration) error { t0 := time.Now() x.logf("starting integrity check...") defer func() { x.logf("integrity check done (after %v)", time.Since(t0).Round(10*time.Millisecond)) }() if x.blobSource == nil { return errors.New("index: can't check sanity of index: no blobSource") } // we don't actually need seen atm, but I anticipate we'll return it at some // point, so we can display the blobs that were tested/seen/missed on the web UI. seen := make([]blob.Ref, 0) notFound := make([]blob.Ref, 0) enumCtx := context.TODO() stopTime := time.NewTimer(timeout) defer stopTime.Stop() var errEOT = errors.New("time's out") if err := blobserver.EnumerateAll(enumCtx, x.blobSource, func(sb blob.SizedRef) error { select { case <-stopTime.C: return errEOT default: } if _, err := x.GetBlobMeta(enumCtx, sb.Ref); err != nil { if !os.IsNotExist(err) { return err } notFound = append(notFound, sb.Ref) return nil } seen = append(seen, sb.Ref) return nil }); err != nil && err != errEOT { return err } if len(notFound) > 0 { // TODO(mpl): at least on GCE, display that message and maybe more on a web UI page as well. x.logf("WARNING: sanity checking of the index found %d non-indexed blobs out of %d tested blobs. Reindexing is advised.", len(notFound), len(notFound)+len(seen)) } return nil }
[ "func", "(", "x", "*", "Index", ")", "integrityCheck", "(", "timeout", "time", ".", "Duration", ")", "error", "{", "t0", ":=", "time", ".", "Now", "(", ")", "\n", "x", ".", "logf", "(", "\"", "\"", ")", "\n", "defer", "func", "(", ")", "{", "x", ".", "logf", "(", "\"", "\"", ",", "time", ".", "Since", "(", "t0", ")", ".", "Round", "(", "10", "*", "time", ".", "Millisecond", ")", ")", "\n", "}", "(", ")", "\n", "if", "x", ".", "blobSource", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// we don't actually need seen atm, but I anticipate we'll return it at some", "// point, so we can display the blobs that were tested/seen/missed on the web UI.", "seen", ":=", "make", "(", "[", "]", "blob", ".", "Ref", ",", "0", ")", "\n", "notFound", ":=", "make", "(", "[", "]", "blob", ".", "Ref", ",", "0", ")", "\n", "enumCtx", ":=", "context", ".", "TODO", "(", ")", "\n", "stopTime", ":=", "time", ".", "NewTimer", "(", "timeout", ")", "\n", "defer", "stopTime", ".", "Stop", "(", ")", "\n", "var", "errEOT", "=", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "if", "err", ":=", "blobserver", ".", "EnumerateAll", "(", "enumCtx", ",", "x", ".", "blobSource", ",", "func", "(", "sb", "blob", ".", "SizedRef", ")", "error", "{", "select", "{", "case", "<-", "stopTime", ".", "C", ":", "return", "errEOT", "\n", "default", ":", "}", "\n", "if", "_", ",", "err", ":=", "x", ".", "GetBlobMeta", "(", "enumCtx", ",", "sb", ".", "Ref", ")", ";", "err", "!=", "nil", "{", "if", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "err", "\n", "}", "\n", "notFound", "=", "append", "(", "notFound", ",", "sb", ".", "Ref", ")", "\n", "return", "nil", "\n", "}", "\n", "seen", "=", "append", "(", "seen", ",", "sb", ".", "Ref", ")", "\n", "return", "nil", "\n", "}", ")", ";", "err", "!=", "nil", "&&", "err", "!=", "errEOT", "{", "return", "err", "\n", "}", "\n", "if", "len", "(", "notFound", ")", ">", "0", "{", "// TODO(mpl): at least on GCE, display that message and maybe more on a web UI page as well.", "x", ".", "logf", "(", "\"", "\"", ",", "len", "(", "notFound", ")", ",", "len", "(", "notFound", ")", "+", "len", "(", "seen", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// integrityCheck enumerates blobs through x.blobSource during timemout, and // verifies for each of them that it has a meta row in the index. It logs a message // if any of them is not found. It only returns an error if something went wrong // during the enumeration.
[ "integrityCheck", "enumerates", "blobs", "through", "x", ".", "blobSource", "during", "timemout", "and", "verifies", "for", "each", "of", "them", "that", "it", "has", "a", "meta", "row", "in", "the", "index", ".", "It", "logs", "a", "message", "if", "any", "of", "them", "is", "not", "found", ".", "It", "only", "returns", "an", "error", "if", "something", "went", "wrong", "during", "the", "enumeration", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/index.go#L561-L602
train
perkeep/perkeep
pkg/index/index.go
schemaVersion
func (x *Index) schemaVersion() int { schemaVersionStr, err := x.s.Get(keySchemaVersion.name) if err != nil { if err == sorted.ErrNotFound { return 0 } panic(fmt.Sprintf("Could not get index schema version: %v", err)) } schemaVersion, err := strconv.Atoi(schemaVersionStr) if err != nil { panic(fmt.Sprintf("Bogus index schema version: %q", schemaVersionStr)) } return schemaVersion }
go
func (x *Index) schemaVersion() int { schemaVersionStr, err := x.s.Get(keySchemaVersion.name) if err != nil { if err == sorted.ErrNotFound { return 0 } panic(fmt.Sprintf("Could not get index schema version: %v", err)) } schemaVersion, err := strconv.Atoi(schemaVersionStr) if err != nil { panic(fmt.Sprintf("Bogus index schema version: %q", schemaVersionStr)) } return schemaVersion }
[ "func", "(", "x", "*", "Index", ")", "schemaVersion", "(", ")", "int", "{", "schemaVersionStr", ",", "err", ":=", "x", ".", "s", ".", "Get", "(", "keySchemaVersion", ".", "name", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "sorted", ".", "ErrNotFound", "{", "return", "0", "\n", "}", "\n", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "}", "\n", "schemaVersion", ",", "err", ":=", "strconv", ".", "Atoi", "(", "schemaVersionStr", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "schemaVersionStr", ")", ")", "\n", "}", "\n", "return", "schemaVersion", "\n", "}" ]
// schemaVersion returns the version of schema as it is found // in the currently used index. If not found, it returns 0.
[ "schemaVersion", "returns", "the", "version", "of", "schema", "as", "it", "is", "found", "in", "the", "currently", "used", "index", ".", "If", "not", "found", "it", "returns", "0", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/index.go#L637-L650
train
perkeep/perkeep
pkg/index/index.go
initDeletesCache
func (x *Index) initDeletesCache() (err error) { x.deletes = newDeletionCache() it := x.queryPrefix(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(x.deletes.m[cl.Target], deletion{ deleter: cl.BlobRef, when: cl.Date, }) sort.Sort(sort.Reverse(byDeletionDate(targetDeletions))) x.deletes.m[cl.Target] = targetDeletions } return err }
go
func (x *Index) initDeletesCache() (err error) { x.deletes = newDeletionCache() it := x.queryPrefix(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(x.deletes.m[cl.Target], deletion{ deleter: cl.BlobRef, when: cl.Date, }) sort.Sort(sort.Reverse(byDeletionDate(targetDeletions))) x.deletes.m[cl.Target] = targetDeletions } return err }
[ "func", "(", "x", "*", "Index", ")", "initDeletesCache", "(", ")", "(", "err", "error", ")", "{", "x", ".", "deletes", "=", "newDeletionCache", "(", ")", "\n", "it", ":=", "x", ".", "queryPrefix", "(", "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", "(", "x", ".", "deletes", ".", "m", "[", "cl", ".", "Target", "]", ",", "deletion", "{", "deleter", ":", "cl", ".", "BlobRef", ",", "when", ":", "cl", ".", "Date", ",", "}", ")", "\n", "sort", ".", "Sort", "(", "sort", ".", "Reverse", "(", "byDeletionDate", "(", "targetDeletions", ")", ")", ")", "\n", "x", ".", "deletes", ".", "m", "[", "cl", ".", "Target", "]", "=", "targetDeletions", "\n", "}", "\n", "return", "err", "\n", "}" ]
// initDeletesCache creates and populates the deletion status cache used by the index // for faster calls to IsDeleted and DeletedAt. It is called by New.
[ "initDeletesCache", "creates", "and", "populates", "the", "deletion", "status", "cache", "used", "by", "the", "index", "for", "faster", "calls", "to", "IsDeleted", "and", "DeletedAt", ".", "It", "is", "called", "by", "New", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/index.go#L676-L694
train
perkeep/perkeep
pkg/index/index.go
isDeleted
func (x *Index) isDeleted(br blob.Ref) bool { deletes, ok := x.deletes.m[br] if !ok { return false } for _, v := range deletes { if !x.isDeleted(v.deleter) { return true } } return false }
go
func (x *Index) isDeleted(br blob.Ref) bool { deletes, ok := x.deletes.m[br] if !ok { return false } for _, v := range deletes { if !x.isDeleted(v.deleter) { return true } } return false }
[ "func", "(", "x", "*", "Index", ")", "isDeleted", "(", "br", "blob", ".", "Ref", ")", "bool", "{", "deletes", ",", "ok", ":=", "x", ".", "deletes", ".", "m", "[", "br", "]", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n", "for", "_", ",", "v", ":=", "range", "deletes", "{", "if", "!", "x", ".", "isDeleted", "(", "v", ".", "deleter", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// The caller must hold x.deletes.mu for read.
[ "The", "caller", "must", "hold", "x", ".", "deletes", ".", "mu", "for", "read", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/index.go#L739-L750
train
perkeep/perkeep
pkg/index/index.go
GetRecentPermanodes
func (x *Index) GetRecentPermanodes(ctx context.Context, dest chan<- camtypes.RecentPermanode, owner blob.Ref, limit int, before time.Time) (err error) { defer close(dest) keyId, err := x.KeyId(ctx, owner) if err == sorted.ErrNotFound { x.logf("no recent permanodes because keyId for owner %v not found", owner) return nil } if err != nil { x.logf("error fetching keyId for owner %v: %v", owner, err) return err } sent := 0 var seenPermanode dupSkipper if before.IsZero() { before = time.Now() } // TODO(bradfitz): handle before efficiently. don't use queryPrefix. it := x.queryPrefix(keyRecentPermanode, keyId) defer closeIterator(it, &err) for it.Next() { permaStr := it.Value() parts := strings.SplitN(it.Key(), "|", 4) if len(parts) != 4 { continue } mTime, _ := time.Parse(time.RFC3339, unreverseTimeString(parts[2])) permaRef, ok := blob.Parse(permaStr) if !ok { continue } if x.IsDeleted(permaRef) { continue } if seenPermanode.Dup(permaStr) { continue } // Skip entries with an mTime less than or equal to before. if !mTime.Before(before) { continue } dest <- camtypes.RecentPermanode{ Permanode: permaRef, Signer: owner, // TODO(bradfitz): kinda. usually. for now. LastModTime: mTime, } sent++ if sent == limit { break } } return nil }
go
func (x *Index) GetRecentPermanodes(ctx context.Context, dest chan<- camtypes.RecentPermanode, owner blob.Ref, limit int, before time.Time) (err error) { defer close(dest) keyId, err := x.KeyId(ctx, owner) if err == sorted.ErrNotFound { x.logf("no recent permanodes because keyId for owner %v not found", owner) return nil } if err != nil { x.logf("error fetching keyId for owner %v: %v", owner, err) return err } sent := 0 var seenPermanode dupSkipper if before.IsZero() { before = time.Now() } // TODO(bradfitz): handle before efficiently. don't use queryPrefix. it := x.queryPrefix(keyRecentPermanode, keyId) defer closeIterator(it, &err) for it.Next() { permaStr := it.Value() parts := strings.SplitN(it.Key(), "|", 4) if len(parts) != 4 { continue } mTime, _ := time.Parse(time.RFC3339, unreverseTimeString(parts[2])) permaRef, ok := blob.Parse(permaStr) if !ok { continue } if x.IsDeleted(permaRef) { continue } if seenPermanode.Dup(permaStr) { continue } // Skip entries with an mTime less than or equal to before. if !mTime.Before(before) { continue } dest <- camtypes.RecentPermanode{ Permanode: permaRef, Signer: owner, // TODO(bradfitz): kinda. usually. for now. LastModTime: mTime, } sent++ if sent == limit { break } } return nil }
[ "func", "(", "x", "*", "Index", ")", "GetRecentPermanodes", "(", "ctx", "context", ".", "Context", ",", "dest", "chan", "<-", "camtypes", ".", "RecentPermanode", ",", "owner", "blob", ".", "Ref", ",", "limit", "int", ",", "before", "time", ".", "Time", ")", "(", "err", "error", ")", "{", "defer", "close", "(", "dest", ")", "\n\n", "keyId", ",", "err", ":=", "x", ".", "KeyId", "(", "ctx", ",", "owner", ")", "\n", "if", "err", "==", "sorted", ".", "ErrNotFound", "{", "x", ".", "logf", "(", "\"", "\"", ",", "owner", ")", "\n", "return", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "x", ".", "logf", "(", "\"", "\"", ",", "owner", ",", "err", ")", "\n", "return", "err", "\n", "}", "\n\n", "sent", ":=", "0", "\n", "var", "seenPermanode", "dupSkipper", "\n\n", "if", "before", ".", "IsZero", "(", ")", "{", "before", "=", "time", ".", "Now", "(", ")", "\n", "}", "\n", "// TODO(bradfitz): handle before efficiently. don't use queryPrefix.", "it", ":=", "x", ".", "queryPrefix", "(", "keyRecentPermanode", ",", "keyId", ")", "\n", "defer", "closeIterator", "(", "it", ",", "&", "err", ")", "\n", "for", "it", ".", "Next", "(", ")", "{", "permaStr", ":=", "it", ".", "Value", "(", ")", "\n", "parts", ":=", "strings", ".", "SplitN", "(", "it", ".", "Key", "(", ")", ",", "\"", "\"", ",", "4", ")", "\n", "if", "len", "(", "parts", ")", "!=", "4", "{", "continue", "\n", "}", "\n", "mTime", ",", "_", ":=", "time", ".", "Parse", "(", "time", ".", "RFC3339", ",", "unreverseTimeString", "(", "parts", "[", "2", "]", ")", ")", "\n", "permaRef", ",", "ok", ":=", "blob", ".", "Parse", "(", "permaStr", ")", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n", "if", "x", ".", "IsDeleted", "(", "permaRef", ")", "{", "continue", "\n", "}", "\n", "if", "seenPermanode", ".", "Dup", "(", "permaStr", ")", "{", "continue", "\n", "}", "\n", "// Skip entries with an mTime less than or equal to before.", "if", "!", "mTime", ".", "Before", "(", "before", ")", "{", "continue", "\n", "}", "\n", "dest", "<-", "camtypes", ".", "RecentPermanode", "{", "Permanode", ":", "permaRef", ",", "Signer", ":", "owner", ",", "// TODO(bradfitz): kinda. usually. for now.", "LastModTime", ":", "mTime", ",", "}", "\n", "sent", "++", "\n", "if", "sent", "==", "limit", "{", "break", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetRecentPermanodes sends results to dest filtered by owner, limit, and // before. A zero value for before will default to the current time. The // results will have duplicates suppressed, with most recent permanode // returned. // Note, permanodes more recent than before will still be fetched from the // index then skipped. This means runtime scales linearly with the number of // nodes more recent than before.
[ "GetRecentPermanodes", "sends", "results", "to", "dest", "filtered", "by", "owner", "limit", "and", "before", ".", "A", "zero", "value", "for", "before", "will", "default", "to", "the", "current", "time", ".", "The", "results", "will", "have", "duplicates", "suppressed", "with", "most", "recent", "permanode", "returned", ".", "Note", "permanodes", "more", "recent", "than", "before", "will", "still", "be", "fetched", "from", "the", "index", "then", "skipped", ".", "This", "means", "runtime", "scales", "linearly", "with", "the", "number", "of", "nodes", "more", "recent", "than", "before", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/index.go#L785-L839
train
perkeep/perkeep
pkg/index/index.go
HasLegacySHA1
func (x *Index) HasLegacySHA1() (ok bool, err error) { if x.corpus != nil { return x.corpus.hasLegacySHA1, err } it := x.queryPrefix(keyWholeToFileRef, "sha1-") defer closeIterator(it, &err) for it.Next() { return true, err } return false, err }
go
func (x *Index) HasLegacySHA1() (ok bool, err error) { if x.corpus != nil { return x.corpus.hasLegacySHA1, err } it := x.queryPrefix(keyWholeToFileRef, "sha1-") defer closeIterator(it, &err) for it.Next() { return true, err } return false, err }
[ "func", "(", "x", "*", "Index", ")", "HasLegacySHA1", "(", ")", "(", "ok", "bool", ",", "err", "error", ")", "{", "if", "x", ".", "corpus", "!=", "nil", "{", "return", "x", ".", "corpus", ".", "hasLegacySHA1", ",", "err", "\n", "}", "\n", "it", ":=", "x", ".", "queryPrefix", "(", "keyWholeToFileRef", ",", "\"", "\"", ")", "\n", "defer", "closeIterator", "(", "it", ",", "&", "err", ")", "\n", "for", "it", ".", "Next", "(", ")", "{", "return", "true", ",", "err", "\n", "}", "\n", "return", "false", ",", "err", "\n", "}" ]
// HasLegacySHA1 reports whether the index has legacy SHA-1 blobs.
[ "HasLegacySHA1", "reports", "whether", "the", "index", "has", "legacy", "SHA", "-", "1", "blobs", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/index.go#L965-L975
train
perkeep/perkeep
pkg/index/index.go
signerRefs
func (x *Index) signerRefs(ctx context.Context, keyID string) (SignerRefSet, error) { if x.corpus != nil { return x.corpus.signerRefs[keyID], nil } it := x.queryPrefixString(keySignerKeyID.name) var err error var refs SignerRefSet defer closeIterator(it, &err) prefix := keySignerKeyID.name + ":" for it.Next() { if it.Value() == keyID { refs = append(refs, strings.TrimPrefix(it.Key(), prefix)) } } return refs, nil }
go
func (x *Index) signerRefs(ctx context.Context, keyID string) (SignerRefSet, error) { if x.corpus != nil { return x.corpus.signerRefs[keyID], nil } it := x.queryPrefixString(keySignerKeyID.name) var err error var refs SignerRefSet defer closeIterator(it, &err) prefix := keySignerKeyID.name + ":" for it.Next() { if it.Value() == keyID { refs = append(refs, strings.TrimPrefix(it.Key(), prefix)) } } return refs, nil }
[ "func", "(", "x", "*", "Index", ")", "signerRefs", "(", "ctx", "context", ".", "Context", ",", "keyID", "string", ")", "(", "SignerRefSet", ",", "error", ")", "{", "if", "x", ".", "corpus", "!=", "nil", "{", "return", "x", ".", "corpus", ".", "signerRefs", "[", "keyID", "]", ",", "nil", "\n", "}", "\n", "it", ":=", "x", ".", "queryPrefixString", "(", "keySignerKeyID", ".", "name", ")", "\n", "var", "err", "error", "\n", "var", "refs", "SignerRefSet", "\n", "defer", "closeIterator", "(", "it", ",", "&", "err", ")", "\n", "prefix", ":=", "keySignerKeyID", ".", "name", "+", "\"", "\"", "\n", "for", "it", ".", "Next", "(", ")", "{", "if", "it", ".", "Value", "(", ")", "==", "keyID", "{", "refs", "=", "append", "(", "refs", ",", "strings", ".", "TrimPrefix", "(", "it", ".", "Key", "(", ")", ",", "prefix", ")", ")", "\n", "}", "\n", "}", "\n", "return", "refs", ",", "nil", "\n", "}" ]
// signerRefs returns the set of signer blobRefs matching the signer keyID. It // does not return an error if none is found.
[ "signerRefs", "returns", "the", "set", "of", "signer", "blobRefs", "matching", "the", "signer", "keyID", ".", "It", "does", "not", "return", "an", "error", "if", "none", "is", "found", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/index.go#L986-L1001
train
perkeep/perkeep
pkg/index/index.go
SearchPermanodesWithAttr
func (x *Index) SearchPermanodesWithAttr(ctx context.Context, dest chan<- blob.Ref, request *camtypes.PermanodeByAttrRequest) (err error) { defer close(dest) if request.FuzzyMatch { // TODO(bradfitz): remove this for now? figure out how to handle it generically? return errors.New("TODO: SearchPermanodesWithAttr: generic indexer doesn't support FuzzyMatch on PermanodeByAttrRequest") } if request.Attribute == "" { return errors.New("index: missing Attribute in SearchPermanodesWithAttr") } if !IsIndexedAttribute(request.Attribute) { return fmt.Errorf("SearchPermanodesWithAttr: called with a non-indexed attribute %q", request.Attribute) } keyId, err := x.KeyId(ctx, request.Signer) if err == sorted.ErrNotFound { return nil } if err != nil { return err } seen := make(map[string]bool) var it sorted.Iterator if request.Query == "" { it = x.queryPrefix(keySignerAttrValue, keyId, request.Attribute) } else { it = x.queryPrefix(keySignerAttrValue, keyId, request.Attribute, request.Query) } defer closeIterator(it, &err) before := request.At if before.IsZero() { before = time.Now() } for it.Next() { cl, ok := kvSignerAttrValue(it.Key(), it.Value()) if !ok { continue } if x.IsDeleted(cl.BlobRef) { continue } if x.IsDeleted(cl.Permanode) { continue } if cl.Date.After(before) { continue } pnstr := cl.Permanode.String() if seen[pnstr] { continue } seen[pnstr] = true dest <- cl.Permanode if len(seen) == request.MaxResults { break } } return nil }
go
func (x *Index) SearchPermanodesWithAttr(ctx context.Context, dest chan<- blob.Ref, request *camtypes.PermanodeByAttrRequest) (err error) { defer close(dest) if request.FuzzyMatch { // TODO(bradfitz): remove this for now? figure out how to handle it generically? return errors.New("TODO: SearchPermanodesWithAttr: generic indexer doesn't support FuzzyMatch on PermanodeByAttrRequest") } if request.Attribute == "" { return errors.New("index: missing Attribute in SearchPermanodesWithAttr") } if !IsIndexedAttribute(request.Attribute) { return fmt.Errorf("SearchPermanodesWithAttr: called with a non-indexed attribute %q", request.Attribute) } keyId, err := x.KeyId(ctx, request.Signer) if err == sorted.ErrNotFound { return nil } if err != nil { return err } seen := make(map[string]bool) var it sorted.Iterator if request.Query == "" { it = x.queryPrefix(keySignerAttrValue, keyId, request.Attribute) } else { it = x.queryPrefix(keySignerAttrValue, keyId, request.Attribute, request.Query) } defer closeIterator(it, &err) before := request.At if before.IsZero() { before = time.Now() } for it.Next() { cl, ok := kvSignerAttrValue(it.Key(), it.Value()) if !ok { continue } if x.IsDeleted(cl.BlobRef) { continue } if x.IsDeleted(cl.Permanode) { continue } if cl.Date.After(before) { continue } pnstr := cl.Permanode.String() if seen[pnstr] { continue } seen[pnstr] = true dest <- cl.Permanode if len(seen) == request.MaxResults { break } } return nil }
[ "func", "(", "x", "*", "Index", ")", "SearchPermanodesWithAttr", "(", "ctx", "context", ".", "Context", ",", "dest", "chan", "<-", "blob", ".", "Ref", ",", "request", "*", "camtypes", ".", "PermanodeByAttrRequest", ")", "(", "err", "error", ")", "{", "defer", "close", "(", "dest", ")", "\n", "if", "request", ".", "FuzzyMatch", "{", "// TODO(bradfitz): remove this for now? figure out how to handle it generically?", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "request", ".", "Attribute", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "!", "IsIndexedAttribute", "(", "request", ".", "Attribute", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "request", ".", "Attribute", ")", "\n", "}", "\n\n", "keyId", ",", "err", ":=", "x", ".", "KeyId", "(", "ctx", ",", "request", ".", "Signer", ")", "\n", "if", "err", "==", "sorted", ".", "ErrNotFound", "{", "return", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "seen", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "var", "it", "sorted", ".", "Iterator", "\n", "if", "request", ".", "Query", "==", "\"", "\"", "{", "it", "=", "x", ".", "queryPrefix", "(", "keySignerAttrValue", ",", "keyId", ",", "request", ".", "Attribute", ")", "\n", "}", "else", "{", "it", "=", "x", ".", "queryPrefix", "(", "keySignerAttrValue", ",", "keyId", ",", "request", ".", "Attribute", ",", "request", ".", "Query", ")", "\n", "}", "\n", "defer", "closeIterator", "(", "it", ",", "&", "err", ")", "\n", "before", ":=", "request", ".", "At", "\n", "if", "before", ".", "IsZero", "(", ")", "{", "before", "=", "time", ".", "Now", "(", ")", "\n", "}", "\n", "for", "it", ".", "Next", "(", ")", "{", "cl", ",", "ok", ":=", "kvSignerAttrValue", "(", "it", ".", "Key", "(", ")", ",", "it", ".", "Value", "(", ")", ")", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n", "if", "x", ".", "IsDeleted", "(", "cl", ".", "BlobRef", ")", "{", "continue", "\n", "}", "\n", "if", "x", ".", "IsDeleted", "(", "cl", ".", "Permanode", ")", "{", "continue", "\n", "}", "\n", "if", "cl", ".", "Date", ".", "After", "(", "before", ")", "{", "continue", "\n", "}", "\n", "pnstr", ":=", "cl", ".", "Permanode", ".", "String", "(", ")", "\n", "if", "seen", "[", "pnstr", "]", "{", "continue", "\n", "}", "\n", "seen", "[", "pnstr", "]", "=", "true", "\n\n", "dest", "<-", "cl", ".", "Permanode", "\n", "if", "len", "(", "seen", ")", "==", "request", ".", "MaxResults", "{", "break", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SearchPermanodesWithAttr is just like PermanodeOfSignerAttrValue // except we return multiple and dup-suppress. If request.Query is // "", it is not used in the prefix search.
[ "SearchPermanodesWithAttr", "is", "just", "like", "PermanodeOfSignerAttrValue", "except", "we", "return", "multiple", "and", "dup", "-", "suppress", ".", "If", "request", ".", "Query", "is", "it", "is", "not", "used", "in", "the", "prefix", "search", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/index.go#L1025-L1083
train
perkeep/perkeep
pkg/index/index.go
ExistingFileSchemas
func (x *Index) ExistingFileSchemas(wholeRef ...blob.Ref) (WholeRefToFile, error) { schemaRefs := make(WholeRefToFile) for _, v := range wholeRef { newRefs, err := x.existingFileSchemas(v) if err != nil { return nil, err } schemaRefs[v.String()] = newRefs } return schemaRefs, nil }
go
func (x *Index) ExistingFileSchemas(wholeRef ...blob.Ref) (WholeRefToFile, error) { schemaRefs := make(WholeRefToFile) for _, v := range wholeRef { newRefs, err := x.existingFileSchemas(v) if err != nil { return nil, err } schemaRefs[v.String()] = newRefs } return schemaRefs, nil }
[ "func", "(", "x", "*", "Index", ")", "ExistingFileSchemas", "(", "wholeRef", "...", "blob", ".", "Ref", ")", "(", "WholeRefToFile", ",", "error", ")", "{", "schemaRefs", ":=", "make", "(", "WholeRefToFile", ")", "\n", "for", "_", ",", "v", ":=", "range", "wholeRef", "{", "newRefs", ",", "err", ":=", "x", ".", "existingFileSchemas", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "schemaRefs", "[", "v", ".", "String", "(", ")", "]", "=", "newRefs", "\n", "}", "\n", "return", "schemaRefs", ",", "nil", "\n", "}" ]
// ExistingFileSchemas returns the file schemas for the provided file contents refs.
[ "ExistingFileSchemas", "returns", "the", "file", "schemas", "for", "the", "provided", "file", "contents", "refs", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/index.go#L1341-L1351
train
perkeep/perkeep
pkg/index/index.go
kvImageInfo
func kvImageInfo(v []byte) (ii camtypes.ImageInfo, ok bool) { pipei := bytes.IndexByte(v, '|') if pipei < 0 { return } w, err := strutil.ParseUintBytes(v[:pipei], 10, 16) if err != nil { return } h, err := strutil.ParseUintBytes(v[pipei+1:], 10, 16) if err != nil { return } ii.Width = uint16(w) ii.Height = uint16(h) return ii, true }
go
func kvImageInfo(v []byte) (ii camtypes.ImageInfo, ok bool) { pipei := bytes.IndexByte(v, '|') if pipei < 0 { return } w, err := strutil.ParseUintBytes(v[:pipei], 10, 16) if err != nil { return } h, err := strutil.ParseUintBytes(v[pipei+1:], 10, 16) if err != nil { return } ii.Width = uint16(w) ii.Height = uint16(h) return ii, true }
[ "func", "kvImageInfo", "(", "v", "[", "]", "byte", ")", "(", "ii", "camtypes", ".", "ImageInfo", ",", "ok", "bool", ")", "{", "pipei", ":=", "bytes", ".", "IndexByte", "(", "v", ",", "'|'", ")", "\n", "if", "pipei", "<", "0", "{", "return", "\n", "}", "\n", "w", ",", "err", ":=", "strutil", ".", "ParseUintBytes", "(", "v", "[", ":", "pipei", "]", ",", "10", ",", "16", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "h", ",", "err", ":=", "strutil", ".", "ParseUintBytes", "(", "v", "[", "pipei", "+", "1", ":", "]", ",", "10", ",", "16", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "ii", ".", "Width", "=", "uint16", "(", "w", ")", "\n", "ii", ".", "Height", "=", "uint16", "(", "h", ")", "\n", "return", "ii", ",", "true", "\n", "}" ]
// v is "width|height"
[ "v", "is", "width|height" ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/index.go#L1420-L1436
train
perkeep/perkeep
pkg/index/index.go
GetDirMembers
func (x *Index) GetDirMembers(ctx context.Context, dir blob.Ref, dest chan<- blob.Ref, limit int) (err error) { defer close(dest) sent := 0 if x.corpus != nil { children, err := x.corpus.GetDirChildren(ctx, dir) if err != nil { return err } for child := range children { dest <- child sent++ if sent == limit { break } } return nil } it := x.queryPrefix(keyStaticDirChild, dir.String()) defer closeIterator(it, &err) for it.Next() { keyPart := strings.Split(it.Key(), "|") if len(keyPart) != 3 { return fmt.Errorf("index: bogus key keyStaticDirChild = %q", it.Key()) } child, ok := blob.Parse(keyPart[2]) if !ok { continue } dest <- child sent++ if sent == limit { break } } return nil }
go
func (x *Index) GetDirMembers(ctx context.Context, dir blob.Ref, dest chan<- blob.Ref, limit int) (err error) { defer close(dest) sent := 0 if x.corpus != nil { children, err := x.corpus.GetDirChildren(ctx, dir) if err != nil { return err } for child := range children { dest <- child sent++ if sent == limit { break } } return nil } it := x.queryPrefix(keyStaticDirChild, dir.String()) defer closeIterator(it, &err) for it.Next() { keyPart := strings.Split(it.Key(), "|") if len(keyPart) != 3 { return fmt.Errorf("index: bogus key keyStaticDirChild = %q", it.Key()) } child, ok := blob.Parse(keyPart[2]) if !ok { continue } dest <- child sent++ if sent == limit { break } } return nil }
[ "func", "(", "x", "*", "Index", ")", "GetDirMembers", "(", "ctx", "context", ".", "Context", ",", "dir", "blob", ".", "Ref", ",", "dest", "chan", "<-", "blob", ".", "Ref", ",", "limit", "int", ")", "(", "err", "error", ")", "{", "defer", "close", "(", "dest", ")", "\n\n", "sent", ":=", "0", "\n", "if", "x", ".", "corpus", "!=", "nil", "{", "children", ",", "err", ":=", "x", ".", "corpus", ".", "GetDirChildren", "(", "ctx", ",", "dir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "child", ":=", "range", "children", "{", "dest", "<-", "child", "\n", "sent", "++", "\n", "if", "sent", "==", "limit", "{", "break", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", "\n\n", "it", ":=", "x", ".", "queryPrefix", "(", "keyStaticDirChild", ",", "dir", ".", "String", "(", ")", ")", "\n", "defer", "closeIterator", "(", "it", ",", "&", "err", ")", "\n", "for", "it", ".", "Next", "(", ")", "{", "keyPart", ":=", "strings", ".", "Split", "(", "it", ".", "Key", "(", ")", ",", "\"", "\"", ")", "\n", "if", "len", "(", "keyPart", ")", "!=", "3", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "it", ".", "Key", "(", ")", ")", "\n", "}", "\n\n", "child", ",", "ok", ":=", "blob", ".", "Parse", "(", "keyPart", "[", "2", "]", ")", "\n", "if", "!", "ok", "{", "continue", "\n", "}", "\n", "dest", "<-", "child", "\n", "sent", "++", "\n", "if", "sent", "==", "limit", "{", "break", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetDirMembers sends on dest the children of the static directory dir.
[ "GetDirMembers", "sends", "on", "dest", "the", "children", "of", "the", "static", "directory", "dir", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/index.go#L1579-L1617
train
perkeep/perkeep
pkg/index/index.go
Close
func (x *Index) Close() error { if cl, ok := x.s.(io.Closer); ok { return cl.Close() } return nil }
go
func (x *Index) Close() error { if cl, ok := x.s.(io.Closer); ok { return cl.Close() } return nil }
[ "func", "(", "x", "*", "Index", ")", "Close", "(", ")", "error", "{", "if", "cl", ",", "ok", ":=", "x", ".", "s", ".", "(", "io", ".", "Closer", ")", ";", "ok", "{", "return", "cl", ".", "Close", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Close closes the underlying sorted.KeyValue, if the storage has a Close method. // The return value is the return value of the underlying Close, or // nil otherwise.
[ "Close", "closes", "the", "underlying", "sorted", ".", "KeyValue", "if", "the", "storage", "has", "a", "Close", "method", ".", "The", "return", "value", "is", "the", "return", "value", "of", "the", "underlying", "Close", "or", "nil", "otherwise", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/index.go#L1726-L1731
train
perkeep/perkeep
pkg/index/index.go
initNeededMaps
func (x *Index) initNeededMaps() (err error) { x.deletes = newDeletionCache() it := x.queryPrefix(keyMissing) defer closeIterator(it, &err) for it.Next() { key := it.KeyBytes() pair := key[len("missing|"):] pipe := bytes.IndexByte(pair, '|') if pipe < 0 { return fmt.Errorf("Bogus missing key %q", key) } have, ok1 := blob.ParseBytes(pair[:pipe]) missing, ok2 := blob.ParseBytes(pair[pipe+1:]) if !ok1 || !ok2 { return fmt.Errorf("Bogus missing key %q", key) } x.noteNeededMemory(have, missing) } return }
go
func (x *Index) initNeededMaps() (err error) { x.deletes = newDeletionCache() it := x.queryPrefix(keyMissing) defer closeIterator(it, &err) for it.Next() { key := it.KeyBytes() pair := key[len("missing|"):] pipe := bytes.IndexByte(pair, '|') if pipe < 0 { return fmt.Errorf("Bogus missing key %q", key) } have, ok1 := blob.ParseBytes(pair[:pipe]) missing, ok2 := blob.ParseBytes(pair[pipe+1:]) if !ok1 || !ok2 { return fmt.Errorf("Bogus missing key %q", key) } x.noteNeededMemory(have, missing) } return }
[ "func", "(", "x", "*", "Index", ")", "initNeededMaps", "(", ")", "(", "err", "error", ")", "{", "x", ".", "deletes", "=", "newDeletionCache", "(", ")", "\n", "it", ":=", "x", ".", "queryPrefix", "(", "keyMissing", ")", "\n", "defer", "closeIterator", "(", "it", ",", "&", "err", ")", "\n", "for", "it", ".", "Next", "(", ")", "{", "key", ":=", "it", ".", "KeyBytes", "(", ")", "\n", "pair", ":=", "key", "[", "len", "(", "\"", "\"", ")", ":", "]", "\n", "pipe", ":=", "bytes", ".", "IndexByte", "(", "pair", ",", "'|'", ")", "\n", "if", "pipe", "<", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "key", ")", "\n", "}", "\n", "have", ",", "ok1", ":=", "blob", ".", "ParseBytes", "(", "pair", "[", ":", "pipe", "]", ")", "\n", "missing", ",", "ok2", ":=", "blob", ".", "ParseBytes", "(", "pair", "[", "pipe", "+", "1", ":", "]", ")", "\n", "if", "!", "ok1", "||", "!", "ok2", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "key", ")", "\n", "}", "\n", "x", ".", "noteNeededMemory", "(", "have", ",", "missing", ")", "\n", "}", "\n", "return", "\n", "}" ]
// initNeededMaps initializes x.needs and x.neededBy on start-up.
[ "initNeededMaps", "initializes", "x", ".", "needs", "and", "x", ".", "neededBy", "on", "start", "-", "up", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/index.go#L1734-L1753
train
perkeep/perkeep
internal/lru/cache.go
NewUnlocked
func NewUnlocked(maxEntries int) *Cache { c := New(maxEntries) c.nolock = true return c }
go
func NewUnlocked(maxEntries int) *Cache { c := New(maxEntries) c.nolock = true return c }
[ "func", "NewUnlocked", "(", "maxEntries", "int", ")", "*", "Cache", "{", "c", ":=", "New", "(", "maxEntries", ")", "\n", "c", ".", "nolock", "=", "true", "\n", "return", "c", "\n", "}" ]
// NewUnlocked is like New but returns a Cache that is not safe // for concurrent access.
[ "NewUnlocked", "is", "like", "New", "but", "returns", "a", "Cache", "that", "is", "not", "safe", "for", "concurrent", "access", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/lru/cache.go#L53-L57
train
perkeep/perkeep
internal/lru/cache.go
RemoveOldest
func (c *Cache) RemoveOldest() (key string, value interface{}) { if !c.nolock { c.mu.Lock() defer c.mu.Unlock() } return c.removeOldest() }
go
func (c *Cache) RemoveOldest() (key string, value interface{}) { if !c.nolock { c.mu.Lock() defer c.mu.Unlock() } return c.removeOldest() }
[ "func", "(", "c", "*", "Cache", ")", "RemoveOldest", "(", ")", "(", "key", "string", ",", "value", "interface", "{", "}", ")", "{", "if", "!", "c", ".", "nolock", "{", "c", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "c", ".", "mu", ".", "Unlock", "(", ")", "\n", "}", "\n", "return", "c", ".", "removeOldest", "(", ")", "\n", "}" ]
// RemoveOldest removes the oldest item in the cache and returns its key and value. // If the cache is empty, the empty string and nil are returned.
[ "RemoveOldest", "removes", "the", "oldest", "item", "in", "the", "cache", "and", "returns", "its", "key", "and", "value", ".", "If", "the", "cache", "is", "empty", "the", "empty", "string", "and", "nil", "are", "returned", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/lru/cache.go#L99-L105
train
perkeep/perkeep
pkg/importer/twitter/twitter.go
importTweets
func (r *run) importTweets(userID string, apiPath string) error { maxId := "" continueRequests := true var tweetsNode *importer.Object var err error var importType string if apiPath == userLikesAPIPath { importType = "likes" } else { importType = "tweets" } tweetsNode, err = r.getTopLevelNode(importType) if err != nil { return err } numTweets := 0 sawTweet := map[string]bool{} // If attrs is changed, so should the expected responses accordingly for the // RoundTripper of MakeTestData (testdata.go). attrs := []string{ "user_id", userID, "count", strconv.Itoa(tweetRequestLimit), } for continueRequests { select { case <-r.Context().Done(): r.errorf("interrupted") return r.Context().Err() default: } var resp []*apiTweetItem var err error if maxId == "" { log.Printf("twitter: fetching %s for userid %s", importType, userID) err = r.doAPI(&resp, apiPath, attrs...) } else { log.Printf("twitter: fetching %s for userid %s with max ID %s", userID, importType, maxId) err = r.doAPI(&resp, apiPath, append(attrs, "max_id", maxId)...) } if err != nil { return err } var ( newThisBatch = 0 allDupMu sync.Mutex allDups = true gate = syncutil.NewGate(tweetsAtOnce) grp syncutil.Group ) for i := range resp { tweet := resp[i] // Dup-suppression. if sawTweet[tweet.Id] { continue } sawTweet[tweet.Id] = true newThisBatch++ maxId = tweet.Id gate.Start() grp.Go(func() error { defer gate.Done() dup, err := r.importTweet(tweetsNode, tweet, true) if !dup { allDupMu.Lock() allDups = false allDupMu.Unlock() } if err != nil { r.errorf("error importing tweet %s %v", tweet.Id, err) } return err }) } if err := grp.Err(); err != nil { return err } numTweets += newThisBatch log.Printf("twitter: imported %d %s this batch; %d total.", newThisBatch, importType, numTweets) if r.incremental && allDups { log.Printf("twitter: incremental import found end batch") break } continueRequests = newThisBatch > 0 } log.Printf("twitter: successfully did full run of importing %d %s", numTweets, importType) return nil }
go
func (r *run) importTweets(userID string, apiPath string) error { maxId := "" continueRequests := true var tweetsNode *importer.Object var err error var importType string if apiPath == userLikesAPIPath { importType = "likes" } else { importType = "tweets" } tweetsNode, err = r.getTopLevelNode(importType) if err != nil { return err } numTweets := 0 sawTweet := map[string]bool{} // If attrs is changed, so should the expected responses accordingly for the // RoundTripper of MakeTestData (testdata.go). attrs := []string{ "user_id", userID, "count", strconv.Itoa(tweetRequestLimit), } for continueRequests { select { case <-r.Context().Done(): r.errorf("interrupted") return r.Context().Err() default: } var resp []*apiTweetItem var err error if maxId == "" { log.Printf("twitter: fetching %s for userid %s", importType, userID) err = r.doAPI(&resp, apiPath, attrs...) } else { log.Printf("twitter: fetching %s for userid %s with max ID %s", userID, importType, maxId) err = r.doAPI(&resp, apiPath, append(attrs, "max_id", maxId)...) } if err != nil { return err } var ( newThisBatch = 0 allDupMu sync.Mutex allDups = true gate = syncutil.NewGate(tweetsAtOnce) grp syncutil.Group ) for i := range resp { tweet := resp[i] // Dup-suppression. if sawTweet[tweet.Id] { continue } sawTweet[tweet.Id] = true newThisBatch++ maxId = tweet.Id gate.Start() grp.Go(func() error { defer gate.Done() dup, err := r.importTweet(tweetsNode, tweet, true) if !dup { allDupMu.Lock() allDups = false allDupMu.Unlock() } if err != nil { r.errorf("error importing tweet %s %v", tweet.Id, err) } return err }) } if err := grp.Err(); err != nil { return err } numTweets += newThisBatch log.Printf("twitter: imported %d %s this batch; %d total.", newThisBatch, importType, numTweets) if r.incremental && allDups { log.Printf("twitter: incremental import found end batch") break } continueRequests = newThisBatch > 0 } log.Printf("twitter: successfully did full run of importing %d %s", numTweets, importType) return nil }
[ "func", "(", "r", "*", "run", ")", "importTweets", "(", "userID", "string", ",", "apiPath", "string", ")", "error", "{", "maxId", ":=", "\"", "\"", "\n", "continueRequests", ":=", "true", "\n\n", "var", "tweetsNode", "*", "importer", ".", "Object", "\n", "var", "err", "error", "\n", "var", "importType", "string", "\n", "if", "apiPath", "==", "userLikesAPIPath", "{", "importType", "=", "\"", "\"", "\n", "}", "else", "{", "importType", "=", "\"", "\"", "\n", "}", "\n", "tweetsNode", ",", "err", "=", "r", ".", "getTopLevelNode", "(", "importType", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "numTweets", ":=", "0", "\n", "sawTweet", ":=", "map", "[", "string", "]", "bool", "{", "}", "\n\n", "// If attrs is changed, so should the expected responses accordingly for the", "// RoundTripper of MakeTestData (testdata.go).", "attrs", ":=", "[", "]", "string", "{", "\"", "\"", ",", "userID", ",", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "tweetRequestLimit", ")", ",", "}", "\n", "for", "continueRequests", "{", "select", "{", "case", "<-", "r", ".", "Context", "(", ")", ".", "Done", "(", ")", ":", "r", ".", "errorf", "(", "\"", "\"", ")", "\n", "return", "r", ".", "Context", "(", ")", ".", "Err", "(", ")", "\n", "default", ":", "}", "\n\n", "var", "resp", "[", "]", "*", "apiTweetItem", "\n", "var", "err", "error", "\n", "if", "maxId", "==", "\"", "\"", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "importType", ",", "userID", ")", "\n", "err", "=", "r", ".", "doAPI", "(", "&", "resp", ",", "apiPath", ",", "attrs", "...", ")", "\n", "}", "else", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "userID", ",", "importType", ",", "maxId", ")", "\n", "err", "=", "r", ".", "doAPI", "(", "&", "resp", ",", "apiPath", ",", "append", "(", "attrs", ",", "\"", "\"", ",", "maxId", ")", "...", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "var", "(", "newThisBatch", "=", "0", "\n", "allDupMu", "sync", ".", "Mutex", "\n", "allDups", "=", "true", "\n", "gate", "=", "syncutil", ".", "NewGate", "(", "tweetsAtOnce", ")", "\n", "grp", "syncutil", ".", "Group", "\n", ")", "\n", "for", "i", ":=", "range", "resp", "{", "tweet", ":=", "resp", "[", "i", "]", "\n\n", "// Dup-suppression.", "if", "sawTweet", "[", "tweet", ".", "Id", "]", "{", "continue", "\n", "}", "\n", "sawTweet", "[", "tweet", ".", "Id", "]", "=", "true", "\n", "newThisBatch", "++", "\n", "maxId", "=", "tweet", ".", "Id", "\n\n", "gate", ".", "Start", "(", ")", "\n", "grp", ".", "Go", "(", "func", "(", ")", "error", "{", "defer", "gate", ".", "Done", "(", ")", "\n", "dup", ",", "err", ":=", "r", ".", "importTweet", "(", "tweetsNode", ",", "tweet", ",", "true", ")", "\n", "if", "!", "dup", "{", "allDupMu", ".", "Lock", "(", ")", "\n", "allDups", "=", "false", "\n", "allDupMu", ".", "Unlock", "(", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "r", ".", "errorf", "(", "\"", "\"", ",", "tweet", ".", "Id", ",", "err", ")", "\n", "}", "\n", "return", "err", "\n", "}", ")", "\n", "}", "\n", "if", "err", ":=", "grp", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "numTweets", "+=", "newThisBatch", "\n", "log", ".", "Printf", "(", "\"", "\"", ",", "newThisBatch", ",", "importType", ",", "numTweets", ")", "\n", "if", "r", ".", "incremental", "&&", "allDups", "{", "log", ".", "Printf", "(", "\"", "\"", ")", "\n", "break", "\n", "}", "\n", "continueRequests", "=", "newThisBatch", ">", "0", "\n", "}", "\n", "log", ".", "Printf", "(", "\"", "\"", ",", "numTweets", ",", "importType", ")", "\n", "return", "nil", "\n", "}" ]
// importTweets imports the tweets related to userID, through apiPath. // If apiPath is userTimeLineAPIPath, the tweets and retweets posted by userID are imported. // If apiPath is userLikesAPIPath, the tweets liked by userID are imported.
[ "importTweets", "imports", "the", "tweets", "related", "to", "userID", "through", "apiPath", ".", "If", "apiPath", "is", "userTimeLineAPIPath", "the", "tweets", "and", "retweets", "posted", "by", "userID", "are", "imported", ".", "If", "apiPath", "is", "userLikesAPIPath", "the", "tweets", "liked", "by", "userID", "are", "imported", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/twitter/twitter.go#L374-L468
train
perkeep/perkeep
pkg/serverinit/serverinit.go
detectConfigChange
func detectConfigChange(conf jsonconfig.Obj) error { oldHTTPSKey, oldHTTPSCert := conf.OptionalString("HTTPSKeyFile", ""), conf.OptionalString("HTTPSCertFile", "") if oldHTTPSKey != "" || oldHTTPSCert != "" { return fmt.Errorf("config keys %q and %q have respectively been renamed to %q and %q, please fix your server config", "HTTPSKeyFile", "HTTPSCertFile", "httpsKey", "httpsCert") } return nil }
go
func detectConfigChange(conf jsonconfig.Obj) error { oldHTTPSKey, oldHTTPSCert := conf.OptionalString("HTTPSKeyFile", ""), conf.OptionalString("HTTPSCertFile", "") if oldHTTPSKey != "" || oldHTTPSCert != "" { return fmt.Errorf("config keys %q and %q have respectively been renamed to %q and %q, please fix your server config", "HTTPSKeyFile", "HTTPSCertFile", "httpsKey", "httpsCert") } return nil }
[ "func", "detectConfigChange", "(", "conf", "jsonconfig", ".", "Obj", ")", "error", "{", "oldHTTPSKey", ",", "oldHTTPSCert", ":=", "conf", ".", "OptionalString", "(", "\"", "\"", ",", "\"", "\"", ")", ",", "conf", ".", "OptionalString", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "oldHTTPSKey", "!=", "\"", "\"", "||", "oldHTTPSCert", "!=", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// detectConfigChange returns an informative error if conf contains obsolete keys.
[ "detectConfigChange", "returns", "an", "informative", "error", "if", "conf", "contains", "obsolete", "keys", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/serverinit/serverinit.go#L467-L474
train
perkeep/perkeep
pkg/serverinit/serverinit.go
Load
func Load(config []byte) (*Config, error) { return load("", func(filename string) (jsonconfig.File, error) { if filename != "" { return nil, errors.New("JSON files with includes not supported with jsonconfig.Load") } return jsonFileImpl{bytes.NewReader(config), "config file"}, nil }) }
go
func Load(config []byte) (*Config, error) { return load("", func(filename string) (jsonconfig.File, error) { if filename != "" { return nil, errors.New("JSON files with includes not supported with jsonconfig.Load") } return jsonFileImpl{bytes.NewReader(config), "config file"}, nil }) }
[ "func", "Load", "(", "config", "[", "]", "byte", ")", "(", "*", "Config", ",", "error", ")", "{", "return", "load", "(", "\"", "\"", ",", "func", "(", "filename", "string", ")", "(", "jsonconfig", ".", "File", ",", "error", ")", "{", "if", "filename", "!=", "\"", "\"", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "jsonFileImpl", "{", "bytes", ".", "NewReader", "(", "config", ")", ",", "\"", "\"", "}", ",", "nil", "\n", "}", ")", "\n", "}" ]
// Load returns a low-level "handler config" from the provided config. // If the config doesn't contain a top-level JSON key of "handlerConfig" // with boolean value true, the configuration is assumed to be a high-level // "user config" file, and transformed into a low-level config.
[ "Load", "returns", "a", "low", "-", "level", "handler", "config", "from", "the", "provided", "config", ".", "If", "the", "config", "doesn", "t", "contain", "a", "top", "-", "level", "JSON", "key", "of", "handlerConfig", "with", "boolean", "value", "true", "the", "configuration", "is", "assumed", "to", "be", "a", "high", "-", "level", "user", "config", "file", "and", "transformed", "into", "a", "low", "-", "level", "config", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/serverinit/serverinit.go#L498-L505
train
perkeep/perkeep
pkg/serverinit/serverinit.go
readFields
func (c *Config) readFields() error { c.camliNetIP = c.jconf.OptionalString("camliNetIP", "") c.listenAddr = c.jconf.OptionalString("listen", "") c.baseURL = strings.TrimSuffix(c.jconf.OptionalString("baseURL", ""), "/") c.httpsCert = c.jconf.OptionalString("httpsCert", "") c.httpsKey = c.jconf.OptionalString("httpsKey", "") c.https = c.jconf.OptionalBool("https", false) _, explicitHTTPS := c.jconf["https"] if c.httpsCert != "" && !explicitHTTPS { return errors.New("httpsCert specified but https was not") } if c.httpsKey != "" && !explicitHTTPS { return errors.New("httpsKey specified but https was not") } return nil }
go
func (c *Config) readFields() error { c.camliNetIP = c.jconf.OptionalString("camliNetIP", "") c.listenAddr = c.jconf.OptionalString("listen", "") c.baseURL = strings.TrimSuffix(c.jconf.OptionalString("baseURL", ""), "/") c.httpsCert = c.jconf.OptionalString("httpsCert", "") c.httpsKey = c.jconf.OptionalString("httpsKey", "") c.https = c.jconf.OptionalBool("https", false) _, explicitHTTPS := c.jconf["https"] if c.httpsCert != "" && !explicitHTTPS { return errors.New("httpsCert specified but https was not") } if c.httpsKey != "" && !explicitHTTPS { return errors.New("httpsKey specified but https was not") } return nil }
[ "func", "(", "c", "*", "Config", ")", "readFields", "(", ")", "error", "{", "c", ".", "camliNetIP", "=", "c", ".", "jconf", ".", "OptionalString", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "c", ".", "listenAddr", "=", "c", ".", "jconf", ".", "OptionalString", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "c", ".", "baseURL", "=", "strings", ".", "TrimSuffix", "(", "c", ".", "jconf", ".", "OptionalString", "(", "\"", "\"", ",", "\"", "\"", ")", ",", "\"", "\"", ")", "\n", "c", ".", "httpsCert", "=", "c", ".", "jconf", ".", "OptionalString", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "c", ".", "httpsKey", "=", "c", ".", "jconf", ".", "OptionalString", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "c", ".", "https", "=", "c", ".", "jconf", ".", "OptionalBool", "(", "\"", "\"", ",", "false", ")", "\n\n", "_", ",", "explicitHTTPS", ":=", "c", ".", "jconf", "[", "\"", "\"", "]", "\n", "if", "c", ".", "httpsCert", "!=", "\"", "\"", "&&", "!", "explicitHTTPS", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "c", ".", "httpsKey", "!=", "\"", "\"", "&&", "!", "explicitHTTPS", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// readFields reads the low-level jsonconfig fields using the jsonconfig package // and copies them into c. This marks them as known fields before a future call to InstallerHandlers
[ "readFields", "reads", "the", "low", "-", "level", "jsonconfig", "fields", "using", "the", "jsonconfig", "package", "and", "copies", "them", "into", "c", ".", "This", "marks", "them", "as", "known", "fields", "before", "a", "future", "call", "to", "InstallerHandlers" ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/serverinit/serverinit.go#L573-L589
train
perkeep/perkeep
pkg/serverinit/serverinit.go
StartApps
func (c *Config) StartApps() error { for _, ap := range c.apps { if err := ap.Start(); err != nil { return fmt.Errorf("error starting app %v: %v", ap.ProgramName(), err) } } return nil }
go
func (c *Config) StartApps() error { for _, ap := range c.apps { if err := ap.Start(); err != nil { return fmt.Errorf("error starting app %v: %v", ap.ProgramName(), err) } } return nil }
[ "func", "(", "c", "*", "Config", ")", "StartApps", "(", ")", "error", "{", "for", "_", ",", "ap", ":=", "range", "c", ".", "apps", "{", "if", "err", ":=", "ap", ".", "Start", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ap", ".", "ProgramName", "(", ")", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// StartApps starts all the server applications that were configured // during InstallHandlers. It should only be called after perkeepd // has started serving, since these apps might request some configuration // from Perkeep to finish initializing.
[ "StartApps", "starts", "all", "the", "server", "applications", "that", "were", "configured", "during", "InstallHandlers", ".", "It", "should", "only", "be", "called", "after", "perkeepd", "has", "started", "serving", "since", "these", "apps", "might", "request", "some", "configuration", "from", "Perkeep", "to", "finish", "initializing", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/serverinit/serverinit.go#L773-L780
train
perkeep/perkeep
pkg/serverinit/serverinit.go
UploadPublicKey
func (c *Config) UploadPublicKey(ctx context.Context) error { if c.signHandler == nil { return nil } return c.signHandler.UploadPublicKey(ctx) }
go
func (c *Config) UploadPublicKey(ctx context.Context) error { if c.signHandler == nil { return nil } return c.signHandler.UploadPublicKey(ctx) }
[ "func", "(", "c", "*", "Config", ")", "UploadPublicKey", "(", "ctx", "context", ".", "Context", ")", "error", "{", "if", "c", ".", "signHandler", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "c", ".", "signHandler", ".", "UploadPublicKey", "(", "ctx", ")", "\n", "}" ]
// UploadPublicKey uploads the public key blob with the sign handler that was // configured during InstallHandlers.
[ "UploadPublicKey", "uploads", "the", "public", "key", "blob", "with", "the", "sign", "handler", "that", "was", "configured", "during", "InstallHandlers", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/serverinit/serverinit.go#L784-L789
train
perkeep/perkeep
pkg/serverinit/serverinit.go
AppURL
func (c *Config) AppURL() map[string]string { appURL := make(map[string]string, len(c.apps)) for _, ap := range c.apps { appURL[ap.ProgramName()] = ap.BackendURL() } return appURL }
go
func (c *Config) AppURL() map[string]string { appURL := make(map[string]string, len(c.apps)) for _, ap := range c.apps { appURL[ap.ProgramName()] = ap.BackendURL() } return appURL }
[ "func", "(", "c", "*", "Config", ")", "AppURL", "(", ")", "map", "[", "string", "]", "string", "{", "appURL", ":=", "make", "(", "map", "[", "string", "]", "string", ",", "len", "(", "c", ".", "apps", ")", ")", "\n", "for", "_", ",", "ap", ":=", "range", "c", ".", "apps", "{", "appURL", "[", "ap", ".", "ProgramName", "(", ")", "]", "=", "ap", ".", "BackendURL", "(", ")", "\n", "}", "\n", "return", "appURL", "\n", "}" ]
// AppURL returns a map of app name to app base URL for all the configured // server apps.
[ "AppURL", "returns", "a", "map", "of", "app", "name", "to", "app", "base", "URL", "for", "all", "the", "configured", "server", "apps", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/serverinit/serverinit.go#L793-L799
train
perkeep/perkeep
pkg/serverinit/serverinit.go
highLevelConfFields
func highLevelConfFields() map[string]bool { knownFields := make(map[string]bool) var c serverconfig.Config s := reflect.ValueOf(&c).Elem() for i := 0; i < s.NumField(); i++ { f := s.Type().Field(i) jsonTag, ok := f.Tag.Lookup("json") if !ok { panic(fmt.Sprintf("%q field in serverconfig.Config does not have a json tag", f.Name)) } jsonFields := strings.Split(strings.TrimSuffix(strings.TrimPrefix(jsonTag, `"`), `"`), ",") jsonName := jsonFields[0] if jsonName == "" { panic(fmt.Sprintf("no json field name for %q field in serverconfig.Config", f.Name)) } knownFields[jsonName] = true } return knownFields }
go
func highLevelConfFields() map[string]bool { knownFields := make(map[string]bool) var c serverconfig.Config s := reflect.ValueOf(&c).Elem() for i := 0; i < s.NumField(); i++ { f := s.Type().Field(i) jsonTag, ok := f.Tag.Lookup("json") if !ok { panic(fmt.Sprintf("%q field in serverconfig.Config does not have a json tag", f.Name)) } jsonFields := strings.Split(strings.TrimSuffix(strings.TrimPrefix(jsonTag, `"`), `"`), ",") jsonName := jsonFields[0] if jsonName == "" { panic(fmt.Sprintf("no json field name for %q field in serverconfig.Config", f.Name)) } knownFields[jsonName] = true } return knownFields }
[ "func", "highLevelConfFields", "(", ")", "map", "[", "string", "]", "bool", "{", "knownFields", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "var", "c", "serverconfig", ".", "Config", "\n", "s", ":=", "reflect", ".", "ValueOf", "(", "&", "c", ")", ".", "Elem", "(", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "s", ".", "NumField", "(", ")", ";", "i", "++", "{", "f", ":=", "s", ".", "Type", "(", ")", ".", "Field", "(", "i", ")", "\n", "jsonTag", ",", "ok", ":=", "f", ".", "Tag", ".", "Lookup", "(", "\"", "\"", ")", "\n", "if", "!", "ok", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "f", ".", "Name", ")", ")", "\n", "}", "\n", "jsonFields", ":=", "strings", ".", "Split", "(", "strings", ".", "TrimSuffix", "(", "strings", ".", "TrimPrefix", "(", "jsonTag", ",", "`\"`", ")", ",", "`\"`", ")", ",", "\"", "\"", ")", "\n", "jsonName", ":=", "jsonFields", "[", "0", "]", "\n", "if", "jsonName", "==", "\"", "\"", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "f", ".", "Name", ")", ")", "\n", "}", "\n", "knownFields", "[", "jsonName", "]", "=", "true", "\n", "}", "\n", "return", "knownFields", "\n", "}" ]
// highLevelConfFields returns all the possible fields of a serverconfig.Config, // in their JSON form. This allows checking that the parameters in the high-level // server configuration file are at least valid names, which is useful to catch // typos.
[ "highLevelConfFields", "returns", "all", "the", "possible", "fields", "of", "a", "serverconfig", ".", "Config", "in", "their", "JSON", "form", ".", "This", "allows", "checking", "that", "the", "parameters", "in", "the", "high", "-", "level", "server", "configuration", "file", "are", "at", "least", "valid", "names", "which", "is", "useful", "to", "catch", "typos", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/serverinit/serverinit.go#L915-L933
train
perkeep/perkeep
internal/azure/storage/client.go
containerURL
func (c *Client) containerURL(container string) string { return fmt.Sprintf("https://%s/%s/", c.hostname(), container) }
go
func (c *Client) containerURL(container string) string { return fmt.Sprintf("https://%s/%s/", c.hostname(), container) }
[ "func", "(", "c", "*", "Client", ")", "containerURL", "(", "container", "string", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "c", ".", "hostname", "(", ")", ",", "container", ")", "\n", "}" ]
// containerURL returns the URL prefix of the container, with trailing slash
[ "containerURL", "returns", "the", "URL", "prefix", "of", "the", "container", "with", "trailing", "slash" ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/azure/storage/client.go#L76-L78
train
perkeep/perkeep
internal/azure/storage/client.go
Containers
func (c *Client) Containers(ctx context.Context) ([]*Container, error) { req := newReq(ctx, "https://"+c.hostname()+"/") c.Auth.SignRequest(req) res, err := c.transport().RoundTrip(req) if err != nil { return nil, err } defer res.Body.Close() if res.StatusCode != http.StatusOK { return nil, fmt.Errorf("azure: Unexpected status code %d fetching container list", res.StatusCode) } return parseListAllMyContainers(res.Body) }
go
func (c *Client) Containers(ctx context.Context) ([]*Container, error) { req := newReq(ctx, "https://"+c.hostname()+"/") c.Auth.SignRequest(req) res, err := c.transport().RoundTrip(req) if err != nil { return nil, err } defer res.Body.Close() if res.StatusCode != http.StatusOK { return nil, fmt.Errorf("azure: Unexpected status code %d fetching container list", res.StatusCode) } return parseListAllMyContainers(res.Body) }
[ "func", "(", "c", "*", "Client", ")", "Containers", "(", "ctx", "context", ".", "Context", ")", "(", "[", "]", "*", "Container", ",", "error", ")", "{", "req", ":=", "newReq", "(", "ctx", ",", "\"", "\"", "+", "c", ".", "hostname", "(", ")", "+", "\"", "\"", ")", "\n", "c", ".", "Auth", ".", "SignRequest", "(", "req", ")", "\n", "res", ",", "err", ":=", "c", ".", "transport", "(", ")", ".", "RoundTrip", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "res", ".", "Body", ".", "Close", "(", ")", "\n", "if", "res", ".", "StatusCode", "!=", "http", ".", "StatusOK", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "res", ".", "StatusCode", ")", "\n", "}", "\n", "return", "parseListAllMyContainers", "(", "res", ".", "Body", ")", "\n", "}" ]
// Containers list the containers active under the current account.
[ "Containers", "list", "the", "containers", "active", "under", "the", "current", "account", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/azure/storage/client.go#L95-L107
train
perkeep/perkeep
internal/azure/storage/client.go
Stat
func (c *Client) Stat(ctx context.Context, key, container string) (size int64, reterr error) { req := newReq(ctx, c.keyURL(container, key)) req.Method = "HEAD" c.Auth.SignRequest(req) res, err := c.transport().RoundTrip(req) if err != nil { return 0, err } if res.Body != nil { defer res.Body.Close() } switch res.StatusCode { case http.StatusNotFound: return 0, os.ErrNotExist case http.StatusOK: return strconv.ParseInt(res.Header.Get("Content-Length"), 10, 64) } return 0, fmt.Errorf("azure: Unexpected status code %d statting object %v", res.StatusCode, key) }
go
func (c *Client) Stat(ctx context.Context, key, container string) (size int64, reterr error) { req := newReq(ctx, c.keyURL(container, key)) req.Method = "HEAD" c.Auth.SignRequest(req) res, err := c.transport().RoundTrip(req) if err != nil { return 0, err } if res.Body != nil { defer res.Body.Close() } switch res.StatusCode { case http.StatusNotFound: return 0, os.ErrNotExist case http.StatusOK: return strconv.ParseInt(res.Header.Get("Content-Length"), 10, 64) } return 0, fmt.Errorf("azure: Unexpected status code %d statting object %v", res.StatusCode, key) }
[ "func", "(", "c", "*", "Client", ")", "Stat", "(", "ctx", "context", ".", "Context", ",", "key", ",", "container", "string", ")", "(", "size", "int64", ",", "reterr", "error", ")", "{", "req", ":=", "newReq", "(", "ctx", ",", "c", ".", "keyURL", "(", "container", ",", "key", ")", ")", "\n", "req", ".", "Method", "=", "\"", "\"", "\n", "c", ".", "Auth", ".", "SignRequest", "(", "req", ")", "\n", "res", ",", "err", ":=", "c", ".", "transport", "(", ")", ".", "RoundTrip", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n", "if", "res", ".", "Body", "!=", "nil", "{", "defer", "res", ".", "Body", ".", "Close", "(", ")", "\n", "}", "\n", "switch", "res", ".", "StatusCode", "{", "case", "http", ".", "StatusNotFound", ":", "return", "0", ",", "os", ".", "ErrNotExist", "\n", "case", "http", ".", "StatusOK", ":", "return", "strconv", ".", "ParseInt", "(", "res", ".", "Header", ".", "Get", "(", "\"", "\"", ")", ",", "10", ",", "64", ")", "\n", "}", "\n", "return", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "res", ".", "StatusCode", ",", "key", ")", "\n", "}" ]
// Stat Stats a blob in Azure. // It returns 0, os.ErrNotExist if not found on Azure, otherwise reterr is real.
[ "Stat", "Stats", "a", "blob", "in", "Azure", ".", "It", "returns", "0", "os", ".", "ErrNotExist", "if", "not", "found", "on", "Azure", "otherwise", "reterr", "is", "real", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/azure/storage/client.go#L124-L142
train
perkeep/perkeep
internal/azure/storage/client.go
PutObject
func (c *Client) PutObject(ctx context.Context, key, container string, md5 hash.Hash, size int64, body io.Reader) error { req := newReq(ctx, c.keyURL(container, key)) req.Method = "PUT" req.ContentLength = size if md5 != nil { b64 := new(bytes.Buffer) encoder := base64.NewEncoder(base64.StdEncoding, b64) encoder.Write(md5.Sum(nil)) encoder.Close() req.Header.Set("Content-MD5", b64.String()) } req.Header.Set("Content-Length", strconv.Itoa(int(size))) req.Header.Set("x-ms-blob-type", "BlockBlob") c.Auth.SignRequest(req) req.Body = ioutil.NopCloser(body) res, err := c.transport().RoundTrip(req) if res != nil && res.Body != nil { defer res.Body.Close() } if err != nil { return err } if res.StatusCode != http.StatusCreated { if res.StatusCode < 500 { aerr := getAzureError("PutObject", res) return aerr } return fmt.Errorf("got response code %d from Azure", res.StatusCode) } return nil }
go
func (c *Client) PutObject(ctx context.Context, key, container string, md5 hash.Hash, size int64, body io.Reader) error { req := newReq(ctx, c.keyURL(container, key)) req.Method = "PUT" req.ContentLength = size if md5 != nil { b64 := new(bytes.Buffer) encoder := base64.NewEncoder(base64.StdEncoding, b64) encoder.Write(md5.Sum(nil)) encoder.Close() req.Header.Set("Content-MD5", b64.String()) } req.Header.Set("Content-Length", strconv.Itoa(int(size))) req.Header.Set("x-ms-blob-type", "BlockBlob") c.Auth.SignRequest(req) req.Body = ioutil.NopCloser(body) res, err := c.transport().RoundTrip(req) if res != nil && res.Body != nil { defer res.Body.Close() } if err != nil { return err } if res.StatusCode != http.StatusCreated { if res.StatusCode < 500 { aerr := getAzureError("PutObject", res) return aerr } return fmt.Errorf("got response code %d from Azure", res.StatusCode) } return nil }
[ "func", "(", "c", "*", "Client", ")", "PutObject", "(", "ctx", "context", ".", "Context", ",", "key", ",", "container", "string", ",", "md5", "hash", ".", "Hash", ",", "size", "int64", ",", "body", "io", ".", "Reader", ")", "error", "{", "req", ":=", "newReq", "(", "ctx", ",", "c", ".", "keyURL", "(", "container", ",", "key", ")", ")", "\n", "req", ".", "Method", "=", "\"", "\"", "\n", "req", ".", "ContentLength", "=", "size", "\n", "if", "md5", "!=", "nil", "{", "b64", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "encoder", ":=", "base64", ".", "NewEncoder", "(", "base64", ".", "StdEncoding", ",", "b64", ")", "\n", "encoder", ".", "Write", "(", "md5", ".", "Sum", "(", "nil", ")", ")", "\n", "encoder", ".", "Close", "(", ")", "\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "b64", ".", "String", "(", ")", ")", "\n", "}", "\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "int", "(", "size", ")", ")", ")", "\n", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "c", ".", "Auth", ".", "SignRequest", "(", "req", ")", "\n", "req", ".", "Body", "=", "ioutil", ".", "NopCloser", "(", "body", ")", "\n\n", "res", ",", "err", ":=", "c", ".", "transport", "(", ")", ".", "RoundTrip", "(", "req", ")", "\n", "if", "res", "!=", "nil", "&&", "res", ".", "Body", "!=", "nil", "{", "defer", "res", ".", "Body", ".", "Close", "(", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "res", ".", "StatusCode", "!=", "http", ".", "StatusCreated", "{", "if", "res", ".", "StatusCode", "<", "500", "{", "aerr", ":=", "getAzureError", "(", "\"", "\"", ",", "res", ")", "\n", "return", "aerr", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "res", ".", "StatusCode", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// PutObject puts a blob to the specified container on Azure
[ "PutObject", "puts", "a", "blob", "to", "the", "specified", "container", "on", "Azure" ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/azure/storage/client.go#L145-L176
train
perkeep/perkeep
internal/azure/storage/client.go
Get
func (c *Client) Get(ctx context.Context, container, key string) (body io.ReadCloser, size int64, err error) { req := newReq(ctx, c.keyURL(container, key)) c.Auth.SignRequest(req) res, err := c.transport().RoundTrip(req) if err != nil { return } switch res.StatusCode { case http.StatusOK: return res.Body, res.ContentLength, nil case http.StatusNotFound: res.Body.Close() return nil, 0, os.ErrNotExist default: res.Body.Close() return nil, 0, fmt.Errorf("azure HTTP error on GET: %d", res.StatusCode) } }
go
func (c *Client) Get(ctx context.Context, container, key string) (body io.ReadCloser, size int64, err error) { req := newReq(ctx, c.keyURL(container, key)) c.Auth.SignRequest(req) res, err := c.transport().RoundTrip(req) if err != nil { return } switch res.StatusCode { case http.StatusOK: return res.Body, res.ContentLength, nil case http.StatusNotFound: res.Body.Close() return nil, 0, os.ErrNotExist default: res.Body.Close() return nil, 0, fmt.Errorf("azure HTTP error on GET: %d", res.StatusCode) } }
[ "func", "(", "c", "*", "Client", ")", "Get", "(", "ctx", "context", ".", "Context", ",", "container", ",", "key", "string", ")", "(", "body", "io", ".", "ReadCloser", ",", "size", "int64", ",", "err", "error", ")", "{", "req", ":=", "newReq", "(", "ctx", ",", "c", ".", "keyURL", "(", "container", ",", "key", ")", ")", "\n", "c", ".", "Auth", ".", "SignRequest", "(", "req", ")", "\n", "res", ",", "err", ":=", "c", ".", "transport", "(", ")", ".", "RoundTrip", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "switch", "res", ".", "StatusCode", "{", "case", "http", ".", "StatusOK", ":", "return", "res", ".", "Body", ",", "res", ".", "ContentLength", ",", "nil", "\n", "case", "http", ".", "StatusNotFound", ":", "res", ".", "Body", ".", "Close", "(", ")", "\n", "return", "nil", ",", "0", ",", "os", ".", "ErrNotExist", "\n", "default", ":", "res", ".", "Body", ".", "Close", "(", ")", "\n", "return", "nil", ",", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "res", ".", "StatusCode", ")", "\n", "}", "\n", "}" ]
// Get retrieves a blob from Azure or returns os.ErrNotExist if not found
[ "Get", "retrieves", "a", "blob", "from", "Azure", "or", "returns", "os", ".", "ErrNotExist", "if", "not", "found" ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/azure/storage/client.go#L274-L291
train
perkeep/perkeep
internal/azure/storage/client.go
GetPartial
func (c *Client) GetPartial(ctx context.Context, container, key string, offset, length int64) (rc io.ReadCloser, err error) { if offset < 0 { return nil, errors.New("invalid negative length") } req := newReq(ctx, c.keyURL(container, key)) if length >= 0 { req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+length-1)) } else { req.Header.Set("Range", fmt.Sprintf("bytes=%d-", offset)) } c.Auth.SignRequest(req) res, err := c.transport().RoundTrip(req) if err != nil { return } switch res.StatusCode { case http.StatusOK, http.StatusPartialContent: return res.Body, nil case http.StatusNotFound: res.Body.Close() return nil, os.ErrNotExist default: res.Body.Close() return nil, fmt.Errorf("azure HTTP error on GET: %d", res.StatusCode) } }
go
func (c *Client) GetPartial(ctx context.Context, container, key string, offset, length int64) (rc io.ReadCloser, err error) { if offset < 0 { return nil, errors.New("invalid negative length") } req := newReq(ctx, c.keyURL(container, key)) if length >= 0 { req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", offset, offset+length-1)) } else { req.Header.Set("Range", fmt.Sprintf("bytes=%d-", offset)) } c.Auth.SignRequest(req) res, err := c.transport().RoundTrip(req) if err != nil { return } switch res.StatusCode { case http.StatusOK, http.StatusPartialContent: return res.Body, nil case http.StatusNotFound: res.Body.Close() return nil, os.ErrNotExist default: res.Body.Close() return nil, fmt.Errorf("azure HTTP error on GET: %d", res.StatusCode) } }
[ "func", "(", "c", "*", "Client", ")", "GetPartial", "(", "ctx", "context", ".", "Context", ",", "container", ",", "key", "string", ",", "offset", ",", "length", "int64", ")", "(", "rc", "io", ".", "ReadCloser", ",", "err", "error", ")", "{", "if", "offset", "<", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "req", ":=", "newReq", "(", "ctx", ",", "c", ".", "keyURL", "(", "container", ",", "key", ")", ")", "\n", "if", "length", ">=", "0", "{", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "offset", ",", "offset", "+", "length", "-", "1", ")", ")", "\n", "}", "else", "{", "req", ".", "Header", ".", "Set", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "offset", ")", ")", "\n", "}", "\n", "c", ".", "Auth", ".", "SignRequest", "(", "req", ")", "\n\n", "res", ",", "err", ":=", "c", ".", "transport", "(", ")", ".", "RoundTrip", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "switch", "res", ".", "StatusCode", "{", "case", "http", ".", "StatusOK", ",", "http", ".", "StatusPartialContent", ":", "return", "res", ".", "Body", ",", "nil", "\n", "case", "http", ".", "StatusNotFound", ":", "res", ".", "Body", ".", "Close", "(", ")", "\n", "return", "nil", ",", "os", ".", "ErrNotExist", "\n", "default", ":", "res", ".", "Body", ".", "Close", "(", ")", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "res", ".", "StatusCode", ")", "\n", "}", "\n", "}" ]
// GetPartial fetches part of the blob in container. // If length is negative, the rest of the object is returned. // The caller must close rc.
[ "GetPartial", "fetches", "part", "of", "the", "blob", "in", "container", ".", "If", "length", "is", "negative", "the", "rest", "of", "the", "object", "is", "returned", ".", "The", "caller", "must", "close", "rc", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/azure/storage/client.go#L296-L323
train
perkeep/perkeep
internal/azure/storage/client.go
Delete
func (c *Client) Delete(ctx context.Context, container, key string) error { req := newReq(ctx, c.keyURL(container, key)) req.Method = "DELETE" c.Auth.SignRequest(req) res, err := c.transport().RoundTrip(req) if err != nil { return err } if res != nil && res.Body != nil { defer res.Body.Close() } if res.StatusCode == http.StatusNotFound || res.StatusCode == http.StatusNoContent || res.StatusCode == http.StatusAccepted { return nil } return fmt.Errorf("azure HTTP error on DELETE: %d", res.StatusCode) }
go
func (c *Client) Delete(ctx context.Context, container, key string) error { req := newReq(ctx, c.keyURL(container, key)) req.Method = "DELETE" c.Auth.SignRequest(req) res, err := c.transport().RoundTrip(req) if err != nil { return err } if res != nil && res.Body != nil { defer res.Body.Close() } if res.StatusCode == http.StatusNotFound || res.StatusCode == http.StatusNoContent || res.StatusCode == http.StatusAccepted { return nil } return fmt.Errorf("azure HTTP error on DELETE: %d", res.StatusCode) }
[ "func", "(", "c", "*", "Client", ")", "Delete", "(", "ctx", "context", ".", "Context", ",", "container", ",", "key", "string", ")", "error", "{", "req", ":=", "newReq", "(", "ctx", ",", "c", ".", "keyURL", "(", "container", ",", "key", ")", ")", "\n", "req", ".", "Method", "=", "\"", "\"", "\n", "c", ".", "Auth", ".", "SignRequest", "(", "req", ")", "\n", "res", ",", "err", ":=", "c", ".", "transport", "(", ")", ".", "RoundTrip", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "res", "!=", "nil", "&&", "res", ".", "Body", "!=", "nil", "{", "defer", "res", ".", "Body", ".", "Close", "(", ")", "\n", "}", "\n", "if", "res", ".", "StatusCode", "==", "http", ".", "StatusNotFound", "||", "res", ".", "StatusCode", "==", "http", ".", "StatusNoContent", "||", "res", ".", "StatusCode", "==", "http", ".", "StatusAccepted", "{", "return", "nil", "\n", "}", "\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "res", ".", "StatusCode", ")", "\n", "}" ]
// Delete deletes a blob from the specified container. // It may take a few moments before the blob is actually deleted by Azure.
[ "Delete", "deletes", "a", "blob", "from", "the", "specified", "container", ".", "It", "may", "take", "a", "few", "moments", "before", "the", "blob", "is", "actually", "deleted", "by", "Azure", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/azure/storage/client.go#L327-L343
train
perkeep/perkeep
internal/azure/storage/client.go
Error
func (e *Error) Error() string { if e.AzureError.Code != "" { return fmt.Sprintf("azure.%s: status %d, code: %s", e.Op, e.Code, e.AzureError.Code) } return fmt.Sprintf("azure.%s: status %d", e.Op, e.Code) }
go
func (e *Error) Error() string { if e.AzureError.Code != "" { return fmt.Sprintf("azure.%s: status %d, code: %s", e.Op, e.Code, e.AzureError.Code) } return fmt.Sprintf("azure.%s: status %d", e.Op, e.Code) }
[ "func", "(", "e", "*", "Error", ")", "Error", "(", ")", "string", "{", "if", "e", ".", "AzureError", ".", "Code", "!=", "\"", "\"", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "e", ".", "Op", ",", "e", ".", "Code", ",", "e", ".", "AzureError", ".", "Code", ")", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "e", ".", "Op", ",", "e", ".", "Code", ")", "\n", "}" ]
// Error returns a formatted error message
[ "Error", "returns", "a", "formatted", "error", "message" ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/azure/storage/client.go#L391-L396
train
perkeep/perkeep
pkg/fs/fs.go
NewDefaultCamliFileSystem
func NewDefaultCamliFileSystem(client *client.Client, fetcher blob.Fetcher) *CamliFileSystem { if client == nil || fetcher == nil { panic("nil argument") } fs := newCamliFileSystem(fetcher) fs.root = &root{fs: fs} // root.go fs.client = client return fs }
go
func NewDefaultCamliFileSystem(client *client.Client, fetcher blob.Fetcher) *CamliFileSystem { if client == nil || fetcher == nil { panic("nil argument") } fs := newCamliFileSystem(fetcher) fs.root = &root{fs: fs} // root.go fs.client = client return fs }
[ "func", "NewDefaultCamliFileSystem", "(", "client", "*", "client", ".", "Client", ",", "fetcher", "blob", ".", "Fetcher", ")", "*", "CamliFileSystem", "{", "if", "client", "==", "nil", "||", "fetcher", "==", "nil", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n", "fs", ":=", "newCamliFileSystem", "(", "fetcher", ")", "\n", "fs", ".", "root", "=", "&", "root", "{", "fs", ":", "fs", "}", "// root.go", "\n", "fs", ".", "client", "=", "client", "\n", "return", "fs", "\n", "}" ]
// NewDefaultCamliFileSystem returns a filesystem with a generic base, from which // users can navigate by blobref, tag, date, etc.
[ "NewDefaultCamliFileSystem", "returns", "a", "filesystem", "with", "a", "generic", "base", "from", "which", "users", "can", "navigate", "by", "blobref", "tag", "date", "etc", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/fs/fs.go#L76-L84
train
perkeep/perkeep
pkg/fs/fs.go
NewRootedCamliFileSystem
func NewRootedCamliFileSystem(cli *client.Client, fetcher blob.Fetcher, root blob.Ref) (*CamliFileSystem, error) { fs := newCamliFileSystem(fetcher) fs.client = cli n, err := fs.newNodeFromBlobRef(root) if err != nil { return nil, err } fs.root = n return fs, nil }
go
func NewRootedCamliFileSystem(cli *client.Client, fetcher blob.Fetcher, root blob.Ref) (*CamliFileSystem, error) { fs := newCamliFileSystem(fetcher) fs.client = cli n, err := fs.newNodeFromBlobRef(root) if err != nil { return nil, err } fs.root = n return fs, nil }
[ "func", "NewRootedCamliFileSystem", "(", "cli", "*", "client", ".", "Client", ",", "fetcher", "blob", ".", "Fetcher", ",", "root", "blob", ".", "Ref", ")", "(", "*", "CamliFileSystem", ",", "error", ")", "{", "fs", ":=", "newCamliFileSystem", "(", "fetcher", ")", "\n", "fs", ".", "client", "=", "cli", "\n\n", "n", ",", "err", ":=", "fs", ".", "newNodeFromBlobRef", "(", "root", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "fs", ".", "root", "=", "n", "\n\n", "return", "fs", ",", "nil", "\n", "}" ]
// NewRootedCamliFileSystem returns a CamliFileSystem with a node based on a blobref // as its base.
[ "NewRootedCamliFileSystem", "returns", "a", "CamliFileSystem", "with", "a", "node", "based", "on", "a", "blobref", "as", "its", "base", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/fs/fs.go#L88-L101
train
perkeep/perkeep
pkg/fs/fs.go
populateAttr
func (n *node) populateAttr() error { meta := n.meta n.attr.Mode = meta.FileMode() if n.fs.IgnoreOwners { n.attr.Uid = uint32(os.Getuid()) n.attr.Gid = uint32(os.Getgid()) executeBit := n.attr.Mode & 0100 n.attr.Mode = (n.attr.Mode ^ n.attr.Mode.Perm()) | 0400 | executeBit } else { n.attr.Uid = uint32(meta.MapUid()) n.attr.Gid = uint32(meta.MapGid()) } // TODO: inode? if mt := meta.ModTime(); !mt.IsZero() { n.attr.Mtime = mt } else { n.attr.Mtime = n.pnodeModTime } switch meta.Type() { case "file": n.attr.Size = uint64(meta.PartsSize()) n.attr.Blocks = 0 // TODO: set? n.attr.Mode |= 0400 case "directory": n.attr.Mode |= 0500 case "symlink": n.attr.Mode |= 0400 default: Logger.Printf("unknown attr ss.Type %q in populateAttr", meta.Type()) } return nil }
go
func (n *node) populateAttr() error { meta := n.meta n.attr.Mode = meta.FileMode() if n.fs.IgnoreOwners { n.attr.Uid = uint32(os.Getuid()) n.attr.Gid = uint32(os.Getgid()) executeBit := n.attr.Mode & 0100 n.attr.Mode = (n.attr.Mode ^ n.attr.Mode.Perm()) | 0400 | executeBit } else { n.attr.Uid = uint32(meta.MapUid()) n.attr.Gid = uint32(meta.MapGid()) } // TODO: inode? if mt := meta.ModTime(); !mt.IsZero() { n.attr.Mtime = mt } else { n.attr.Mtime = n.pnodeModTime } switch meta.Type() { case "file": n.attr.Size = uint64(meta.PartsSize()) n.attr.Blocks = 0 // TODO: set? n.attr.Mode |= 0400 case "directory": n.attr.Mode |= 0500 case "symlink": n.attr.Mode |= 0400 default: Logger.Printf("unknown attr ss.Type %q in populateAttr", meta.Type()) } return nil }
[ "func", "(", "n", "*", "node", ")", "populateAttr", "(", ")", "error", "{", "meta", ":=", "n", ".", "meta", "\n\n", "n", ".", "attr", ".", "Mode", "=", "meta", ".", "FileMode", "(", ")", "\n\n", "if", "n", ".", "fs", ".", "IgnoreOwners", "{", "n", ".", "attr", ".", "Uid", "=", "uint32", "(", "os", ".", "Getuid", "(", ")", ")", "\n", "n", ".", "attr", ".", "Gid", "=", "uint32", "(", "os", ".", "Getgid", "(", ")", ")", "\n", "executeBit", ":=", "n", ".", "attr", ".", "Mode", "&", "0100", "\n", "n", ".", "attr", ".", "Mode", "=", "(", "n", ".", "attr", ".", "Mode", "^", "n", ".", "attr", ".", "Mode", ".", "Perm", "(", ")", ")", "|", "0400", "|", "executeBit", "\n", "}", "else", "{", "n", ".", "attr", ".", "Uid", "=", "uint32", "(", "meta", ".", "MapUid", "(", ")", ")", "\n", "n", ".", "attr", ".", "Gid", "=", "uint32", "(", "meta", ".", "MapGid", "(", ")", ")", "\n", "}", "\n\n", "// TODO: inode?", "if", "mt", ":=", "meta", ".", "ModTime", "(", ")", ";", "!", "mt", ".", "IsZero", "(", ")", "{", "n", ".", "attr", ".", "Mtime", "=", "mt", "\n", "}", "else", "{", "n", ".", "attr", ".", "Mtime", "=", "n", ".", "pnodeModTime", "\n", "}", "\n\n", "switch", "meta", ".", "Type", "(", ")", "{", "case", "\"", "\"", ":", "n", ".", "attr", ".", "Size", "=", "uint64", "(", "meta", ".", "PartsSize", "(", ")", ")", "\n", "n", ".", "attr", ".", "Blocks", "=", "0", "// TODO: set?", "\n", "n", ".", "attr", ".", "Mode", "|=", "0400", "\n", "case", "\"", "\"", ":", "n", ".", "attr", ".", "Mode", "|=", "0500", "\n", "case", "\"", "\"", ":", "n", ".", "attr", ".", "Mode", "|=", "0400", "\n", "default", ":", "Logger", ".", "Printf", "(", "\"", "\"", ",", "meta", ".", "Type", "(", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// populateAttr should only be called once n.ss is known to be set and // non-nil
[ "populateAttr", "should", "only", "be", "called", "once", "n", ".", "ss", "is", "known", "to", "be", "set", "and", "non", "-", "nil" ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/fs/fs.go#L283-L319
train
perkeep/perkeep
pkg/fs/fs.go
newNodeFromBlobRef
func (fs *CamliFileSystem) newNodeFromBlobRef(root blob.Ref) (fusefs.Node, error) { blob, err := fs.fetchSchemaMeta(context.TODO(), root) if err != nil { return nil, err } switch blob.Type() { case "directory": n := &node{fs: fs, blobref: root, meta: blob} n.populateAttr() return n, nil case "permanode": // other mutDirs listed in the default fileystem have names and are displayed return &mutDir{fs: fs, permanode: root, name: "-"}, nil } return nil, fmt.Errorf("Blobref must be of a directory or permanode got a %v", blob.Type()) }
go
func (fs *CamliFileSystem) newNodeFromBlobRef(root blob.Ref) (fusefs.Node, error) { blob, err := fs.fetchSchemaMeta(context.TODO(), root) if err != nil { return nil, err } switch blob.Type() { case "directory": n := &node{fs: fs, blobref: root, meta: blob} n.populateAttr() return n, nil case "permanode": // other mutDirs listed in the default fileystem have names and are displayed return &mutDir{fs: fs, permanode: root, name: "-"}, nil } return nil, fmt.Errorf("Blobref must be of a directory or permanode got a %v", blob.Type()) }
[ "func", "(", "fs", "*", "CamliFileSystem", ")", "newNodeFromBlobRef", "(", "root", "blob", ".", "Ref", ")", "(", "fusefs", ".", "Node", ",", "error", ")", "{", "blob", ",", "err", ":=", "fs", ".", "fetchSchemaMeta", "(", "context", ".", "TODO", "(", ")", ",", "root", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "switch", "blob", ".", "Type", "(", ")", "{", "case", "\"", "\"", ":", "n", ":=", "&", "node", "{", "fs", ":", "fs", ",", "blobref", ":", "root", ",", "meta", ":", "blob", "}", "\n", "n", ".", "populateAttr", "(", ")", "\n", "return", "n", ",", "nil", "\n\n", "case", "\"", "\"", ":", "// other mutDirs listed in the default fileystem have names and are displayed", "return", "&", "mutDir", "{", "fs", ":", "fs", ",", "permanode", ":", "root", ",", "name", ":", "\"", "\"", "}", ",", "nil", "\n", "}", "\n\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "blob", ".", "Type", "(", ")", ")", "\n", "}" ]
// consolated logic for determining a node to mount based on an arbitrary blobref
[ "consolated", "logic", "for", "determining", "a", "node", "to", "mount", "based", "on", "an", "arbitrary", "blobref" ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/fs/fs.go#L367-L385
train
perkeep/perkeep
dev/devcam/devcam.go
build
func build(targets ...string) error { if v, _ := strconv.ParseBool(os.Getenv("CAMLI_FAST_DEV")); v { // Demo mode. See dev/demo.sh. return nil } var fullTargets []string for _, t := range targets { t = filepath.ToSlash(t) if !strings.HasPrefix(t, "perkeep.org") { t = pathpkg.Join("perkeep.org", t) } fullTargets = append(fullTargets, t) } targetsComma := strings.Join(fullTargets, ",") args := []string{ "run", "make.go", "--quiet", "--race=" + strconv.FormatBool(*race), "--embed_static=false", "--sqlite=" + strconv.FormatBool(withSqlite), "--targets=" + targetsComma, } cmd := exec.Command("go", args...) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { return fmt.Errorf("error building %v: %v", targetsComma, err) } return nil }
go
func build(targets ...string) error { if v, _ := strconv.ParseBool(os.Getenv("CAMLI_FAST_DEV")); v { // Demo mode. See dev/demo.sh. return nil } var fullTargets []string for _, t := range targets { t = filepath.ToSlash(t) if !strings.HasPrefix(t, "perkeep.org") { t = pathpkg.Join("perkeep.org", t) } fullTargets = append(fullTargets, t) } targetsComma := strings.Join(fullTargets, ",") args := []string{ "run", "make.go", "--quiet", "--race=" + strconv.FormatBool(*race), "--embed_static=false", "--sqlite=" + strconv.FormatBool(withSqlite), "--targets=" + targetsComma, } cmd := exec.Command("go", args...) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { return fmt.Errorf("error building %v: %v", targetsComma, err) } return nil }
[ "func", "build", "(", "targets", "...", "string", ")", "error", "{", "if", "v", ",", "_", ":=", "strconv", ".", "ParseBool", "(", "os", ".", "Getenv", "(", "\"", "\"", ")", ")", ";", "v", "{", "// Demo mode. See dev/demo.sh.", "return", "nil", "\n", "}", "\n", "var", "fullTargets", "[", "]", "string", "\n", "for", "_", ",", "t", ":=", "range", "targets", "{", "t", "=", "filepath", ".", "ToSlash", "(", "t", ")", "\n", "if", "!", "strings", ".", "HasPrefix", "(", "t", ",", "\"", "\"", ")", "{", "t", "=", "pathpkg", ".", "Join", "(", "\"", "\"", ",", "t", ")", "\n", "}", "\n", "fullTargets", "=", "append", "(", "fullTargets", ",", "t", ")", "\n", "}", "\n", "targetsComma", ":=", "strings", ".", "Join", "(", "fullTargets", ",", "\"", "\"", ")", "\n", "args", ":=", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "+", "strconv", ".", "FormatBool", "(", "*", "race", ")", ",", "\"", "\"", ",", "\"", "\"", "+", "strconv", ".", "FormatBool", "(", "withSqlite", ")", ",", "\"", "\"", "+", "targetsComma", ",", "}", "\n", "cmd", ":=", "exec", ".", "Command", "(", "\"", "\"", ",", "args", "...", ")", "\n", "cmd", ".", "Stdout", "=", "os", ".", "Stdout", "\n", "cmd", ".", "Stderr", "=", "os", ".", "Stderr", "\n", "if", "err", ":=", "cmd", ".", "Run", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "targetsComma", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// build builds the named perkeep targets. // Each target may have its "perkeep.org" prefix removed.
[ "build", "builds", "the", "named", "perkeep", "targets", ".", "Each", "target", "may", "have", "its", "perkeep", ".", "org", "prefix", "removed", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/dev/devcam/devcam.go#L238-L267
train
perkeep/perkeep
pkg/index/location.go
NewLocationHelper
func NewLocationHelper(ix *Index) *LocationHelper { lh := &LocationHelper{index: ix} if ix.corpus != nil { lh.corpus = ix.corpus } return lh }
go
func NewLocationHelper(ix *Index) *LocationHelper { lh := &LocationHelper{index: ix} if ix.corpus != nil { lh.corpus = ix.corpus } return lh }
[ "func", "NewLocationHelper", "(", "ix", "*", "Index", ")", "*", "LocationHelper", "{", "lh", ":=", "&", "LocationHelper", "{", "index", ":", "ix", "}", "\n", "if", "ix", ".", "corpus", "!=", "nil", "{", "lh", ".", "corpus", "=", "ix", ".", "corpus", "\n", "}", "\n", "return", "lh", "\n", "}" ]
// NewLocationHelper returns a new location handler // that uses ix to query blob attributes.
[ "NewLocationHelper", "returns", "a", "new", "location", "handler", "that", "uses", "ix", "to", "query", "blob", "attributes", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/location.go#L26-L32
train
perkeep/perkeep
pkg/index/location.go
get
func (pa permAttr) get(attr string) string { if pa.attrs != nil { v := pa.attrs[attr] if len(v) != 0 { return v[0] } return "" } if pa.claims != nil { return claimsIntfAttrValue(pa.claims, attr, pa.at, pa.signerFilter) } return "" }
go
func (pa permAttr) get(attr string) string { if pa.attrs != nil { v := pa.attrs[attr] if len(v) != 0 { return v[0] } return "" } if pa.claims != nil { return claimsIntfAttrValue(pa.claims, attr, pa.at, pa.signerFilter) } return "" }
[ "func", "(", "pa", "permAttr", ")", "get", "(", "attr", "string", ")", "string", "{", "if", "pa", ".", "attrs", "!=", "nil", "{", "v", ":=", "pa", ".", "attrs", "[", "attr", "]", "\n", "if", "len", "(", "v", ")", "!=", "0", "{", "return", "v", "[", "0", "]", "\n", "}", "\n", "return", "\"", "\"", "\n", "}", "\n\n", "if", "pa", ".", "claims", "!=", "nil", "{", "return", "claimsIntfAttrValue", "(", "pa", ".", "claims", ",", "attr", ",", "pa", ".", "at", ",", "pa", ".", "signerFilter", ")", "\n", "}", "\n\n", "return", "\"", "\"", "\n", "}" ]
// get returns the value of attr.
[ "get", "returns", "the", "value", "of", "attr", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/index/location.go#L147-L161
train
perkeep/perkeep
pkg/fileembed/fileembed.go
IsEmpty
func (f *Files) IsEmpty() bool { f.lk.Lock() defer f.lk.Unlock() return len(f.file) == 0 }
go
func (f *Files) IsEmpty() bool { f.lk.Lock() defer f.lk.Unlock() return len(f.file) == 0 }
[ "func", "(", "f", "*", "Files", ")", "IsEmpty", "(", ")", "bool", "{", "f", ".", "lk", ".", "Lock", "(", ")", "\n", "defer", "f", ".", "lk", ".", "Unlock", "(", ")", "\n", "return", "len", "(", "f", ".", "file", ")", "==", "0", "\n", "}" ]
// IsEmpty reports whether f is empty.
[ "IsEmpty", "reports", "whether", "f", "is", "empty", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/fileembed/fileembed.go#L121-L125
train
perkeep/perkeep
pkg/fileembed/fileembed.go
Add
func (f *Files) Add(filename string, size int64, modtime time.Time, o Opener) { f.lk.Lock() defer f.lk.Unlock() r, err := o.Open() if err != nil { log.Printf("Could not add file %v: %v", filename, err) return } contents, err := ioutil.ReadAll(r) if err != nil { log.Printf("Could not read contents of file %v: %v", filename, err) return } f.add(filename, &staticFile{ name: filename, contents: contents, modtime: modtime, }) }
go
func (f *Files) Add(filename string, size int64, modtime time.Time, o Opener) { f.lk.Lock() defer f.lk.Unlock() r, err := o.Open() if err != nil { log.Printf("Could not add file %v: %v", filename, err) return } contents, err := ioutil.ReadAll(r) if err != nil { log.Printf("Could not read contents of file %v: %v", filename, err) return } f.add(filename, &staticFile{ name: filename, contents: contents, modtime: modtime, }) }
[ "func", "(", "f", "*", "Files", ")", "Add", "(", "filename", "string", ",", "size", "int64", ",", "modtime", "time", ".", "Time", ",", "o", "Opener", ")", "{", "f", ".", "lk", ".", "Lock", "(", ")", "\n", "defer", "f", ".", "lk", ".", "Unlock", "(", ")", "\n\n", "r", ",", "err", ":=", "o", ".", "Open", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "filename", ",", "err", ")", "\n", "return", "\n", "}", "\n", "contents", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "filename", ",", "err", ")", "\n", "return", "\n", "}", "\n\n", "f", ".", "add", "(", "filename", ",", "&", "staticFile", "{", "name", ":", "filename", ",", "contents", ":", "contents", ",", "modtime", ":", "modtime", ",", "}", ")", "\n", "}" ]
// Add adds a file to the file set.
[ "Add", "adds", "a", "file", "to", "the", "file", "set", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/fileembed/fileembed.go#L128-L148
train
perkeep/perkeep
pkg/fileembed/fileembed.go
add
func (f *Files) add(filename string, sf *staticFile) { if f.file == nil { f.file = make(map[string]*staticFile) } f.file[filename] = sf }
go
func (f *Files) add(filename string, sf *staticFile) { if f.file == nil { f.file = make(map[string]*staticFile) } f.file[filename] = sf }
[ "func", "(", "f", "*", "Files", ")", "add", "(", "filename", "string", ",", "sf", "*", "staticFile", ")", "{", "if", "f", ".", "file", "==", "nil", "{", "f", ".", "file", "=", "make", "(", "map", "[", "string", "]", "*", "staticFile", ")", "\n", "}", "\n", "f", ".", "file", "[", "filename", "]", "=", "sf", "\n", "}" ]
// f.lk must be locked
[ "f", ".", "lk", "must", "be", "locked" ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/fileembed/fileembed.go#L151-L156
train
perkeep/perkeep
pkg/fileembed/fileembed.go
openFallback
func (f *Files) openFallback(filename string) (http.File, error) { if f.DirFallback == "" { return nil, os.ErrNotExist } of, err := os.Open(filepath.Join(f.DirFallback, filename)) switch { case err != nil: return nil, err case f.SlurpToMemory: defer of.Close() bs, err := ioutil.ReadAll(of) if err != nil { return nil, err } fi, err := of.Stat() sf := &staticFile{ name: filename, contents: bs, modtime: fi.ModTime(), } f.add(filename, sf) return &fileHandle{sf: sf}, nil } return of, nil }
go
func (f *Files) openFallback(filename string) (http.File, error) { if f.DirFallback == "" { return nil, os.ErrNotExist } of, err := os.Open(filepath.Join(f.DirFallback, filename)) switch { case err != nil: return nil, err case f.SlurpToMemory: defer of.Close() bs, err := ioutil.ReadAll(of) if err != nil { return nil, err } fi, err := of.Stat() sf := &staticFile{ name: filename, contents: bs, modtime: fi.ModTime(), } f.add(filename, sf) return &fileHandle{sf: sf}, nil } return of, nil }
[ "func", "(", "f", "*", "Files", ")", "openFallback", "(", "filename", "string", ")", "(", "http", ".", "File", ",", "error", ")", "{", "if", "f", ".", "DirFallback", "==", "\"", "\"", "{", "return", "nil", ",", "os", ".", "ErrNotExist", "\n", "}", "\n", "of", ",", "err", ":=", "os", ".", "Open", "(", "filepath", ".", "Join", "(", "f", ".", "DirFallback", ",", "filename", ")", ")", "\n", "switch", "{", "case", "err", "!=", "nil", ":", "return", "nil", ",", "err", "\n", "case", "f", ".", "SlurpToMemory", ":", "defer", "of", ".", "Close", "(", ")", "\n", "bs", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "of", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "fi", ",", "err", ":=", "of", ".", "Stat", "(", ")", "\n\n", "sf", ":=", "&", "staticFile", "{", "name", ":", "filename", ",", "contents", ":", "bs", ",", "modtime", ":", "fi", ".", "ModTime", "(", ")", ",", "}", "\n", "f", ".", "add", "(", "filename", ",", "sf", ")", "\n", "return", "&", "fileHandle", "{", "sf", ":", "sf", "}", ",", "nil", "\n", "}", "\n", "return", "of", ",", "nil", "\n", "}" ]
// f.lk is held
[ "f", ".", "lk", "is", "held" ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/fileembed/fileembed.go#L180-L205
train
perkeep/perkeep
website/pk-web/format.go
commentSelection
func commentSelection(src []byte) Selection { var s scanner.Scanner fset := token.NewFileSet() file := fset.AddFile("", fset.Base(), len(src)) s.Init(file, src, nil, scanner.ScanComments) return func() (seg []int) { for { pos, tok, lit := s.Scan() if tok == token.EOF { break } offs := file.Offset(pos) if tok == token.COMMENT { seg = []int{offs, offs + len(lit)} break } } return } }
go
func commentSelection(src []byte) Selection { var s scanner.Scanner fset := token.NewFileSet() file := fset.AddFile("", fset.Base(), len(src)) s.Init(file, src, nil, scanner.ScanComments) return func() (seg []int) { for { pos, tok, lit := s.Scan() if tok == token.EOF { break } offs := file.Offset(pos) if tok == token.COMMENT { seg = []int{offs, offs + len(lit)} break } } return } }
[ "func", "commentSelection", "(", "src", "[", "]", "byte", ")", "Selection", "{", "var", "s", "scanner", ".", "Scanner", "\n", "fset", ":=", "token", ".", "NewFileSet", "(", ")", "\n", "file", ":=", "fset", ".", "AddFile", "(", "\"", "\"", ",", "fset", ".", "Base", "(", ")", ",", "len", "(", "src", ")", ")", "\n", "s", ".", "Init", "(", "file", ",", "src", ",", "nil", ",", "scanner", ".", "ScanComments", ")", "\n", "return", "func", "(", ")", "(", "seg", "[", "]", "int", ")", "{", "for", "{", "pos", ",", "tok", ",", "lit", ":=", "s", ".", "Scan", "(", ")", "\n", "if", "tok", "==", "token", ".", "EOF", "{", "break", "\n", "}", "\n", "offs", ":=", "file", ".", "Offset", "(", "pos", ")", "\n", "if", "tok", "==", "token", ".", "COMMENT", "{", "seg", "=", "[", "]", "int", "{", "offs", ",", "offs", "+", "len", "(", "lit", ")", "}", "\n", "break", "\n", "}", "\n", "}", "\n", "return", "\n", "}", "\n", "}" ]
// commentSelection returns the sequence of consecutive comments // in the Go src text as a Selection. //
[ "commentSelection", "returns", "the", "sequence", "of", "consecutive", "comments", "in", "the", "Go", "src", "text", "as", "a", "Selection", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/website/pk-web/format.go#L232-L251
train
perkeep/perkeep
website/pk-web/format.go
makeSelection
func makeSelection(matches [][]int) Selection { return func() (seg []int) { if len(matches) > 0 { seg = matches[0] matches = matches[1:] } return } }
go
func makeSelection(matches [][]int) Selection { return func() (seg []int) { if len(matches) > 0 { seg = matches[0] matches = matches[1:] } return } }
[ "func", "makeSelection", "(", "matches", "[", "]", "[", "]", "int", ")", "Selection", "{", "return", "func", "(", ")", "(", "seg", "[", "]", "int", ")", "{", "if", "len", "(", "matches", ")", ">", "0", "{", "seg", "=", "matches", "[", "0", "]", "\n", "matches", "=", "matches", "[", "1", ":", "]", "\n", "}", "\n", "return", "\n", "}", "\n", "}" ]
// makeSelection is a helper function to make a Selection from a slice of pairs.
[ "makeSelection", "is", "a", "helper", "function", "to", "make", "a", "Selection", "from", "a", "slice", "of", "pairs", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/website/pk-web/format.go#L254-L262
train
perkeep/perkeep
website/pk-web/format.go
regexpSelection
func regexpSelection(text []byte, expr string) Selection { var matches [][]int if rx, err := regexp.Compile(expr); err == nil { matches = rx.FindAllIndex(text, -1) } return makeSelection(matches) }
go
func regexpSelection(text []byte, expr string) Selection { var matches [][]int if rx, err := regexp.Compile(expr); err == nil { matches = rx.FindAllIndex(text, -1) } return makeSelection(matches) }
[ "func", "regexpSelection", "(", "text", "[", "]", "byte", ",", "expr", "string", ")", "Selection", "{", "var", "matches", "[", "]", "[", "]", "int", "\n", "if", "rx", ",", "err", ":=", "regexp", ".", "Compile", "(", "expr", ")", ";", "err", "==", "nil", "{", "matches", "=", "rx", ".", "FindAllIndex", "(", "text", ",", "-", "1", ")", "\n", "}", "\n", "return", "makeSelection", "(", "matches", ")", "\n", "}" ]
// regexpSelection computes the Selection for the regular expression expr in text.
[ "regexpSelection", "computes", "the", "Selection", "for", "the", "regular", "expression", "expr", "in", "text", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/website/pk-web/format.go#L265-L271
train
perkeep/perkeep
website/pk-web/format.go
rangeSelection
func rangeSelection(str string) Selection { m := selRx.FindStringSubmatch(str) if len(m) >= 2 { from, _ := strconv.Atoi(m[1]) to, _ := strconv.Atoi(m[2]) if from < to { return makeSelection([][]int{{from, to}}) } } return nil }
go
func rangeSelection(str string) Selection { m := selRx.FindStringSubmatch(str) if len(m) >= 2 { from, _ := strconv.Atoi(m[1]) to, _ := strconv.Atoi(m[2]) if from < to { return makeSelection([][]int{{from, to}}) } } return nil }
[ "func", "rangeSelection", "(", "str", "string", ")", "Selection", "{", "m", ":=", "selRx", ".", "FindStringSubmatch", "(", "str", ")", "\n", "if", "len", "(", "m", ")", ">=", "2", "{", "from", ",", "_", ":=", "strconv", ".", "Atoi", "(", "m", "[", "1", "]", ")", "\n", "to", ",", "_", ":=", "strconv", ".", "Atoi", "(", "m", "[", "2", "]", ")", "\n", "if", "from", "<", "to", "{", "return", "makeSelection", "(", "[", "]", "[", "]", "int", "{", "{", "from", ",", "to", "}", "}", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// rangeSelection computes the Selection for a text range described // by the argument str; the range description must match the selRx // regular expression. //
[ "rangeSelection", "computes", "the", "Selection", "for", "a", "text", "range", "described", "by", "the", "argument", "str", ";", "the", "range", "description", "must", "match", "the", "selRx", "regular", "expression", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/website/pk-web/format.go#L279-L289
train
perkeep/perkeep
clients/android/build-in-docker.go
getVersion
func getVersion() string { slurp, err := ioutil.ReadFile(filepath.Join(camliDir, "VERSION")) if err == nil { return strings.TrimSpace(string(slurp)) } return gitVersion() }
go
func getVersion() string { slurp, err := ioutil.ReadFile(filepath.Join(camliDir, "VERSION")) if err == nil { return strings.TrimSpace(string(slurp)) } return gitVersion() }
[ "func", "getVersion", "(", ")", "string", "{", "slurp", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "filepath", ".", "Join", "(", "camliDir", ",", "\"", "\"", ")", ")", "\n", "if", "err", "==", "nil", "{", "return", "strings", ".", "TrimSpace", "(", "string", "(", "slurp", ")", ")", "\n", "}", "\n", "return", "gitVersion", "(", ")", "\n", "}" ]
// getVersion returns the version of Perkeep. Either from a VERSION file at the root, // or from git.
[ "getVersion", "returns", "the", "version", "of", "Perkeep", ".", "Either", "from", "a", "VERSION", "file", "at", "the", "root", "or", "from", "git", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/clients/android/build-in-docker.go#L107-L113
train
perkeep/perkeep
clients/android/build-in-docker.go
gitVersion
func gitVersion() string { cmd := exec.Command("git", "rev-list", "--max-count=1", "--pretty=format:'%ad-%h'", "--date=short", "--abbrev=10", "HEAD") cmd.Dir = camliDir out, err := cmd.Output() if err != nil { log.Fatalf("Error running git rev-list in %s: %v", camliDir, err) } v := strings.TrimSpace(string(out)) if m := gitVersionRx.FindStringSubmatch(v); m != nil { v = m[0] } else { panic("Failed to find git version in " + v) } cmd = exec.Command("git", "diff", "--exit-code") cmd.Dir = camliDir if err := cmd.Run(); err != nil { v += "+" } return v }
go
func gitVersion() string { cmd := exec.Command("git", "rev-list", "--max-count=1", "--pretty=format:'%ad-%h'", "--date=short", "--abbrev=10", "HEAD") cmd.Dir = camliDir out, err := cmd.Output() if err != nil { log.Fatalf("Error running git rev-list in %s: %v", camliDir, err) } v := strings.TrimSpace(string(out)) if m := gitVersionRx.FindStringSubmatch(v); m != nil { v = m[0] } else { panic("Failed to find git version in " + v) } cmd = exec.Command("git", "diff", "--exit-code") cmd.Dir = camliDir if err := cmd.Run(); err != nil { v += "+" } return v }
[ "func", "gitVersion", "(", ")", "string", "{", "cmd", ":=", "exec", ".", "Command", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Dir", "=", "camliDir", "\n", "out", ",", "err", ":=", "cmd", ".", "Output", "(", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "camliDir", ",", "err", ")", "\n", "}", "\n", "v", ":=", "strings", ".", "TrimSpace", "(", "string", "(", "out", ")", ")", "\n", "if", "m", ":=", "gitVersionRx", ".", "FindStringSubmatch", "(", "v", ")", ";", "m", "!=", "nil", "{", "v", "=", "m", "[", "0", "]", "\n", "}", "else", "{", "panic", "(", "\"", "\"", "+", "v", ")", "\n", "}", "\n", "cmd", "=", "exec", ".", "Command", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cmd", ".", "Dir", "=", "camliDir", "\n", "if", "err", ":=", "cmd", ".", "Run", "(", ")", ";", "err", "!=", "nil", "{", "v", "+=", "\"", "\"", "\n", "}", "\n", "return", "v", "\n", "}" ]
// gitVersion returns the git version of the git repo at camRoot as a // string of the form "yyyy-mm-dd-xxxxxxx", with an optional trailing // '+' if there are any local uncommitted modifications to the tree.
[ "gitVersion", "returns", "the", "git", "version", "of", "the", "git", "repo", "at", "camRoot", "as", "a", "string", "of", "the", "form", "yyyy", "-", "mm", "-", "dd", "-", "xxxxxxx", "with", "an", "optional", "trailing", "+", "if", "there", "are", "any", "local", "uncommitted", "modifications", "to", "the", "tree", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/clients/android/build-in-docker.go#L120-L140
train
perkeep/perkeep
pkg/importer/picasa/picasa.go
findExistingPermanode
func findExistingPermanode(ctx context.Context, qs search.QueryDescriber, wholeRef blob.Ref) (pn blob.Ref, err error) { res, err := qs.Query(ctx, &search.SearchQuery{ Constraint: &search.Constraint{ Permanode: &search.PermanodeConstraint{ Attr: "camliContent", ValueInSet: &search.Constraint{ File: &search.FileConstraint{ WholeRef: wholeRef, }, }, }, }, Describe: &search.DescribeRequest{ Depth: 1, }, }) if err != nil { return } if res.Describe == nil { return pn, os.ErrNotExist } Res: for _, resBlob := range res.Blobs { br := resBlob.Blob desBlob, ok := res.Describe.Meta[br.String()] if !ok || desBlob.Permanode == nil { continue } attrs := desBlob.Permanode.Attr for _, attr := range sensitiveAttrs { if attrs.Get(attr) != "" { continue Res } } return br, nil } return pn, os.ErrNotExist }
go
func findExistingPermanode(ctx context.Context, qs search.QueryDescriber, wholeRef blob.Ref) (pn blob.Ref, err error) { res, err := qs.Query(ctx, &search.SearchQuery{ Constraint: &search.Constraint{ Permanode: &search.PermanodeConstraint{ Attr: "camliContent", ValueInSet: &search.Constraint{ File: &search.FileConstraint{ WholeRef: wholeRef, }, }, }, }, Describe: &search.DescribeRequest{ Depth: 1, }, }) if err != nil { return } if res.Describe == nil { return pn, os.ErrNotExist } Res: for _, resBlob := range res.Blobs { br := resBlob.Blob desBlob, ok := res.Describe.Meta[br.String()] if !ok || desBlob.Permanode == nil { continue } attrs := desBlob.Permanode.Attr for _, attr := range sensitiveAttrs { if attrs.Get(attr) != "" { continue Res } } return br, nil } return pn, os.ErrNotExist }
[ "func", "findExistingPermanode", "(", "ctx", "context", ".", "Context", ",", "qs", "search", ".", "QueryDescriber", ",", "wholeRef", "blob", ".", "Ref", ")", "(", "pn", "blob", ".", "Ref", ",", "err", "error", ")", "{", "res", ",", "err", ":=", "qs", ".", "Query", "(", "ctx", ",", "&", "search", ".", "SearchQuery", "{", "Constraint", ":", "&", "search", ".", "Constraint", "{", "Permanode", ":", "&", "search", ".", "PermanodeConstraint", "{", "Attr", ":", "\"", "\"", ",", "ValueInSet", ":", "&", "search", ".", "Constraint", "{", "File", ":", "&", "search", ".", "FileConstraint", "{", "WholeRef", ":", "wholeRef", ",", "}", ",", "}", ",", "}", ",", "}", ",", "Describe", ":", "&", "search", ".", "DescribeRequest", "{", "Depth", ":", "1", ",", "}", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "res", ".", "Describe", "==", "nil", "{", "return", "pn", ",", "os", ".", "ErrNotExist", "\n", "}", "\n", "Res", ":", "for", "_", ",", "resBlob", ":=", "range", "res", ".", "Blobs", "{", "br", ":=", "resBlob", ".", "Blob", "\n", "desBlob", ",", "ok", ":=", "res", ".", "Describe", ".", "Meta", "[", "br", ".", "String", "(", ")", "]", "\n", "if", "!", "ok", "||", "desBlob", ".", "Permanode", "==", "nil", "{", "continue", "\n", "}", "\n", "attrs", ":=", "desBlob", ".", "Permanode", ".", "Attr", "\n", "for", "_", ",", "attr", ":=", "range", "sensitiveAttrs", "{", "if", "attrs", ".", "Get", "(", "attr", ")", "!=", "\"", "\"", "{", "continue", "Res", "\n", "}", "\n", "}", "\n", "return", "br", ",", "nil", "\n", "}", "\n", "return", "pn", ",", "os", ".", "ErrNotExist", "\n", "}" ]
// findExistingPermanode finds an existing permanode that has a // camliContent pointing to a file with the provided wholeRef and // doesn't have any conflicting attributes that would prevent the // picasa importer from re-using that permanode for its own use.
[ "findExistingPermanode", "finds", "an", "existing", "permanode", "that", "has", "a", "camliContent", "pointing", "to", "a", "file", "with", "the", "provided", "wholeRef", "and", "doesn", "t", "have", "any", "conflicting", "attributes", "that", "would", "prevent", "the", "picasa", "importer", "from", "re", "-", "using", "that", "permanode", "for", "its", "own", "use", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/picasa/picasa.go#L550-L588
train
perkeep/perkeep
server/perkeepd/ui/goui/importshare/importshare.go
Import
func Import(ctx context.Context, config map[string]string, shareURL string, updateDialogFunc func(message string, importedBlobRef string)) { printerr := func(msg string) { showError(msg, func(msg string) { updateDialogFunc(msg, "") }) } if config == nil { printerr("Nil config for Import share") return } authToken, ok := config["authToken"] if !ok { printerr("No authToken in config for Import share") return } importSharePrefix, ok := config["importShare"] if !ok { printerr("No importShare in config for Import share") return } am, err := auth.TokenOrNone(authToken) if err != nil { printerr(fmt.Sprintf("Error with authToken: %v", err)) return } cl, err := client.New(client.OptionAuthMode(am)) if err != nil { printerr(fmt.Sprintf("Error with client initialization: %v", err)) return } go func() { if err := cl.Post(ctx, importSharePrefix, "application/x-www-form-urlencoded", strings.NewReader(url.Values{"shareurl": {shareURL}}.Encode())); err != nil { printerr(err.Error()) return } for { select { case <-ctx.Done(): printerr(ctx.Err().Error()) return case <-time.After(refreshPeriod): var progress camtypes.ShareImportProgress res, err := ctxhttp.Get(ctx, cl.HTTPClient(), importSharePrefix) if err != nil { printerr(err.Error()) continue } if err := httputil.DecodeJSON(res, &progress); err != nil { printerr(err.Error()) continue } updateDialog(progress, updateDialogFunc) if !progress.Running { return } } } }() }
go
func Import(ctx context.Context, config map[string]string, shareURL string, updateDialogFunc func(message string, importedBlobRef string)) { printerr := func(msg string) { showError(msg, func(msg string) { updateDialogFunc(msg, "") }) } if config == nil { printerr("Nil config for Import share") return } authToken, ok := config["authToken"] if !ok { printerr("No authToken in config for Import share") return } importSharePrefix, ok := config["importShare"] if !ok { printerr("No importShare in config for Import share") return } am, err := auth.TokenOrNone(authToken) if err != nil { printerr(fmt.Sprintf("Error with authToken: %v", err)) return } cl, err := client.New(client.OptionAuthMode(am)) if err != nil { printerr(fmt.Sprintf("Error with client initialization: %v", err)) return } go func() { if err := cl.Post(ctx, importSharePrefix, "application/x-www-form-urlencoded", strings.NewReader(url.Values{"shareurl": {shareURL}}.Encode())); err != nil { printerr(err.Error()) return } for { select { case <-ctx.Done(): printerr(ctx.Err().Error()) return case <-time.After(refreshPeriod): var progress camtypes.ShareImportProgress res, err := ctxhttp.Get(ctx, cl.HTTPClient(), importSharePrefix) if err != nil { printerr(err.Error()) continue } if err := httputil.DecodeJSON(res, &progress); err != nil { printerr(err.Error()) continue } updateDialog(progress, updateDialogFunc) if !progress.Running { return } } } }() }
[ "func", "Import", "(", "ctx", "context", ".", "Context", ",", "config", "map", "[", "string", "]", "string", ",", "shareURL", "string", ",", "updateDialogFunc", "func", "(", "message", "string", ",", "importedBlobRef", "string", ")", ")", "{", "printerr", ":=", "func", "(", "msg", "string", ")", "{", "showError", "(", "msg", ",", "func", "(", "msg", "string", ")", "{", "updateDialogFunc", "(", "msg", ",", "\"", "\"", ")", "\n", "}", ")", "\n", "}", "\n", "if", "config", "==", "nil", "{", "printerr", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "authToken", ",", "ok", ":=", "config", "[", "\"", "\"", "]", "\n", "if", "!", "ok", "{", "printerr", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "importSharePrefix", ",", "ok", ":=", "config", "[", "\"", "\"", "]", "\n", "if", "!", "ok", "{", "printerr", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "am", ",", "err", ":=", "auth", ".", "TokenOrNone", "(", "authToken", ")", "\n", "if", "err", "!=", "nil", "{", "printerr", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "return", "\n", "}", "\n", "cl", ",", "err", ":=", "client", ".", "New", "(", "client", ".", "OptionAuthMode", "(", "am", ")", ")", "\n", "if", "err", "!=", "nil", "{", "printerr", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "err", ")", ")", "\n", "return", "\n", "}", "\n", "go", "func", "(", ")", "{", "if", "err", ":=", "cl", ".", "Post", "(", "ctx", ",", "importSharePrefix", ",", "\"", "\"", ",", "strings", ".", "NewReader", "(", "url", ".", "Values", "{", "\"", "\"", ":", "{", "shareURL", "}", "}", ".", "Encode", "(", ")", ")", ")", ";", "err", "!=", "nil", "{", "printerr", "(", "err", ".", "Error", "(", ")", ")", "\n", "return", "\n", "}", "\n", "for", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "printerr", "(", "ctx", ".", "Err", "(", ")", ".", "Error", "(", ")", ")", "\n", "return", "\n", "case", "<-", "time", ".", "After", "(", "refreshPeriod", ")", ":", "var", "progress", "camtypes", ".", "ShareImportProgress", "\n", "res", ",", "err", ":=", "ctxhttp", ".", "Get", "(", "ctx", ",", "cl", ".", "HTTPClient", "(", ")", ",", "importSharePrefix", ")", "\n", "if", "err", "!=", "nil", "{", "printerr", "(", "err", ".", "Error", "(", ")", ")", "\n", "continue", "\n", "}", "\n", "if", "err", ":=", "httputil", ".", "DecodeJSON", "(", "res", ",", "&", "progress", ")", ";", "err", "!=", "nil", "{", "printerr", "(", "err", ".", "Error", "(", ")", ")", "\n", "continue", "\n", "}", "\n", "updateDialog", "(", "progress", ",", "updateDialogFunc", ")", "\n", "if", "!", "progress", ".", "Running", "{", "return", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "}" ]
// Import sends the shareURL to the server, so it can import all the blobs // transitively reachable through the claim in that share URL. It then regularly // polls the server to get the state of the currently running import process, and // it uses updateDialogFunc to update the web UI with that state. Message is // printed everytime the dialog updates, and importedBlobRef, if not nil, is used // at the end of a successful import to create a link to the newly imported file or // directory.
[ "Import", "sends", "the", "shareURL", "to", "the", "server", "so", "it", "can", "import", "all", "the", "blobs", "transitively", "reachable", "through", "the", "claim", "in", "that", "share", "URL", ".", "It", "then", "regularly", "polls", "the", "server", "to", "get", "the", "state", "of", "the", "currently", "running", "import", "process", "and", "it", "uses", "updateDialogFunc", "to", "update", "the", "web", "UI", "with", "that", "state", ".", "Message", "is", "printed", "everytime", "the", "dialog", "updates", "and", "importedBlobRef", "if", "not", "nil", "is", "used", "at", "the", "end", "of", "a", "successful", "import", "to", "create", "a", "link", "to", "the", "newly", "imported", "file", "or", "directory", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/server/perkeepd/ui/goui/importshare/importshare.go#L45-L107
train
perkeep/perkeep
server/perkeepd/ui/goui/importshare/importshare.go
updateDialog
func updateDialog(progress camtypes.ShareImportProgress, updateDialogFunc func(message string, importedBlobRef string)) { if progress.Running { if progress.Assembled { updateDialogFunc("Importing file in progress", "") return } updateDialogFunc(fmt.Sprintf("Working - %d/%d files imported", progress.FilesCopied, progress.FilesSeen), "") return } if progress.Assembled { updateDialogFunc(fmt.Sprintf("File successfully imported as"), progress.BlobRef.String()) return } updateDialogFunc(fmt.Sprintf("Done - %d/%d files imported under", progress.FilesCopied, progress.FilesSeen), progress.BlobRef.String()) }
go
func updateDialog(progress camtypes.ShareImportProgress, updateDialogFunc func(message string, importedBlobRef string)) { if progress.Running { if progress.Assembled { updateDialogFunc("Importing file in progress", "") return } updateDialogFunc(fmt.Sprintf("Working - %d/%d files imported", progress.FilesCopied, progress.FilesSeen), "") return } if progress.Assembled { updateDialogFunc(fmt.Sprintf("File successfully imported as"), progress.BlobRef.String()) return } updateDialogFunc(fmt.Sprintf("Done - %d/%d files imported under", progress.FilesCopied, progress.FilesSeen), progress.BlobRef.String()) }
[ "func", "updateDialog", "(", "progress", "camtypes", ".", "ShareImportProgress", ",", "updateDialogFunc", "func", "(", "message", "string", ",", "importedBlobRef", "string", ")", ")", "{", "if", "progress", ".", "Running", "{", "if", "progress", ".", "Assembled", "{", "updateDialogFunc", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "updateDialogFunc", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "progress", ".", "FilesCopied", ",", "progress", ".", "FilesSeen", ")", ",", "\"", "\"", ")", "\n", "return", "\n", "}", "\n\n", "if", "progress", ".", "Assembled", "{", "updateDialogFunc", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ")", ",", "progress", ".", "BlobRef", ".", "String", "(", ")", ")", "\n", "return", "\n", "}", "\n", "updateDialogFunc", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "progress", ".", "FilesCopied", ",", "progress", ".", "FilesSeen", ")", ",", "progress", ".", "BlobRef", ".", "String", "(", ")", ")", "\n", "}" ]
// updateDialog uses updateDialogFunc to refresh the dialog that displays the // status of the import. Message is printed first in the dialog, and // importBlobRef is only passed when the import is done, to be displayed below as a // link to the newly imported file or directory.
[ "updateDialog", "uses", "updateDialogFunc", "to", "refresh", "the", "dialog", "that", "displays", "the", "status", "of", "the", "import", ".", "Message", "is", "printed", "first", "in", "the", "dialog", "and", "importBlobRef", "is", "only", "passed", "when", "the", "import", "is", "done", "to", "be", "displayed", "below", "as", "a", "link", "to", "the", "newly", "imported", "file", "or", "directory", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/server/perkeepd/ui/goui/importshare/importshare.go#L113-L129
train
perkeep/perkeep
pkg/webserver/listen/listen.go
NewFlag
func NewFlag(flagName, defaultValue string, serverType string) *Addr { addr := &Addr{ s: defaultValue, } flag.Var(addr, flagName, Usage(serverType)) return addr }
go
func NewFlag(flagName, defaultValue string, serverType string) *Addr { addr := &Addr{ s: defaultValue, } flag.Var(addr, flagName, Usage(serverType)) return addr }
[ "func", "NewFlag", "(", "flagName", ",", "defaultValue", "string", ",", "serverType", "string", ")", "*", "Addr", "{", "addr", ":=", "&", "Addr", "{", "s", ":", "defaultValue", ",", "}", "\n", "flag", ".", "Var", "(", "addr", ",", "flagName", ",", "Usage", "(", "serverType", ")", ")", "\n", "return", "addr", "\n", "}" ]
// NewFlag returns a flag that implements the flag.Value interface.
[ "NewFlag", "returns", "a", "flag", "that", "implements", "the", "flag", ".", "Value", "interface", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/webserver/listen/listen.go#L31-L37
train
perkeep/perkeep
pkg/webserver/listen/listen.go
Usage
func Usage(name string) string { if name == "" { name = "Listen address" } if !strings.HasSuffix(name, " address") { name += " address" } return name + "; may be port, :port, ip:port, or FD:<fd_num>" }
go
func Usage(name string) string { if name == "" { name = "Listen address" } if !strings.HasSuffix(name, " address") { name += " address" } return name + "; may be port, :port, ip:port, or FD:<fd_num>" }
[ "func", "Usage", "(", "name", "string", ")", "string", "{", "if", "name", "==", "\"", "\"", "{", "name", "=", "\"", "\"", "\n", "}", "\n", "if", "!", "strings", ".", "HasSuffix", "(", "name", ",", "\"", "\"", ")", "{", "name", "+=", "\"", "\"", "\n", "}", "\n", "return", "name", "+", "\"", "\"", "\n", "}" ]
// Usage returns a descriptive usage message for a flag given the name // of thing being addressed.
[ "Usage", "returns", "a", "descriptive", "usage", "message", "for", "a", "flag", "given", "the", "name", "of", "thing", "being", "addressed", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/webserver/listen/listen.go#L49-L57
train
perkeep/perkeep
pkg/webserver/listen/listen.go
Listen
func (a *Addr) Listen() (net.Listener, error) { // Start the listener now, if there's a default // and nothing's called Set yet. if a.err == nil && a.ln == nil && a.s != "" { if err := a.Set(a.s); err != nil { return nil, err } } if a.err != nil { return nil, a.err } if a.ln != nil { return a.ln, nil } return nil, errors.New("listen: no error or listener") }
go
func (a *Addr) Listen() (net.Listener, error) { // Start the listener now, if there's a default // and nothing's called Set yet. if a.err == nil && a.ln == nil && a.s != "" { if err := a.Set(a.s); err != nil { return nil, err } } if a.err != nil { return nil, a.err } if a.ln != nil { return a.ln, nil } return nil, errors.New("listen: no error or listener") }
[ "func", "(", "a", "*", "Addr", ")", "Listen", "(", ")", "(", "net", ".", "Listener", ",", "error", ")", "{", "// Start the listener now, if there's a default", "// and nothing's called Set yet.", "if", "a", ".", "err", "==", "nil", "&&", "a", ".", "ln", "==", "nil", "&&", "a", ".", "s", "!=", "\"", "\"", "{", "if", "err", ":=", "a", ".", "Set", "(", "a", ".", "s", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "if", "a", ".", "err", "!=", "nil", "{", "return", "nil", ",", "a", ".", "err", "\n", "}", "\n", "if", "a", ".", "ln", "!=", "nil", "{", "return", "a", ".", "ln", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}" ]
// Listen returns the address's TCP listener.
[ "Listen", "returns", "the", "address", "s", "TCP", "listener", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/webserver/listen/listen.go#L118-L133
train
perkeep/perkeep
pkg/schema/dirreader.go
NewDirReader
func NewDirReader(ctx context.Context, fetcher blob.Fetcher, dirBlobRef blob.Ref) (*DirReader, error) { ss := new(superset) err := ss.setFromBlobRef(ctx, fetcher, dirBlobRef) if err != nil { return nil, err } if ss.Type != "directory" { return nil, fmt.Errorf("schema/dirreader: expected \"directory\" schema blob for %s, got %q", dirBlobRef, ss.Type) } dr, err := ss.NewDirReader(fetcher) if err != nil { return nil, fmt.Errorf("schema/dirreader: creating DirReader for %s: %v", dirBlobRef, err) } dr.current = 0 return dr, nil }
go
func NewDirReader(ctx context.Context, fetcher blob.Fetcher, dirBlobRef blob.Ref) (*DirReader, error) { ss := new(superset) err := ss.setFromBlobRef(ctx, fetcher, dirBlobRef) if err != nil { return nil, err } if ss.Type != "directory" { return nil, fmt.Errorf("schema/dirreader: expected \"directory\" schema blob for %s, got %q", dirBlobRef, ss.Type) } dr, err := ss.NewDirReader(fetcher) if err != nil { return nil, fmt.Errorf("schema/dirreader: creating DirReader for %s: %v", dirBlobRef, err) } dr.current = 0 return dr, nil }
[ "func", "NewDirReader", "(", "ctx", "context", ".", "Context", ",", "fetcher", "blob", ".", "Fetcher", ",", "dirBlobRef", "blob", ".", "Ref", ")", "(", "*", "DirReader", ",", "error", ")", "{", "ss", ":=", "new", "(", "superset", ")", "\n", "err", ":=", "ss", ".", "setFromBlobRef", "(", "ctx", ",", "fetcher", ",", "dirBlobRef", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "ss", ".", "Type", "!=", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\\\"", "\\\"", "\"", ",", "dirBlobRef", ",", "ss", ".", "Type", ")", "\n", "}", "\n", "dr", ",", "err", ":=", "ss", ".", "NewDirReader", "(", "fetcher", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "dirBlobRef", ",", "err", ")", "\n", "}", "\n", "dr", ".", "current", "=", "0", "\n", "return", "dr", ",", "nil", "\n", "}" ]
// NewDirReader creates a new directory reader and prepares to // fetch the static-set entries
[ "NewDirReader", "creates", "a", "new", "directory", "reader", "and", "prepares", "to", "fetch", "the", "static", "-", "set", "entries" ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/schema/dirreader.go#L43-L58
train
perkeep/perkeep
pkg/schema/dirreader.go
StaticSet
func (dr *DirReader) StaticSet(ctx context.Context) ([]blob.Ref, error) { if dr.staticSet != nil { return dr.staticSet, nil } staticSetBlobref := dr.ss.Entries if !staticSetBlobref.Valid() { return nil, errors.New("schema/dirreader: Invalid blobref") } members, err := staticSet(ctx, staticSetBlobref, dr.fetcher) if err != nil { return nil, err } dr.staticSet = members return dr.staticSet, nil }
go
func (dr *DirReader) StaticSet(ctx context.Context) ([]blob.Ref, error) { if dr.staticSet != nil { return dr.staticSet, nil } staticSetBlobref := dr.ss.Entries if !staticSetBlobref.Valid() { return nil, errors.New("schema/dirreader: Invalid blobref") } members, err := staticSet(ctx, staticSetBlobref, dr.fetcher) if err != nil { return nil, err } dr.staticSet = members return dr.staticSet, nil }
[ "func", "(", "dr", "*", "DirReader", ")", "StaticSet", "(", "ctx", "context", ".", "Context", ")", "(", "[", "]", "blob", ".", "Ref", ",", "error", ")", "{", "if", "dr", ".", "staticSet", "!=", "nil", "{", "return", "dr", ".", "staticSet", ",", "nil", "\n", "}", "\n", "staticSetBlobref", ":=", "dr", ".", "ss", ".", "Entries", "\n", "if", "!", "staticSetBlobref", ".", "Valid", "(", ")", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "members", ",", "err", ":=", "staticSet", "(", "ctx", ",", "staticSetBlobref", ",", "dr", ".", "fetcher", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "dr", ".", "staticSet", "=", "members", "\n", "return", "dr", ".", "staticSet", ",", "nil", "\n", "}" ]
// StaticSet returns the whole of the static set members of that directory
[ "StaticSet", "returns", "the", "whole", "of", "the", "static", "set", "members", "of", "that", "directory" ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/schema/dirreader.go#L88-L102
train
perkeep/perkeep
pkg/schema/dirreader.go
Readdir
func (dr *DirReader) Readdir(ctx context.Context, n int) (entries []DirectoryEntry, err error) { sts, err := dr.StaticSet(ctx) if err != nil { return nil, fmt.Errorf("schema/dirreader: can't get StaticSet: %v", err) } up := dr.current + n if n <= 0 { dr.current = 0 up = len(sts) } else { if n > (len(sts) - dr.current) { err = io.EOF up = len(sts) } } // TODO(bradfitz): push down information to the fetcher // (e.g. cachingfetcher -> remote client http) that we're // going to load a bunch, so the HTTP client (if not using // SPDY) can do discovery and see if the server supports a // batch handler, then get them all in one round-trip, rather // than attacking the server with hundreds of parallel TLS // setups. type res struct { ent DirectoryEntry err error } var cs []chan res // Kick off all directory entry loads. gate := syncutil.NewGate(20) // Limit IO concurrency for _, entRef := range sts[dr.current:up] { c := make(chan res, 1) cs = append(cs, c) gate.Start() go func(entRef blob.Ref) { defer gate.Done() entry, err := NewDirectoryEntryFromBlobRef(ctx, dr.fetcher, entRef) c <- res{entry, err} }(entRef) } for _, c := range cs { res := <-c if res.err != nil { return nil, fmt.Errorf("schema/dirreader: can't create dirEntry: %v", res.err) } entries = append(entries, res.ent) } return entries, nil }
go
func (dr *DirReader) Readdir(ctx context.Context, n int) (entries []DirectoryEntry, err error) { sts, err := dr.StaticSet(ctx) if err != nil { return nil, fmt.Errorf("schema/dirreader: can't get StaticSet: %v", err) } up := dr.current + n if n <= 0 { dr.current = 0 up = len(sts) } else { if n > (len(sts) - dr.current) { err = io.EOF up = len(sts) } } // TODO(bradfitz): push down information to the fetcher // (e.g. cachingfetcher -> remote client http) that we're // going to load a bunch, so the HTTP client (if not using // SPDY) can do discovery and see if the server supports a // batch handler, then get them all in one round-trip, rather // than attacking the server with hundreds of parallel TLS // setups. type res struct { ent DirectoryEntry err error } var cs []chan res // Kick off all directory entry loads. gate := syncutil.NewGate(20) // Limit IO concurrency for _, entRef := range sts[dr.current:up] { c := make(chan res, 1) cs = append(cs, c) gate.Start() go func(entRef blob.Ref) { defer gate.Done() entry, err := NewDirectoryEntryFromBlobRef(ctx, dr.fetcher, entRef) c <- res{entry, err} }(entRef) } for _, c := range cs { res := <-c if res.err != nil { return nil, fmt.Errorf("schema/dirreader: can't create dirEntry: %v", res.err) } entries = append(entries, res.ent) } return entries, nil }
[ "func", "(", "dr", "*", "DirReader", ")", "Readdir", "(", "ctx", "context", ".", "Context", ",", "n", "int", ")", "(", "entries", "[", "]", "DirectoryEntry", ",", "err", "error", ")", "{", "sts", ",", "err", ":=", "dr", ".", "StaticSet", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "up", ":=", "dr", ".", "current", "+", "n", "\n", "if", "n", "<=", "0", "{", "dr", ".", "current", "=", "0", "\n", "up", "=", "len", "(", "sts", ")", "\n", "}", "else", "{", "if", "n", ">", "(", "len", "(", "sts", ")", "-", "dr", ".", "current", ")", "{", "err", "=", "io", ".", "EOF", "\n", "up", "=", "len", "(", "sts", ")", "\n", "}", "\n", "}", "\n\n", "// TODO(bradfitz): push down information to the fetcher", "// (e.g. cachingfetcher -> remote client http) that we're", "// going to load a bunch, so the HTTP client (if not using", "// SPDY) can do discovery and see if the server supports a", "// batch handler, then get them all in one round-trip, rather", "// than attacking the server with hundreds of parallel TLS", "// setups.", "type", "res", "struct", "{", "ent", "DirectoryEntry", "\n", "err", "error", "\n", "}", "\n", "var", "cs", "[", "]", "chan", "res", "\n\n", "// Kick off all directory entry loads.", "gate", ":=", "syncutil", ".", "NewGate", "(", "20", ")", "// Limit IO concurrency", "\n", "for", "_", ",", "entRef", ":=", "range", "sts", "[", "dr", ".", "current", ":", "up", "]", "{", "c", ":=", "make", "(", "chan", "res", ",", "1", ")", "\n", "cs", "=", "append", "(", "cs", ",", "c", ")", "\n", "gate", ".", "Start", "(", ")", "\n", "go", "func", "(", "entRef", "blob", ".", "Ref", ")", "{", "defer", "gate", ".", "Done", "(", ")", "\n", "entry", ",", "err", ":=", "NewDirectoryEntryFromBlobRef", "(", "ctx", ",", "dr", ".", "fetcher", ",", "entRef", ")", "\n", "c", "<-", "res", "{", "entry", ",", "err", "}", "\n", "}", "(", "entRef", ")", "\n", "}", "\n\n", "for", "_", ",", "c", ":=", "range", "cs", "{", "res", ":=", "<-", "c", "\n", "if", "res", ".", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "res", ".", "err", ")", "\n", "}", "\n", "entries", "=", "append", "(", "entries", ",", "res", ".", "ent", ")", "\n", "}", "\n", "return", "entries", ",", "nil", "\n", "}" ]
// Readdir implements the Directory interface.
[ "Readdir", "implements", "the", "Directory", "interface", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/schema/dirreader.go#L146-L197
train
perkeep/perkeep
server/perkeepd/ui/goui/selectallbutton/gen_SelectAllBtn_reactGen.go
Props
func (s SelectAllBtnDef) Props() SelectAllBtnProps { uprops := s.ComponentDef.Props() return uprops.(SelectAllBtnProps) }
go
func (s SelectAllBtnDef) Props() SelectAllBtnProps { uprops := s.ComponentDef.Props() return uprops.(SelectAllBtnProps) }
[ "func", "(", "s", "SelectAllBtnDef", ")", "Props", "(", ")", "SelectAllBtnProps", "{", "uprops", ":=", "s", ".", "ComponentDef", ".", "Props", "(", ")", "\n", "return", "uprops", ".", "(", "SelectAllBtnProps", ")", "\n", "}" ]
// Props is an auto-generated proxy to the current props of SelectAllBtn
[ "Props", "is", "an", "auto", "-", "generated", "proxy", "to", "the", "current", "props", "of", "SelectAllBtn" ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/server/perkeepd/ui/goui/selectallbutton/gen_SelectAllBtn_reactGen.go#L30-L33
train
perkeep/perkeep
pkg/blobserver/dir/dir.go
New
func New(dir string) (blobserver.Storage, error) { if v, err := diskpacked.IsDir(dir); err != nil { return nil, err } else if v { return diskpacked.New(dir) } if v, err := localdisk.IsDir(dir); err != nil { return nil, err } else if v { return localdisk.New(dir) } return diskpacked.New(dir) }
go
func New(dir string) (blobserver.Storage, error) { if v, err := diskpacked.IsDir(dir); err != nil { return nil, err } else if v { return diskpacked.New(dir) } if v, err := localdisk.IsDir(dir); err != nil { return nil, err } else if v { return localdisk.New(dir) } return diskpacked.New(dir) }
[ "func", "New", "(", "dir", "string", ")", "(", "blobserver", ".", "Storage", ",", "error", ")", "{", "if", "v", ",", "err", ":=", "diskpacked", ".", "IsDir", "(", "dir", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "else", "if", "v", "{", "return", "diskpacked", ".", "New", "(", "dir", ")", "\n", "}", "\n", "if", "v", ",", "err", ":=", "localdisk", ".", "IsDir", "(", "dir", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "else", "if", "v", "{", "return", "localdisk", ".", "New", "(", "dir", ")", "\n", "}", "\n", "return", "diskpacked", ".", "New", "(", "dir", ")", "\n", "}" ]
// New returns a new blobserver Storage implementation, storing blobs in the provided dir. // If dir has an index.kv file, a diskpacked implementation is returned.
[ "New", "returns", "a", "new", "blobserver", "Storage", "implementation", "storing", "blobs", "in", "the", "provided", "dir", ".", "If", "dir", "has", "an", "index", ".", "kv", "file", "a", "diskpacked", "implementation", "is", "returned", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/dir/dir.go#L30-L42
train
perkeep/perkeep
pkg/blobserver/localdisk/localdisk.go
New
func New(root string) (*DiskStorage, error) { // Local disk. fi, err := os.Stat(root) if os.IsNotExist(err) { // As a special case, we auto-created the "packed" directory for subpacked. if filepath.Base(root) == "packed" { if err := os.Mkdir(root, 0700); err != nil { return nil, fmt.Errorf("failed to mkdir packed directory: %v", err) } fi, err = os.Stat(root) } else { return nil, fmt.Errorf("Storage root %q doesn't exist", root) } } if err != nil { return nil, fmt.Errorf("Failed to stat directory %q: %v", root, err) } if !fi.IsDir() { return nil, fmt.Errorf("storage root %q exists but is not a directory", root) } fileSto := files.NewStorage(files.OSFS(), root) ds := &DiskStorage{ Storage: fileSto, SubFetcher: fileSto, root: root, gen: local.NewGenerationer(root), } if _, _, err := ds.StorageGeneration(); err != nil { return nil, fmt.Errorf("Error initialization generation for %q: %v", root, err) } ul, err := osutil.MaxFD() if err != nil { if err == osutil.ErrNotSupported { // Do not set the gate on Windows, since we don't know the ulimit. return ds, nil } return nil, err } if ul < minFDLimit { return nil, fmt.Errorf("the max number of open file descriptors on your system (ulimit -n) is too low. Please fix it with 'ulimit -S -n X' with X being at least %d", recommendedFDLimit) } // Setting the gate to 80% of the ulimit, to leave a bit of room for other file ops happening in Perkeep. // TODO(mpl): make this used and enforced Perkeep-wide. Issue #837. fileSto.SetNewFileGate(syncutil.NewGate(int(ul * 80 / 100))) err = ds.checkFS() if err != nil { return nil, err } return ds, nil }
go
func New(root string) (*DiskStorage, error) { // Local disk. fi, err := os.Stat(root) if os.IsNotExist(err) { // As a special case, we auto-created the "packed" directory for subpacked. if filepath.Base(root) == "packed" { if err := os.Mkdir(root, 0700); err != nil { return nil, fmt.Errorf("failed to mkdir packed directory: %v", err) } fi, err = os.Stat(root) } else { return nil, fmt.Errorf("Storage root %q doesn't exist", root) } } if err != nil { return nil, fmt.Errorf("Failed to stat directory %q: %v", root, err) } if !fi.IsDir() { return nil, fmt.Errorf("storage root %q exists but is not a directory", root) } fileSto := files.NewStorage(files.OSFS(), root) ds := &DiskStorage{ Storage: fileSto, SubFetcher: fileSto, root: root, gen: local.NewGenerationer(root), } if _, _, err := ds.StorageGeneration(); err != nil { return nil, fmt.Errorf("Error initialization generation for %q: %v", root, err) } ul, err := osutil.MaxFD() if err != nil { if err == osutil.ErrNotSupported { // Do not set the gate on Windows, since we don't know the ulimit. return ds, nil } return nil, err } if ul < minFDLimit { return nil, fmt.Errorf("the max number of open file descriptors on your system (ulimit -n) is too low. Please fix it with 'ulimit -S -n X' with X being at least %d", recommendedFDLimit) } // Setting the gate to 80% of the ulimit, to leave a bit of room for other file ops happening in Perkeep. // TODO(mpl): make this used and enforced Perkeep-wide. Issue #837. fileSto.SetNewFileGate(syncutil.NewGate(int(ul * 80 / 100))) err = ds.checkFS() if err != nil { return nil, err } return ds, nil }
[ "func", "New", "(", "root", "string", ")", "(", "*", "DiskStorage", ",", "error", ")", "{", "// Local disk.", "fi", ",", "err", ":=", "os", ".", "Stat", "(", "root", ")", "\n", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "// As a special case, we auto-created the \"packed\" directory for subpacked.", "if", "filepath", ".", "Base", "(", "root", ")", "==", "\"", "\"", "{", "if", "err", ":=", "os", ".", "Mkdir", "(", "root", ",", "0700", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "fi", ",", "err", "=", "os", ".", "Stat", "(", "root", ")", "\n", "}", "else", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "root", ")", "\n", "}", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "root", ",", "err", ")", "\n", "}", "\n", "if", "!", "fi", ".", "IsDir", "(", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "root", ")", "\n", "}", "\n", "fileSto", ":=", "files", ".", "NewStorage", "(", "files", ".", "OSFS", "(", ")", ",", "root", ")", "\n", "ds", ":=", "&", "DiskStorage", "{", "Storage", ":", "fileSto", ",", "SubFetcher", ":", "fileSto", ",", "root", ":", "root", ",", "gen", ":", "local", ".", "NewGenerationer", "(", "root", ")", ",", "}", "\n", "if", "_", ",", "_", ",", "err", ":=", "ds", ".", "StorageGeneration", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "root", ",", "err", ")", "\n", "}", "\n", "ul", ",", "err", ":=", "osutil", ".", "MaxFD", "(", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "osutil", ".", "ErrNotSupported", "{", "// Do not set the gate on Windows, since we don't know the ulimit.", "return", "ds", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "if", "ul", "<", "minFDLimit", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "recommendedFDLimit", ")", "\n", "}", "\n", "// Setting the gate to 80% of the ulimit, to leave a bit of room for other file ops happening in Perkeep.", "// TODO(mpl): make this used and enforced Perkeep-wide. Issue #837.", "fileSto", ".", "SetNewFileGate", "(", "syncutil", ".", "NewGate", "(", "int", "(", "ul", "*", "80", "/", "100", ")", ")", ")", "\n\n", "err", "=", "ds", ".", "checkFS", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "ds", ",", "nil", "\n", "}" ]
// New returns a new local disk storage implementation at the provided // root directory, which must already exist.
[ "New", "returns", "a", "new", "local", "disk", "storage", "implementation", "at", "the", "provided", "root", "directory", "which", "must", "already", "exist", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/localdisk/localdisk.go#L96-L146
train
perkeep/perkeep
app/scanningcabinet/models.go
MakeMediaObjectViewModels
func MakeMediaObjectViewModels(mediaObjects []mediaObject) []MediaObjectVM { models := make([]MediaObjectVM, len(mediaObjects)) for i := 0; i < len(mediaObjects); i++ { models[i] = mediaObjects[i].MakeViewModel() } return models }
go
func MakeMediaObjectViewModels(mediaObjects []mediaObject) []MediaObjectVM { models := make([]MediaObjectVM, len(mediaObjects)) for i := 0; i < len(mediaObjects); i++ { models[i] = mediaObjects[i].MakeViewModel() } return models }
[ "func", "MakeMediaObjectViewModels", "(", "mediaObjects", "[", "]", "mediaObject", ")", "[", "]", "MediaObjectVM", "{", "models", ":=", "make", "(", "[", "]", "MediaObjectVM", ",", "len", "(", "mediaObjects", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "mediaObjects", ")", ";", "i", "++", "{", "models", "[", "i", "]", "=", "mediaObjects", "[", "i", "]", ".", "MakeViewModel", "(", ")", "\n", "}", "\n", "return", "models", "\n", "}" ]
// MakeMediaObjectViewModels takes a slice of MediaObjects and returns a slice of // the same number of MediaObjectVMs with the data converted.
[ "MakeMediaObjectViewModels", "takes", "a", "slice", "of", "MediaObjects", "and", "returns", "a", "slice", "of", "the", "same", "number", "of", "MediaObjectVMs", "with", "the", "data", "converted", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/scanningcabinet/models.go#L93-L99
train
perkeep/perkeep
app/scanningcabinet/models.go
someTitle
func (doc *document) someTitle() string { if doc.title != "" { return doc.title } if doc.tags.isEmpty() { return fmt.Sprintf("Doc Ref %s", doc.permanode) } return strings.Join(doc.tags, ",") }
go
func (doc *document) someTitle() string { if doc.title != "" { return doc.title } if doc.tags.isEmpty() { return fmt.Sprintf("Doc Ref %s", doc.permanode) } return strings.Join(doc.tags, ",") }
[ "func", "(", "doc", "*", "document", ")", "someTitle", "(", ")", "string", "{", "if", "doc", ".", "title", "!=", "\"", "\"", "{", "return", "doc", ".", "title", "\n", "}", "\n", "if", "doc", ".", "tags", ".", "isEmpty", "(", ")", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "doc", ".", "permanode", ")", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "doc", ".", "tags", ",", "\"", "\"", ")", "\n", "}" ]
// SomeTitle returns this struct's title or, failing that, its tags - // and even failing that, its IntID
[ "SomeTitle", "returns", "this", "struct", "s", "title", "or", "failing", "that", "its", "tags", "-", "and", "even", "failing", "that", "its", "IntID" ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/scanningcabinet/models.go#L154-L162
train
perkeep/perkeep
app/scanningcabinet/models.go
formatYyyyMmDd
func formatYyyyMmDd(indate time.Time) string { if indate.IsZero() { return "" } return indate.Format(dateformatYyyyMmDd) }
go
func formatYyyyMmDd(indate time.Time) string { if indate.IsZero() { return "" } return indate.Format(dateformatYyyyMmDd) }
[ "func", "formatYyyyMmDd", "(", "indate", "time", ".", "Time", ")", "string", "{", "if", "indate", ".", "IsZero", "(", ")", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "indate", ".", "Format", "(", "dateformatYyyyMmDd", ")", "\n", "}" ]
// formatYyyyMmDd is a convenience function that formats a given Time according to // the DateformatYyyyMmDd const
[ "formatYyyyMmDd", "is", "a", "convenience", "function", "that", "formats", "a", "given", "Time", "according", "to", "the", "DateformatYyyyMmDd", "const" ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/scanningcabinet/models.go#L176-L181
train
perkeep/perkeep
app/scanningcabinet/models.go
MakeDocumentViewModels
func MakeDocumentViewModels(docs []*document) []DocumentVM { models := make([]DocumentVM, len(docs)) for i := 0; i < len(docs); i++ { models[i] = docs[i].MakeViewModel() } return models }
go
func MakeDocumentViewModels(docs []*document) []DocumentVM { models := make([]DocumentVM, len(docs)) for i := 0; i < len(docs); i++ { models[i] = docs[i].MakeViewModel() } return models }
[ "func", "MakeDocumentViewModels", "(", "docs", "[", "]", "*", "document", ")", "[", "]", "DocumentVM", "{", "models", ":=", "make", "(", "[", "]", "DocumentVM", ",", "len", "(", "docs", ")", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "docs", ")", ";", "i", "++", "{", "models", "[", "i", "]", "=", "docs", "[", "i", "]", ".", "MakeViewModel", "(", ")", "\n", "}", "\n", "return", "models", "\n", "}" ]
// MakeDocumentViewModels takes a slice of Documents and returns a slice of // the same number of DocumentVMs with the data converted.
[ "MakeDocumentViewModels", "takes", "a", "slice", "of", "Documents", "and", "returns", "a", "slice", "of", "the", "same", "number", "of", "DocumentVMs", "with", "the", "data", "converted", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/app/scanningcabinet/models.go#L211-L217
train
perkeep/perkeep
pkg/blobserver/gethandler/get.go
ServeBlobRef
func ServeBlobRef(rw http.ResponseWriter, req *http.Request, blobRef blob.Ref, fetcher blob.Fetcher) { ctx := req.Context() if fetcher == nil { log.Printf("gethandler: no fetcher configured for %s (ref=%v)", req.URL.Path, blobRef) rw.WriteHeader(http.StatusNotFound) io.WriteString(rw, "no fetcher configured") return } rc, size, err := fetcher.Fetch(ctx, blobRef) switch err { case nil: break case os.ErrNotExist: rw.WriteHeader(http.StatusNotFound) fmt.Fprintf(rw, "Blob %q not found", blobRef) return default: httputil.ServeError(rw, req, err) return } defer rc.Close() rw.Header().Set("Content-Type", "application/octet-stream") var content io.ReadSeeker = readerutil.NewFakeSeeker(rc, int64(size)) rangeHeader := req.Header.Get("Range") != "" const small = 32 << 10 var b *blob.Blob if rangeHeader || size < small { // Slurp to memory, so we can actually seek on it (for Range support), // or if we're going to be showing it in the browser (below). b, err = blob.FromReader(ctx, blobRef, rc, size) if err != nil { httputil.ServeError(rw, req, err) return } content, err = b.ReadAll(ctx) if err != nil { httputil.ServeError(rw, req, err) return } } if !rangeHeader && size < small { // If it's small and all UTF-8, assume it's text and // just render it in the browser. This is more for // demos/debuggability than anything else. It isn't // part of the spec. isUTF8, err := b.IsUTF8(ctx) if err != nil { httputil.ServeError(rw, req, err) return } if isUTF8 { rw.Header().Set("Content-Type", "text/plain; charset=utf-8") } } http.ServeContent(rw, req, "", dummyModTime, content) }
go
func ServeBlobRef(rw http.ResponseWriter, req *http.Request, blobRef blob.Ref, fetcher blob.Fetcher) { ctx := req.Context() if fetcher == nil { log.Printf("gethandler: no fetcher configured for %s (ref=%v)", req.URL.Path, blobRef) rw.WriteHeader(http.StatusNotFound) io.WriteString(rw, "no fetcher configured") return } rc, size, err := fetcher.Fetch(ctx, blobRef) switch err { case nil: break case os.ErrNotExist: rw.WriteHeader(http.StatusNotFound) fmt.Fprintf(rw, "Blob %q not found", blobRef) return default: httputil.ServeError(rw, req, err) return } defer rc.Close() rw.Header().Set("Content-Type", "application/octet-stream") var content io.ReadSeeker = readerutil.NewFakeSeeker(rc, int64(size)) rangeHeader := req.Header.Get("Range") != "" const small = 32 << 10 var b *blob.Blob if rangeHeader || size < small { // Slurp to memory, so we can actually seek on it (for Range support), // or if we're going to be showing it in the browser (below). b, err = blob.FromReader(ctx, blobRef, rc, size) if err != nil { httputil.ServeError(rw, req, err) return } content, err = b.ReadAll(ctx) if err != nil { httputil.ServeError(rw, req, err) return } } if !rangeHeader && size < small { // If it's small and all UTF-8, assume it's text and // just render it in the browser. This is more for // demos/debuggability than anything else. It isn't // part of the spec. isUTF8, err := b.IsUTF8(ctx) if err != nil { httputil.ServeError(rw, req, err) return } if isUTF8 { rw.Header().Set("Content-Type", "text/plain; charset=utf-8") } } http.ServeContent(rw, req, "", dummyModTime, content) }
[ "func", "ServeBlobRef", "(", "rw", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ",", "blobRef", "blob", ".", "Ref", ",", "fetcher", "blob", ".", "Fetcher", ")", "{", "ctx", ":=", "req", ".", "Context", "(", ")", "\n", "if", "fetcher", "==", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "req", ".", "URL", ".", "Path", ",", "blobRef", ")", "\n", "rw", ".", "WriteHeader", "(", "http", ".", "StatusNotFound", ")", "\n", "io", ".", "WriteString", "(", "rw", ",", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "rc", ",", "size", ",", "err", ":=", "fetcher", ".", "Fetch", "(", "ctx", ",", "blobRef", ")", "\n", "switch", "err", "{", "case", "nil", ":", "break", "\n", "case", "os", ".", "ErrNotExist", ":", "rw", ".", "WriteHeader", "(", "http", ".", "StatusNotFound", ")", "\n", "fmt", ".", "Fprintf", "(", "rw", ",", "\"", "\"", ",", "blobRef", ")", "\n", "return", "\n", "default", ":", "httputil", ".", "ServeError", "(", "rw", ",", "req", ",", "err", ")", "\n", "return", "\n", "}", "\n", "defer", "rc", ".", "Close", "(", ")", "\n", "rw", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "var", "content", "io", ".", "ReadSeeker", "=", "readerutil", ".", "NewFakeSeeker", "(", "rc", ",", "int64", "(", "size", ")", ")", "\n", "rangeHeader", ":=", "req", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "!=", "\"", "\"", "\n", "const", "small", "=", "32", "<<", "10", "\n", "var", "b", "*", "blob", ".", "Blob", "\n", "if", "rangeHeader", "||", "size", "<", "small", "{", "// Slurp to memory, so we can actually seek on it (for Range support),", "// or if we're going to be showing it in the browser (below).", "b", ",", "err", "=", "blob", ".", "FromReader", "(", "ctx", ",", "blobRef", ",", "rc", ",", "size", ")", "\n", "if", "err", "!=", "nil", "{", "httputil", ".", "ServeError", "(", "rw", ",", "req", ",", "err", ")", "\n", "return", "\n", "}", "\n", "content", ",", "err", "=", "b", ".", "ReadAll", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "httputil", ".", "ServeError", "(", "rw", ",", "req", ",", "err", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "if", "!", "rangeHeader", "&&", "size", "<", "small", "{", "// If it's small and all UTF-8, assume it's text and", "// just render it in the browser. This is more for", "// demos/debuggability than anything else. It isn't", "// part of the spec.", "isUTF8", ",", "err", ":=", "b", ".", "IsUTF8", "(", "ctx", ")", "\n", "if", "err", "!=", "nil", "{", "httputil", ".", "ServeError", "(", "rw", ",", "req", ",", "err", ")", "\n", "return", "\n", "}", "\n", "if", "isUTF8", "{", "rw", ".", "Header", "(", ")", ".", "Set", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "http", ".", "ServeContent", "(", "rw", ",", "req", ",", "\"", "\"", ",", "dummyModTime", ",", "content", ")", "\n", "}" ]
// ServeBlobRef serves a blob.
[ "ServeBlobRef", "serves", "a", "blob", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/gethandler/get.go#L65-L121
train
perkeep/perkeep
pkg/blobserver/gethandler/get.go
simulatePrematurelyClosedConnection
func simulatePrematurelyClosedConnection(rw http.ResponseWriter, req *http.Request) { flusher, ok := rw.(http.Flusher) if !ok { return } hj, ok := rw.(http.Hijacker) if !ok { return } for n := 1; n <= 100; n++ { fmt.Fprintf(rw, "line %d\n", n) flusher.Flush() } wrc, _, _ := hj.Hijack() wrc.Close() // without sending final chunk; should be an error for the client }
go
func simulatePrematurelyClosedConnection(rw http.ResponseWriter, req *http.Request) { flusher, ok := rw.(http.Flusher) if !ok { return } hj, ok := rw.(http.Hijacker) if !ok { return } for n := 1; n <= 100; n++ { fmt.Fprintf(rw, "line %d\n", n) flusher.Flush() } wrc, _, _ := hj.Hijack() wrc.Close() // without sending final chunk; should be an error for the client }
[ "func", "simulatePrematurelyClosedConnection", "(", "rw", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "flusher", ",", "ok", ":=", "rw", ".", "(", "http", ".", "Flusher", ")", "\n", "if", "!", "ok", "{", "return", "\n", "}", "\n", "hj", ",", "ok", ":=", "rw", ".", "(", "http", ".", "Hijacker", ")", "\n", "if", "!", "ok", "{", "return", "\n", "}", "\n", "for", "n", ":=", "1", ";", "n", "<=", "100", ";", "n", "++", "{", "fmt", ".", "Fprintf", "(", "rw", ",", "\"", "\\n", "\"", ",", "n", ")", "\n", "flusher", ".", "Flush", "(", ")", "\n", "}", "\n", "wrc", ",", "_", ",", "_", ":=", "hj", ".", "Hijack", "(", ")", "\n", "wrc", ".", "Close", "(", ")", "// without sending final chunk; should be an error for the client", "\n", "}" ]
// For client testing.
[ "For", "client", "testing", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/gethandler/get.go#L138-L153
train
perkeep/perkeep
pkg/fileembed/genfileembed/genfileembed.go
matchingFiles
func matchingFiles(p *regexp.Regexp) []string { var f []string err := filepath.Walk(".", func(path string, fi os.FileInfo, err error) error { if err != nil { return err } n := filepath.Base(path) if !fi.IsDir() && !strings.HasPrefix(n, "zembed_") && p.MatchString(n) { f = append(f, path) } return nil }) if err != nil { log.Fatalf("Error walking directory tree: %s", err) return nil } return f }
go
func matchingFiles(p *regexp.Regexp) []string { var f []string err := filepath.Walk(".", func(path string, fi os.FileInfo, err error) error { if err != nil { return err } n := filepath.Base(path) if !fi.IsDir() && !strings.HasPrefix(n, "zembed_") && p.MatchString(n) { f = append(f, path) } return nil }) if err != nil { log.Fatalf("Error walking directory tree: %s", err) return nil } return f }
[ "func", "matchingFiles", "(", "p", "*", "regexp", ".", "Regexp", ")", "[", "]", "string", "{", "var", "f", "[", "]", "string", "\n", "err", ":=", "filepath", ".", "Walk", "(", "\"", "\"", ",", "func", "(", "path", "string", ",", "fi", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "n", ":=", "filepath", ".", "Base", "(", "path", ")", "\n", "if", "!", "fi", ".", "IsDir", "(", ")", "&&", "!", "strings", ".", "HasPrefix", "(", "n", ",", "\"", "\"", ")", "&&", "p", ".", "MatchString", "(", "n", ")", "{", "f", "=", "append", "(", "f", ",", "path", ")", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "nil", "\n", "}", "\n", "return", "f", "\n", "}" ]
// matchingFiles finds all files matching a regex that should be embedded. This // skips files prefixed with "zembed_", since those are an implementation // detail of the embedding process itself.
[ "matchingFiles", "finds", "all", "files", "matching", "a", "regex", "that", "should", "be", "embedded", ".", "This", "skips", "files", "prefixed", "with", "zembed_", "since", "those", "are", "an", "implementation", "detail", "of", "the", "embedding", "process", "itself", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/fileembed/genfileembed/genfileembed.go#L265-L282
train
perkeep/perkeep
pkg/jsonsign/signhandler/sig.go
UploadPublicKey
func (h *Handler) UploadPublicKey(ctx context.Context) error { h.pubKeyUploadMu.RLock() if h.pubKeyUploaded { h.pubKeyUploadMu.RUnlock() return nil } h.pubKeyUploadMu.RUnlock() sto := h.pubKeyDest h.pubKeyUploadMu.Lock() defer h.pubKeyUploadMu.Unlock() if h.pubKeyUploaded { return nil } _, err := blobserver.StatBlob(ctx, sto, h.pubKeyBlobRef) if err == nil { h.pubKeyUploaded = true return nil } _, err = blobserver.Receive(ctx, sto, h.pubKeyBlobRef, strings.NewReader(h.pubKey)) h.pubKeyUploaded = (err == nil) return err }
go
func (h *Handler) UploadPublicKey(ctx context.Context) error { h.pubKeyUploadMu.RLock() if h.pubKeyUploaded { h.pubKeyUploadMu.RUnlock() return nil } h.pubKeyUploadMu.RUnlock() sto := h.pubKeyDest h.pubKeyUploadMu.Lock() defer h.pubKeyUploadMu.Unlock() if h.pubKeyUploaded { return nil } _, err := blobserver.StatBlob(ctx, sto, h.pubKeyBlobRef) if err == nil { h.pubKeyUploaded = true return nil } _, err = blobserver.Receive(ctx, sto, h.pubKeyBlobRef, strings.NewReader(h.pubKey)) h.pubKeyUploaded = (err == nil) return err }
[ "func", "(", "h", "*", "Handler", ")", "UploadPublicKey", "(", "ctx", "context", ".", "Context", ")", "error", "{", "h", ".", "pubKeyUploadMu", ".", "RLock", "(", ")", "\n", "if", "h", ".", "pubKeyUploaded", "{", "h", ".", "pubKeyUploadMu", ".", "RUnlock", "(", ")", "\n", "return", "nil", "\n", "}", "\n", "h", ".", "pubKeyUploadMu", ".", "RUnlock", "(", ")", "\n\n", "sto", ":=", "h", ".", "pubKeyDest", "\n\n", "h", ".", "pubKeyUploadMu", ".", "Lock", "(", ")", "\n", "defer", "h", ".", "pubKeyUploadMu", ".", "Unlock", "(", ")", "\n", "if", "h", ".", "pubKeyUploaded", "{", "return", "nil", "\n", "}", "\n", "_", ",", "err", ":=", "blobserver", ".", "StatBlob", "(", "ctx", ",", "sto", ",", "h", ".", "pubKeyBlobRef", ")", "\n", "if", "err", "==", "nil", "{", "h", ".", "pubKeyUploaded", "=", "true", "\n", "return", "nil", "\n", "}", "\n", "_", ",", "err", "=", "blobserver", ".", "Receive", "(", "ctx", ",", "sto", ",", "h", ".", "pubKeyBlobRef", ",", "strings", ".", "NewReader", "(", "h", ".", "pubKey", ")", ")", "\n", "h", ".", "pubKeyUploaded", "=", "(", "err", "==", "nil", ")", "\n", "return", "err", "\n", "}" ]
// UploadPublicKey writes the public key to the destination blobserver // defined for the handler, if needed.
[ "UploadPublicKey", "writes", "the", "public", "key", "to", "the", "destination", "blobserver", "defined", "for", "the", "handler", "if", "needed", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/jsonsign/signhandler/sig.go#L136-L159
train
perkeep/perkeep
pkg/jsonsign/signhandler/sig.go
Discovery
func (h *Handler) Discovery(base string) *camtypes.SignDiscovery { sd := &camtypes.SignDiscovery{ PublicKeyID: h.entity.PrimaryKey.KeyIdString(), SignHandler: base + "camli/sig/sign", VerifyHandler: base + "camli/sig/verify", } if h.pubKeyBlobRef.Valid() { sd.PublicKeyBlobRef = h.pubKeyBlobRef sd.PublicKey = base + h.pubKeyBlobRefServeSuffix } return sd }
go
func (h *Handler) Discovery(base string) *camtypes.SignDiscovery { sd := &camtypes.SignDiscovery{ PublicKeyID: h.entity.PrimaryKey.KeyIdString(), SignHandler: base + "camli/sig/sign", VerifyHandler: base + "camli/sig/verify", } if h.pubKeyBlobRef.Valid() { sd.PublicKeyBlobRef = h.pubKeyBlobRef sd.PublicKey = base + h.pubKeyBlobRefServeSuffix } return sd }
[ "func", "(", "h", "*", "Handler", ")", "Discovery", "(", "base", "string", ")", "*", "camtypes", ".", "SignDiscovery", "{", "sd", ":=", "&", "camtypes", ".", "SignDiscovery", "{", "PublicKeyID", ":", "h", ".", "entity", ".", "PrimaryKey", ".", "KeyIdString", "(", ")", ",", "SignHandler", ":", "base", "+", "\"", "\"", ",", "VerifyHandler", ":", "base", "+", "\"", "\"", ",", "}", "\n", "if", "h", ".", "pubKeyBlobRef", ".", "Valid", "(", ")", "{", "sd", ".", "PublicKeyBlobRef", "=", "h", ".", "pubKeyBlobRef", "\n", "sd", ".", "PublicKey", "=", "base", "+", "h", ".", "pubKeyBlobRefServeSuffix", "\n", "}", "\n", "return", "sd", "\n", "}" ]
// Discovery returns the Discovery response for the signing handler.
[ "Discovery", "returns", "the", "Discovery", "response", "for", "the", "signing", "handler", "." ]
e28bbbd1588d64df8ab7a82393afd39d64c061f7
https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/jsonsign/signhandler/sig.go#L162-L173
train
jwilder/docker-gen
template.go
generalizedGroupBy
func generalizedGroupBy(funcName string, entries interface{}, getValue func(interface{}) (interface{}, error), addEntry func(map[string][]interface{}, interface{}, interface{})) (map[string][]interface{}, error) { entriesVal, err := getArrayValues(funcName, entries) if err != nil { return nil, err } groups := make(map[string][]interface{}) for i := 0; i < entriesVal.Len(); i++ { v := reflect.Indirect(entriesVal.Index(i)).Interface() value, err := getValue(v) if err != nil { return nil, err } if value != nil { addEntry(groups, value, v) } } return groups, nil }
go
func generalizedGroupBy(funcName string, entries interface{}, getValue func(interface{}) (interface{}, error), addEntry func(map[string][]interface{}, interface{}, interface{})) (map[string][]interface{}, error) { entriesVal, err := getArrayValues(funcName, entries) if err != nil { return nil, err } groups := make(map[string][]interface{}) for i := 0; i < entriesVal.Len(); i++ { v := reflect.Indirect(entriesVal.Index(i)).Interface() value, err := getValue(v) if err != nil { return nil, err } if value != nil { addEntry(groups, value, v) } } return groups, nil }
[ "func", "generalizedGroupBy", "(", "funcName", "string", ",", "entries", "interface", "{", "}", ",", "getValue", "func", "(", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", ",", "addEntry", "func", "(", "map", "[", "string", "]", "[", "]", "interface", "{", "}", ",", "interface", "{", "}", ",", "interface", "{", "}", ")", ")", "(", "map", "[", "string", "]", "[", "]", "interface", "{", "}", ",", "error", ")", "{", "entriesVal", ",", "err", ":=", "getArrayValues", "(", "funcName", ",", "entries", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "groups", ":=", "make", "(", "map", "[", "string", "]", "[", "]", "interface", "{", "}", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "entriesVal", ".", "Len", "(", ")", ";", "i", "++", "{", "v", ":=", "reflect", ".", "Indirect", "(", "entriesVal", ".", "Index", "(", "i", ")", ")", ".", "Interface", "(", ")", "\n", "value", ",", "err", ":=", "getValue", "(", "v", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "value", "!=", "nil", "{", "addEntry", "(", "groups", ",", "value", ",", "v", ")", "\n", "}", "\n", "}", "\n", "return", "groups", ",", "nil", "\n", "}" ]
// Generalized groupBy function
[ "Generalized", "groupBy", "function" ]
4edc190faa34342313589a80e3a736cafb45919b
https://github.com/jwilder/docker-gen/blob/4edc190faa34342313589a80e3a736cafb45919b/template.go#L54-L73
train
jwilder/docker-gen
template.go
groupBy
func groupBy(entries interface{}, key string) (map[string][]interface{}, error) { return generalizedGroupByKey("groupBy", entries, key, func(groups map[string][]interface{}, value interface{}, v interface{}) { groups[value.(string)] = append(groups[value.(string)], v) }) }
go
func groupBy(entries interface{}, key string) (map[string][]interface{}, error) { return generalizedGroupByKey("groupBy", entries, key, func(groups map[string][]interface{}, value interface{}, v interface{}) { groups[value.(string)] = append(groups[value.(string)], v) }) }
[ "func", "groupBy", "(", "entries", "interface", "{", "}", ",", "key", "string", ")", "(", "map", "[", "string", "]", "[", "]", "interface", "{", "}", ",", "error", ")", "{", "return", "generalizedGroupByKey", "(", "\"", "\"", ",", "entries", ",", "key", ",", "func", "(", "groups", "map", "[", "string", "]", "[", "]", "interface", "{", "}", ",", "value", "interface", "{", "}", ",", "v", "interface", "{", "}", ")", "{", "groups", "[", "value", ".", "(", "string", ")", "]", "=", "append", "(", "groups", "[", "value", ".", "(", "string", ")", "]", ",", "v", ")", "\n", "}", ")", "\n", "}" ]
// groupBy groups a generic array or slice by the path property key
[ "groupBy", "groups", "a", "generic", "array", "or", "slice", "by", "the", "path", "property", "key" ]
4edc190faa34342313589a80e3a736cafb45919b
https://github.com/jwilder/docker-gen/blob/4edc190faa34342313589a80e3a736cafb45919b/template.go#L92-L96
train
jwilder/docker-gen
template.go
groupByKeys
func groupByKeys(entries interface{}, key string) ([]string, error) { keys, err := generalizedGroupByKey("groupByKeys", entries, key, func(groups map[string][]interface{}, value interface{}, v interface{}) { groups[value.(string)] = append(groups[value.(string)], v) }) if err != nil { return nil, err } ret := []string{} for k := range keys { ret = append(ret, k) } return ret, nil }
go
func groupByKeys(entries interface{}, key string) ([]string, error) { keys, err := generalizedGroupByKey("groupByKeys", entries, key, func(groups map[string][]interface{}, value interface{}, v interface{}) { groups[value.(string)] = append(groups[value.(string)], v) }) if err != nil { return nil, err } ret := []string{} for k := range keys { ret = append(ret, k) } return ret, nil }
[ "func", "groupByKeys", "(", "entries", "interface", "{", "}", ",", "key", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "keys", ",", "err", ":=", "generalizedGroupByKey", "(", "\"", "\"", ",", "entries", ",", "key", ",", "func", "(", "groups", "map", "[", "string", "]", "[", "]", "interface", "{", "}", ",", "value", "interface", "{", "}", ",", "v", "interface", "{", "}", ")", "{", "groups", "[", "value", ".", "(", "string", ")", "]", "=", "append", "(", "groups", "[", "value", ".", "(", "string", ")", "]", ",", "v", ")", "\n", "}", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "ret", ":=", "[", "]", "string", "{", "}", "\n", "for", "k", ":=", "range", "keys", "{", "ret", "=", "append", "(", "ret", ",", "k", ")", "\n", "}", "\n", "return", "ret", ",", "nil", "\n", "}" ]
// groupByKeys is the same as groupBy but only returns a list of keys
[ "groupByKeys", "is", "the", "same", "as", "groupBy", "but", "only", "returns", "a", "list", "of", "keys" ]
4edc190faa34342313589a80e3a736cafb45919b
https://github.com/jwilder/docker-gen/blob/4edc190faa34342313589a80e3a736cafb45919b/template.go#L99-L113
train
jwilder/docker-gen
template.go
groupByLabel
func groupByLabel(entries interface{}, label string) (map[string][]interface{}, error) { getLabel := func(v interface{}) (interface{}, error) { if container, ok := v.(RuntimeContainer); ok { if value, ok := container.Labels[label]; ok { return value, nil } return nil, nil } return nil, fmt.Errorf("Must pass an array or slice of RuntimeContainer to 'groupByLabel'; received %v", v) } return generalizedGroupBy("groupByLabel", entries, getLabel, func(groups map[string][]interface{}, value interface{}, v interface{}) { groups[value.(string)] = append(groups[value.(string)], v) }) }
go
func groupByLabel(entries interface{}, label string) (map[string][]interface{}, error) { getLabel := func(v interface{}) (interface{}, error) { if container, ok := v.(RuntimeContainer); ok { if value, ok := container.Labels[label]; ok { return value, nil } return nil, nil } return nil, fmt.Errorf("Must pass an array or slice of RuntimeContainer to 'groupByLabel'; received %v", v) } return generalizedGroupBy("groupByLabel", entries, getLabel, func(groups map[string][]interface{}, value interface{}, v interface{}) { groups[value.(string)] = append(groups[value.(string)], v) }) }
[ "func", "groupByLabel", "(", "entries", "interface", "{", "}", ",", "label", "string", ")", "(", "map", "[", "string", "]", "[", "]", "interface", "{", "}", ",", "error", ")", "{", "getLabel", ":=", "func", "(", "v", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "if", "container", ",", "ok", ":=", "v", ".", "(", "RuntimeContainer", ")", ";", "ok", "{", "if", "value", ",", "ok", ":=", "container", ".", "Labels", "[", "label", "]", ";", "ok", "{", "return", "value", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "v", ")", "\n", "}", "\n", "return", "generalizedGroupBy", "(", "\"", "\"", ",", "entries", ",", "getLabel", ",", "func", "(", "groups", "map", "[", "string", "]", "[", "]", "interface", "{", "}", ",", "value", "interface", "{", "}", ",", "v", "interface", "{", "}", ")", "{", "groups", "[", "value", ".", "(", "string", ")", "]", "=", "append", "(", "groups", "[", "value", ".", "(", "string", ")", "]", ",", "v", ")", "\n", "}", ")", "\n", "}" ]
// groupByLabel is the same as groupBy but over a given label
[ "groupByLabel", "is", "the", "same", "as", "groupBy", "but", "over", "a", "given", "label" ]
4edc190faa34342313589a80e3a736cafb45919b
https://github.com/jwilder/docker-gen/blob/4edc190faa34342313589a80e3a736cafb45919b/template.go#L116-L129
train
jwilder/docker-gen
template.go
generalizedWhere
func generalizedWhere(funcName string, entries interface{}, key string, test func(interface{}) bool) (interface{}, error) { entriesVal, err := getArrayValues(funcName, entries) if err != nil { return nil, err } selection := make([]interface{}, 0) for i := 0; i < entriesVal.Len(); i++ { v := reflect.Indirect(entriesVal.Index(i)).Interface() value := deepGet(v, key) if test(value) { selection = append(selection, v) } } return selection, nil }
go
func generalizedWhere(funcName string, entries interface{}, key string, test func(interface{}) bool) (interface{}, error) { entriesVal, err := getArrayValues(funcName, entries) if err != nil { return nil, err } selection := make([]interface{}, 0) for i := 0; i < entriesVal.Len(); i++ { v := reflect.Indirect(entriesVal.Index(i)).Interface() value := deepGet(v, key) if test(value) { selection = append(selection, v) } } return selection, nil }
[ "func", "generalizedWhere", "(", "funcName", "string", ",", "entries", "interface", "{", "}", ",", "key", "string", ",", "test", "func", "(", "interface", "{", "}", ")", "bool", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "entriesVal", ",", "err", ":=", "getArrayValues", "(", "funcName", ",", "entries", ")", "\n\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "selection", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "0", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "entriesVal", ".", "Len", "(", ")", ";", "i", "++", "{", "v", ":=", "reflect", ".", "Indirect", "(", "entriesVal", ".", "Index", "(", "i", ")", ")", ".", "Interface", "(", ")", "\n\n", "value", ":=", "deepGet", "(", "v", ",", "key", ")", "\n", "if", "test", "(", "value", ")", "{", "selection", "=", "append", "(", "selection", ",", "v", ")", "\n", "}", "\n", "}", "\n\n", "return", "selection", ",", "nil", "\n", "}" ]
// Generalized where function
[ "Generalized", "where", "function" ]
4edc190faa34342313589a80e3a736cafb45919b
https://github.com/jwilder/docker-gen/blob/4edc190faa34342313589a80e3a736cafb45919b/template.go#L132-L150
train
jwilder/docker-gen
template.go
where
func where(entries interface{}, key string, cmp interface{}) (interface{}, error) { return generalizedWhere("where", entries, key, func(value interface{}) bool { return reflect.DeepEqual(value, cmp) }) }
go
func where(entries interface{}, key string, cmp interface{}) (interface{}, error) { return generalizedWhere("where", entries, key, func(value interface{}) bool { return reflect.DeepEqual(value, cmp) }) }
[ "func", "where", "(", "entries", "interface", "{", "}", ",", "key", "string", ",", "cmp", "interface", "{", "}", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "return", "generalizedWhere", "(", "\"", "\"", ",", "entries", ",", "key", ",", "func", "(", "value", "interface", "{", "}", ")", "bool", "{", "return", "reflect", ".", "DeepEqual", "(", "value", ",", "cmp", ")", "\n", "}", ")", "\n", "}" ]
// selects entries based on key
[ "selects", "entries", "based", "on", "key" ]
4edc190faa34342313589a80e3a736cafb45919b
https://github.com/jwilder/docker-gen/blob/4edc190faa34342313589a80e3a736cafb45919b/template.go#L153-L157
train
jwilder/docker-gen
template.go
whereExist
func whereExist(entries interface{}, key string) (interface{}, error) { return generalizedWhere("whereExist", entries, key, func(value interface{}) bool { return value != nil }) }
go
func whereExist(entries interface{}, key string) (interface{}, error) { return generalizedWhere("whereExist", entries, key, func(value interface{}) bool { return value != nil }) }
[ "func", "whereExist", "(", "entries", "interface", "{", "}", ",", "key", "string", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "return", "generalizedWhere", "(", "\"", "\"", ",", "entries", ",", "key", ",", "func", "(", "value", "interface", "{", "}", ")", "bool", "{", "return", "value", "!=", "nil", "\n", "}", ")", "\n", "}" ]
// selects entries where a key exists
[ "selects", "entries", "where", "a", "key", "exists" ]
4edc190faa34342313589a80e3a736cafb45919b
https://github.com/jwilder/docker-gen/blob/4edc190faa34342313589a80e3a736cafb45919b/template.go#L167-L171
train
jwilder/docker-gen
template.go
whereAny
func whereAny(entries interface{}, key, sep string, cmp []string) (interface{}, error) { return generalizedWhere("whereAny", entries, key, func(value interface{}) bool { if value == nil { return false } else { items := strings.Split(value.(string), sep) return len(intersect(cmp, items)) > 0 } }) }
go
func whereAny(entries interface{}, key, sep string, cmp []string) (interface{}, error) { return generalizedWhere("whereAny", entries, key, func(value interface{}) bool { if value == nil { return false } else { items := strings.Split(value.(string), sep) return len(intersect(cmp, items)) > 0 } }) }
[ "func", "whereAny", "(", "entries", "interface", "{", "}", ",", "key", ",", "sep", "string", ",", "cmp", "[", "]", "string", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "return", "generalizedWhere", "(", "\"", "\"", ",", "entries", ",", "key", ",", "func", "(", "value", "interface", "{", "}", ")", "bool", "{", "if", "value", "==", "nil", "{", "return", "false", "\n", "}", "else", "{", "items", ":=", "strings", ".", "Split", "(", "value", ".", "(", "string", ")", ",", "sep", ")", "\n", "return", "len", "(", "intersect", "(", "cmp", ",", "items", ")", ")", ">", "0", "\n", "}", "\n", "}", ")", "\n", "}" ]
// selects entries based on key. Assumes key is delimited and breaks it apart before comparing
[ "selects", "entries", "based", "on", "key", ".", "Assumes", "key", "is", "delimited", "and", "breaks", "it", "apart", "before", "comparing" ]
4edc190faa34342313589a80e3a736cafb45919b
https://github.com/jwilder/docker-gen/blob/4edc190faa34342313589a80e3a736cafb45919b/template.go#L181-L190
train
jwilder/docker-gen
template.go
generalizedWhereLabel
func generalizedWhereLabel(funcName string, containers Context, label string, test func(string, bool) bool) (Context, error) { selection := make([]*RuntimeContainer, 0) for i := 0; i < len(containers); i++ { container := containers[i] value, ok := container.Labels[label] if test(value, ok) { selection = append(selection, container) } } return selection, nil }
go
func generalizedWhereLabel(funcName string, containers Context, label string, test func(string, bool) bool) (Context, error) { selection := make([]*RuntimeContainer, 0) for i := 0; i < len(containers); i++ { container := containers[i] value, ok := container.Labels[label] if test(value, ok) { selection = append(selection, container) } } return selection, nil }
[ "func", "generalizedWhereLabel", "(", "funcName", "string", ",", "containers", "Context", ",", "label", "string", ",", "test", "func", "(", "string", ",", "bool", ")", "bool", ")", "(", "Context", ",", "error", ")", "{", "selection", ":=", "make", "(", "[", "]", "*", "RuntimeContainer", ",", "0", ")", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "containers", ")", ";", "i", "++", "{", "container", ":=", "containers", "[", "i", "]", "\n\n", "value", ",", "ok", ":=", "container", ".", "Labels", "[", "label", "]", "\n", "if", "test", "(", "value", ",", "ok", ")", "{", "selection", "=", "append", "(", "selection", ",", "container", ")", "\n", "}", "\n", "}", "\n\n", "return", "selection", ",", "nil", "\n", "}" ]
// generalized whereLabel function
[ "generalized", "whereLabel", "function" ]
4edc190faa34342313589a80e3a736cafb45919b
https://github.com/jwilder/docker-gen/blob/4edc190faa34342313589a80e3a736cafb45919b/template.go#L206-L219
train
jwilder/docker-gen
template.go
whereLabelExists
func whereLabelExists(containers Context, label string) (Context, error) { return generalizedWhereLabel("whereLabelExists", containers, label, func(_ string, ok bool) bool { return ok }) }
go
func whereLabelExists(containers Context, label string) (Context, error) { return generalizedWhereLabel("whereLabelExists", containers, label, func(_ string, ok bool) bool { return ok }) }
[ "func", "whereLabelExists", "(", "containers", "Context", ",", "label", "string", ")", "(", "Context", ",", "error", ")", "{", "return", "generalizedWhereLabel", "(", "\"", "\"", ",", "containers", ",", "label", ",", "func", "(", "_", "string", ",", "ok", "bool", ")", "bool", "{", "return", "ok", "\n", "}", ")", "\n", "}" ]
// selects containers that have a particular label
[ "selects", "containers", "that", "have", "a", "particular", "label" ]
4edc190faa34342313589a80e3a736cafb45919b
https://github.com/jwilder/docker-gen/blob/4edc190faa34342313589a80e3a736cafb45919b/template.go#L222-L226
train
jwilder/docker-gen
template.go
whereLabelValueMatches
func whereLabelValueMatches(containers Context, label, pattern string) (Context, error) { rx, err := regexp.Compile(pattern) if err != nil { return nil, err } return generalizedWhereLabel("whereLabelValueMatches", containers, label, func(value string, ok bool) bool { return ok && rx.MatchString(value) }) }
go
func whereLabelValueMatches(containers Context, label, pattern string) (Context, error) { rx, err := regexp.Compile(pattern) if err != nil { return nil, err } return generalizedWhereLabel("whereLabelValueMatches", containers, label, func(value string, ok bool) bool { return ok && rx.MatchString(value) }) }
[ "func", "whereLabelValueMatches", "(", "containers", "Context", ",", "label", ",", "pattern", "string", ")", "(", "Context", ",", "error", ")", "{", "rx", ",", "err", ":=", "regexp", ".", "Compile", "(", "pattern", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "generalizedWhereLabel", "(", "\"", "\"", ",", "containers", ",", "label", ",", "func", "(", "value", "string", ",", "ok", "bool", ")", "bool", "{", "return", "ok", "&&", "rx", ".", "MatchString", "(", "value", ")", "\n", "}", ")", "\n", "}" ]
// selects containers with a particular label whose value matches a regular expression
[ "selects", "containers", "with", "a", "particular", "label", "whose", "value", "matches", "a", "regular", "expression" ]
4edc190faa34342313589a80e3a736cafb45919b
https://github.com/jwilder/docker-gen/blob/4edc190faa34342313589a80e3a736cafb45919b/template.go#L236-L245
train
jwilder/docker-gen
template.go
arrayFirst
func arrayFirst(input interface{}) interface{} { if input == nil { return nil } arr := reflect.ValueOf(input) if arr.Len() == 0 { return nil } return arr.Index(0).Interface() }
go
func arrayFirst(input interface{}) interface{} { if input == nil { return nil } arr := reflect.ValueOf(input) if arr.Len() == 0 { return nil } return arr.Index(0).Interface() }
[ "func", "arrayFirst", "(", "input", "interface", "{", "}", ")", "interface", "{", "}", "{", "if", "input", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "arr", ":=", "reflect", ".", "ValueOf", "(", "input", ")", "\n\n", "if", "arr", ".", "Len", "(", ")", "==", "0", "{", "return", "nil", "\n", "}", "\n\n", "return", "arr", ".", "Index", "(", "0", ")", ".", "Interface", "(", ")", "\n", "}" ]
// arrayFirst returns first item in the array or nil if the // input is nil or empty
[ "arrayFirst", "returns", "first", "item", "in", "the", "array", "or", "nil", "if", "the", "input", "is", "nil", "or", "empty" ]
4edc190faa34342313589a80e3a736cafb45919b
https://github.com/jwilder/docker-gen/blob/4edc190faa34342313589a80e3a736cafb45919b/template.go#L341-L353
train
jwilder/docker-gen
template.go
arrayLast
func arrayLast(input interface{}) interface{} { arr := reflect.ValueOf(input) return arr.Index(arr.Len() - 1).Interface() }
go
func arrayLast(input interface{}) interface{} { arr := reflect.ValueOf(input) return arr.Index(arr.Len() - 1).Interface() }
[ "func", "arrayLast", "(", "input", "interface", "{", "}", ")", "interface", "{", "}", "{", "arr", ":=", "reflect", ".", "ValueOf", "(", "input", ")", "\n", "return", "arr", ".", "Index", "(", "arr", ".", "Len", "(", ")", "-", "1", ")", ".", "Interface", "(", ")", "\n", "}" ]
// arrayLast returns last item in the array
[ "arrayLast", "returns", "last", "item", "in", "the", "array" ]
4edc190faa34342313589a80e3a736cafb45919b
https://github.com/jwilder/docker-gen/blob/4edc190faa34342313589a80e3a736cafb45919b/template.go#L356-L359
train
jwilder/docker-gen
template.go
arrayClosest
func arrayClosest(values []string, input string) string { best := "" for _, v := range values { if strings.Contains(input, v) && len(v) > len(best) { best = v } } return best }
go
func arrayClosest(values []string, input string) string { best := "" for _, v := range values { if strings.Contains(input, v) && len(v) > len(best) { best = v } } return best }
[ "func", "arrayClosest", "(", "values", "[", "]", "string", ",", "input", "string", ")", "string", "{", "best", ":=", "\"", "\"", "\n", "for", "_", ",", "v", ":=", "range", "values", "{", "if", "strings", ".", "Contains", "(", "input", ",", "v", ")", "&&", "len", "(", "v", ")", ">", "len", "(", "best", ")", "{", "best", "=", "v", "\n", "}", "\n", "}", "\n", "return", "best", "\n", "}" ]
// arrayClosest find the longest matching substring in values // that matches input
[ "arrayClosest", "find", "the", "longest", "matching", "substring", "in", "values", "that", "matches", "input" ]
4edc190faa34342313589a80e3a736cafb45919b
https://github.com/jwilder/docker-gen/blob/4edc190faa34342313589a80e3a736cafb45919b/template.go#L363-L371
train
jwilder/docker-gen
template.go
dirList
func dirList(path string) ([]string, error) { names := []string{} files, err := ioutil.ReadDir(path) if err != nil { log.Printf("Template error: %v", err) return names, nil } for _, f := range files { names = append(names, f.Name()) } return names, nil }
go
func dirList(path string) ([]string, error) { names := []string{} files, err := ioutil.ReadDir(path) if err != nil { log.Printf("Template error: %v", err) return names, nil } for _, f := range files { names = append(names, f.Name()) } return names, nil }
[ "func", "dirList", "(", "path", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "names", ":=", "[", "]", "string", "{", "}", "\n", "files", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Printf", "(", "\"", "\"", ",", "err", ")", "\n", "return", "names", ",", "nil", "\n", "}", "\n", "for", "_", ",", "f", ":=", "range", "files", "{", "names", "=", "append", "(", "names", ",", "f", ".", "Name", "(", ")", ")", "\n", "}", "\n", "return", "names", ",", "nil", "\n", "}" ]
// dirList returns a list of files in the specified path
[ "dirList", "returns", "a", "list", "of", "files", "in", "the", "specified", "path" ]
4edc190faa34342313589a80e3a736cafb45919b
https://github.com/jwilder/docker-gen/blob/4edc190faa34342313589a80e3a736cafb45919b/template.go#L374-L385
train
gliderlabs/logspout
httpstream/httpstream.go
LogStreamer
func LogStreamer() http.Handler { logs := mux.NewRouter() logsHandler := func(w http.ResponseWriter, req *http.Request) { params := mux.Vars(req) route := new(router.Route) if params["value"] != "" { switch params["predicate"] { case "id": route.FilterID = params["value"] if len(route.ID) > 12 { route.FilterID = route.FilterID[:12] } case "name": route.FilterName = params["value"] } } if route.FilterID != "" && !router.Routes.RoutingFrom(route.FilterID) { http.NotFound(w, req) return } defer debug("http: logs streamer disconnected") logstream := make(chan *router.Message) defer close(logstream) var closer <-chan bool if req.Header.Get("Upgrade") == "websocket" { debug("http: logs streamer connected [websocket]") closerBi := make(chan bool) defer websocketStreamer(w, req, logstream, closerBi) closer = closerBi } else { debug("http: logs streamer connected [http]") defer httpStreamer(w, req, logstream, route.MultiContainer()) closer = w.(http.CloseNotifier).CloseNotify() } route.OverrideCloser(closer) router.Routes.Route(route, logstream) } logs.HandleFunc("/logs/{predicate:[a-zA-Z]+}:{value}", logsHandler).Methods("GET") logs.HandleFunc("/logs", logsHandler).Methods("GET") return logs }
go
func LogStreamer() http.Handler { logs := mux.NewRouter() logsHandler := func(w http.ResponseWriter, req *http.Request) { params := mux.Vars(req) route := new(router.Route) if params["value"] != "" { switch params["predicate"] { case "id": route.FilterID = params["value"] if len(route.ID) > 12 { route.FilterID = route.FilterID[:12] } case "name": route.FilterName = params["value"] } } if route.FilterID != "" && !router.Routes.RoutingFrom(route.FilterID) { http.NotFound(w, req) return } defer debug("http: logs streamer disconnected") logstream := make(chan *router.Message) defer close(logstream) var closer <-chan bool if req.Header.Get("Upgrade") == "websocket" { debug("http: logs streamer connected [websocket]") closerBi := make(chan bool) defer websocketStreamer(w, req, logstream, closerBi) closer = closerBi } else { debug("http: logs streamer connected [http]") defer httpStreamer(w, req, logstream, route.MultiContainer()) closer = w.(http.CloseNotifier).CloseNotify() } route.OverrideCloser(closer) router.Routes.Route(route, logstream) } logs.HandleFunc("/logs/{predicate:[a-zA-Z]+}:{value}", logsHandler).Methods("GET") logs.HandleFunc("/logs", logsHandler).Methods("GET") return logs }
[ "func", "LogStreamer", "(", ")", "http", ".", "Handler", "{", "logs", ":=", "mux", ".", "NewRouter", "(", ")", "\n", "logsHandler", ":=", "func", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "params", ":=", "mux", ".", "Vars", "(", "req", ")", "\n", "route", ":=", "new", "(", "router", ".", "Route", ")", "\n\n", "if", "params", "[", "\"", "\"", "]", "!=", "\"", "\"", "{", "switch", "params", "[", "\"", "\"", "]", "{", "case", "\"", "\"", ":", "route", ".", "FilterID", "=", "params", "[", "\"", "\"", "]", "\n", "if", "len", "(", "route", ".", "ID", ")", ">", "12", "{", "route", ".", "FilterID", "=", "route", ".", "FilterID", "[", ":", "12", "]", "\n", "}", "\n", "case", "\"", "\"", ":", "route", ".", "FilterName", "=", "params", "[", "\"", "\"", "]", "\n", "}", "\n", "}", "\n\n", "if", "route", ".", "FilterID", "!=", "\"", "\"", "&&", "!", "router", ".", "Routes", ".", "RoutingFrom", "(", "route", ".", "FilterID", ")", "{", "http", ".", "NotFound", "(", "w", ",", "req", ")", "\n", "return", "\n", "}", "\n\n", "defer", "debug", "(", "\"", "\"", ")", "\n", "logstream", ":=", "make", "(", "chan", "*", "router", ".", "Message", ")", "\n", "defer", "close", "(", "logstream", ")", "\n\n", "var", "closer", "<-", "chan", "bool", "\n", "if", "req", ".", "Header", ".", "Get", "(", "\"", "\"", ")", "==", "\"", "\"", "{", "debug", "(", "\"", "\"", ")", "\n", "closerBi", ":=", "make", "(", "chan", "bool", ")", "\n", "defer", "websocketStreamer", "(", "w", ",", "req", ",", "logstream", ",", "closerBi", ")", "\n", "closer", "=", "closerBi", "\n", "}", "else", "{", "debug", "(", "\"", "\"", ")", "\n", "defer", "httpStreamer", "(", "w", ",", "req", ",", "logstream", ",", "route", ".", "MultiContainer", "(", ")", ")", "\n", "closer", "=", "w", ".", "(", "http", ".", "CloseNotifier", ")", ".", "CloseNotify", "(", ")", "\n", "}", "\n", "route", ".", "OverrideCloser", "(", "closer", ")", "\n\n", "router", ".", "Routes", ".", "Route", "(", "route", ",", "logstream", ")", "\n", "}", "\n", "logs", ".", "HandleFunc", "(", "\"", "\"", ",", "logsHandler", ")", ".", "Methods", "(", "\"", "\"", ")", "\n", "logs", ".", "HandleFunc", "(", "\"", "\"", ",", "logsHandler", ")", ".", "Methods", "(", "\"", "\"", ")", "\n", "return", "logs", "\n", "}" ]
// LogStreamer returns a http.Handler that can stream logs
[ "LogStreamer", "returns", "a", "http", ".", "Handler", "that", "can", "stream", "logs" ]
29d77641f9664a74fafea2ce655f610d796a63d4
https://github.com/gliderlabs/logspout/blob/29d77641f9664a74fafea2ce655f610d796a63d4/httpstream/httpstream.go#L27-L72
train
gliderlabs/logspout
routesapi/routesapi.go
RoutesAPI
func RoutesAPI() http.Handler { routes := router.Routes r := mux.NewRouter() r.HandleFunc("/routes/{id}", func(w http.ResponseWriter, req *http.Request) { params := mux.Vars(req) route, _ := routes.Get(params["id"]) if route == nil { http.NotFound(w, req) return } w.Write(append(marshal(route), '\n')) }).Methods("GET") r.HandleFunc("/routes/{id}", func(w http.ResponseWriter, req *http.Request) { params := mux.Vars(req) if ok := routes.Remove(params["id"]); !ok { http.NotFound(w, req) } }).Methods("DELETE") r.HandleFunc("/routes", func(w http.ResponseWriter, req *http.Request) { w.Header().Add("Content-Type", "application/json") rts, _ := routes.GetAll() w.Write(append(marshal(rts), '\n')) return }).Methods("GET") r.HandleFunc("/routes", func(w http.ResponseWriter, req *http.Request) { route := new(router.Route) if err := unmarshal(req.Body, route); err != nil { http.Error(w, "Bad request: "+err.Error(), http.StatusBadRequest) return } err := routes.Add(route) if err != nil { http.Error(w, "Bad route: "+err.Error(), http.StatusBadRequest) return } w.Header().Add("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) w.Write(append(marshal(route), '\n')) }).Methods("POST") return r }
go
func RoutesAPI() http.Handler { routes := router.Routes r := mux.NewRouter() r.HandleFunc("/routes/{id}", func(w http.ResponseWriter, req *http.Request) { params := mux.Vars(req) route, _ := routes.Get(params["id"]) if route == nil { http.NotFound(w, req) return } w.Write(append(marshal(route), '\n')) }).Methods("GET") r.HandleFunc("/routes/{id}", func(w http.ResponseWriter, req *http.Request) { params := mux.Vars(req) if ok := routes.Remove(params["id"]); !ok { http.NotFound(w, req) } }).Methods("DELETE") r.HandleFunc("/routes", func(w http.ResponseWriter, req *http.Request) { w.Header().Add("Content-Type", "application/json") rts, _ := routes.GetAll() w.Write(append(marshal(rts), '\n')) return }).Methods("GET") r.HandleFunc("/routes", func(w http.ResponseWriter, req *http.Request) { route := new(router.Route) if err := unmarshal(req.Body, route); err != nil { http.Error(w, "Bad request: "+err.Error(), http.StatusBadRequest) return } err := routes.Add(route) if err != nil { http.Error(w, "Bad route: "+err.Error(), http.StatusBadRequest) return } w.Header().Add("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) w.Write(append(marshal(route), '\n')) }).Methods("POST") return r }
[ "func", "RoutesAPI", "(", ")", "http", ".", "Handler", "{", "routes", ":=", "router", ".", "Routes", "\n", "r", ":=", "mux", ".", "NewRouter", "(", ")", "\n\n", "r", ".", "HandleFunc", "(", "\"", "\"", ",", "func", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "params", ":=", "mux", ".", "Vars", "(", "req", ")", "\n", "route", ",", "_", ":=", "routes", ".", "Get", "(", "params", "[", "\"", "\"", "]", ")", "\n", "if", "route", "==", "nil", "{", "http", ".", "NotFound", "(", "w", ",", "req", ")", "\n", "return", "\n", "}", "\n", "w", ".", "Write", "(", "append", "(", "marshal", "(", "route", ")", ",", "'\\n'", ")", ")", "\n", "}", ")", ".", "Methods", "(", "\"", "\"", ")", "\n\n", "r", ".", "HandleFunc", "(", "\"", "\"", ",", "func", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "params", ":=", "mux", ".", "Vars", "(", "req", ")", "\n", "if", "ok", ":=", "routes", ".", "Remove", "(", "params", "[", "\"", "\"", "]", ")", ";", "!", "ok", "{", "http", ".", "NotFound", "(", "w", ",", "req", ")", "\n", "}", "\n", "}", ")", ".", "Methods", "(", "\"", "\"", ")", "\n\n", "r", ".", "HandleFunc", "(", "\"", "\"", ",", "func", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "w", ".", "Header", "(", ")", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "rts", ",", "_", ":=", "routes", ".", "GetAll", "(", ")", "\n", "w", ".", "Write", "(", "append", "(", "marshal", "(", "rts", ")", ",", "'\\n'", ")", ")", "\n", "return", "\n", "}", ")", ".", "Methods", "(", "\"", "\"", ")", "\n\n", "r", ".", "HandleFunc", "(", "\"", "\"", ",", "func", "(", "w", "http", ".", "ResponseWriter", ",", "req", "*", "http", ".", "Request", ")", "{", "route", ":=", "new", "(", "router", ".", "Route", ")", "\n", "if", "err", ":=", "unmarshal", "(", "req", ".", "Body", ",", "route", ")", ";", "err", "!=", "nil", "{", "http", ".", "Error", "(", "w", ",", "\"", "\"", "+", "err", ".", "Error", "(", ")", ",", "http", ".", "StatusBadRequest", ")", "\n", "return", "\n", "}", "\n", "err", ":=", "routes", ".", "Add", "(", "route", ")", "\n", "if", "err", "!=", "nil", "{", "http", ".", "Error", "(", "w", ",", "\"", "\"", "+", "err", ".", "Error", "(", ")", ",", "http", ".", "StatusBadRequest", ")", "\n", "return", "\n", "}", "\n", "w", ".", "Header", "(", ")", ".", "Add", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "w", ".", "WriteHeader", "(", "http", ".", "StatusCreated", ")", "\n", "w", ".", "Write", "(", "append", "(", "marshal", "(", "route", ")", ",", "'\\n'", ")", ")", "\n", "}", ")", ".", "Methods", "(", "\"", "\"", ")", "\n\n", "return", "r", "\n", "}" ]
// RoutesAPI returns a handler for the routes API
[ "RoutesAPI", "returns", "a", "handler", "for", "the", "routes", "API" ]
29d77641f9664a74fafea2ce655f610d796a63d4
https://github.com/gliderlabs/logspout/blob/29d77641f9664a74fafea2ce655f610d796a63d4/routesapi/routesapi.go#L18-L63
train
gliderlabs/logspout
transports/tls/tls.go
createTLSConfig
func createTLSConfig() (tlsConfig *tls.Config, err error) { tlsConfig = &tls.Config{} // use stronger TLS settings if enabled // TODO: perhaps this should be default setting if os.Getenv(envTLSHardening) == "true" { tlsConfig.InsecureSkipVerify = false tlsConfig.MinVersion = hardenedMinVersion tlsConfig.CipherSuites = hardenedCiphers tlsConfig.CurvePreferences = hardenedCurvePreferences } // load possible TLS CA chain(s) for server certificate validation // starting with an empty pool tlsConfig.RootCAs = x509.NewCertPool() // load system root CA trust store by default, unless configured not to // if we cannot, then it's fatal. // NOTE that we ONLY fail if SystemCertPool returns an error, // not if our system trust store is empty or doesn't exist! if os.Getenv(envDisableSystemRoots) != "true" { tlsConfig.RootCAs, err = x509.SystemCertPool() if err != nil { return } } // load custom certificates specified by configuration: // we expect a comma separated list of certificate file paths // if we fail to load a certificate, we should treat this to be fatal // as the user may not wish to send logs through an untrusted TLS connection // also note that each file specified above can contain one or more certificates // and we also _DO NOT_ check if they are CA certificates (in case of self-signed) if certsEnv := os.Getenv(envCaCerts); certsEnv != "" { certFilePaths := strings.Split(certsEnv, ",") for _, certFilePath := range certFilePaths { // each pem file may contain more than one certficate var certBytes []byte certBytes, err = ioutil.ReadFile(certFilePath) if err != nil { return } if !tlsConfig.RootCAs.AppendCertsFromPEM(certBytes) { err = fmt.Errorf("failed to load CA certificate(s): %s", certFilePath) return } } } // load a client certificate and key if enabled // we should only attempt this if BOTH cert and key are defined clientCertFilePath := os.Getenv(envClientCert) clientKeyFilePath := os.Getenv(envClientKey) if clientCertFilePath != "" && clientKeyFilePath != "" { var clientCert tls.Certificate clientCert, err = tls.LoadX509KeyPair(clientCertFilePath, clientKeyFilePath) // we should fail if unable to load the keypair since the user intended mutual authentication if err != nil { return } // according to TLS spec (RFC 5246 appendix F.1.1) the certificate message // must provide a valid certificate chain leading to an acceptable certificate authority. // We will make this optional; the client cert pem file can contain more than one certificate tlsConfig.Certificates = []tls.Certificate{clientCert} } return }
go
func createTLSConfig() (tlsConfig *tls.Config, err error) { tlsConfig = &tls.Config{} // use stronger TLS settings if enabled // TODO: perhaps this should be default setting if os.Getenv(envTLSHardening) == "true" { tlsConfig.InsecureSkipVerify = false tlsConfig.MinVersion = hardenedMinVersion tlsConfig.CipherSuites = hardenedCiphers tlsConfig.CurvePreferences = hardenedCurvePreferences } // load possible TLS CA chain(s) for server certificate validation // starting with an empty pool tlsConfig.RootCAs = x509.NewCertPool() // load system root CA trust store by default, unless configured not to // if we cannot, then it's fatal. // NOTE that we ONLY fail if SystemCertPool returns an error, // not if our system trust store is empty or doesn't exist! if os.Getenv(envDisableSystemRoots) != "true" { tlsConfig.RootCAs, err = x509.SystemCertPool() if err != nil { return } } // load custom certificates specified by configuration: // we expect a comma separated list of certificate file paths // if we fail to load a certificate, we should treat this to be fatal // as the user may not wish to send logs through an untrusted TLS connection // also note that each file specified above can contain one or more certificates // and we also _DO NOT_ check if they are CA certificates (in case of self-signed) if certsEnv := os.Getenv(envCaCerts); certsEnv != "" { certFilePaths := strings.Split(certsEnv, ",") for _, certFilePath := range certFilePaths { // each pem file may contain more than one certficate var certBytes []byte certBytes, err = ioutil.ReadFile(certFilePath) if err != nil { return } if !tlsConfig.RootCAs.AppendCertsFromPEM(certBytes) { err = fmt.Errorf("failed to load CA certificate(s): %s", certFilePath) return } } } // load a client certificate and key if enabled // we should only attempt this if BOTH cert and key are defined clientCertFilePath := os.Getenv(envClientCert) clientKeyFilePath := os.Getenv(envClientKey) if clientCertFilePath != "" && clientKeyFilePath != "" { var clientCert tls.Certificate clientCert, err = tls.LoadX509KeyPair(clientCertFilePath, clientKeyFilePath) // we should fail if unable to load the keypair since the user intended mutual authentication if err != nil { return } // according to TLS spec (RFC 5246 appendix F.1.1) the certificate message // must provide a valid certificate chain leading to an acceptable certificate authority. // We will make this optional; the client cert pem file can contain more than one certificate tlsConfig.Certificates = []tls.Certificate{clientCert} } return }
[ "func", "createTLSConfig", "(", ")", "(", "tlsConfig", "*", "tls", ".", "Config", ",", "err", "error", ")", "{", "tlsConfig", "=", "&", "tls", ".", "Config", "{", "}", "\n\n", "// use stronger TLS settings if enabled", "// TODO: perhaps this should be default setting", "if", "os", ".", "Getenv", "(", "envTLSHardening", ")", "==", "\"", "\"", "{", "tlsConfig", ".", "InsecureSkipVerify", "=", "false", "\n", "tlsConfig", ".", "MinVersion", "=", "hardenedMinVersion", "\n", "tlsConfig", ".", "CipherSuites", "=", "hardenedCiphers", "\n", "tlsConfig", ".", "CurvePreferences", "=", "hardenedCurvePreferences", "\n", "}", "\n\n", "// load possible TLS CA chain(s) for server certificate validation", "// starting with an empty pool", "tlsConfig", ".", "RootCAs", "=", "x509", ".", "NewCertPool", "(", ")", "\n\n", "// load system root CA trust store by default, unless configured not to", "// if we cannot, then it's fatal.", "// NOTE that we ONLY fail if SystemCertPool returns an error,", "// not if our system trust store is empty or doesn't exist!", "if", "os", ".", "Getenv", "(", "envDisableSystemRoots", ")", "!=", "\"", "\"", "{", "tlsConfig", ".", "RootCAs", ",", "err", "=", "x509", ".", "SystemCertPool", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "\n\n", "// load custom certificates specified by configuration:", "// we expect a comma separated list of certificate file paths", "// if we fail to load a certificate, we should treat this to be fatal", "// as the user may not wish to send logs through an untrusted TLS connection", "// also note that each file specified above can contain one or more certificates", "// and we also _DO NOT_ check if they are CA certificates (in case of self-signed)", "if", "certsEnv", ":=", "os", ".", "Getenv", "(", "envCaCerts", ")", ";", "certsEnv", "!=", "\"", "\"", "{", "certFilePaths", ":=", "strings", ".", "Split", "(", "certsEnv", ",", "\"", "\"", ")", "\n", "for", "_", ",", "certFilePath", ":=", "range", "certFilePaths", "{", "// each pem file may contain more than one certficate", "var", "certBytes", "[", "]", "byte", "\n", "certBytes", ",", "err", "=", "ioutil", ".", "ReadFile", "(", "certFilePath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "!", "tlsConfig", ".", "RootCAs", ".", "AppendCertsFromPEM", "(", "certBytes", ")", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "certFilePath", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// load a client certificate and key if enabled", "// we should only attempt this if BOTH cert and key are defined", "clientCertFilePath", ":=", "os", ".", "Getenv", "(", "envClientCert", ")", "\n", "clientKeyFilePath", ":=", "os", ".", "Getenv", "(", "envClientKey", ")", "\n", "if", "clientCertFilePath", "!=", "\"", "\"", "&&", "clientKeyFilePath", "!=", "\"", "\"", "{", "var", "clientCert", "tls", ".", "Certificate", "\n", "clientCert", ",", "err", "=", "tls", ".", "LoadX509KeyPair", "(", "clientCertFilePath", ",", "clientKeyFilePath", ")", "\n", "// we should fail if unable to load the keypair since the user intended mutual authentication", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "// according to TLS spec (RFC 5246 appendix F.1.1) the certificate message", "// must provide a valid certificate chain leading to an acceptable certificate authority.", "// We will make this optional; the client cert pem file can contain more than one certificate", "tlsConfig", ".", "Certificates", "=", "[", "]", "tls", ".", "Certificate", "{", "clientCert", "}", "\n", "}", "\n", "return", "\n", "}" ]
// createTLSConfig creates the required TLS configuration that we need to establish a TLS connection
[ "createTLSConfig", "creates", "the", "required", "TLS", "configuration", "that", "we", "need", "to", "establish", "a", "TLS", "connection" ]
29d77641f9664a74fafea2ce655f610d796a63d4
https://github.com/gliderlabs/logspout/blob/29d77641f9664a74fafea2ce655f610d796a63d4/transports/tls/tls.go#L95-L161
train
gliderlabs/logspout
adapters/syslog/syslog.go
NewSyslogAdapter
func NewSyslogAdapter(route *router.Route) (router.LogAdapter, error) { transport, found := router.AdapterTransports.Lookup(route.AdapterTransport("udp")) if !found { return nil, errors.New("bad transport: " + route.Adapter) } conn, err := transport.Dial(route.Address, route.Options) if err != nil { return nil, err } format := getopt("SYSLOG_FORMAT", "rfc5424") priority := getopt("SYSLOG_PRIORITY", "{{.Priority}}") pid := getopt("SYSLOG_PID", "{{.Container.State.Pid}}") hostname = getHostname() tag := getopt("SYSLOG_TAG", "{{.ContainerName}}"+route.Options["append_tag"]) structuredData := getopt("SYSLOG_STRUCTURED_DATA", "") if route.Options["structured_data"] != "" { structuredData = route.Options["structured_data"] } data := getopt("SYSLOG_DATA", "{{.Data}}") timestamp := getopt("SYSLOG_TIMESTAMP", "{{.Timestamp}}") if structuredData == "" { structuredData = "-" } else { structuredData = fmt.Sprintf("[%s]", structuredData) } var tmplStr string switch format { case "rfc5424": tmplStr = fmt.Sprintf("<%s>1 %s %s %s %s - %s %s\n", priority, timestamp, hostname, tag, pid, structuredData, data) case "rfc3164": tmplStr = fmt.Sprintf("<%s>%s %s %s[%s]: %s\n", priority, timestamp, hostname, tag, pid, data) default: return nil, errors.New("unsupported syslog format: " + format) } tmpl, err := template.New("syslog").Parse(tmplStr) if err != nil { return nil, err } return &Adapter{ route: route, conn: conn, tmpl: tmpl, transport: transport, }, nil }
go
func NewSyslogAdapter(route *router.Route) (router.LogAdapter, error) { transport, found := router.AdapterTransports.Lookup(route.AdapterTransport("udp")) if !found { return nil, errors.New("bad transport: " + route.Adapter) } conn, err := transport.Dial(route.Address, route.Options) if err != nil { return nil, err } format := getopt("SYSLOG_FORMAT", "rfc5424") priority := getopt("SYSLOG_PRIORITY", "{{.Priority}}") pid := getopt("SYSLOG_PID", "{{.Container.State.Pid}}") hostname = getHostname() tag := getopt("SYSLOG_TAG", "{{.ContainerName}}"+route.Options["append_tag"]) structuredData := getopt("SYSLOG_STRUCTURED_DATA", "") if route.Options["structured_data"] != "" { structuredData = route.Options["structured_data"] } data := getopt("SYSLOG_DATA", "{{.Data}}") timestamp := getopt("SYSLOG_TIMESTAMP", "{{.Timestamp}}") if structuredData == "" { structuredData = "-" } else { structuredData = fmt.Sprintf("[%s]", structuredData) } var tmplStr string switch format { case "rfc5424": tmplStr = fmt.Sprintf("<%s>1 %s %s %s %s - %s %s\n", priority, timestamp, hostname, tag, pid, structuredData, data) case "rfc3164": tmplStr = fmt.Sprintf("<%s>%s %s %s[%s]: %s\n", priority, timestamp, hostname, tag, pid, data) default: return nil, errors.New("unsupported syslog format: " + format) } tmpl, err := template.New("syslog").Parse(tmplStr) if err != nil { return nil, err } return &Adapter{ route: route, conn: conn, tmpl: tmpl, transport: transport, }, nil }
[ "func", "NewSyslogAdapter", "(", "route", "*", "router", ".", "Route", ")", "(", "router", ".", "LogAdapter", ",", "error", ")", "{", "transport", ",", "found", ":=", "router", ".", "AdapterTransports", ".", "Lookup", "(", "route", ".", "AdapterTransport", "(", "\"", "\"", ")", ")", "\n", "if", "!", "found", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", "+", "route", ".", "Adapter", ")", "\n", "}", "\n", "conn", ",", "err", ":=", "transport", ".", "Dial", "(", "route", ".", "Address", ",", "route", ".", "Options", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "format", ":=", "getopt", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "priority", ":=", "getopt", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "pid", ":=", "getopt", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "hostname", "=", "getHostname", "(", ")", "\n\n", "tag", ":=", "getopt", "(", "\"", "\"", ",", "\"", "\"", "+", "route", ".", "Options", "[", "\"", "\"", "]", ")", "\n", "structuredData", ":=", "getopt", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "route", ".", "Options", "[", "\"", "\"", "]", "!=", "\"", "\"", "{", "structuredData", "=", "route", ".", "Options", "[", "\"", "\"", "]", "\n", "}", "\n", "data", ":=", "getopt", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "timestamp", ":=", "getopt", "(", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "if", "structuredData", "==", "\"", "\"", "{", "structuredData", "=", "\"", "\"", "\n", "}", "else", "{", "structuredData", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "structuredData", ")", "\n", "}", "\n\n", "var", "tmplStr", "string", "\n", "switch", "format", "{", "case", "\"", "\"", ":", "tmplStr", "=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "priority", ",", "timestamp", ",", "hostname", ",", "tag", ",", "pid", ",", "structuredData", ",", "data", ")", "\n", "case", "\"", "\"", ":", "tmplStr", "=", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "priority", ",", "timestamp", ",", "hostname", ",", "tag", ",", "pid", ",", "data", ")", "\n", "default", ":", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", "+", "format", ")", "\n", "}", "\n", "tmpl", ",", "err", ":=", "template", ".", "New", "(", "\"", "\"", ")", ".", "Parse", "(", "tmplStr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "Adapter", "{", "route", ":", "route", ",", "conn", ":", "conn", ",", "tmpl", ":", "tmpl", ",", "transport", ":", "transport", ",", "}", ",", "nil", "\n", "}" ]
// NewSyslogAdapter returnas a configured syslog.Adapter
[ "NewSyslogAdapter", "returnas", "a", "configured", "syslog", ".", "Adapter" ]
29d77641f9664a74fafea2ce655f610d796a63d4
https://github.com/gliderlabs/logspout/blob/29d77641f9664a74fafea2ce655f610d796a63d4/adapters/syslog/syslog.go#L70-L120
train
gliderlabs/logspout
adapters/syslog/syslog.go
Render
func (m *Message) Render(tmpl *template.Template) ([]byte, error) { buf := new(bytes.Buffer) err := tmpl.Execute(buf, m) if err != nil { return nil, err } return buf.Bytes(), nil }
go
func (m *Message) Render(tmpl *template.Template) ([]byte, error) { buf := new(bytes.Buffer) err := tmpl.Execute(buf, m) if err != nil { return nil, err } return buf.Bytes(), nil }
[ "func", "(", "m", "*", "Message", ")", "Render", "(", "tmpl", "*", "template", ".", "Template", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "buf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "err", ":=", "tmpl", ".", "Execute", "(", "buf", ",", "m", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "buf", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// Render transforms the log message using the Syslog template
[ "Render", "transforms", "the", "log", "message", "using", "the", "Syslog", "template" ]
29d77641f9664a74fafea2ce655f610d796a63d4
https://github.com/gliderlabs/logspout/blob/29d77641f9664a74fafea2ce655f610d796a63d4/adapters/syslog/syslog.go#L234-L241
train
gliderlabs/logspout
adapters/syslog/syslog.go
Priority
func (m *Message) Priority() syslog.Priority { switch m.Message.Source { case "stdout": return syslog.LOG_USER | syslog.LOG_INFO case "stderr": return syslog.LOG_USER | syslog.LOG_ERR default: return syslog.LOG_DAEMON | syslog.LOG_INFO } }
go
func (m *Message) Priority() syslog.Priority { switch m.Message.Source { case "stdout": return syslog.LOG_USER | syslog.LOG_INFO case "stderr": return syslog.LOG_USER | syslog.LOG_ERR default: return syslog.LOG_DAEMON | syslog.LOG_INFO } }
[ "func", "(", "m", "*", "Message", ")", "Priority", "(", ")", "syslog", ".", "Priority", "{", "switch", "m", ".", "Message", ".", "Source", "{", "case", "\"", "\"", ":", "return", "syslog", ".", "LOG_USER", "|", "syslog", ".", "LOG_INFO", "\n", "case", "\"", "\"", ":", "return", "syslog", ".", "LOG_USER", "|", "syslog", ".", "LOG_ERR", "\n", "default", ":", "return", "syslog", ".", "LOG_DAEMON", "|", "syslog", ".", "LOG_INFO", "\n", "}", "\n", "}" ]
// Priority returns a syslog.Priority based on the message source
[ "Priority", "returns", "a", "syslog", ".", "Priority", "based", "on", "the", "message", "source" ]
29d77641f9664a74fafea2ce655f610d796a63d4
https://github.com/gliderlabs/logspout/blob/29d77641f9664a74fafea2ce655f610d796a63d4/adapters/syslog/syslog.go#L244-L253
train
gliderlabs/logspout
adapters/syslog/syslog.go
Timestamp
func (m *Message) Timestamp() string { return m.Message.Time.Format(time.RFC3339) }
go
func (m *Message) Timestamp() string { return m.Message.Time.Format(time.RFC3339) }
[ "func", "(", "m", "*", "Message", ")", "Timestamp", "(", ")", "string", "{", "return", "m", ".", "Message", ".", "Time", ".", "Format", "(", "time", ".", "RFC3339", ")", "\n", "}" ]
// Timestamp returns the message's syslog formatted timestamp
[ "Timestamp", "returns", "the", "message", "s", "syslog", "formatted", "timestamp" ]
29d77641f9664a74fafea2ce655f610d796a63d4
https://github.com/gliderlabs/logspout/blob/29d77641f9664a74fafea2ce655f610d796a63d4/adapters/syslog/syslog.go#L261-L263
train