1package repository
2
3import (
4 "io/ioutil"
5 "log"
6 "os"
7 "strings"
8 "testing"
9)
10
11// This is intended for testing only
12
13func CreateTestRepo(bare bool) *GitRepo {
14 dir, err := ioutil.TempDir("", "")
15 if err != nil {
16 log.Fatal(err)
17 }
18
19 // fmt.Println("Creating repo:", dir)
20
21 var creator func(string) (*GitRepo, error)
22
23 if bare {
24 creator = InitBareGitRepo
25 } else {
26 creator = InitGitRepo
27 }
28
29 repo, err := creator(dir)
30 if err != nil {
31 log.Fatal(err)
32 }
33
34 config := repo.LocalConfig()
35 if err := config.Store("user.name", "testuser"); err != nil {
36 log.Fatal("failed to set user.name for test repository: ", err)
37 }
38 if err := config.Store("user.email", "testuser@example.com"); err != nil {
39 log.Fatal("failed to set user.email for test repository: ", err)
40 }
41
42 return repo
43}
44
45func CleanupTestRepos(t testing.TB, repos ...Repo) {
46 var firstErr error
47 for _, repo := range repos {
48 path := repo.GetPath()
49 if strings.HasSuffix(path, "/.git") {
50 // for a normal repository (not --bare), we want to remove everything
51 // including the parent directory where files are checked out
52 path = strings.TrimSuffix(path, "/.git")
53
54 // Testing non-bare repo should also check path is
55 // only .git (i.e. ./.git), but doing so, we should
56 // try to remove the current directory and hav some
57 // trouble. In the present case, this case should not
58 // occur.
59 // TODO consider warning or error when path == ".git"
60 }
61 // fmt.Println("Cleaning repo:", path)
62 err := os.RemoveAll(path)
63 if err != nil {
64 log.Println(err)
65 if firstErr == nil {
66 firstErr = err
67 }
68 }
69 }
70
71 if firstErr != nil {
72 t.Fatal(firstErr)
73 }
74}
75
76func SetupReposAndRemote(t testing.TB) (repoA, repoB, remote *GitRepo) {
77 repoA = CreateTestRepo(false)
78 repoB = CreateTestRepo(false)
79 remote = CreateTestRepo(true)
80
81 remoteAddr := "file://" + remote.GetPath()
82
83 err := repoA.AddRemote("origin", remoteAddr)
84 if err != nil {
85 t.Fatal(err)
86 }
87
88 err = repoB.AddRemote("origin", remoteAddr)
89 if err != nil {
90 t.Fatal(err)
91 }
92
93 return repoA, repoB, remote
94}