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