github.com/scorpionis/hub@v2.2.1+incompatible/commands/fetch.go (about) 1 package commands 2 3 import ( 4 "regexp" 5 "strings" 6 7 "github.com/github/hub/github" 8 "github.com/github/hub/utils" 9 ) 10 11 var cmdFetch = &Command{ 12 Run: fetch, 13 GitExtension: true, 14 Usage: "fetch [USER...]", 15 Short: "Download data, tags and branches from a remote repository", 16 Long: `Adds missing remote(s) with git remote add prior to fetching. New 17 remotes are only added if they correspond to valid forks on GitHub. 18 `, 19 } 20 21 func init() { 22 CmdRunner.Use(cmdFetch) 23 } 24 25 /* 26 $ gh fetch jingweno 27 > git remote add jingweno git://github.com/jingweno/REPO.git 28 > git fetch jingweno 29 30 $ git fetch jingweno,foo 31 > git remote add jingweno ... 32 > git remote add foo ... 33 > git fetch --multiple jingweno foo 34 35 $ git fetch --multiple jingweno foo 36 > git remote add jingweno ... 37 > git remote add foo ... 38 > git fetch --multiple jingweno foo 39 */ 40 func fetch(command *Command, args *Args) { 41 if !args.IsParamsEmpty() { 42 err := tranformFetchArgs(args) 43 utils.Check(err) 44 } 45 } 46 47 func tranformFetchArgs(args *Args) error { 48 names := parseRemoteNames(args) 49 50 localRepo, err := github.LocalRepo() 51 utils.Check(err) 52 53 projects := make(map[*github.Project]bool) 54 ownerRegexp := regexp.MustCompile(OwnerRe) 55 for _, name := range names { 56 if ownerRegexp.MatchString(name) { 57 _, err := localRepo.RemoteByName(name) 58 if err != nil { 59 project := github.NewProject(name, "", "") 60 gh := github.NewClient(project.Host) 61 repo, err := gh.Repository(project) 62 if err != nil { 63 continue 64 } 65 66 projects[project] = repo.Private 67 } 68 } 69 } 70 71 for project, private := range projects { 72 args.Before("git", "remote", "add", project.Owner, project.GitURL("", "", private)) 73 } 74 75 return nil 76 } 77 78 func parseRemoteNames(args *Args) (names []string) { 79 words := args.Words() 80 if i := args.IndexOfParam("--multiple"); i != -1 { 81 if args.ParamsSize() > 1 { 82 names = words 83 } 84 } else if len(words) > 0 { 85 remoteName := words[0] 86 remoteNameRegexp := regexp.MustCompile("^\\w+(,\\w+)$") 87 if remoteNameRegexp.MatchString(remoteName) { 88 i := args.IndexOfParam(remoteName) 89 args.RemoveParam(i) 90 names = strings.Split(remoteName, ",") 91 args.InsertParam(i, names...) 92 args.InsertParam(i, "--multiple") 93 } else { 94 names = append(names, remoteName) 95 } 96 } 97 98 return 99 }