github.com/nkprince007/lab@v0.6.2-0.20171218071646-19d68b56f403/cmd/fork.go (about)

     1  package cmd
     2  
     3  import (
     4  	"log"
     5  	"strings"
     6  
     7  	"github.com/spf13/cobra"
     8  	"github.com/tcnksm/go-gitconfig"
     9  	"github.com/zaquestion/lab/internal/git"
    10  	lab "github.com/zaquestion/lab/internal/gitlab"
    11  )
    12  
    13  // forkCmd represents the fork command
    14  var forkCmd = &cobra.Command{
    15  	Use:   "fork",
    16  	Short: "Fork a remote repository on GitLab and add as remote",
    17  	Long:  ``,
    18  	Args:  cobra.MaximumNArgs(1),
    19  	Run: func(cmd *cobra.Command, args []string) {
    20  		if len(args) == 1 {
    21  			forkToUpstream(cmd, args)
    22  			return
    23  		}
    24  		forkFromOrigin(cmd, args)
    25  	},
    26  }
    27  
    28  func forkFromOrigin(cmd *cobra.Command, args []string) {
    29  	if _, err := gitconfig.Local("remote." + lab.User() + ".url"); err == nil {
    30  		log.Println("remote:", lab.User, "already exists")
    31  		return
    32  	}
    33  
    34  	remoteURL, err := gitconfig.Local("remote.origin.url")
    35  	if err != nil {
    36  		log.Fatal(err)
    37  	}
    38  	if git.IsHub && strings.Contains(remoteURL, "github.com") {
    39  		git := git.New("fork")
    40  		git.Run()
    41  		if err != nil {
    42  			log.Fatal(err)
    43  		}
    44  		return
    45  	}
    46  
    47  	project, err := git.PathWithNameSpace("origin")
    48  	if err != nil {
    49  		log.Fatal(err)
    50  	}
    51  	remote, err := lab.Fork(project)
    52  	if err != nil {
    53  		log.Fatal(err)
    54  	}
    55  
    56  	err = git.RemoteAdd(lab.User(), remote, ".")
    57  	if err != nil {
    58  		log.Fatal(err)
    59  	}
    60  }
    61  func forkToUpstream(cmd *cobra.Command, args []string) {
    62  	_, err := lab.Fork(args[0])
    63  	if err != nil {
    64  		log.Fatal(err)
    65  	}
    66  	cloneCmd.Run(nil, []string{strings.Split(args[0], "/")[1]})
    67  }
    68  
    69  func init() {
    70  	RootCmd.AddCommand(forkCmd)
    71  }