github.com/erikjuhani/git-gong@v0.0.0-20220213141213-6b9fa82d4e7c/gong/gong.go (about) 1 package gong 2 3 import ( 4 "errors" 5 "fmt" 6 "io/ioutil" 7 "os" 8 "strings" 9 ) 10 11 var ( 12 ErrNothingToCommit = errors.New("nothing to commit") 13 ) 14 15 var ( 16 DefaultReference = "main" 17 ) 18 19 const ( 20 headRef = "refs/heads/" 21 ) 22 23 func TestRepo() (*testRepository, func(), error) { 24 path, err := ioutil.TempDir("", "gong") 25 if err != nil { 26 return nil, nil, err 27 } 28 29 repo, err := Init(path, false, "") 30 if err != nil { 31 return nil, nil, err 32 } 33 34 return &testRepository{repo}, cleanup(repo), nil 35 } 36 37 // TODO: Move this somewhere more appropriate 38 func checkEmptyString(str string) bool { 39 return len(strings.TrimSpace(str)) == 0 40 } 41 42 type freer interface { 43 Free() 44 } 45 46 // Free function frees memory for any struct that implements a Free() function. 47 // This is an utility functionality to free pointers from memory from the underlying libgit. 48 func Free(f freer) { 49 f.Free() 50 } 51 52 type testRepository struct { 53 *Repository 54 } 55 56 func (repo *testRepository) Seed(commitMsg string, files ...string) (*Commit, error) { 57 if len(files) == 0 { 58 files = []string{"README.md", "gongo-bongo.go"} 59 } 60 61 for _, f := range files { 62 path := fmt.Sprintf("%s/%s", repo.Path, f) 63 if err := ioutil.WriteFile(path, []byte("temp\n"), 0644); err != nil { 64 return nil, err 65 } 66 } 67 68 tree, err := repo.AddToIndex(files) 69 if err != nil { 70 return nil, err 71 } 72 defer Free(tree) 73 74 return repo.CreateCommit(tree, commitMsg) 75 } 76 77 func cleanup(r *Repository) func() { 78 return func() { 79 if err := os.RemoveAll(r.Path); err != nil { 80 panic(err) 81 } 82 } 83 }