github.com/stevenmatthewt/agent@v3.5.4+incompatible/bootstrap/integration/git.go (about) 1 package integration 2 3 import ( 4 "fmt" 5 "io/ioutil" 6 "os" 7 "os/exec" 8 "path/filepath" 9 ) 10 11 func createTestGitRespository() (*gitRepository, error) { 12 repo, err := newGitRepository() 13 if err != nil { 14 return nil, err 15 } 16 17 if err := ioutil.WriteFile(filepath.Join(repo.Path, "test.txt"), []byte("This is a test"), 0600); err != nil { 18 return nil, err 19 } 20 21 if err = repo.Add("test.txt"); err != nil { 22 return nil, err 23 } 24 25 if err = repo.Commit("Initial Commit"); err != nil { 26 return nil, err 27 } 28 29 return repo, nil 30 } 31 32 type gitRepository struct { 33 Path string 34 } 35 36 func newGitRepository() (*gitRepository, error) { 37 tempDir, err := ioutil.TempDir("", "git-repo") 38 if err != nil { 39 return nil, fmt.Errorf("Error creating temp dir: %v", err) 40 } 41 42 gr := &gitRepository{Path: tempDir} 43 gitErr := gr.ExecuteAll([][]string{ 44 {"init"}, 45 {"config", "user.email", "you@example.com"}, 46 {"config", "user.name", "Your Name"}, 47 }) 48 49 return gr, gitErr 50 } 51 52 func (gr *gitRepository) Add(path string) error { 53 if _, err := gr.Execute("add", path); err != nil { 54 return err 55 } 56 return nil 57 } 58 59 func (gr *gitRepository) Commit(message string, params ...interface{}) error { 60 if _, err := gr.Execute("commit", "-m", fmt.Sprintf(message, params...)); err != nil { 61 return err 62 } 63 return nil 64 } 65 66 func (gr *gitRepository) Close() error { 67 return os.RemoveAll(gr.Path) 68 } 69 70 func (gr *gitRepository) Execute(args ...string) (string, error) { 71 path, err := exec.LookPath("git") 72 if err != nil { 73 return "", err 74 } 75 cmd := exec.Command(path, args...) 76 cmd.Dir = gr.Path 77 // log.Printf("$ git %v", args) 78 out, err := cmd.CombinedOutput() 79 // log.Printf("Result: %v %s", err, out) 80 return string(out), err 81 } 82 83 func (gr *gitRepository) ExecuteAll(argsSlice [][]string) error { 84 for _, args := range argsSlice { 85 if _, err := gr.Execute(args...); err != nil { 86 return err 87 } 88 } 89 return nil 90 } 91 92 func (gr *gitRepository) RevParse(rev string) (string, error) { 93 return gr.Execute("rev-parse", rev) 94 }