1
0

feat: improve error handling

This commit is contained in:
Wiktor Zykubek 2025-01-01 21:01:11 +01:00
parent f9e2eb8a4e
commit 0c17136956
Signed by: wzykubek
GPG Key ID: 2221881F957D89B9
4 changed files with 24 additions and 10 deletions

View File

@ -21,7 +21,7 @@ func init() {
} }
var addCmd = &cobra.Command{ var addCmd = &cobra.Command{
Use: "add [license]", Use: "add [license id]",
Short: "Add LICENSE based on SPDX ID", Short: "Add LICENSE based on SPDX ID",
Args: cobra.ExactArgs(1), Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
@ -39,13 +39,18 @@ var addCmd = &cobra.Command{
} }
err = license.Gen() err = license.Gen()
if err != nil && err.Error() == "usupported license" { if err != nil {
fmt.Printf("Error: There is no '%s' license\n", licenseID) if err.Error() == "usupported license" {
os.Exit(2) fmt.Printf("Error: There is no '%s' license\n", licenseID)
os.Exit(2)
} else {
fmt.Println("Internal Error:", err)
os.Exit(127)
}
} }
if err = license.Write(OutputFile); err != nil { if err = license.Write(OutputFile); err != nil {
panic(err) fmt.Println("Error: Can't write file:", err)
} }
}, },
} }

View File

@ -2,6 +2,7 @@ package cmd
import ( import (
"fmt" "fmt"
"os"
"strings" "strings"
t "go.wzykubek.xyz/licensmith/internal/template" t "go.wzykubek.xyz/licensmith/internal/template"
@ -17,7 +18,12 @@ var listCmd = &cobra.Command{
Use: "list", Use: "list",
Short: "List available licenses", Short: "List available licenses",
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
templates := t.List() templates, err := t.List()
if err != nil {
fmt.Println("Internal Error:", err)
os.Exit(127)
}
fmt.Println(strings.Join(templates, ", ")) fmt.Println(strings.Join(templates, ", "))
}, },
} }

View File

@ -22,7 +22,10 @@ func (l *License) Gen() error {
return errors.New("usupported license") return errors.New("usupported license")
} }
body, _ := template.New(l.ID).Parse(tmpl.Body) body, err := template.New(l.ID).Parse(tmpl.Body)
if err != nil {
return err
}
var output bytes.Buffer var output bytes.Buffer
body.Execute(&output, l.Context) body.Execute(&output, l.Context)

View File

@ -36,10 +36,10 @@ func Parse(path string) (Template, error) {
return tmpl, nil return tmpl, nil
} }
func List() []string { func List() ([]string, error) {
files, err := fs.ReadDir(FS, ".") files, err := fs.ReadDir(FS, ".")
if err != nil { if err != nil {
panic(err) return []string{}, err
} }
var templates []string var templates []string
@ -47,5 +47,5 @@ func List() []string {
templates = append(templates, strings.Replace(v.Name(), ".tmpl", "", 1)) templates = append(templates, strings.Replace(v.Name(), ".tmpl", "", 1))
} }
return templates return templates, nil
} }