github.com/kamiazya/dot-github@v1.3.0/generator.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"path"
     7  	"strings"
     8  	"text/template"
     9  )
    10  
    11  type Generator struct {
    12  	templateDir  string
    13  	dotGithubDir string
    14  	repo         *Repository
    15  	FileCreated  bool
    16  }
    17  
    18  func NewGenerator(temp string, repo *Repository) *Generator {
    19  	dotdir := path.Join(repo.Path, ".github")
    20  	if _, err := os.Stat(dotdir); os.IsNotExist(err) {
    21  		if err := os.MkdirAll(dotdir, os.ModeDir|os.ModePerm); err != nil {
    22  			panic(err)
    23  		}
    24  	}
    25  	return &Generator{
    26  		temp,
    27  		dotdir,
    28  		repo,
    29  		false,
    30  	}
    31  }
    32  
    33  type Placeholders struct {
    34  	IsPullRequest  bool
    35  	IsIssue        bool
    36  	IsContributing bool
    37  	RepoUser       string
    38  	RepoName       string
    39  }
    40  
    41  func (g *Generator) applyTemplate(src_path string, dst_path string) {
    42  	dst, err := os.Create(dst_path)
    43  	if err != nil {
    44  		panic(err)
    45  	}
    46  	defer dst.Close()
    47  
    48  	tmpl, err := template.ParseFiles(src_path)
    49  	if err != nil {
    50  		panic(err)
    51  	}
    52  
    53  	holders := Placeholders{
    54  		strings.Contains(dst_path, "PULL_REQUEST_TEMPLATE.md"),
    55  		strings.Contains(dst_path, "ISSUE_TEMPLATE.md"),
    56  		strings.Contains(dst_path, "CONTRIBUTING.md"),
    57  		g.repo.User,
    58  		g.repo.Name,
    59  	}
    60  
    61  	if err := tmpl.Execute(dst, holders); err != nil {
    62  		panic(err)
    63  	}
    64  
    65  	fmt.Println("Created " + dst_path)
    66  }
    67  
    68  func (g *Generator) generateFile(name string, fallback string) {
    69  	src := path.Join(g.templateDir, name)
    70  	if len(fallback) != 0 {
    71  		if _, err := os.Stat(src); os.IsNotExist(err) {
    72  			src = path.Join(g.templateDir, fallback)
    73  		}
    74  	}
    75  	if _, err := os.Stat(src); os.IsNotExist(err) {
    76  		return
    77  	}
    78  	dst := path.Join(g.dotGithubDir, name)
    79  	g.applyTemplate(src, dst)
    80  	g.FileCreated = true
    81  }
    82  
    83  func (g *Generator) GenerateIssueTemplate() {
    84  	g.generateFile("ISSUE_TEMPLATE.md", "ISSUE_AND_PULL_REQUEST_TEMPLATE.md")
    85  }
    86  
    87  func (g *Generator) GeneratePRTemplate() {
    88  	g.generateFile("PULL_REQUEST_TEMPLATE.md", "ISSUE_AND_PULL_REQUEST_TEMPLATE.md")
    89  }
    90  
    91  func (g *Generator) GenerateContributingTemplate() {
    92  	g.generateFile("CONTRIBUTING.md", "")
    93  }
    94  
    95  func (g *Generator) GenerateAllTemplates() {
    96  	g.GenerateIssueTemplate()
    97  	g.GeneratePRTemplate()
    98  	g.GenerateContributingTemplate()
    99  }