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/query"
15 "github.com/sourcegraph/zoekt/search"
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 t.Parallel()
52
53 dir := t.TempDir()
54
55 if err := createSourcegraphignoreRepo(dir); err != nil {
56 t.Fatalf("createSourcegraphignoreRepo: %v", err)
57 }
58
59 indexDir := t.TempDir()
60
61 buildOpts := index.Options{
62 IndexDir: indexDir,
63 RepositoryDescription: zoekt.Repository{
64 Name: "repo",
65 },
66 }
67 buildOpts.SetDefaults()
68
69 opts := Options{
70 RepoDir: filepath.Join(dir + "/repo"),
71 BuildOptions: buildOpts,
72 BranchPrefix: "refs/heads",
73 Branches: []string{"master", "branchdir/*"},
74 Submodules: true,
75 Incremental: true,
76 }
77 if _, err := IndexGitRepo(opts); err != nil {
78 t.Fatalf("IndexGitRepo: %v", err)
79 }
80
81 searcher, err := search.NewDirectorySearcher(indexDir)
82 if err != nil {
83 t.Fatal("NewDirectorySearcher", err)
84 }
85 defer searcher.Close()
86
87 res, err := searcher.Search(context.Background(), &query.Substring{}, &zoekt.SearchOptions{})
88 if err != nil {
89 t.Fatal(err)
90 }
91
92 if len(res.Files) != 3 {
93 t.Fatalf("expected 3 file matches")
94 }
95 for _, match := range res.Files {
96 switch match.FileName {
97 case "afile":
98 if !reflect.DeepEqual(match.Branches, []string{"master", "branchdir/abranch"}) {
99 t.Fatalf("expected afile to be present on both branches")
100 }
101 case "subdir/sub-file":
102 if len(match.Branches) != 1 || match.Branches[0] != "branchdir/abranch" {
103 t.Fatalf("expected sub-file to be present only on branchdir/abranch")
104 }
105 case ".sourcegraph/ignore":
106 if len(match.Branches) != 1 || match.Branches[0] != "master" {
107 t.Fatalf("expected sourcegraphignore to be present only on master")
108 }
109 default:
110 t.Fatalf("match %+v not handled", match)
111 }
112 }
113}