git.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package gitutils
  2. import (
  3. "fmt"
  4. "os"
  5. "strings"
  6. "github.com/cli/cli/git"
  7. )
  8. func GitDirectory(fullpath string) (string, error) {
  9. currDir, err := os.Getwd()
  10. if err != nil {
  11. return "", fmt.Errorf("could not read current directory: %s", err.Error())
  12. }
  13. err = os.Chdir(fullpath)
  14. if err != nil {
  15. return "", nil
  16. }
  17. res, gitErr := git.ToplevelDir()
  18. err = os.Chdir(currDir)
  19. if err != nil {
  20. return "", err
  21. }
  22. return res, gitErr
  23. }
  24. func GetRemoteBranch(fullpath string) (*git.Remote, string, error) {
  25. var remote *git.Remote
  26. currDir, err := os.Getwd()
  27. if err != nil {
  28. return nil, "", fmt.Errorf("could not read current directory: %s", err.Error())
  29. }
  30. err = os.Chdir(fullpath)
  31. if err != nil {
  32. return nil, "", nil
  33. }
  34. // read the current branch
  35. branch, gitErr := git.CurrentBranch()
  36. if gitErr == nil {
  37. branchConf := git.ReadBranchConfig(branch)
  38. remoteName := "origin"
  39. if branchConf.RemoteName != "" {
  40. remoteName = branchConf.RemoteName
  41. }
  42. remotes, err := git.Remotes()
  43. if err != nil {
  44. return nil, "", err
  45. }
  46. for _, _remote := range remotes {
  47. if _remote.Name == remoteName {
  48. remote = _remote
  49. break
  50. }
  51. }
  52. if remote == nil {
  53. return nil, "", fmt.Errorf("remote repository not found")
  54. }
  55. }
  56. err = os.Chdir(currDir)
  57. if err != nil {
  58. return nil, "", err
  59. }
  60. return remote, branch, gitErr
  61. }
  62. func ParseGithubRemote(remote *git.Remote) (bool, string) {
  63. if remote == nil || remote.FetchURL == nil {
  64. return false, ""
  65. }
  66. if remote.FetchURL.Host != "github.com" {
  67. return false, ""
  68. }
  69. if !strings.Contains(remote.FetchURL.Path, ".git") {
  70. return false, ""
  71. }
  72. return true, strings.Trim(strings.TrimSuffix(remote.FetchURL.Path, ".git"), "/")
  73. }