github.com/echohead/hub@v2.2.1+incompatible/fixtures/test_repo.go (about) 1 package fixtures 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "os" 7 "path/filepath" 8 9 "github.com/github/hub/cmd" 10 ) 11 12 var pwd, home string 13 14 func init() { 15 // caching `pwd` and $HOME and reset them after test repo is teared down 16 // `pwd` is changed to the bin temp dir during test run 17 pwd, _ = os.Getwd() 18 home = os.Getenv("HOME") 19 } 20 21 type TestRepo struct { 22 pwd string 23 dir string 24 home string 25 Remote string 26 } 27 28 func (r *TestRepo) Setup() { 29 dir, err := ioutil.TempDir("", "test-repo") 30 if err != nil { 31 panic(err) 32 } 33 r.dir = dir 34 35 os.Setenv("HOME", r.dir) 36 37 targetPath := filepath.Join(r.dir, "test.git") 38 err = r.clone(r.Remote, targetPath) 39 if err != nil { 40 panic(err) 41 } 42 43 err = os.Chdir(targetPath) 44 if err != nil { 45 panic(err) 46 } 47 } 48 49 func (r *TestRepo) clone(repo, dir string) error { 50 cmd := cmd.New("git").WithArgs("clone", repo, dir) 51 output, err := cmd.CombinedOutput() 52 if err != nil { 53 err = fmt.Errorf("error cloning %s to %s: %s", repo, dir, output) 54 } 55 56 return err 57 } 58 59 func (r *TestRepo) TearDown() { 60 err := os.Chdir(r.pwd) 61 if err != nil { 62 panic(err) 63 } 64 65 os.Setenv("HOME", r.home) 66 67 err = os.RemoveAll(r.dir) 68 if err != nil { 69 panic(err) 70 } 71 72 } 73 74 func SetupTestRepo() *TestRepo { 75 remotePath := filepath.Join(pwd, "..", "fixtures", "test.git") 76 repo := &TestRepo{pwd: pwd, home: home, Remote: remotePath} 77 repo.Setup() 78 79 return repo 80 }