cli/pkg/githubtemplate/github_template.go
Mislav Marohnić d5ba3de751 Add template support to issue create, pr create
If multiple templates are found, the user is prompted to select one.

The templates are searched for, in order of preference:

- issues:
  1. `.github/ISSUE_TEMPLATE/*.md`
  2. `.github/ISSUE_TEMPLATE.md`
  3. `ISSUE_TEMPLATE/*.md`
  4. `ISSUE_TEMPLATE.md`
  5. `docs/ISSUE_TEMPLATE/*.md`
  6. `docs/ISSUE_TEMPLATE.md`

- pull requests:
  1. `.github/PULL_REQUEST_TEMPLATE/*.md`
  2. `.github/PULL_REQUEST_TEMPLATE.md`
  3. `PULL_REQUEST_TEMPLATE/*.md`
  4. `PULL_REQUEST_TEMPLATE.md`
  5. `docs/PULL_REQUEST_TEMPLATE/*.md`
  6. `docs/PULL_REQUEST_TEMPLATE.md`

The filename matches are case-insensitive.
2019-12-18 22:15:20 +01:00

99 lines
2.3 KiB
Go

package githubtemplate
import (
"io/ioutil"
"path"
"regexp"
"sort"
"strings"
"gopkg.in/yaml.v3"
)
// Find returns the list of template file paths
func Find(rootDir string, name string) []string {
results := []string{}
// https://help.github.com/en/github/building-a-strong-community/creating-a-pull-request-template-for-your-repository
candidateDirs := []string{
path.Join(rootDir, ".github"),
rootDir,
path.Join(rootDir, "docs"),
}
for _, dir := range candidateDirs {
files, err := ioutil.ReadDir(dir)
if err != nil {
continue
}
// detect multiple templates in a subdirectory
for _, file := range files {
if strings.EqualFold(file.Name(), name) && file.IsDir() {
templates, err := ioutil.ReadDir(path.Join(dir, file.Name()))
if err != nil {
break
}
for _, tf := range templates {
if strings.HasSuffix(tf.Name(), ".md") {
results = append(results, path.Join(dir, file.Name(), tf.Name()))
}
}
if len(results) > 0 {
goto done
}
break
}
}
// detect a single template file
for _, file := range files {
if strings.EqualFold(file.Name(), name+".md") {
results = append(results, path.Join(dir, file.Name()))
break
}
}
if len(results) > 0 {
goto done
}
}
done:
sort.Sort(sort.StringSlice(results))
return results
}
// ExtractName returns the name of the template from YAML front-matter
func ExtractName(filePath string) string {
contents, err := ioutil.ReadFile(filePath)
if err == nil && detectFrontmatter(contents)[0] == 0 {
templateData := struct {
Name string
}{}
if err := yaml.Unmarshal(contents, &templateData); err == nil && templateData.Name != "" {
return templateData.Name
}
}
return path.Base(filePath)
}
// ExtractContents returns the template contents without the YAML front-matter
func ExtractContents(filePath string) []byte {
contents, err := ioutil.ReadFile(filePath)
if err != nil {
return []byte{}
}
if frontmatterBoundaries := detectFrontmatter(contents); frontmatterBoundaries[0] == 0 {
return contents[frontmatterBoundaries[1]:]
}
return contents
}
var yamlPattern = regexp.MustCompile(`(?m)^---\r?\n(\s*\r?\n)?`)
func detectFrontmatter(c []byte) []int {
if matches := yamlPattern.FindAllIndex(c, 2); len(matches) > 1 {
return []int{matches[0][0], matches[1][1]}
}
return []int{-1, -1}
}