Skip to content

Commit 9118ea8

Browse files
refactor: unify error handling in internal/cmd
Added `handleError` utility function to standardize error handling
1 parent dddbe77 commit 9118ea8

File tree

10 files changed

+93
-61
lines changed

10 files changed

+93
-61
lines changed

go.mod

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
11
module github.com/conventionalcommit/commitlint
22

3-
go 1.17
3+
go 1.23.0
44

55
require (
66
github.com/conventionalcommit/parser v0.7.1
7-
github.com/urfave/cli/v2 v2.11.1
8-
golang.org/x/mod v0.5.1
7+
github.com/urfave/cli/v2 v2.27.5
8+
golang.org/x/mod v0.21.0
99
gopkg.in/yaml.v2 v2.4.0
1010
)
1111

1212
require (
13-
github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect
13+
github.com/cpuguy83/go-md2man/v2 v2.0.5 // indirect
1414
github.com/russross/blackfriday/v2 v2.1.0 // indirect
15-
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 // indirect
15+
github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 // indirect
1616
)

go.sum

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,24 @@ github.com/conventionalcommit/parser v0.7.1 h1:oAzcrEqyyGnzCeNOBqGx2qnxISxneUuBi
33
github.com/conventionalcommit/parser v0.7.1/go.mod h1:k3teTA7nWpRrk7sjAihpAXm+1QLu1OscGrxclMHgEyc=
44
github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w=
55
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
6+
github.com/cpuguy83/go-md2man/v2 v2.0.5 h1:ZtcqGrnekaHpVLArFSe4HK5DoKx1T0rq2DwVB0alcyc=
7+
github.com/cpuguy83/go-md2man/v2 v2.0.5/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
68
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
79
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
810
github.com/urfave/cli/v2 v2.11.1 h1:UKK6SP7fV3eKOefbS87iT9YHefv7iB/53ih6e+GNAsE=
911
github.com/urfave/cli/v2 v2.11.1/go.mod h1:f8iq5LtQ/bLxafbdBSLPPNsgaW0l/2fYYEHhAyPlwvo=
12+
github.com/urfave/cli/v2 v2.27.5 h1:WoHEJLdsXr6dDWoJgMq/CboDmyY/8HMMH1fTECbih+w=
13+
github.com/urfave/cli/v2 v2.27.5/go.mod h1:3Sevf16NykTbInEnD0yKkjDAeZDS0A6bzhBH5hrMvTQ=
1014
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU=
1115
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8=
16+
github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 h1:gEOO8jv9F4OT7lGCjxCBTO/36wtF6j2nSip77qHd4x4=
17+
github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1/go.mod h1:Ohn+xnUBiLI6FVj/9LpzZWtj1/D6lUovWYBkxHVV3aM=
1218
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
1319
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
1420
golang.org/x/mod v0.5.1 h1:OJxoQ/rynoF0dcCdI7cLPktw/hR2cueqYfjm43oqK38=
1521
golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro=
22+
golang.org/x/mod v0.21.0 h1:vvrHzRwRfVKSiLrG+d4FMl/Qi4ukBCE6kZlTUkDYRT0=
23+
golang.org/x/mod v0.21.0/go.mod h1:6SkKJ3Xj0I0BrPOZoBy3bdMptDDU9oJrpohJ3eWZ1fY=
1624
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
1725
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
1826
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=

internal/cmd/cli.go

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ package cmd
44
import (
55
"fmt"
66

7-
cli "github.com/urfave/cli/v2"
7+
"github.com/urfave/cli/v2"
88

99
"github.com/conventionalcommit/commitlint/internal"
1010
)
@@ -49,7 +49,8 @@ func newLintCmd() *cli.Command {
4949
Action: func(ctx *cli.Context) error {
5050
confFilePath := ctx.String("config")
5151
fileInput := ctx.String("message")
52-
return lintMsg(confFilePath, fileInput)
52+
err := lintMsg(confFilePath, fileInput)
53+
return handleError(err, "Failed to run lint command")
5354
},
5455
}
5556
}
@@ -76,7 +77,7 @@ func newInitCmd() *cli.Command {
7677
hooksPath := ctx.String("hookspath")
7778

7879
err := initLint(confPath, hooksPath, isGlobal, isReplace)
79-
if err != nil {
80+
if handleError(err, "Failed to initialize commitlint") != nil {
8081
if isHookExists(err) {
8182
fmt.Println("commitlint init failed")
8283
fmt.Println("run with --replace to replace existing files")
@@ -112,7 +113,7 @@ func newConfigCmd() *cli.Command {
112113
isReplace := ctx.Bool("replace")
113114
fileName := ctx.String("file")
114115
err := configCreate(fileName, isReplace)
115-
if err != nil {
116+
if handleError(err, "Failed to create config file") != nil {
116117
if isConfExists(err) {
117118
fmt.Println("config create failed")
118119
fmt.Println("run with --replace to replace existing file")
@@ -144,10 +145,10 @@ func newConfigCmd() *cli.Command {
144145
return nil
145146
}
146147
if len(errs) == 1 {
147-
return errs[0]
148+
return handleError(errs[0], "Config check failed")
148149
}
149150
merr := multiError(errs)
150-
return &merr
151+
return handleError(&merr, "Config check failed")
151152
},
152153
}
153154

@@ -170,9 +171,9 @@ func newHookCmd() *cli.Command {
170171
isReplace := ctx.Bool("replace")
171172
hooksPath := ctx.String("hookspath")
172173
err := hookCreate(hooksPath, isReplace)
173-
if err != nil {
174+
if handleError(err, "Failed to create hooks") != nil {
174175
if isHookExists(err) {
175-
fmt.Println("create failed. hook files already exists")
176+
fmt.Println("create failed. hook files already exist")
176177
fmt.Println("run with --replace to replace existing hook files")
177178
return nil
178179
}
@@ -195,7 +196,7 @@ func newDebugCmd() *cli.Command {
195196
Name: "debug",
196197
Usage: "prints useful information for debugging",
197198
Action: func(ctx *cli.Context) error {
198-
return printDebug()
199+
return handleError(printDebug(), "Debugging information failed")
199200
},
200201
}
201202
}

internal/cmd/cmd.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ import (
77

88
// Run runs commitlint cli with os.Args
99
func Run() error {
10-
return newCliApp().Run(os.Args)
10+
err := newCliApp().Run(os.Args)
11+
return handleError(err, "Failed to run commitlint CLI")
1112
}
1213

1314
type multiError []error

internal/cmd/config.go

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,41 +11,42 @@ import (
1111
// configCreate is the callback function for create config command
1212
func configCreate(fileName string, isReplace bool) (retErr error) {
1313
outPath := filepath.Join(".", fileName)
14+
1415
// if config file already exists skip creating or overwriting it
1516
if _, err := os.Stat(outPath); !os.IsNotExist(err) {
1617
if !isReplace {
17-
return errConfigExist
18+
return handleError(errConfigExist, "Config file already exists")
1819
}
1920
}
2021

2122
outFilePath := filepath.Clean(outPath)
2223
f, err := os.Create(outFilePath)
23-
if err != nil {
24+
if handleError(err, "Failed to create config file") != nil {
2425
return err
2526
}
2627
defer func() {
2728
err := f.Close()
2829
if retErr == nil && err != nil {
29-
retErr = err
30+
retErr = handleError(err, "Failed to close config file")
3031
}
3132
}()
3233

3334
w := bufio.NewWriter(f)
3435
defer func() {
3536
err := w.Flush()
3637
if retErr == nil && err != nil {
37-
retErr = err
38+
retErr = handleError(err, "Failed to flush writer")
3839
}
3940
}()
4041

4142
defConf := config.NewDefault()
42-
return config.WriteTo(w, defConf)
43+
return handleError(config.WriteTo(w, defConf), "Failed to write config to file")
4344
}
4445

4546
// configCheck is the callback function for check/verify command
4647
func configCheck(confPath string) []error {
4748
conf, err := config.Parse(confPath)
48-
if err != nil {
49+
if handleError(err, "Failed to parse configuration file") != nil {
4950
return []error{err}
5051
}
5152
return config.Validate(conf)

internal/cmd/debug.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,22 +17,22 @@ func printDebug() error {
1717
w.WriteByte('\n')
1818

1919
gitVer, err := getGitVersion()
20-
if err != nil {
20+
if handleError(err, "Failed to get Git version") != nil {
2121
return err
2222
}
2323

2424
localConf, err := getGitHookConfig(false)
25-
if err != nil {
25+
if handleError(err, "Failed to get local Git hook configuration") != nil {
2626
return err
2727
}
2828

2929
globalConf, err := getGitHookConfig(true)
30-
if err != nil {
30+
if handleError(err, "Failed to get global Git hook configuration") != nil {
3131
return err
3232
}
3333

3434
confFile, confType, err := internal.LookupConfigPath()
35-
if err != nil {
35+
if handleError(err, "Failed to lookup configuration path") != nil {
3636
return err
3737
}
3838

@@ -67,7 +67,7 @@ func getGitVersion() (string, error) {
6767
cmd.Stdout = b
6868
cmd.Stderr = os.Stderr
6969
err := cmd.Run()
70-
if err != nil {
70+
if handleError(err, "Failed to execute 'git version' command") != nil {
7171
return "", err
7272
}
7373

@@ -90,7 +90,7 @@ func getGitHookConfig(isGlobal bool) (string, error) {
9090
cmd.Stdout = b
9191

9292
err := cmd.Run()
93-
if err != nil {
93+
if handleError(err, "Failed to execute 'git config core.hooksPath' command") != nil {
9494
return "", err
9595
}
9696

internal/cmd/error.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package cmd
2+
3+
import (
4+
"fmt"
5+
"os"
6+
7+
"github.com/urfave/cli/v2"
8+
)
9+
10+
// handleError handles and logs errors in a consistent way
11+
func handleError(err error, customMessage string) error {
12+
if err != nil {
13+
fmt.Fprintf(os.Stderr, "ERROR: %s - %v\n", customMessage, err)
14+
return cli.Exit(customMessage, 1)
15+
}
16+
return nil
17+
}

internal/cmd/hook.go

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -25,54 +25,58 @@ func hookCreate(hooksPath string, isReplace bool) error {
2525
hooksPath = filepath.Join(".", defaultHooksPath)
2626
}
2727
hooksPath = filepath.Clean(hooksPath)
28-
return createHooks(hooksPath, isReplace)
28+
return handleError(createHooks(hooksPath, isReplace), "Failed to create hooks")
2929
}
3030

3131
func initHooks(confPath, hookFlag string, isGlobal, isReplace bool) (string, error) {
3232
hookDir, err := getHookDir(hookFlag, isGlobal)
33-
if err != nil {
33+
if handleError(err, "Failed to get hook directory") != nil {
3434
return "", err
3535
}
3636

3737
err = writeHooks(hookDir, isReplace)
38-
if err != nil {
38+
if handleError(err, "Failed to write hooks") != nil {
3939
return "", err
4040
}
4141
return hookDir, nil
4242
}
4343

4444
func createHooks(hookBaseDir string, isReplace bool) error {
45-
return writeHooks(hookBaseDir, isReplace)
45+
return handleError(writeHooks(hookBaseDir, isReplace), "Failed to write hooks to base directory")
4646
}
4747

4848
func writeHooks(hookDir string, isReplace bool) error {
4949
// if commit-msg already exists skip creating or overwriting it
5050
if _, err := os.Stat(hookDir); !os.IsNotExist(err) {
5151
if !isReplace {
52-
return errHooksExist
52+
return handleError(errHooksExist, "Hook already exists and replace option not set")
5353
}
5454
}
5555

5656
err := os.MkdirAll(hookDir, os.ModePerm)
57-
if err != nil {
57+
if handleError(err, "Failed to create hook directory") != nil {
5858
return err
5959
}
6060

6161
// create hook file
62-
return hook.WriteHooks(hookDir)
62+
return handleError(hook.WriteHooks(hookDir), "Failed to write hooks to directory")
6363
}
6464

6565
func getHookDir(hookFlag string, isGlobal bool) (string, error) {
6666
if hookFlag != "" {
67-
return filepath.Abs(hookFlag)
67+
absPath, err := filepath.Abs(hookFlag)
68+
if handleError(err, "Failed to get absolute path for hook directory") != nil {
69+
return "", err
70+
}
71+
return absPath, nil
6872
}
6973

7074
hookFlag = defaultHooksPath
7175

7276
if isGlobal {
7377
// get user home dir
7478
homeDir, err := os.UserHomeDir()
75-
if err != nil {
79+
if handleError(err, "Failed to get user home directory") != nil {
7680
return "", err
7781
}
7882

@@ -82,7 +86,7 @@ func getHookDir(hookFlag string, isGlobal bool) (string, error) {
8286
}
8387

8488
gitDir, err := getRepoRootDir()
85-
if err != nil {
89+
if handleError(err, "Failed to get repository root directory") != nil {
8690
return "", err
8791
}
8892
return filepath.Join(gitDir, hookFlag), nil
@@ -96,7 +100,7 @@ func getRepoRootDir() (string, error) {
96100
cmd.Stderr = os.Stderr
97101

98102
err := cmd.Run()
99-
if err != nil {
103+
if handleError(err, "Failed to get repository root directory with git command") != nil {
100104
return "", err
101105
}
102106

@@ -109,9 +113,9 @@ func getRepoRootDir() (string, error) {
109113
}
110114

111115
func isHookExists(err error) bool {
112-
return err == errHooksExist
116+
return errors.Is(err, errHooksExist)
113117
}
114118

115119
func isConfExists(err error) bool {
116-
return err == errConfigExist
120+
return errors.Is(err, errConfigExist)
117121
}

internal/cmd/init.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,13 @@ import (
55
"os/exec"
66
)
77

8-
// initLint is the callback function for init command
8+
// initLint is the callback function for the init command
99
func initLint(confPath, hooksPath string, isGlobal, isReplace bool) error {
1010
hookDir, err := initHooks(confPath, hooksPath, isGlobal, isReplace)
11-
if err != nil {
11+
if handleError(err, "Failed to initialize hooks") != nil {
1212
return err
1313
}
14-
return setGitConf(hookDir, isGlobal)
14+
return handleError(setGitConf(hookDir, isGlobal), "Failed to set git configuration")
1515
}
1616

1717
func setGitConf(hookDir string, isGlobal bool) error {
@@ -23,5 +23,5 @@ func setGitConf(hookDir string, isGlobal bool) error {
2323

2424
cmd := exec.Command("git", args...)
2525
cmd.Stderr = os.Stderr
26-
return cmd.Run()
26+
return handleError(cmd.Run(), "Failed to execute git config command")
2727
}

0 commit comments

Comments
 (0)