Skip to content

Commit 965f270

Browse files
committed
repo fork: reuse existing git remote
Avoid adding a new git remote for a fork if an existing remote is found that points to the exact forked repo.
1 parent 0f98d56 commit 965f270

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

command/repo.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,15 @@ func repoFork(cmd *cobra.Command, args []string) error {
328328
}
329329

330330
if inParent {
331+
remotes, err := ctx.Remotes()
332+
if err != nil {
333+
return err
334+
}
335+
if remote, err := remotes.FindByRepo(forkedRepo.RepoOwner(), forkedRepo.RepoName()); err == nil {
336+
fmt.Fprintf(out, "%s Using existing remote %s\n", greenCheck, utils.Bold(remote.Name))
337+
return nil
338+
}
339+
331340
remoteDesired := remotePref == "true"
332341
if remotePref == "prompt" {
333342
err = Confirm("Would you like to add a remote for the fork?", &remoteDesired)

command/repo_test.go

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,31 @@ func TestRepoFork_already_forked(t *testing.T) {
4040
}
4141
}
4242

43+
func TestRepoFork_reuseRemote(t *testing.T) {
44+
initContext = func() context.Context {
45+
ctx := context.NewBlank()
46+
ctx.SetBaseRepo("OWNER/REPO")
47+
ctx.SetBranch("master")
48+
ctx.SetRemotes(map[string]string{
49+
"upstream": "OWNER/REPO",
50+
"origin": "someone/REPO",
51+
})
52+
return ctx
53+
}
54+
http := initFakeHTTP()
55+
http.StubRepoResponse("OWNER", "REPO")
56+
defer http.StubWithFixture(200, "forkResult.json")()
57+
58+
output, err := RunCommand(repoForkCmd, "repo fork")
59+
if err != nil {
60+
t.Errorf("got unexpected error: %v", err)
61+
}
62+
if !strings.Contains(output.String(), "Using existing remote origin") {
63+
t.Errorf("output did not match: %q", output)
64+
return
65+
}
66+
}
67+
4368
func stubSince(d time.Duration) func() {
4469
originalSince := Since
4570
Since = func(t time.Time) time.Duration {
@@ -579,7 +604,6 @@ func TestRepoCreate_orgWithTeam(t *testing.T) {
579604
}
580605
}
581606

582-
583607
func TestRepoView(t *testing.T) {
584608
initBlankContext("OWNER/REPO", "master")
585609
http := initFakeHTTP()

0 commit comments

Comments
 (0)