forked from mislav/hub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fork.go
92 lines (75 loc) · 2.15 KB
/
fork.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package commands
import (
"fmt"
"os"
"github.com/github/hub/github"
"github.com/github/hub/utils"
)
var cmdFork = &Command{
Run: fork,
Usage: "fork [--no-remote]",
Long: `Fork the current project on GitHub and add a git remote for it.
## Options:
--no-remote
Skip adding a git remote for the fork.
## Examples:
$ hub fork
[ repo forked on GitHub ]
> git remote add -f USER git@github.com:USER/REPO.git
## See also:
hub-clone(1), hub(1)
`,
}
var flagForkNoRemote bool
func init() {
cmdFork.Flag.BoolVar(&flagForkNoRemote, "no-remote", false, "")
CmdRunner.Use(cmdFork)
}
func fork(cmd *Command, args *Args) {
localRepo, err := github.LocalRepo()
utils.Check(err)
project, err := localRepo.MainProject()
if err != nil {
utils.Check(fmt.Errorf("Error: repository under 'origin' remote is not a GitHub project"))
}
config := github.CurrentConfig()
host, err := config.PromptForHost(project.Host)
if err != nil {
utils.Check(github.FormatError("forking repository", err))
}
originRemote, err := localRepo.OriginRemote()
if err != nil {
utils.Check(fmt.Errorf("Error creating fork: %s", err))
}
forkProject := github.NewProject(host.User, project.Name, project.Host)
newRemoteName := forkProject.Owner
client := github.NewClient(project.Host)
existingRepo, err := client.Repository(forkProject)
if err == nil {
var parentURL *github.URL
if parent := existingRepo.Parent; parent != nil {
parentURL, _ = github.ParseURL(parent.HTMLURL)
}
if parentURL == nil || !project.SameAs(parentURL.Project) {
err = fmt.Errorf("Error creating fork: %s already exists on %s",
forkProject, forkProject.Host)
utils.Check(err)
}
} else {
if !args.Noop {
newRepo, err := client.ForkRepository(project)
utils.Check(err)
forkProject.Owner = newRepo.Owner.Login
forkProject.Name = newRepo.Name
}
}
if flagForkNoRemote {
os.Exit(0)
} else {
originURL := originRemote.URL.String()
url := forkProject.GitURL("", "", true)
args.Replace("git", "remote", "add", "-f", newRemoteName, originURL)
args.After("git", "remote", "set-url", newRemoteName, url)
args.After("echo", fmt.Sprintf("new remote: %s", newRemoteName))
}
}