generated from deweysasser/golang-program
-
Notifications
You must be signed in to change notification settings - Fork 0
/
program.go
102 lines (85 loc) · 2.48 KB
/
program.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
package program
import (
"fmt"
"github.com/alecthomas/kong"
"github.com/mattn/go-colorable"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"io"
"os"
"runtime"
)
// Options is the structure of program options
type Options struct {
Version bool `help:"Show program version"`
// VersionCmd VersionCmd `name:"version" cmd:"" help:"show program version"`
Debug bool `group:"Info" help:"Show debugging information"`
OutputFormat string `group:"Info" enum:"auto,jsonl,terminal" default:"auto" help:"How to show program output (auto|terminal|jsonl)"`
Quiet bool `group:"Info" help:"Be less verbose than usual"`
Cmd1 Subcommand1 `cmd:""`
Cmd2 Subcommand2 `cmd:""`
}
type Subcommand1 struct {
Dir1 string `group:"dir" help:"get a directory" type:"existingdir" default:"dir1"`
}
type Subcommand2 struct {
Dir2 string `group:"dir" help:"get a directory" type:"existingdir" default:"dir2"`
}
// Parse calls the CLI parsing routines
func (program *Options) Parse(args []string) (*kong.Context, error) {
parser, err := kong.New(program,
kong.ShortUsageOnError(),
// kong.Description("Brief Program Summary"),
)
if err != nil {
fmt.Println(err)
return nil, err
}
return parser.Parse(args)
}
// Run runs the program
func (program *Options) Run() error {
return nil
}
// AfterApply runs after the options are parsed but before anything runs
func (program *Options) AfterApply() error {
program.initLogging()
return nil
}
func (program *Options) initLogging() {
if program.Version {
fmt.Println(Version)
os.Exit(0)
}
switch {
case program.Debug:
zerolog.SetGlobalLevel(zerolog.DebugLevel)
case program.Quiet:
zerolog.SetGlobalLevel(zerolog.WarnLevel)
default:
zerolog.SetGlobalLevel(zerolog.InfoLevel)
}
var out io.Writer = os.Stdout
if os.Getenv("TERM") == "" && runtime.GOOS == "windows" {
out = colorable.NewColorableStdout()
}
if program.OutputFormat == "terminal" ||
(program.OutputFormat == "auto" && isTerminal(os.Stdout)) {
log.Logger = log.Output(zerolog.ConsoleWriter{Out: out})
} else {
log.Logger = log.Output(out)
}
log.Logger.Debug().
Str("version", Version).
Str("program", os.Args[0]).
Msg("Starting")
}
// isTerminal returns true if the file given points to a character device (i.e. a terminal)
func isTerminal(file *os.File) bool {
if fileInfo, err := file.Stat(); err != nil {
log.Err(err).Msg("Error running stat")
return false
} else {
return (fileInfo.Mode() & os.ModeCharDevice) != 0
}
}