From 0c17136956b68f6855c22e6807e3f91a63250cdd Mon Sep 17 00:00:00 2001 From: Wiktor Zykubek Date: Wed, 1 Jan 2025 21:01:11 +0100 Subject: [PATCH] feat: improve error handling --- cmd/add.go | 15 ++++++++++----- cmd/list.go | 8 +++++++- internal/license/license.go | 5 ++++- internal/template/template.go | 6 +++--- 4 files changed, 24 insertions(+), 10 deletions(-) diff --git a/cmd/add.go b/cmd/add.go index 7d030ad..5581124 100644 --- a/cmd/add.go +++ b/cmd/add.go @@ -21,7 +21,7 @@ func init() { } var addCmd = &cobra.Command{ - Use: "add [license]", + Use: "add [license id]", Short: "Add LICENSE based on SPDX ID", Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { @@ -39,13 +39,18 @@ var addCmd = &cobra.Command{ } err = license.Gen() - if err != nil && err.Error() == "usupported license" { - fmt.Printf("Error: There is no '%s' license\n", licenseID) - os.Exit(2) + if err != nil { + if err.Error() == "usupported license" { + 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 { - panic(err) + fmt.Println("Error: Can't write file:", err) } }, } diff --git a/cmd/list.go b/cmd/list.go index 5968ca9..cb9c310 100644 --- a/cmd/list.go +++ b/cmd/list.go @@ -2,6 +2,7 @@ package cmd import ( "fmt" + "os" "strings" t "go.wzykubek.xyz/licensmith/internal/template" @@ -17,7 +18,12 @@ var listCmd = &cobra.Command{ Use: "list", Short: "List available licenses", 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, ", ")) }, } diff --git a/internal/license/license.go b/internal/license/license.go index 8cdddc6..5fdbdc6 100644 --- a/internal/license/license.go +++ b/internal/license/license.go @@ -22,7 +22,10 @@ func (l *License) Gen() error { 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 body.Execute(&output, l.Context) diff --git a/internal/template/template.go b/internal/template/template.go index 2b5d743..8d1c09b 100644 --- a/internal/template/template.go +++ b/internal/template/template.go @@ -36,10 +36,10 @@ func Parse(path string) (Template, error) { return tmpl, nil } -func List() []string { +func List() ([]string, error) { files, err := fs.ReadDir(FS, ".") if err != nil { - panic(err) + return []string{}, err } var templates []string @@ -47,5 +47,5 @@ func List() []string { templates = append(templates, strings.Replace(v.Name(), ".tmpl", "", 1)) } - return templates + return templates, nil }