feat: add outputFlag

main
Tran Hau 2021-01-21 15:41:40 +07:00
parent f03d806f8e
commit 729ed9e4af
3 changed files with 52 additions and 8 deletions

View File

@ -14,7 +14,7 @@ const (
// map template name with filename
var templates = map[string]templateInfo{
"MIT": {
filename: "mit",
filename: "mit.txt",
args: []string{
"[year]",
"[fullname]",
@ -27,7 +27,7 @@ type templateInfo struct {
args []string
}
func generateLicense(name string, values map[string]string) (string, error) {
func generateLicense(name string) (string, error) {
if name == "" {
return "", fmt.Errorf("empty license name")
}
@ -47,10 +47,8 @@ func generateLicense(name string, values map[string]string) (string, error) {
// Replace template
template := string(templateRaw)
for _, arg := range templateInfo.args {
value, ok := values[arg]
if !ok {
return "", fmt.Errorf("missing arg %s", arg)
}
fmt.Printf("What is your %s: ", arg)
value := readStdin()
template = strings.ReplaceAll(template, arg, value)
}

24
main.go
View File

@ -2,7 +2,9 @@ package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"github.com/fatih/color"
"github.com/urfave/cli/v2"
@ -12,6 +14,10 @@ const (
appName = "license"
nameFlag = "name"
outputFlag = "output"
currentDir = "."
licenseFilename = "LICENSE"
)
var fmtErr = color.New(color.FgRed)
@ -28,6 +34,12 @@ func main() {
Aliases: []string{"n"},
Usage: "which `LICENSE`",
},
&cli.StringFlag{
Name: outputFlag,
Aliases: []string{"o"},
Usage: "output directory",
DefaultText: currentDir,
},
},
Action: a.Run,
}
@ -42,6 +54,7 @@ func main() {
type action struct {
flags struct {
name string
output string
}
}
@ -53,9 +66,20 @@ func (a *action) Run(c *cli.Context) error {
a.getFlags(c)
license, err := generateLicense(a.flags.name)
if err != nil {
return fmt.Errorf("failed to generate license %s: %w", a.flags.name, err)
}
outputFile := filepath.Join(a.flags.output, licenseFilename)
if err := ioutil.WriteFile(outputFile, []byte(license), os.ModePerm); err != nil {
return fmt.Errorf("failed to write file %s: %w", outputFile, err)
}
return nil
}
func (a *action) getFlags(c *cli.Context) {
a.flags.name = c.String(nameFlag)
a.flags.output = c.String(outputFlag)
}

22
stdin.go Normal file
View File

@ -0,0 +1,22 @@
package main
import (
"bufio"
"os"
"strings"
)
func readStdin() string {
bs := bufio.NewScanner(os.Stdin)
for bs.Scan() {
line := bs.Text()
line = strings.TrimSpace(line)
if line == "" {
continue
}
return line
}
return ""
}