-
Notifications
You must be signed in to change notification settings - Fork 21
/
main.go
122 lines (100 loc) · 2.12 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package main
import (
"cmp"
"errors"
"fmt"
"io"
"os"
"os/exec"
"runtime/debug"
"syscall"
"github.com/urfave/cli"
"github.com/rliebz/tusk/appcli"
"github.com/rliebz/tusk/runner"
"github.com/rliebz/tusk/ui"
)
var version string
func main() {
status := run(config{
args: os.Args,
stdout: os.Stdout,
stderr: os.Stderr,
})
os.Exit(status)
}
type config struct {
args []string
stdout io.Writer
stderr io.Writer
}
func run(cfg config) (status int) {
defer func() {
if r := recover(); r != nil {
if !appcli.IsCompleting(cfg.args) {
ui.New().Error(fmt.Errorf("recovered from panic: %v", r))
}
status = cmp.Or(status, 1)
}
}()
meta, err := appcli.GetConfigMetadata(cfg.args)
if err != nil {
if !appcli.IsCompleting(cfg.args) {
ui.New().Error(err)
}
return 1
}
meta.Logger.Stdout = cfg.stdout
meta.Logger.Stderr = cfg.stderr
status, err = runMeta(meta, cfg.args)
if err != nil {
meta.Logger.Error(err)
return cmp.Or(status, 1)
}
return status
}
func runMeta(meta *runner.Metadata, args []string) (exitStatus int, err error) {
printHelp := false
switch {
case appcli.IsCompleting(args):
case meta.PrintHelp:
printHelp = true
case meta.PrintVersion:
printVersion(meta)
return 0, nil
case meta.InstallCompletion != "":
return 0, appcli.InstallCompletion(meta)
case meta.UninstallCompletion != "":
return 0, appcli.UninstallCompletion(meta)
}
app, err := appcli.NewApp(args, meta)
if err != nil {
return 1, err
}
if printHelp {
appcli.ShowAppHelp(meta.Logger, app)
return 0, nil
}
return runApp(app, meta, args)
}
func printVersion(meta *runner.Metadata) {
if version == "" {
if info, ok := debug.ReadBuildInfo(); ok {
version = info.Main.Version
}
}
meta.Logger.Println(version)
}
func runApp(app *cli.App, meta *runner.Metadata, args []string) (int, error) {
if err := app.Run(args); err != nil {
var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
if meta.Logger.Verbosity < ui.VerbosityLevelVerbose {
err = nil
}
ws := exitErr.Sys().(syscall.WaitStatus)
return ws.ExitStatus(), err
}
return 1, err
}
return 0, nil
}