github.com/kamiazya/dot-github@v1.3.0/git.go (about) 1 package main 2 3 import ( 4 "os" 5 "os/exec" 6 "path/filepath" 7 "regexp" 8 "strings" 9 ) 10 11 func gitCmdPath() string { 12 cmd := os.Getenv("DOT_GITHUB_GIT_CMD") 13 if len(cmd) == 0 { 14 cmd = "git" // Default 15 } 16 17 path, err := exec.LookPath(cmd) 18 if err != nil { 19 panic("'" + cmd + "' command not found. Specify $DOT_GITHUB_GIT_CMD properly.") 20 } 21 return path 22 } 23 24 func ValidateGitHubURL(u string) bool { 25 return regexp.MustCompile(`^(:?https|http|git)://github(:?\..+)?\.com`).MatchString(u) || 26 regexp.MustCompile(`^git@github(:?\..+)?\.com:`).MatchString(u) 27 } 28 29 func GitHubRemoteURL(name string) string { 30 cmd := exec.Command(gitCmdPath(), "ls-remote", "--get-url", name) 31 out, err := cmd.Output() 32 if err != nil { 33 panic(err) 34 } 35 u := string(out[:]) 36 if !ValidateGitHubURL(u) { 37 panic("Invalid GitHub remote: " + name) 38 } 39 return strings.TrimSpace(u) 40 } 41 42 func GitRoot() string { 43 cmd := exec.Command(gitCmdPath(), "rev-parse", "--show-cdup") 44 out, err := cmd.Output() 45 if err != nil { 46 panic("Current directory is not in git repository") 47 } 48 rel := strings.TrimSpace(string(out[:])) 49 if len(rel) == 0 { 50 // Note: 51 // Passing empty string to Abs() causes panic() in Windows 52 rel = "." 53 } 54 root, err := filepath.Abs(rel) 55 if err != nil { 56 panic(err.Error() + ": " + rel) 57 } 58 return root 59 }