fork of https://github.com/sourcegraph/zoekt
1package main
2
3import (
4 "context"
5 "os"
6 "path/filepath"
7 "strings"
8
9 "go.uber.org/multierr"
10
11 "github.com/sourcegraph/zoekt/index"
12 "github.com/sourcegraph/zoekt/internal/tenant"
13)
14
15// purgeTenantShards removes all simple shards from dir on a best-effort basis.
16// It returns an error if there is no tenant in the context or if it encounters
17// an error while removing a shard.
18func purgeTenantShards(ctx context.Context, dir string) error {
19 tnt, err := tenant.FromContext(ctx)
20 if err != nil {
21 return err
22 }
23
24 d, err := os.Open(dir)
25 if err != nil {
26 return err
27 }
28 defer d.Close()
29
30 names, err := d.Readdirnames(-1)
31 if err != nil {
32 return err
33 }
34
35 var merr error
36 for _, n := range names {
37 path := filepath.Join(dir, n)
38 fi, err := os.Stat(path)
39 if err != nil {
40 merr = multierr.Append(merr, err)
41 continue
42 }
43 if fi.IsDir() || filepath.Ext(path) != ".zoekt" {
44 continue
45 }
46
47 // Skip compound shards.
48 if strings.HasPrefix(filepath.Base(path), "compound-") {
49 continue
50 }
51
52 repos, _, err := index.ReadMetadataPath(path)
53 if err != nil {
54 merr = multierr.Append(merr, err)
55 continue
56 }
57 // Since we excluded compound shards, we know there is exactly one repo
58 if repos[0].TenantID == tnt.ID() {
59 paths, err := index.IndexFilePaths(path)
60 if err != nil {
61 merr = multierr.Append(merr, err)
62 continue
63 }
64 for _, p := range paths {
65 if err := os.Remove(p); err != nil {
66 merr = multierr.Append(merr, err)
67 }
68 }
69 }
70 }
71
72 return merr
73}