repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
perkeep/perkeep | internal/images/images.go | Decode | func Decode(r io.Reader, opts *DecodeOpts) (image.Image, Config, error) {
var (
angle int
buf bytes.Buffer
c Config
flipMode FlipDirection
)
tr := io.TeeReader(io.LimitReader(r, 2<<20), &buf)
if opts.useEXIF() {
angle, flipMode = exifOrientation(tr)
} else {
var err error
angle, flipMode, err = opts.forcedOrientation()
if err != nil {
return nil, c, err
}
}
// Orientation changing rotations should have their dimensions swapped
// when scaling.
var swapDimensions bool
switch angle {
case 90, -90:
swapDimensions = true
}
mr := io.MultiReader(&buf, r)
im, format, err, rescaled := decode(mr, opts, swapDimensions)
if err != nil {
return nil, c, err
}
c.Modified = rescaled
if angle != 0 {
im = rotate(im, angle)
c.Modified = true
}
if flipMode != 0 {
im = flip(im, flipMode)
c.Modified = true
}
c.Format = format
c.setBounds(im)
return im, c, nil
} | go | func Decode(r io.Reader, opts *DecodeOpts) (image.Image, Config, error) {
var (
angle int
buf bytes.Buffer
c Config
flipMode FlipDirection
)
tr := io.TeeReader(io.LimitReader(r, 2<<20), &buf)
if opts.useEXIF() {
angle, flipMode = exifOrientation(tr)
} else {
var err error
angle, flipMode, err = opts.forcedOrientation()
if err != nil {
return nil, c, err
}
}
// Orientation changing rotations should have their dimensions swapped
// when scaling.
var swapDimensions bool
switch angle {
case 90, -90:
swapDimensions = true
}
mr := io.MultiReader(&buf, r)
im, format, err, rescaled := decode(mr, opts, swapDimensions)
if err != nil {
return nil, c, err
}
c.Modified = rescaled
if angle != 0 {
im = rotate(im, angle)
c.Modified = true
}
if flipMode != 0 {
im = flip(im, flipMode)
c.Modified = true
}
c.Format = format
c.setBounds(im)
return im, c, nil
} | [
"func",
"Decode",
"(",
"r",
"io",
".",
"Reader",
",",
"opts",
"*",
"DecodeOpts",
")",
"(",
"image",
".",
"Image",
",",
"Config",
",",
"error",
")",
"{",
"var",
"(",
"angle",
"int",
"\n",
"buf",
"bytes",
".",
"Buffer",
"\n",
"c",
"Config",
"\n",
"... | // Decode decodes an image from r using the provided decoding options.
// The Config returned is similar to the one from the image package,
// with the addition of the Modified field which indicates if the
// image was actually flipped, rotated, or scaled.
// If opts is nil, the defaults are used. | [
"Decode",
"decodes",
"an",
"image",
"from",
"r",
"using",
"the",
"provided",
"decoding",
"options",
".",
"The",
"Config",
"returned",
"is",
"similar",
"to",
"the",
"one",
"from",
"the",
"image",
"package",
"with",
"the",
"addition",
"of",
"the",
"Modified",
... | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/images/images.go#L568-L615 | train |
perkeep/perkeep | internal/images/images.go | localImageMagick | func localImageMagick() string {
bin, err := exec.LookPath("magick")
if err != nil {
return ""
}
magickHasHEIC.Lock()
defer magickHasHEIC.Unlock()
if magickHasHEIC.checked {
if magickHasHEIC.heic {
return bin
}
return ""
}
magickHasHEIC.checked = true
out, err := exec.Command(bin, "-version").CombinedOutput()
if err != nil {
log.Printf("internal/images: error checking local machine's imagemagick version: %v, %s", err, out)
return ""
}
if strings.Contains(string(out), " heic") {
magickHasHEIC.heic = true
return bin
}
return ""
} | go | func localImageMagick() string {
bin, err := exec.LookPath("magick")
if err != nil {
return ""
}
magickHasHEIC.Lock()
defer magickHasHEIC.Unlock()
if magickHasHEIC.checked {
if magickHasHEIC.heic {
return bin
}
return ""
}
magickHasHEIC.checked = true
out, err := exec.Command(bin, "-version").CombinedOutput()
if err != nil {
log.Printf("internal/images: error checking local machine's imagemagick version: %v, %s", err, out)
return ""
}
if strings.Contains(string(out), " heic") {
magickHasHEIC.heic = true
return bin
}
return ""
} | [
"func",
"localImageMagick",
"(",
")",
"string",
"{",
"bin",
",",
"err",
":=",
"exec",
".",
"LookPath",
"(",
"\"magick\"",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
"\n",
"}",
"\n",
"magickHasHEIC",
".",
"Lock",
"(",
")",
"\n",
"defe... | // localImageMagick returns the path to the local ImageMagick "magick" binary,
// if it's new enough. Otherwise it returns the empty string. | [
"localImageMagick",
"returns",
"the",
"path",
"to",
"the",
"local",
"ImageMagick",
"magick",
"binary",
"if",
"it",
"s",
"new",
"enough",
".",
"Otherwise",
"it",
"returns",
"the",
"empty",
"string",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/images/images.go#L633-L657 | train |
perkeep/perkeep | internal/images/images.go | HEIFToJPEG | func HEIFToJPEG(fr io.Reader, maxSize *Dimensions) ([]byte, error) {
convertGate.Start()
defer convertGate.Done()
useDocker := false
bin := localImageMagick()
if bin == "" {
if err := setUpThumbnailContainer(); err != nil {
return nil, NoHEICTOJPEGError{fmt.Errorf("recent ImageMagick magick binary not found in PATH, and could not fallback on docker image because %v. Install a modern ImageMagick or install docker.", err)}
}
bin = "docker"
useDocker = true
}
outDir, err := ioutil.TempDir("", "perkeep-heif")
if err != nil {
return nil, err
}
defer os.RemoveAll(outDir)
inFile := filepath.Join(outDir, "input.heic")
outFile := filepath.Join(outDir, "output.jpg")
// first create the input file in tmp as heiftojpeg cannot take a piped stdin
f, err := os.Create(inFile)
if err != nil {
return nil, err
}
if _, err := io.Copy(f, fr); err != nil {
f.Close()
return nil, err
}
if err := f.Close(); err != nil {
return nil, err
}
// now actually run ImageMagick
var args []string
outFileArg := outFile
if useDocker {
args = append(args, "run",
"--rm",
"-v", outDir+":/out/",
thumbnailImage,
"/usr/local/bin/magick",
)
inFile = "/out/input.heic"
outFileArg = "/out/output.jpg"
}
args = append(args, "convert")
if maxSize != nil {
args = append(args, "-thumbnail", fmt.Sprintf("%dx%d", maxSize.MaxWidth, maxSize.MaxHeight))
}
args = append(args, inFile, "-colorspace", "RGB", "-auto-orient", outFileArg)
cmd := exec.Command(bin, args...)
t0 := time.Now()
if debug {
log.Printf("internal/images: running imagemagick heic conversion: %q %q", bin, args)
}
var buf bytes.Buffer
cmd.Stderr = &buf
if err = cmd.Run(); err != nil {
if debug {
log.Printf("internal/images: error running imagemagick heic conversion: %s", buf.Bytes())
}
return nil, fmt.Errorf("error running imagemagick: %v, %s", err, buf.Bytes())
}
if debug {
log.Printf("internal/images: ran imagemagick heic conversion in %v", time.Since(t0))
}
return ioutil.ReadFile(outFile)
} | go | func HEIFToJPEG(fr io.Reader, maxSize *Dimensions) ([]byte, error) {
convertGate.Start()
defer convertGate.Done()
useDocker := false
bin := localImageMagick()
if bin == "" {
if err := setUpThumbnailContainer(); err != nil {
return nil, NoHEICTOJPEGError{fmt.Errorf("recent ImageMagick magick binary not found in PATH, and could not fallback on docker image because %v. Install a modern ImageMagick or install docker.", err)}
}
bin = "docker"
useDocker = true
}
outDir, err := ioutil.TempDir("", "perkeep-heif")
if err != nil {
return nil, err
}
defer os.RemoveAll(outDir)
inFile := filepath.Join(outDir, "input.heic")
outFile := filepath.Join(outDir, "output.jpg")
// first create the input file in tmp as heiftojpeg cannot take a piped stdin
f, err := os.Create(inFile)
if err != nil {
return nil, err
}
if _, err := io.Copy(f, fr); err != nil {
f.Close()
return nil, err
}
if err := f.Close(); err != nil {
return nil, err
}
// now actually run ImageMagick
var args []string
outFileArg := outFile
if useDocker {
args = append(args, "run",
"--rm",
"-v", outDir+":/out/",
thumbnailImage,
"/usr/local/bin/magick",
)
inFile = "/out/input.heic"
outFileArg = "/out/output.jpg"
}
args = append(args, "convert")
if maxSize != nil {
args = append(args, "-thumbnail", fmt.Sprintf("%dx%d", maxSize.MaxWidth, maxSize.MaxHeight))
}
args = append(args, inFile, "-colorspace", "RGB", "-auto-orient", outFileArg)
cmd := exec.Command(bin, args...)
t0 := time.Now()
if debug {
log.Printf("internal/images: running imagemagick heic conversion: %q %q", bin, args)
}
var buf bytes.Buffer
cmd.Stderr = &buf
if err = cmd.Run(); err != nil {
if debug {
log.Printf("internal/images: error running imagemagick heic conversion: %s", buf.Bytes())
}
return nil, fmt.Errorf("error running imagemagick: %v, %s", err, buf.Bytes())
}
if debug {
log.Printf("internal/images: ran imagemagick heic conversion in %v", time.Since(t0))
}
return ioutil.ReadFile(outFile)
} | [
"func",
"HEIFToJPEG",
"(",
"fr",
"io",
".",
"Reader",
",",
"maxSize",
"*",
"Dimensions",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"convertGate",
".",
"Start",
"(",
")",
"\n",
"defer",
"convertGate",
".",
"Done",
"(",
")",
"\n",
"useDocker"... | // HEIFToJPEG converts the HEIF file in fr to JPEG. It optionally resizes it
// to the given maxSize argument, if any. It returns the contents of the JPEG file. | [
"HEIFToJPEG",
"converts",
"the",
"HEIF",
"file",
"in",
"fr",
"to",
"JPEG",
".",
"It",
"optionally",
"resizes",
"it",
"to",
"the",
"given",
"maxSize",
"argument",
"if",
"any",
".",
"It",
"returns",
"the",
"contents",
"of",
"the",
"JPEG",
"file",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/internal/images/images.go#L665-L735 | train |
perkeep/perkeep | pkg/server/sync.go | enumerateQueuedBlobs | func (sh *SyncHandler) enumerateQueuedBlobs(dst chan<- blob.SizedRef, intr <-chan struct{}) error {
defer close(dst)
it := sh.queue.Find("", "")
for it.Next() {
br, ok := blob.Parse(it.Key())
size, err := strconv.ParseUint(it.Value(), 10, 32)
if !ok || err != nil {
sh.logf("ERROR: bogus sync queue entry: %q => %q", it.Key(), it.Value())
continue
}
select {
case dst <- blob.SizedRef{Ref: br, Size: uint32(size)}:
case <-intr:
return it.Close()
}
}
return it.Close()
} | go | func (sh *SyncHandler) enumerateQueuedBlobs(dst chan<- blob.SizedRef, intr <-chan struct{}) error {
defer close(dst)
it := sh.queue.Find("", "")
for it.Next() {
br, ok := blob.Parse(it.Key())
size, err := strconv.ParseUint(it.Value(), 10, 32)
if !ok || err != nil {
sh.logf("ERROR: bogus sync queue entry: %q => %q", it.Key(), it.Value())
continue
}
select {
case dst <- blob.SizedRef{Ref: br, Size: uint32(size)}:
case <-intr:
return it.Close()
}
}
return it.Close()
} | [
"func",
"(",
"sh",
"*",
"SyncHandler",
")",
"enumerateQueuedBlobs",
"(",
"dst",
"chan",
"<-",
"blob",
".",
"SizedRef",
",",
"intr",
"<-",
"chan",
"struct",
"{",
"}",
")",
"error",
"{",
"defer",
"close",
"(",
"dst",
")",
"\n",
"it",
":=",
"sh",
".",
... | // enumerateQueuedBlobs yields blobs from the on-disk sorted.KeyValue store.
// This differs from enumeratePendingBlobs, which sends from the in-memory pending list. | [
"enumerateQueuedBlobs",
"yields",
"blobs",
"from",
"the",
"on",
"-",
"disk",
"sorted",
".",
"KeyValue",
"store",
".",
"This",
"differs",
"from",
"enumeratePendingBlobs",
"which",
"sends",
"from",
"the",
"in",
"-",
"memory",
"pending",
"list",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/server/sync.go#L544-L561 | train |
perkeep/perkeep | pkg/server/sync.go | startValidatePrefix | func (sh *SyncHandler) startValidatePrefix(ctx context.Context, pfx string, doDest bool) (<-chan blob.SizedRef, <-chan error) {
var e blobserver.BlobEnumerator
if doDest {
e = sh.to
} else {
e = sh.from
}
c := make(chan blob.SizedRef, 64)
errc := make(chan error, 1)
go func() {
defer close(c)
var last string // last blobref seen; to double check storage's enumeration works correctly.
err := blobserver.EnumerateAllFrom(ctx, e, pfx, func(sb blob.SizedRef) error {
// Just double-check that the storage target is returning sorted results correctly.
brStr := sb.Ref.String()
if brStr < pfx {
log.Fatalf("Storage target %T enumerate not behaving: %q < requested prefix %q", e, brStr, pfx)
}
if last != "" && last >= brStr {
log.Fatalf("Storage target %T enumerate not behaving: previous %q >= current %q", e, last, brStr)
}
last = brStr
// TODO: could add a more efficient method on blob.Ref to do this,
// that doesn't involve call String().
if !strings.HasPrefix(brStr, pfx) {
return errNotPrefix
}
select {
case c <- sb:
sh.mu.Lock()
if doDest {
sh.vdestCount++
sh.vdestBytes += int64(sb.Size)
} else {
sh.vsrcCount++
sh.vsrcBytes += int64(sb.Size)
}
sh.mu.Unlock()
return nil
case <-ctx.Done():
return ctx.Err()
}
})
if err == errNotPrefix {
err = nil
}
if err != nil {
// Send a zero value to shut down ListMissingDestinationBlobs.
c <- blob.SizedRef{}
}
errc <- err
}()
return c, errc
} | go | func (sh *SyncHandler) startValidatePrefix(ctx context.Context, pfx string, doDest bool) (<-chan blob.SizedRef, <-chan error) {
var e blobserver.BlobEnumerator
if doDest {
e = sh.to
} else {
e = sh.from
}
c := make(chan blob.SizedRef, 64)
errc := make(chan error, 1)
go func() {
defer close(c)
var last string // last blobref seen; to double check storage's enumeration works correctly.
err := blobserver.EnumerateAllFrom(ctx, e, pfx, func(sb blob.SizedRef) error {
// Just double-check that the storage target is returning sorted results correctly.
brStr := sb.Ref.String()
if brStr < pfx {
log.Fatalf("Storage target %T enumerate not behaving: %q < requested prefix %q", e, brStr, pfx)
}
if last != "" && last >= brStr {
log.Fatalf("Storage target %T enumerate not behaving: previous %q >= current %q", e, last, brStr)
}
last = brStr
// TODO: could add a more efficient method on blob.Ref to do this,
// that doesn't involve call String().
if !strings.HasPrefix(brStr, pfx) {
return errNotPrefix
}
select {
case c <- sb:
sh.mu.Lock()
if doDest {
sh.vdestCount++
sh.vdestBytes += int64(sb.Size)
} else {
sh.vsrcCount++
sh.vsrcBytes += int64(sb.Size)
}
sh.mu.Unlock()
return nil
case <-ctx.Done():
return ctx.Err()
}
})
if err == errNotPrefix {
err = nil
}
if err != nil {
// Send a zero value to shut down ListMissingDestinationBlobs.
c <- blob.SizedRef{}
}
errc <- err
}()
return c, errc
} | [
"func",
"(",
"sh",
"*",
"SyncHandler",
")",
"startValidatePrefix",
"(",
"ctx",
"context",
".",
"Context",
",",
"pfx",
"string",
",",
"doDest",
"bool",
")",
"(",
"<-",
"chan",
"blob",
".",
"SizedRef",
",",
"<-",
"chan",
"error",
")",
"{",
"var",
"e",
... | // doDest is false for source and true for dest. | [
"doDest",
"is",
"false",
"for",
"source",
"and",
"true",
"for",
"dest",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/server/sync.go#L837-L891 | train |
perkeep/perkeep | pkg/server/sync.go | hourlyCompare | func (sh *SyncHandler) hourlyCompare(hourlyBytes uint64) {
ctx := context.TODO()
ticker := time.NewTicker(time.Hour).C
for {
content := make([]byte, 16)
if _, err := rand.Read(content); err != nil {
panic(err)
}
after := blob.RefFromBytes(content).String()
var roundBytes uint64
var roundBlobs int
err := blobserver.EnumerateAllFrom(ctx, sh.from, after, func(sr blob.SizedRef) error {
sh.mu.Lock()
if _, ok := sh.needCopy[sr.Ref]; ok {
sh.mu.Unlock()
return nil // skip blobs in the copy queue
}
sh.mu.Unlock()
if roundBytes+uint64(sr.Size) > hourlyBytes {
return errStopEnumerating
}
blob, size, err := sh.to.(blob.Fetcher).Fetch(ctx, sr.Ref)
if err != nil {
return fmt.Errorf("error fetching %s: %v", sr.Ref, err)
}
if size != sr.Size {
return fmt.Errorf("%s: expected size %d, got %d", sr.Ref, sr.Size, size)
}
h := sr.Ref.Hash()
if _, err := io.Copy(h, blob); err != nil {
return fmt.Errorf("error while reading %s: %v", sr.Ref, err)
}
if !sr.HashMatches(h) {
return fmt.Errorf("expected %s, got %x", sr.Ref, h.Sum(nil))
}
sh.mu.Lock()
sh.comparedBlobs++
sh.comparedBytes += uint64(size)
sh.compLastBlob = sr.Ref.String()
sh.mu.Unlock()
roundBlobs++
roundBytes += uint64(size)
return nil
})
sh.mu.Lock()
if err != nil && err != errStopEnumerating {
sh.compareErrors = append(sh.compareErrors, fmt.Sprintf("%s %v", time.Now(), err))
sh.logf("!! hourly compare error !!: %v", err)
}
sh.comparedRounds++
sh.mu.Unlock()
sh.logf("compared %d blobs (%d bytes)", roundBlobs, roundBytes)
<-ticker
}
} | go | func (sh *SyncHandler) hourlyCompare(hourlyBytes uint64) {
ctx := context.TODO()
ticker := time.NewTicker(time.Hour).C
for {
content := make([]byte, 16)
if _, err := rand.Read(content); err != nil {
panic(err)
}
after := blob.RefFromBytes(content).String()
var roundBytes uint64
var roundBlobs int
err := blobserver.EnumerateAllFrom(ctx, sh.from, after, func(sr blob.SizedRef) error {
sh.mu.Lock()
if _, ok := sh.needCopy[sr.Ref]; ok {
sh.mu.Unlock()
return nil // skip blobs in the copy queue
}
sh.mu.Unlock()
if roundBytes+uint64(sr.Size) > hourlyBytes {
return errStopEnumerating
}
blob, size, err := sh.to.(blob.Fetcher).Fetch(ctx, sr.Ref)
if err != nil {
return fmt.Errorf("error fetching %s: %v", sr.Ref, err)
}
if size != sr.Size {
return fmt.Errorf("%s: expected size %d, got %d", sr.Ref, sr.Size, size)
}
h := sr.Ref.Hash()
if _, err := io.Copy(h, blob); err != nil {
return fmt.Errorf("error while reading %s: %v", sr.Ref, err)
}
if !sr.HashMatches(h) {
return fmt.Errorf("expected %s, got %x", sr.Ref, h.Sum(nil))
}
sh.mu.Lock()
sh.comparedBlobs++
sh.comparedBytes += uint64(size)
sh.compLastBlob = sr.Ref.String()
sh.mu.Unlock()
roundBlobs++
roundBytes += uint64(size)
return nil
})
sh.mu.Lock()
if err != nil && err != errStopEnumerating {
sh.compareErrors = append(sh.compareErrors, fmt.Sprintf("%s %v", time.Now(), err))
sh.logf("!! hourly compare error !!: %v", err)
}
sh.comparedRounds++
sh.mu.Unlock()
sh.logf("compared %d blobs (%d bytes)", roundBlobs, roundBytes)
<-ticker
}
} | [
"func",
"(",
"sh",
"*",
"SyncHandler",
")",
"hourlyCompare",
"(",
"hourlyBytes",
"uint64",
")",
"{",
"ctx",
":=",
"context",
".",
"TODO",
"(",
")",
"\n",
"ticker",
":=",
"time",
".",
"NewTicker",
"(",
"time",
".",
"Hour",
")",
".",
"C",
"\n",
"for",
... | // Every hour, hourlyCompare picks blob names from a random point in the source,
// downloads up to hourlyBytes from the destination, and verifies them. | [
"Every",
"hour",
"hourlyCompare",
"picks",
"blob",
"names",
"from",
"a",
"random",
"point",
"in",
"the",
"source",
"downloads",
"up",
"to",
"hourlyBytes",
"from",
"the",
"destination",
"and",
"verifies",
"them",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/server/sync.go#L1078-L1134 | train |
perkeep/perkeep | pkg/importer/swarm/swarm.go | urlFileRef | func (r *run) urlFileRef(urlstr, filename string) string {
im := r.im
im.mu.Lock()
if br, ok := im.imageFileRef[urlstr]; ok {
im.mu.Unlock()
return br.String()
}
im.mu.Unlock()
if urlstr == "" {
return ""
}
res, err := ctxutil.Client(r.Context()).Get(urlstr)
if err != nil {
log.Printf("swarm: couldn't fetch image %q: %v", urlstr, err)
return ""
}
defer res.Body.Close()
fileRef, err := schema.WriteFileFromReader(r.Context(), r.Host.Target(), filename, res.Body)
if err != nil {
r.errorf("couldn't write file: %v", err)
return ""
}
im.mu.Lock()
defer im.mu.Unlock()
im.imageFileRef[urlstr] = fileRef
return fileRef.String()
} | go | func (r *run) urlFileRef(urlstr, filename string) string {
im := r.im
im.mu.Lock()
if br, ok := im.imageFileRef[urlstr]; ok {
im.mu.Unlock()
return br.String()
}
im.mu.Unlock()
if urlstr == "" {
return ""
}
res, err := ctxutil.Client(r.Context()).Get(urlstr)
if err != nil {
log.Printf("swarm: couldn't fetch image %q: %v", urlstr, err)
return ""
}
defer res.Body.Close()
fileRef, err := schema.WriteFileFromReader(r.Context(), r.Host.Target(), filename, res.Body)
if err != nil {
r.errorf("couldn't write file: %v", err)
return ""
}
im.mu.Lock()
defer im.mu.Unlock()
im.imageFileRef[urlstr] = fileRef
return fileRef.String()
} | [
"func",
"(",
"r",
"*",
"run",
")",
"urlFileRef",
"(",
"urlstr",
",",
"filename",
"string",
")",
"string",
"{",
"im",
":=",
"r",
".",
"im",
"\n",
"im",
".",
"mu",
".",
"Lock",
"(",
")",
"\n",
"if",
"br",
",",
"ok",
":=",
"im",
".",
"imageFileRef... | // urlFileRef slurps urlstr from the net, writes to a file and returns its
// fileref or "" on error or if urlstr was empty. | [
"urlFileRef",
"slurps",
"urlstr",
"from",
"the",
"net",
"writes",
"to",
"a",
"file",
"and",
"returns",
"its",
"fileref",
"or",
"on",
"error",
"or",
"if",
"urlstr",
"was",
"empty",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/swarm/swarm.go#L183-L212 | train |
perkeep/perkeep | pkg/importer/swarm/swarm.go | auth | func auth(ctx *importer.SetupContext) (*oauth2.Config, error) {
clientID, secret, err := ctx.Credentials()
if err != nil {
return nil, err
}
return &oauth2.Config{
ClientID: clientID,
ClientSecret: secret,
Endpoint: oauth2.Endpoint{
AuthURL: authURL,
TokenURL: tokenURL,
},
RedirectURL: ctx.CallbackURL(),
// No scope needed for foursquare as far as I can tell
}, nil
} | go | func auth(ctx *importer.SetupContext) (*oauth2.Config, error) {
clientID, secret, err := ctx.Credentials()
if err != nil {
return nil, err
}
return &oauth2.Config{
ClientID: clientID,
ClientSecret: secret,
Endpoint: oauth2.Endpoint{
AuthURL: authURL,
TokenURL: tokenURL,
},
RedirectURL: ctx.CallbackURL(),
// No scope needed for foursquare as far as I can tell
}, nil
} | [
"func",
"auth",
"(",
"ctx",
"*",
"importer",
".",
"SetupContext",
")",
"(",
"*",
"oauth2",
".",
"Config",
",",
"error",
")",
"{",
"clientID",
",",
"secret",
",",
"err",
":=",
"ctx",
".",
"Credentials",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",... | // auth returns a new oauth2 Config | [
"auth",
"returns",
"a",
"new",
"oauth2",
"Config"
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/importer/swarm/swarm.go#L537-L552 | train |
perkeep/perkeep | pkg/schema/schema.go | mixedArrayFromString | func mixedArrayFromString(s string) (parts []interface{}) {
for len(s) > 0 {
if n := utf8StrLen(s); n > 0 {
parts = append(parts, s[:n])
s = s[n:]
} else {
parts = append(parts, s[0])
s = s[1:]
}
}
return parts
} | go | func mixedArrayFromString(s string) (parts []interface{}) {
for len(s) > 0 {
if n := utf8StrLen(s); n > 0 {
parts = append(parts, s[:n])
s = s[n:]
} else {
parts = append(parts, s[0])
s = s[1:]
}
}
return parts
} | [
"func",
"mixedArrayFromString",
"(",
"s",
"string",
")",
"(",
"parts",
"[",
"]",
"interface",
"{",
"}",
")",
"{",
"for",
"len",
"(",
"s",
")",
">",
"0",
"{",
"if",
"n",
":=",
"utf8StrLen",
"(",
"s",
")",
";",
"n",
">",
"0",
"{",
"parts",
"=",
... | // mixedArrayFromString is the inverse of stringFromMixedArray. It
// splits a string to a series of either UTF-8 strings and non-UTF-8
// bytes. | [
"mixedArrayFromString",
"is",
"the",
"inverse",
"of",
"stringFromMixedArray",
".",
"It",
"splits",
"a",
"string",
"to",
"a",
"series",
"of",
"either",
"UTF",
"-",
"8",
"strings",
"and",
"non",
"-",
"UTF",
"-",
"8",
"bytes",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/schema/schema.go#L400-L411 | train |
perkeep/perkeep | pkg/schema/schema.go | utf8StrLen | func utf8StrLen(s string) int {
for i, r := range s {
for r == utf8.RuneError {
// The RuneError value can be an error
// sentinel value (if it's size 1) or the same
// value encoded properly. Decode it to see if
// it's the 1 byte sentinel value.
_, size := utf8.DecodeRuneInString(s[i:])
if size == 1 {
return i
}
}
}
return len(s)
} | go | func utf8StrLen(s string) int {
for i, r := range s {
for r == utf8.RuneError {
// The RuneError value can be an error
// sentinel value (if it's size 1) or the same
// value encoded properly. Decode it to see if
// it's the 1 byte sentinel value.
_, size := utf8.DecodeRuneInString(s[i:])
if size == 1 {
return i
}
}
}
return len(s)
} | [
"func",
"utf8StrLen",
"(",
"s",
"string",
")",
"int",
"{",
"for",
"i",
",",
"r",
":=",
"range",
"s",
"{",
"for",
"r",
"==",
"utf8",
".",
"RuneError",
"{",
"_",
",",
"size",
":=",
"utf8",
".",
"DecodeRuneInString",
"(",
"s",
"[",
"i",
":",
"]",
... | // utf8StrLen returns how many prefix bytes of s are valid UTF-8. | [
"utf8StrLen",
"returns",
"how",
"many",
"prefix",
"bytes",
"of",
"s",
"are",
"valid",
"UTF",
"-",
"8",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/schema/schema.go#L414-L428 | train |
perkeep/perkeep | pkg/schema/schema.go | FileNameString | func (ss *superset) FileNameString() string {
v := ss.FileName
if v == "" {
v = stringFromMixedArray(ss.FileNameBytes)
}
if v != "" {
if strings.Contains(v, "/") {
// Bogus schema blob; ignore.
return ""
}
if strings.Contains(v, "\\") {
// Bogus schema blob; ignore.
return ""
}
}
return v
} | go | func (ss *superset) FileNameString() string {
v := ss.FileName
if v == "" {
v = stringFromMixedArray(ss.FileNameBytes)
}
if v != "" {
if strings.Contains(v, "/") {
// Bogus schema blob; ignore.
return ""
}
if strings.Contains(v, "\\") {
// Bogus schema blob; ignore.
return ""
}
}
return v
} | [
"func",
"(",
"ss",
"*",
"superset",
")",
"FileNameString",
"(",
")",
"string",
"{",
"v",
":=",
"ss",
".",
"FileName",
"\n",
"if",
"v",
"==",
"\"\"",
"{",
"v",
"=",
"stringFromMixedArray",
"(",
"ss",
".",
"FileNameBytes",
")",
"\n",
"}",
"\n",
"if",
... | // FileNameString returns the schema blob's base filename.
//
// If the fileName field of the blob accidentally or maliciously
// contains a slash, this function returns an empty string instead. | [
"FileNameString",
"returns",
"the",
"schema",
"blob",
"s",
"base",
"filename",
".",
"If",
"the",
"fileName",
"field",
"of",
"the",
"blob",
"accidentally",
"or",
"maliciously",
"contains",
"a",
"slash",
"this",
"function",
"returns",
"an",
"empty",
"string",
"i... | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/schema/schema.go#L448-L464 | train |
perkeep/perkeep | pkg/schema/schema.go | NewUnsignedPermanode | func NewUnsignedPermanode() *Builder {
bb := base(1, "permanode")
chars := make([]byte, 20)
_, err := io.ReadFull(rand.Reader, chars)
if err != nil {
panic("error reading random bytes: " + err.Error())
}
bb.m["random"] = base64.StdEncoding.EncodeToString(chars)
return bb
} | go | func NewUnsignedPermanode() *Builder {
bb := base(1, "permanode")
chars := make([]byte, 20)
_, err := io.ReadFull(rand.Reader, chars)
if err != nil {
panic("error reading random bytes: " + err.Error())
}
bb.m["random"] = base64.StdEncoding.EncodeToString(chars)
return bb
} | [
"func",
"NewUnsignedPermanode",
"(",
")",
"*",
"Builder",
"{",
"bb",
":=",
"base",
"(",
"1",
",",
"\"permanode\"",
")",
"\n",
"chars",
":=",
"make",
"(",
"[",
"]",
"byte",
",",
"20",
")",
"\n",
"_",
",",
"err",
":=",
"io",
".",
"ReadFull",
"(",
"... | // NewUnsignedPermanode returns a new random permanode, not yet signed. | [
"NewUnsignedPermanode",
"returns",
"a",
"new",
"random",
"permanode",
"not",
"yet",
"signed",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/schema/schema.go#L660-L669 | train |
perkeep/perkeep | pkg/schema/schema.go | NewHashPlannedPermanode | func NewHashPlannedPermanode(h hash.Hash) *Builder {
return NewPlannedPermanode(blob.RefFromHash(h).String())
} | go | func NewHashPlannedPermanode(h hash.Hash) *Builder {
return NewPlannedPermanode(blob.RefFromHash(h).String())
} | [
"func",
"NewHashPlannedPermanode",
"(",
"h",
"hash",
".",
"Hash",
")",
"*",
"Builder",
"{",
"return",
"NewPlannedPermanode",
"(",
"blob",
".",
"RefFromHash",
"(",
"h",
")",
".",
"String",
"(",
")",
")",
"\n",
"}"
] | // NewHashPlannedPermanode returns a planned permanode with the sum
// of the hash, prefixed with "sha1-", as the key. | [
"NewHashPlannedPermanode",
"returns",
"a",
"planned",
"permanode",
"with",
"the",
"sum",
"of",
"the",
"hash",
"prefixed",
"with",
"sha1",
"-",
"as",
"the",
"key",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/schema/schema.go#L684-L686 | train |
perkeep/perkeep | pkg/schema/schema.go | PopulateParts | func (bb *Builder) PopulateParts(size int64, parts []BytesPart) error {
return populateParts(bb.m, size, parts)
} | go | func (bb *Builder) PopulateParts(size int64, parts []BytesPart) error {
return populateParts(bb.m, size, parts)
} | [
"func",
"(",
"bb",
"*",
"Builder",
")",
"PopulateParts",
"(",
"size",
"int64",
",",
"parts",
"[",
"]",
"BytesPart",
")",
"error",
"{",
"return",
"populateParts",
"(",
"bb",
".",
"m",
",",
"size",
",",
"parts",
")",
"\n",
"}"
] | // PopulateParts sets the "parts" field of the blob with the provided
// parts. The sum of the sizes of parts must match the provided size
// or an error is returned. Also, each BytesPart may only contain either
// a BytesPart or a BlobRef, but not both. | [
"PopulateParts",
"sets",
"the",
"parts",
"field",
"of",
"the",
"blob",
"with",
"the",
"provided",
"parts",
".",
"The",
"sum",
"of",
"the",
"sizes",
"of",
"parts",
"must",
"match",
"the",
"provided",
"size",
"or",
"an",
"error",
"is",
"returned",
".",
"Al... | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/schema/schema.go#L754-L756 | train |
perkeep/perkeep | pkg/schema/schema.go | NewDelAttributeClaim | func NewDelAttributeClaim(permaNode blob.Ref, attr, value string) *Builder {
return newClaim(&claimParam{
permanode: permaNode,
claimType: DelAttributeClaim,
attribute: attr,
value: value,
})
} | go | func NewDelAttributeClaim(permaNode blob.Ref, attr, value string) *Builder {
return newClaim(&claimParam{
permanode: permaNode,
claimType: DelAttributeClaim,
attribute: attr,
value: value,
})
} | [
"func",
"NewDelAttributeClaim",
"(",
"permaNode",
"blob",
".",
"Ref",
",",
"attr",
",",
"value",
"string",
")",
"*",
"Builder",
"{",
"return",
"newClaim",
"(",
"&",
"claimParam",
"{",
"permanode",
":",
"permaNode",
",",
"claimType",
":",
"DelAttributeClaim",
... | // NewDelAttributeClaim creates a new claim to remove value from the
// values set for the attribute attr of permaNode. If value is empty then
// all the values for attribute are cleared. | [
"NewDelAttributeClaim",
"creates",
"a",
"new",
"claim",
"to",
"remove",
"value",
"from",
"the",
"values",
"set",
"for",
"the",
"attribute",
"attr",
"of",
"permaNode",
".",
"If",
"value",
"is",
"empty",
"then",
"all",
"the",
"values",
"for",
"attribute",
"are... | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/schema/schema.go#L887-L894 | train |
perkeep/perkeep | pkg/schema/schema.go | NewDeleteClaim | func NewDeleteClaim(target blob.Ref) *Builder {
return newClaim(&claimParam{
target: target,
claimType: DeleteClaim,
})
} | go | func NewDeleteClaim(target blob.Ref) *Builder {
return newClaim(&claimParam{
target: target,
claimType: DeleteClaim,
})
} | [
"func",
"NewDeleteClaim",
"(",
"target",
"blob",
".",
"Ref",
")",
"*",
"Builder",
"{",
"return",
"newClaim",
"(",
"&",
"claimParam",
"{",
"target",
":",
"target",
",",
"claimType",
":",
"DeleteClaim",
",",
"}",
")",
"\n",
"}"
] | // NewDeleteClaim creates a new claim to delete a target claim or permanode. | [
"NewDeleteClaim",
"creates",
"a",
"new",
"claim",
"to",
"delete",
"a",
"target",
"claim",
"or",
"permanode",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/schema/schema.go#L897-L902 | train |
perkeep/perkeep | pkg/schema/schema.go | IsZoneKnown | func IsZoneKnown(t time.Time) bool {
if t.Location() == UnknownLocation {
return false
}
if _, off := t.Zone(); off == -60 {
return false
}
return true
} | go | func IsZoneKnown(t time.Time) bool {
if t.Location() == UnknownLocation {
return false
}
if _, off := t.Zone(); off == -60 {
return false
}
return true
} | [
"func",
"IsZoneKnown",
"(",
"t",
"time",
".",
"Time",
")",
"bool",
"{",
"if",
"t",
".",
"Location",
"(",
")",
"==",
"UnknownLocation",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"_",
",",
"off",
":=",
"t",
".",
"Zone",
"(",
")",
";",
"off",
... | // IsZoneKnown reports whether t is in a known timezone.
// Perkeep uses the magic timezone offset of 1 minute west of UTC
// to mean that the timezone wasn't known. | [
"IsZoneKnown",
"reports",
"whether",
"t",
"is",
"in",
"a",
"known",
"timezone",
".",
"Perkeep",
"uses",
"the",
"magic",
"timezone",
"offset",
"of",
"1",
"minute",
"west",
"of",
"UTC",
"to",
"mean",
"that",
"the",
"timezone",
"wasn",
"t",
"known",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/schema/schema.go#L918-L926 | train |
perkeep/perkeep | pkg/server/help.go | SetServerConfig | func (hh *HelpHandler) SetServerConfig(config jsonconfig.Obj) {
if hh.serverConfig == nil {
hh.serverConfig = config
}
} | go | func (hh *HelpHandler) SetServerConfig(config jsonconfig.Obj) {
if hh.serverConfig == nil {
hh.serverConfig = config
}
} | [
"func",
"(",
"hh",
"*",
"HelpHandler",
")",
"SetServerConfig",
"(",
"config",
"jsonconfig",
".",
"Obj",
")",
"{",
"if",
"hh",
".",
"serverConfig",
"==",
"nil",
"{",
"hh",
".",
"serverConfig",
"=",
"config",
"\n",
"}",
"\n",
"}"
] | // SetServerConfig enables the handler to receive the server config
// before InitHandler, which generates a client config from the server config, is called. | [
"SetServerConfig",
"enables",
"the",
"handler",
"to",
"receive",
"the",
"server",
"config",
"before",
"InitHandler",
"which",
"generates",
"a",
"client",
"config",
"from",
"the",
"server",
"config",
"is",
"called",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/server/help.go#L73-L77 | train |
perkeep/perkeep | pkg/client/get.go | UpdateShareChain | func (c *Client) UpdateShareChain(b blob.Ref, r io.Reader) error {
c.viaMu.Lock()
defer c.viaMu.Unlock()
if c.via == nil {
// Not in sharing mode, so return immediately.
return ErrNotSharing
}
// Slurp 1 MB to find references to other blobrefs for the via path.
var buf bytes.Buffer
const maxSlurp = 1 << 20
if _, err := io.Copy(&buf, io.LimitReader(r, maxSlurp)); err != nil {
return err
}
// If it looks like a JSON schema blob (starts with '{')
if schema.LikelySchemaBlob(buf.Bytes()) {
for _, blobstr := range blobsRx.FindAllString(buf.String(), -1) {
br, ok := blob.Parse(blobstr)
if !ok {
c.printf("Invalid blob ref %q noticed in schema of %v", blobstr, b)
continue
}
c.via[br] = b
}
}
return nil
} | go | func (c *Client) UpdateShareChain(b blob.Ref, r io.Reader) error {
c.viaMu.Lock()
defer c.viaMu.Unlock()
if c.via == nil {
// Not in sharing mode, so return immediately.
return ErrNotSharing
}
// Slurp 1 MB to find references to other blobrefs for the via path.
var buf bytes.Buffer
const maxSlurp = 1 << 20
if _, err := io.Copy(&buf, io.LimitReader(r, maxSlurp)); err != nil {
return err
}
// If it looks like a JSON schema blob (starts with '{')
if schema.LikelySchemaBlob(buf.Bytes()) {
for _, blobstr := range blobsRx.FindAllString(buf.String(), -1) {
br, ok := blob.Parse(blobstr)
if !ok {
c.printf("Invalid blob ref %q noticed in schema of %v", blobstr, b)
continue
}
c.via[br] = b
}
}
return nil
} | [
"func",
"(",
"c",
"*",
"Client",
")",
"UpdateShareChain",
"(",
"b",
"blob",
".",
"Ref",
",",
"r",
"io",
".",
"Reader",
")",
"error",
"{",
"c",
".",
"viaMu",
".",
"Lock",
"(",
")",
"\n",
"defer",
"c",
".",
"viaMu",
".",
"Unlock",
"(",
")",
"\n",... | // UpdateShareChain reads the schema of b from r, and instructs the client that
// all blob refs found in this schema should use b as a preceding chain link, in
// all subsequent shared blobs fetches. If the client was not created with
// NewFromShareRoot, ErrNotSharing is returned. | [
"UpdateShareChain",
"reads",
"the",
"schema",
"of",
"b",
"from",
"r",
"and",
"instructs",
"the",
"client",
"that",
"all",
"blob",
"refs",
"found",
"in",
"this",
"schema",
"should",
"use",
"b",
"as",
"a",
"preceding",
"chain",
"link",
"in",
"all",
"subseque... | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/client/get.go#L165-L190 | train |
perkeep/perkeep | pkg/blobserver/archiver/archiver.go | RunOnce | func (a *Archiver) RunOnce(ctx context.Context) error {
if a.Source == nil {
return errors.New("archiver: nil Source")
}
if a.Store == nil {
return errors.New("archiver: nil Store func")
}
pz := &potentialZip{a: a}
err := blobserver.EnumerateAll(ctx, a.Source, func(sb blob.SizedRef) error {
if err := pz.addBlob(ctx, sb); err != nil {
return err
}
if pz.bigEnough() {
return errStopEnumerate
}
return nil
})
if err == errStopEnumerate {
err = nil
}
if err != nil {
return err
}
if err := pz.condClose(); err != nil {
return err
}
if !pz.bigEnough() {
return ErrSourceTooSmall
}
if err := a.Store(pz.buf.Bytes(), pz.blobs); err != nil {
return err
}
if a.DeleteSourceAfterStore {
blobs := make([]blob.Ref, 0, len(pz.blobs))
for _, sb := range pz.blobs {
blobs = append(blobs, sb.Ref)
}
if err := a.Source.RemoveBlobs(ctx, blobs); err != nil {
return err
}
}
return nil
} | go | func (a *Archiver) RunOnce(ctx context.Context) error {
if a.Source == nil {
return errors.New("archiver: nil Source")
}
if a.Store == nil {
return errors.New("archiver: nil Store func")
}
pz := &potentialZip{a: a}
err := blobserver.EnumerateAll(ctx, a.Source, func(sb blob.SizedRef) error {
if err := pz.addBlob(ctx, sb); err != nil {
return err
}
if pz.bigEnough() {
return errStopEnumerate
}
return nil
})
if err == errStopEnumerate {
err = nil
}
if err != nil {
return err
}
if err := pz.condClose(); err != nil {
return err
}
if !pz.bigEnough() {
return ErrSourceTooSmall
}
if err := a.Store(pz.buf.Bytes(), pz.blobs); err != nil {
return err
}
if a.DeleteSourceAfterStore {
blobs := make([]blob.Ref, 0, len(pz.blobs))
for _, sb := range pz.blobs {
blobs = append(blobs, sb.Ref)
}
if err := a.Source.RemoveBlobs(ctx, blobs); err != nil {
return err
}
}
return nil
} | [
"func",
"(",
"a",
"*",
"Archiver",
")",
"RunOnce",
"(",
"ctx",
"context",
".",
"Context",
")",
"error",
"{",
"if",
"a",
".",
"Source",
"==",
"nil",
"{",
"return",
"errors",
".",
"New",
"(",
"\"archiver: nil Source\"",
")",
"\n",
"}",
"\n",
"if",
"a",... | // RunOnce scans a.Source and conditionally creates a new zip.
// It returns ErrSourceTooSmall if there aren't enough blobs on Source. | [
"RunOnce",
"scans",
"a",
".",
"Source",
"and",
"conditionally",
"creates",
"a",
"new",
"zip",
".",
"It",
"returns",
"ErrSourceTooSmall",
"if",
"there",
"aren",
"t",
"enough",
"blobs",
"on",
"Source",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/archiver/archiver.go#L80-L122 | train |
perkeep/perkeep | pkg/blobserver/enumerate.go | EnumerateAll | func EnumerateAll(ctx context.Context, src BlobEnumerator, fn func(blob.SizedRef) error) error {
return EnumerateAllFrom(ctx, src, "", fn)
} | go | func EnumerateAll(ctx context.Context, src BlobEnumerator, fn func(blob.SizedRef) error) error {
return EnumerateAllFrom(ctx, src, "", fn)
} | [
"func",
"EnumerateAll",
"(",
"ctx",
"context",
".",
"Context",
",",
"src",
"BlobEnumerator",
",",
"fn",
"func",
"(",
"blob",
".",
"SizedRef",
")",
"error",
")",
"error",
"{",
"return",
"EnumerateAllFrom",
"(",
"ctx",
",",
"src",
",",
"\"\"",
",",
"fn",
... | // EnumerateAll runs fn for each blob in src.
// If fn returns an error, iteration stops and fn isn't called again.
// EnumerateAll will not return concurrently with fn. | [
"EnumerateAll",
"runs",
"fn",
"for",
"each",
"blob",
"in",
"src",
".",
"If",
"fn",
"returns",
"an",
"error",
"iteration",
"stops",
"and",
"fn",
"isn",
"t",
"called",
"again",
".",
"EnumerateAll",
"will",
"not",
"return",
"concurrently",
"with",
"fn",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/enumerate.go#L29-L31 | train |
perkeep/perkeep | pkg/blobserver/enumerate.go | EnumerateAllFrom | func EnumerateAllFrom(ctx context.Context, src BlobEnumerator, after string, fn func(blob.SizedRef) error) error {
const batchSize = 1000
var mu sync.Mutex // protects returning with an error while fn is still running
errc := make(chan error, 1)
for {
ch := make(chan blob.SizedRef, 16)
n := 0
go func() {
var err error
for sb := range ch {
if err != nil {
continue
}
mu.Lock()
err = fn(sb)
mu.Unlock()
after = sb.Ref.String()
n++
}
errc <- err
}()
err := src.EnumerateBlobs(ctx, ch, after, batchSize)
if err != nil {
mu.Lock() // make sure fn callback finished; no need to unlock
return err
}
if err := <-errc; err != nil {
return err
}
if n == 0 {
return nil
}
}
} | go | func EnumerateAllFrom(ctx context.Context, src BlobEnumerator, after string, fn func(blob.SizedRef) error) error {
const batchSize = 1000
var mu sync.Mutex // protects returning with an error while fn is still running
errc := make(chan error, 1)
for {
ch := make(chan blob.SizedRef, 16)
n := 0
go func() {
var err error
for sb := range ch {
if err != nil {
continue
}
mu.Lock()
err = fn(sb)
mu.Unlock()
after = sb.Ref.String()
n++
}
errc <- err
}()
err := src.EnumerateBlobs(ctx, ch, after, batchSize)
if err != nil {
mu.Lock() // make sure fn callback finished; no need to unlock
return err
}
if err := <-errc; err != nil {
return err
}
if n == 0 {
return nil
}
}
} | [
"func",
"EnumerateAllFrom",
"(",
"ctx",
"context",
".",
"Context",
",",
"src",
"BlobEnumerator",
",",
"after",
"string",
",",
"fn",
"func",
"(",
"blob",
".",
"SizedRef",
")",
"error",
")",
"error",
"{",
"const",
"batchSize",
"=",
"1000",
"\n",
"var",
"mu... | // EnumerateAllFrom is like EnumerateAll, but takes an after parameter. | [
"EnumerateAllFrom",
"is",
"like",
"EnumerateAll",
"but",
"takes",
"an",
"after",
"parameter",
"."
] | e28bbbd1588d64df8ab7a82393afd39d64c061f7 | https://github.com/perkeep/perkeep/blob/e28bbbd1588d64df8ab7a82393afd39d64c061f7/pkg/blobserver/enumerate.go#L34-L67 | train |
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",
"... | // 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",
"(",
"\"docker\"",
",",
"\"pull\"",
",",
"image",
")",
"\n",
"cmd",
".",
"Stdout",
"=",
"&",... | // 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",
... | // 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",
... | // 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",
... | 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",
"==",
... | // 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",
"... | 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",
"!=",
... | // 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",
... | // 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",
".",
"... | // 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",
"(",
"\"starting integrity check...\"",
")",
"\n",
"defer",
"func",
"("... | // 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",... | 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"... | // 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",... | // 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... | // 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",
... | // 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",
... | 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",
... | // 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",
".",
"sign... | // 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",
")",
"{",
"de... | // 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... | // 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",... | // 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",
... | // 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",
... | // 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",
... | // 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",
".",... | // 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",
"var",
"tweetsNode",
"*",
"importer",
".",
"Object",
"\n",
"var"... | // 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",
"userLike... | 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",
"(",
"\"HTTPSKeyFile\"",
",",
"\"\"",
")",
",",
"conf",
".",
"OptionalString",
"(",
"\"HTTPSCertFile\... | // 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",
... | // 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",
... | 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",
"(",
"\"camliNetIP\"",
",",
"\"\"",
")",
"\n",
"c",
".",
"listenAddr",
"=",
"c",
".",
"jconf",
".",
"... | // 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",
"Installer... | 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",
".",
"Erro... | // 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",
... | 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",
".",
"UploadPublicK... | // 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",
":... | // 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",
"(",... | // 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",
"configu... | 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",
"(",
"\"https://%s/%s/\"",
",",
"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",
",",
"\"https://\"",
"+",
"c",
".",
"hostname",
"(",
")",
... | // 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",
... | // 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",
":=... | // 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",
"(",
... | // 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",
... | // 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",
")",
")",
... | // 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",
"(",
"\"azure.%s: status %d, code: %s\"",
",",
"e",
".",
"Op",
",",
"e",
".",
"Code"... | // 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",
"(",
"\"nil argument\"",
")",... | // 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... | // 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",
".",
"attr",
".",
"Mode",
"=",
"meta",
".",
"FileMode",
"(",
")",
"\n",
"if",
"n",
".",
"fs",
".",
"IgnoreOwners",
"{",
"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",
"(",
... | // 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",
"(",
"\"CAMLI_FAST_DEV\"",
")",
")",
";",
"v",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"var",
"ful... | // 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",
... | // 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"... | // 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",... | // 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"... | // 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"... | // 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",
".... | // 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",
"]",... | // 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",
"==",
... | // 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",
"[",
... | // 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",
",",
"\"VERSION\"",
")",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"strings",
".",
"TrimSpace"... | // 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",
"(",
"\"git\"",
",",
"\"rev-list\"",
",",
"\"--max-count=1\"",
",",
"\"--pretty=format:'%ad-%h'\"",
",",
"\"--date=short\"",
",",
"\"--abbrev=10\"",
",",
"\"HEAD\"",
")",
"\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... | 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",
... | // 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",
... | 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",
... | // 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",
... | 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"... | // 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",
"... | 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",
",",
"U... | // 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",
"=",
"\"Listen address\"",
"\n",
"}",
"\n",
"if",
"!",
"strings",
".",
"HasSuffix",
"(",
"name",
",",
"\" address\"",
")",
"{",
"name",
"+=",
"\" addre... | // 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",
")",
"{",
"if",
"a",
".",
"err",
"==",
"nil",
"&&",
"a",
".",
"ln",
"==",
"nil",
"&&",
"a",
".",
"s",
"!=",
"\"\"",
"{",
"if",
"err",
":=",
... | // 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",
":... | // 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",
",",
"... | // 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"... | // 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",
"}",
... | // 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",
")",
"{",
"fi",
",",
"err",
":=",
"os",
".",
"Stat",
"(",
"root",
")",
"\n",
"if",
"os",
".",
"IsNotExist",
"(",
"err",
")",
"{",
"if",
"filepath",
".",
"Base",
"... | // 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",
";",
"... | // 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"... | // 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",
... | // 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",... | // 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",
"... | // 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",
".",
"Fi... | // 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",
... | 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",
".",
"RUnlo... | // 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",
".",
"KeyIdStri... | // 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.