license/license.go

67 lines
1.2 KiB
Go
Raw Normal View History

2021-01-21 07:32:21 +00:00
package main
2021-01-21 08:15:34 +00:00
import (
"embed"
2021-01-21 08:15:34 +00:00
"fmt"
"path/filepath"
"strings"
2021-12-02 07:08:28 +00:00
"github.com/make-go-great/ioe-go"
2021-01-21 08:15:34 +00:00
)
const (
templatesPath = "templates"
)
//go:embed templates/*
var embedFS embed.FS
2021-01-21 08:15:34 +00:00
// map template name with filename
// always use upercase for license name
2021-01-21 08:15:34 +00:00
var templates = map[string]templateInfo{
"MIT": {
2021-01-21 08:41:40 +00:00
filename: "mit.txt",
2021-01-21 08:15:34 +00:00
args: []string{
"[year]",
"[fullname]",
},
},
}
type templateInfo struct {
filename string
args []string
}
2021-01-21 08:41:40 +00:00
func generateLicense(name string) (string, error) {
2021-01-21 08:15:34 +00:00
if name == "" {
return "", fmt.Errorf("empty license name")
}
name = strings.ToUpper(name)
2021-01-21 08:15:34 +00:00
templateInfo, ok := templates[name]
if !ok {
return "", fmt.Errorf("not support license %s", name)
}
// Get correct path of license
2021-01-21 08:15:34 +00:00
path := filepath.Join(templatesPath, templateInfo.filename)
// Read template
templateRaw, err := embedFS.ReadFile(path)
2021-01-21 08:15:34 +00:00
if err != nil {
return "", fmt.Errorf("failed to read file %s: %w", path, err)
}
// Replace template
template := string(templateRaw)
for _, arg := range templateInfo.args {
2021-01-21 08:41:40 +00:00
fmt.Printf("What is your %s: ", arg)
value := ioe.ReadInput()
2021-01-21 08:15:34 +00:00
template = strings.ReplaceAll(template, arg, value)
}
return template, nil
}