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 if err := repo.StoreConfig("user.name", "testuser"); err != nil {
35 log.Fatal("failed to set user.name for test repository: ", err)
36 }
37 if err := repo.StoreConfig("user.email", "testuser@example.com"); err != nil {
38 log.Fatal("failed to set user.email for test repository: ", err)
39 }
40
41 return repo
42}
43
44func CleanupTestRepos(t testing.TB, repos ...Repo) {
45 var firstErr error
46 for _, repo := range repos {
47 path := repo.GetPath()
48 if strings.HasSuffix(path, "/.git") {
49 // for a normal repository (not --bare), we want to remove everything
50 // including the parent directory where files are checked out
51 path = strings.TrimSuffix(path, "/.git")
52
53 // Testing non-bare repo should also check path is
54 // only .git (i.e. ./.git), but doing so, we should
55 // try to remove the current directory and hav some
56 // trouble. In the present case, this case should not
57 // occur.
58 // TODO consider warning or error when path == ".git"
59 }
60 // fmt.Println("Cleaning repo:", path)
61 err := os.RemoveAll(path)
62 if err != nil {
63 log.Println(err)
64 if firstErr == nil {
65 firstErr = err
66 }
67 }
68 }
69
70 if firstErr != nil {
71 t.Fatal(firstErr)
72 }
73}
74
75func SetupReposAndRemote(t testing.TB) (repoA, repoB, remote *GitRepo) {
76 repoA = CreateTestRepo(false)
77 repoB = CreateTestRepo(false)
78 remote = CreateTestRepo(true)
79
80 remoteAddr := "file://" + remote.GetPath()
81
82 err := repoA.AddRemote("origin", remoteAddr)
83 if err != nil {
84 t.Fatal(err)
85 }
86
87 err = repoB.AddRemote("origin", remoteAddr)
88 if err != nil {
89 t.Fatal(err)
90 }
91
92 return repoA, repoB, remote
93}