File: template.go

package info (click to toggle)
hub 2.14.2~ds1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,376 kB
  • sloc: sh: 1,049; ruby: 857; makefile: 89
file content (81 lines) | stat: -rw-r--r-- 1,721 bytes parent folder | download | duplicates (3)
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
package github

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"sort"
	"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
}

type sortedFiles []os.FileInfo

func (s sortedFiles) Len() int {
	return len(s)
}
func (s sortedFiles) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}
func (s sortedFiles) Less(i, j int) bool {
	return strings.Compare(strings.ToLower(s[i].Name()), strings.ToLower(s[j].Name())) > 0
}

func getFilePath(dir, pattern string) (found string, err error) {
	files, err := ioutil.ReadDir(dir)
	if err != nil {
		return
	}

	sort.Sort(sortedFiles(files))

	for _, file := range files {
		fileName := file.Name()
		path := strings.TrimSuffix(fileName, ".md")
		path = strings.TrimSuffix(path, ".txt")

		if strings.EqualFold(pattern, path) {
			found = filepath.Join(dir, fileName)
			return
		}
	}
	return
}

func readContentsFromFile(filename string) (contents string, err error) {
	content, err := ioutil.ReadFile(filename)
	if err != nil {
		if strings.HasSuffix(err.Error(), " is a directory") {
			err = nil
		}
		return
	}

	contents = strings.Replace(string(content), "\r\n", "\n", -1)
	contents = strings.TrimSuffix(contents, "\n")
	return
}