diff options
author | Colton McCurdy <mccurdyc22@gmail.com> | 2018-11-01 08:01:34 -0400 |
---|---|---|
committer | Colton McCurdy <mccurdyc22@gmail.com> | 2018-11-01 08:01:34 -0400 |
commit | 3fe6f65a9955d25d51d195d5d4ce43339c813534 (patch) | |
tree | 5b1f0168b856665a1fb2a9eabab3af4bb056e28f /repository.go | |
parent | 43d4551b4b6e49af1a1402047b3a81fbcd6a85e9 (diff) | |
parent | 959dc01faa3352c0b41ff0fa257239f5f00165db (diff) | |
download | go-git-3fe6f65a9955d25d51d195d5d4ce43339c813534.tar.gz |
Merge branch 'master' of github.com:src-d/go-git into mccurdyc/Issue#969/fix-flaky-ssh-test
Diffstat (limited to 'repository.go')
-rw-r--r-- | repository.go | 72 |
1 files changed, 71 insertions, 1 deletions
diff --git a/repository.go b/repository.go index 507ff44..9420af9 100644 --- a/repository.go +++ b/repository.go @@ -5,6 +5,7 @@ import ( "context" "errors" "fmt" + "io" stdioutil "io/ioutil" "os" "path" @@ -342,12 +343,22 @@ func PlainClone(path string, isBare bool, o *CloneOptions) (*Repository, error) // // TODO(mcuadros): move isBare to CloneOptions in v5 func PlainCloneContext(ctx context.Context, path string, isBare bool, o *CloneOptions) (*Repository, error) { + dirExists, err := checkExistsAndIsEmptyDir(path) + if err != nil { + return nil, err + } + r, err := PlainInit(path, isBare) if err != nil { return nil, err } - return r, r.clone(ctx, o) + err = r.clone(ctx, o) + if err != nil && err != ErrRepositoryAlreadyExists { + cleanUpDir(path, !dirExists) + } + + return r, err } func newRepository(s storage.Storer, worktree billy.Filesystem) *Repository { @@ -358,6 +369,65 @@ func newRepository(s storage.Storer, worktree billy.Filesystem) *Repository { } } +func checkExistsAndIsEmptyDir(path string) (exists bool, err error) { + fi, err := os.Stat(path) + if err != nil { + if os.IsNotExist(err) { + return false, nil + } + + return false, err + } + + if !fi.IsDir() { + return false, fmt.Errorf("path is not a directory: %s", path) + } + + f, err := os.Open(path) + if err != nil { + return false, err + } + + defer ioutil.CheckClose(f, &err) + + _, err = f.Readdirnames(1) + if err == io.EOF { + return true, nil + } + + if err != nil { + return true, err + } + + return true, fmt.Errorf("directory is not empty: %s", path) +} + +func cleanUpDir(path string, all bool) error { + if all { + return os.RemoveAll(path) + } + + f, err := os.Open(path) + if err != nil { + return err + } + + defer ioutil.CheckClose(f, &err) + + names, err := f.Readdirnames(-1) + if err != nil { + return err + } + + for _, name := range names { + if err := os.RemoveAll(filepath.Join(path, name)); err != nil { + return err + } + } + + return nil +} + // Config return the repository config func (r *Repository) Config() (*config.Config, error) { return r.Storer.Config() |