license/main.go

86 lines
1.5 KiB
Go
Raw Normal View History

2021-01-21 07:32:21 +00:00
package main
import (
"fmt"
2021-01-21 08:41:40 +00:00
"io/ioutil"
2021-01-21 07:32:21 +00:00
"os"
2021-01-21 08:41:40 +00:00
"path/filepath"
2021-01-21 07:32:21 +00:00
"github.com/fatih/color"
"github.com/urfave/cli/v2"
)
const (
appName = "license"
2021-01-21 08:41:40 +00:00
nameFlag = "name"
outputFlag = "output"
currentDir = "."
licenseFilename = "LICENSE"
2021-01-21 07:32:21 +00:00
)
var fmtErr = color.New(color.FgRed)
func main() {
a := action{}
app := &cli.App{
Name: appName,
Usage: "generate LICENSE",
Flags: []cli.Flag{
&cli.StringFlag{
Name: nameFlag,
Aliases: []string{"n"},
Usage: "which `LICENSE`",
},
2021-01-21 08:41:40 +00:00
&cli.StringFlag{
Name: outputFlag,
Aliases: []string{"o"},
Usage: "output directory",
DefaultText: currentDir,
},
2021-01-21 07:32:21 +00:00
},
Action: a.Run,
}
if err := app.Run(os.Args); err != nil {
// Highlight error
fmtErr.Printf("[%s error]: ", appName)
fmt.Printf("%s\n", err.Error())
}
}
type action struct {
flags struct {
2021-01-21 08:41:40 +00:00
name string
output string
2021-01-21 07:32:21 +00:00
}
}
func (a *action) Run(c *cli.Context) error {
// Show help if there is nothing
if c.NArg() == 0 && c.NumFlags() == 0 {
return cli.ShowAppHelp(c)
}
a.getFlags(c)
2021-01-21 08:41:40 +00:00
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)
}
2021-01-21 07:32:21 +00:00
return nil
}
func (a *action) getFlags(c *cli.Context) {
a.flags.name = c.String(nameFlag)
2021-01-21 08:41:40 +00:00
a.flags.output = c.String(outputFlag)
2021-01-21 07:32:21 +00:00
}