fork of https://github.com/sourcegraph/zoekt
1package gitindex
2
3import (
4 "context"
5 "fmt"
6 "os"
7 "os/exec"
8 "path/filepath"
9 "reflect"
10 "testing"
11
12 "github.com/sourcegraph/zoekt"
13 "github.com/sourcegraph/zoekt/index"
14 "github.com/sourcegraph/zoekt/internal/shards"
15 "github.com/sourcegraph/zoekt/query"
16)
17
18func createSourcegraphignoreRepo(dir string) error {
19 if err := os.MkdirAll(dir, 0o755); err != nil {
20 return err
21 }
22 script := `mkdir repo
23cd repo
24git init -b master
25mkdir subdir
26echo acont > afile
27echo sub-cont > subdir/sub-file
28git add afile subdir/sub-file
29git config user.email "you@example.com"
30git config user.name "Your Name"
31git commit -am amsg
32
33git branch branchdir/abranch
34
35mkdir .sourcegraph
36echo subdir/ > .sourcegraph/ignore
37git add .sourcegraph/ignore
38git commit -am "ignore subdir/"
39
40git update-ref refs/meta/config HEAD
41`
42 cmd := exec.Command("/bin/sh", "-euxc", script)
43 cmd.Dir = dir
44 if out, err := cmd.CombinedOutput(); err != nil {
45 return fmt.Errorf("execution error: %v, output %s", err, out)
46 }
47 return nil
48}
49
50func TestIgnore(t *testing.T) {
51 dir := t.TempDir()
52
53 if err := createSourcegraphignoreRepo(dir); err != nil {
54 t.Fatalf("createSourcegraphignoreRepo: %v", err)
55 }
56
57 indexDir := t.TempDir()
58
59 buildOpts := index.Options{
60 IndexDir: indexDir,
61 RepositoryDescription: zoekt.Repository{
62 Name: "repo",
63 },
64 }
65 buildOpts.SetDefaults()
66
67 opts := Options{
68 RepoDir: filepath.Join(dir + "/repo"),
69 BuildOptions: buildOpts,
70 BranchPrefix: "refs/heads",
71 Branches: []string{"master", "branchdir/*"},
72 Submodules: true,
73 Incremental: true,
74 }
75 if _, err := IndexGitRepo(opts); err != nil {
76 t.Fatalf("IndexGitRepo: %v", err)
77 }
78
79 searcher, err := shards.NewDirectorySearcher(indexDir)
80 if err != nil {
81 t.Fatal("NewDirectorySearcher", err)
82 }
83 defer searcher.Close()
84
85 res, err := searcher.Search(context.Background(), &query.Substring{}, &zoekt.SearchOptions{})
86 if err != nil {
87 t.Fatal(err)
88 }
89
90 if len(res.Files) != 3 {
91 t.Fatalf("expected 3 file matches")
92 }
93 for _, match := range res.Files {
94 switch match.FileName {
95 case "afile":
96 if !reflect.DeepEqual(match.Branches, []string{"master", "branchdir/abranch"}) {
97 t.Fatalf("expected afile to be present on both branches")
98 }
99 case "subdir/sub-file":
100 if len(match.Branches) != 1 || match.Branches[0] != "branchdir/abranch" {
101 t.Fatalf("expected sub-file to be present only on branchdir/abranch")
102 }
103 case ".sourcegraph/ignore":
104 if len(match.Branches) != 1 || match.Branches[0] != "master" {
105 t.Fatalf("expected sourcegraphignore to be present only on master")
106 }
107 default:
108 t.Fatalf("match %+v not handled", match)
109 }
110 }
111}