forked from loov/gistsnip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
github.go
54 lines (44 loc) · 1.44 KB
/
github.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package main
import (
"errors"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"
)
// one of:
// https://github.com/loov/watchrun.git
// [email protected]:loov/watchrun.git
var rxGithub = regexp.MustCompile(`^(?:https://github.com/|[email protected]:)(.*)\.git$`)
func GithubLinkToFile(path string, line int) (repositoryLink, sourceLink string, err error) {
dir := filepath.Dir(path)
remoteurl, err := gitexec(dir, "remote", "get-url", "origin")
if err != nil {
return "", "", err
}
filename, err := gitexec(dir, "ls-files", "--full-name", filepath.Base(path))
if err != nil {
return "", "", err
}
hash, err := gitexec(dir, "rev-parse", "HEAD")
if err != nil {
return "", "", err
}
// remoteurl = [email protected]:loov/watchrun.git
// filename = 00_yolo/main.go
// hash = 872c42f3b01ebc324fb2e0ac1a51e7b5539c7b50
// result: https://github.com/egonelbre/db-demo/blob/872c42f3b01ebc324fb2e0ac1a51e7b5539c7b50/00_yolo/main.go#L11
matches := rxGithub.FindStringSubmatch(remoteurl)
if len(matches) == 0 {
return "", "", errors.New("not a github repository")
}
repository := matches[1]
return "https://github.com/" + repository, "https://github.com/" + repository + "/blob/" + hash + "/" + filename + "#L" + strconv.Itoa(line), nil
}
func gitexec(dir string, args ...string) (string, error) {
cmd := exec.Command("git", args...)
cmd.Dir = dir
result, err := cmd.CombinedOutput()
return strings.TrimSpace(string(result)), err
}