Skip to content

Commit a2a0814

Browse files
committed
cmd/crowdsec: use flagset
1 parent ba3ea99 commit a2a0814

File tree

2 files changed

+51
-35
lines changed

2 files changed

+51
-35
lines changed

cmd/crowdsec/flags.go

Lines changed: 40 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package main
33
import (
44
"flag"
55
"fmt"
6+
"os"
67
"runtime"
78
"strings"
89

@@ -54,36 +55,44 @@ func (l *labelsMap) Set(label string) error {
5455
return nil
5556
}
5657

57-
func (f *Flags) parse() {
58-
flag.StringVar(&f.ConfigFile, "c", csconfig.DefaultConfigPath("config.yaml"), "configuration file")
58+
func parseFlags(argv []string) (Flags, error) {
59+
var f Flags
5960

60-
var trace, debug, info, warn, erro, fatal bool
61+
fs := flag.NewFlagSet("crowdsec", flag.ExitOnError)
62+
fs.SetOutput(os.Stderr)
63+
64+
fs.StringVar(&f.ConfigFile, "c", csconfig.DefaultConfigPath("config.yaml"), "configuration file")
6165

62-
flag.BoolVar(&trace, "trace", false, "set log level to 'trace' (VERY verbose)")
63-
flag.BoolVar(&debug, "debug", false, "set log level to 'debug'")
64-
flag.BoolVar(&info, "info", false, "set log level to 'info'")
65-
flag.BoolVar(&warn, "warning", false, "set log level to 'warning'")
66-
flag.BoolVar(&erro, "error", false, "set log level to 'error'")
67-
flag.BoolVar(&fatal, "fatal", false, "set log level to 'fatal'")
68-
69-
flag.BoolVar(&f.PrintVersion, "version", false, "display version")
70-
flag.StringVar(&f.OneShotDSN, "dsn", "", "Process a single data source in time-machine")
71-
flag.StringVar(&f.Transform, "transform", "", "expr to apply on the event after acquisition")
72-
flag.StringVar(&f.SingleFileType, "type", "", "Labels.type for file in time-machine")
73-
flag.Var(&f.Labels, "label", "Additional Labels for file in time-machine")
74-
flag.BoolVar(&f.TestMode, "t", false, "only test configs")
75-
flag.BoolVar(&f.DisableAgent, "no-cs", false, "disable crowdsec agent")
76-
flag.BoolVar(&f.DisableAPI, "no-api", false, "disable local API")
77-
flag.BoolVar(&f.DisableCAPI, "no-capi", false, "disable communication with Central API")
78-
flag.BoolVar(&f.OrderEvent, "order-event", false, "enforce event ordering with significant performance cost")
66+
var trace, debug, info, warn, erro, fatal bool
67+
fs.BoolVar(&trace, "trace", false, "set log level to 'trace' (VERY verbose)")
68+
fs.BoolVar(&debug, "debug", false, "set log level to 'debug'")
69+
fs.BoolVar(&info, "info", false, "set log level to 'info'")
70+
fs.BoolVar(&warn, "warning", false, "set log level to 'warning'")
71+
fs.BoolVar(&erro, "error", false, "set log level to 'error'")
72+
fs.BoolVar(&fatal, "fatal", false, "set log level to 'fatal'")
73+
74+
fs.BoolVar(&f.PrintVersion, "version", false, "display version")
75+
fs.StringVar(&f.OneShotDSN, "dsn", "", "Process a single data source in time-machine")
76+
fs.StringVar(&f.Transform, "transform", "", "expr to apply on the event after acquisition")
77+
fs.StringVar(&f.SingleFileType, "type", "", "Labels.type for file in time-machine")
78+
f.Labels = make(labelsMap)
79+
fs.Var(&f.Labels, "label", "Additional Labels for file in time-machine")
80+
fs.BoolVar(&f.TestMode, "t", false, "only test configs")
81+
fs.BoolVar(&f.DisableAgent, "no-cs", false, "disable crowdsec agent")
82+
fs.BoolVar(&f.DisableAPI, "no-api", false, "disable local API")
83+
fs.BoolVar(&f.DisableCAPI, "no-capi", false, "disable communication with Central API")
84+
fs.BoolVar(&f.OrderEvent, "order-event", false, "enforce event ordering with significant performance cost")
7985

8086
if runtime.GOOS == "windows" {
81-
flag.StringVar(&f.WinSvc, "winsvc", "", "Windows service Action: Install, Remove etc..")
87+
fs.StringVar(&f.WinSvc, "winsvc", "", "Windows service Action: Install, Remove etc..")
8288
}
8389

84-
flag.StringVar(&f.DumpDir, "dump-data", "", "dump parsers/buckets raw outputs")
85-
flag.StringVar(&f.CPUProfile, "cpu-profile", "", "write cpu profile to file")
86-
flag.Parse()
90+
fs.StringVar(&f.DumpDir, "dump-data", "", "dump parsers/buckets raw outputs")
91+
fs.StringVar(&f.CPUProfile, "cpu-profile", "", "write cpu profile to file")
92+
93+
if err := fs.Parse(argv); err != nil {
94+
return f, err
95+
}
8796

8897
// Set the log level selected by the --trace, --debug, --info, etc. flags,
8998
// giving precedence to the most verbose flag if multiple are set. If no flag is specified,
@@ -102,4 +111,11 @@ func (f *Flags) parse() {
102111
case fatal:
103112
f.LogLevel = log.FatalLevel
104113
}
114+
115+
if len(fs.Args()) > 0 {
116+
return f, fmt.Errorf("argument provided but not defined: %s", fs.Args()[0])
117+
118+
}
119+
120+
return f, nil
105121
}

cmd/crowdsec/main.go

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,14 @@ package main
33
import (
44
"context"
55
"errors"
6-
"flag"
76
"fmt"
87
_ "net/http/pprof"
98
"os"
109
"path/filepath"
1110
"runtime/pprof"
1211
"time"
1312

13+
"github.com/fatih/color"
1414
log "github.com/sirupsen/logrus"
1515
"gopkg.in/tomb.v2"
1616

@@ -192,7 +192,7 @@ func LoadConfig(configFile string, disableAgent bool, disableAPI bool, quiet boo
192192
// or uptime of the application
193193
var crowdsecT0 time.Time
194194

195-
func run() error {
195+
func run(flags Flags) error {
196196
if flags.CPUProfile != "" {
197197
f, err := os.Create(flags.CPUProfile)
198198
if err != nil {
@@ -238,22 +238,22 @@ func main() {
238238

239239
crowdsecT0 = time.Now()
240240

241-
// Handle command line arguments
242-
flags.parse()
243-
244-
if len(flag.Args()) > 0 {
245-
fmt.Fprintf(os.Stderr, "argument provided but not defined: %s\n", flag.Args()[0])
246-
flag.Usage()
247-
// the flag package exits with 2 in case of unknown flag
241+
parsedFlags, err := parseFlags(os.Args[1:])
242+
if err != nil {
243+
fmt.Fprintln(os.Stderr, color.RedString("Error:"), err)
244+
// the flag package exits with 2 in case of unknown flag,
245+
// we do the same for extra arguments
248246
os.Exit(2)
249247
}
250248

249+
flags = parsedFlags
250+
251251
if flags.PrintVersion {
252252
os.Stdout.WriteString(cwversion.FullString())
253-
os.Exit(0)
253+
return
254254
}
255255

256-
if err := run(); err != nil {
256+
if err := run(flags); err != nil {
257257
log.Fatal(err)
258258
}
259259
}

0 commit comments

Comments
 (0)