/commands/init.go

https://github.com/ap0ught/hub · Go · 100 lines · 81 code · 15 blank · 4 comment · 11 complexity · 2086d3336c18e67f885c1c3fe7ce910b MD5 · raw file

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