forked from owenthereal/gh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fork.go
72 lines (61 loc) · 1.73 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
package commands
import (
"fmt"
"github.com/jingweno/gh/github"
"github.com/jingweno/gh/utils"
"os"
"reflect"
)
var cmdFork = &Command{
Run: fork,
Usage: "fork [--no-remote]",
Short: "Make a fork of a remote repository on GitHub and add as remote",
Long: `Forks the original project (referenced by "origin" remote) on GitHub and
adds a new remote for it under your username.
`,
}
var flagForkNoRemote bool
func init() {
cmdFork.Flag.BoolVar(&flagForkNoRemote, "no-remote", false, "")
CmdRunner.Use(cmdFork)
}
/*
$ gh fork
[ repo forked on GitHub ]
> git remote add -f YOUR_USER git@github.com:YOUR_USER/CURRENT_REPO.git
$ gh fork --no-remote
[ repo forked on GitHub ]
*/
func fork(cmd *Command, args *Args) {
localRepo := github.LocalRepo()
project, err := localRepo.MainProject()
utils.Check(err)
configs := github.CurrentConfigs()
credentials := configs.PromptFor(project.Host)
forkProject := github.NewProject(credentials.User, project.Name, project.Host)
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 || !reflect.DeepEqual(parentURL.Project, project) {
err = fmt.Errorf("Error creating fork: %s already exists on %s",
forkProject, forkProject.Host)
utils.Check(err)
}
} else {
if !args.Noop {
_, err := client.ForkRepository(project)
utils.Check(err)
}
}
if flagForkNoRemote {
os.Exit(0)
} else {
u := forkProject.GitURL("", "", true)
args.Replace("git", "remote", "add", "-f", forkProject.Owner, u)
args.After("echo", fmt.Sprintf("new remote: %s", forkProject.Owner))
}
}