forked from mislav/hub
/
template.go
69 lines (57 loc) · 1.43 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
package github
import (
"io/ioutil"
"path/filepath"
"strings"
)
const (
PullRequestTemplate = "pull_request_template"
IssueTemplate = "issue_template"
githubTemplateDir = ".github"
docsDir = "docs"
)
func ReadTemplate(kind, workdir string) (body string, err error) {
templateDir := filepath.Join(workdir, githubTemplateDir)
path, err := getFilePath(templateDir, kind)
if err != nil || path == "" {
docsDir := filepath.Join(workdir, docsDir)
path, err = getFilePath(docsDir, kind)
}
if err != nil || path == "" {
path, err = getFilePath(workdir, kind)
}
if path != "" {
body, err = readContentsFromFile(path)
}
return
}
func getFilePath(dir, pattern string) (found string, err error) {
files, err := ioutil.ReadDir(dir)
if err != nil {
return
}
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 {
found = filepath.Join(dir, fileName)
return
}
}
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.TrimSuffix(contents, "\n")
return
}