Skip to content
This repository has been archived by the owner on Mar 16, 2024. It is now read-only.

Commit

Permalink
Check if dir is a git repo before adding remote in it (#2245) (#2249)
Browse files Browse the repository at this point in the history
Signed-off-by: Oscar Ward <[email protected]>
  • Loading branch information
Oscar Ward authored Oct 17, 2023
1 parent bedfa29 commit 87ccaa2
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion pkg/vcs/vcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,10 @@ func ImageInfoFromApp(ctx context.Context, app *apiv1.App, cloneDir string) (str
func getRemoteRepo(ctx context.Context, workdir string, vcs v1.VCS, idx int) error {
remote := vcs.Remotes[idx]
remoteName := fmt.Sprintf("remote%d", idx)
fullPath, err := filepath.Abs(workdir)
if err != nil {
return err
}

// Check for the directory we want to use
f, err := os.Open(workdir)
Expand All @@ -136,12 +140,18 @@ func getRemoteRepo(ctx context.Context, workdir string, vcs v1.VCS, idx int) err
_, err = f.ReadDir(1)
if err != nil {
// Directory is empty, clone the repo
fmt.Printf("Cloning into empty directory %q\n", fullPath)
err = gitClone(ctx, workdir, remote)
if err != nil {
return err
}
} else {
// Directory is not empty, we assume it already exists, add a new remote and try to fetch
// Directory is not empty, check that it's a repo, add a new remote and try to fetch
fmt.Printf("Fetching into existing directory %q\n", fullPath)
err = gitCheckRepo(ctx, workdir)
if err != nil {
return err
}
err = gitRemoteAdd(ctx, workdir, remoteName, remote)
if err != nil {
return err
Expand All @@ -153,6 +163,7 @@ func getRemoteRepo(ctx context.Context, workdir string, vcs v1.VCS, idx int) err
}
} else if os.IsNotExist(err) {
// Directory does not exist, just clone to create it
fmt.Printf("Cloning into new directory %q\n", fullPath)
err = gitClone(ctx, workdir, remote)
if err != nil {
return err
Expand Down Expand Up @@ -181,6 +192,16 @@ func gitClone(ctx context.Context, workdir, remote string) (err error) {
return
}

func gitCheckRepo(ctx context.Context, workdir string) (err error) {
args := []string{"-C", workdir, "rev-parse"}
cmd := exec.CommandContext(ctx, "git", args...)
cmdErr := cmd.Run()
if cmdErr != nil {
err = fmt.Errorf("directory %q is not empty and is not a git repository", workdir)
}
return
}

func gitRemoteAdd(ctx context.Context, workdir, remoteName, remote string) (err error) {
args := []string{"-C", workdir, "remote", "add", remoteName, remote}
cmd := exec.CommandContext(ctx, "git", args...)
Expand Down

0 comments on commit 87ccaa2

Please sign in to comment.