github.com/echohead/hub@v2.2.1+incompatible/commands/init.go (about) 1 package commands 2 3 import ( 4 "path/filepath" 5 "regexp" 6 "strings" 7 8 "github.com/github/hub/github" 9 "github.com/github/hub/utils" 10 ) 11 12 var cmdInit = &Command{ 13 Run: gitInit, 14 GitExtension: true, 15 Usage: "init -g", 16 Short: "Create an empty git repository or reinitialize an existing one", 17 Long: `Create a git repository as with git-init(1) and add remote origin at 18 "git@github.com:USER/REPOSITORY.git"; USER is your GitHub username and 19 REPOSITORY is the current working directory's basename. 20 `, 21 } 22 23 func init() { 24 CmdRunner.Use(cmdInit) 25 } 26 27 /* 28 $ gh init -g 29 > git init 30 > git remote add origin git@github.com:USER/REPO.git 31 */ 32 func gitInit(command *Command, args *Args) { 33 err := transformInitArgs(args) 34 utils.Check(err) 35 } 36 37 func transformInitArgs(args *Args) error { 38 if !parseInitFlag(args) { 39 return nil 40 } 41 42 var err error 43 dirToInit := "." 44 hasValueRegxp := regexp.MustCompile("^--(template|separate-git-dir|shared)$") 45 46 // Find the first argument that isn't related to any of the init flags. 47 // We assume this is the optional `directory` argument to git init. 48 for i := 0; i < args.ParamsSize(); i++ { 49 arg := args.Params[i] 50 if hasValueRegxp.MatchString(arg) { 51 i++ 52 } else if !strings.HasPrefix(arg, "-") { 53 dirToInit = arg 54 break 55 } 56 } 57 58 dirToInit, err = filepath.Abs(dirToInit) 59 if err != nil { 60 return err 61 } 62 63 // Assume that the name of the working directory is going to be the name of 64 // the project on GitHub. 65 projectName := strings.Replace(filepath.Base(dirToInit), " ", "-", -1) 66 project := github.NewProject("", projectName, "") 67 url := project.GitURL("", "", true) 68 69 addRemote := []string{ 70 "git", "--git-dir", filepath.Join(dirToInit, ".git"), 71 "remote", "add", "origin", url, 72 } 73 args.After(addRemote...) 74 75 return nil 76 } 77 78 func parseInitFlag(args *Args) bool { 79 if i := args.IndexOfParam("-g"); i != -1 { 80 args.RemoveParam(i) 81 return true 82 } 83 84 return false 85 }