forked from mislav/hub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.go
82 lines (65 loc) · 1.5 KB
/
template.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package github
import (
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/github/hub/utils"
)
const (
pullRequestTemplate = "pull_request_template"
issueTemplate = "issue_template"
githubTemplateDir = ".github"
)
func GetPullRequestTemplate() string {
return getGithubTemplate(pullRequestTemplate)
}
func GetIssueTemplate() string {
return getGithubTemplate(issueTemplate)
}
func getGithubTemplate(pat string) (body string) {
var path string
if _, err := os.Stat(githubTemplateDir); err == nil {
if p := getFilePath(githubTemplateDir, pat); p != "" {
path = p
}
}
if path == "" {
if p := getFilePath(".", pat); p != "" {
path = p
}
}
if path == "" {
return
}
body, err := readContentsFromFile(path)
utils.Check(err)
return
}
func getFilePath(dir, pattern string) string {
files, err := ioutil.ReadDir(dir)
utils.Check(err)
for _, file := range files {
fileName := file.Name()
path := fileName
if ext := filepath.Ext(fileName); ext == ".md" {
path = strings.TrimRight(fileName, ".md")
} else if ext == ".txt" {
path = strings.TrimRight(fileName, ".txt")
}
path = strings.ToLower(path)
if ok, _ := filepath.Match(pattern, path); ok {
return filepath.Join(dir, fileName)
}
}
return ""
}
func readContentsFromFile(filename string) (contents string, err error) {
content, err := ioutil.ReadFile(filename)
if err != nil {
return
}
contents = strings.Replace(string(content), "\r\n", "\n", -1)
contents = strings.TrimSpace(contents)
return
}