From 71333817c6a2bbee25260be414b18d15ca76891f Mon Sep 17 00:00:00 2001 From: Chetan Sarva Date: Tue, 4 Jan 2022 09:21:50 -0500 Subject: [PATCH] feat: optionally read args from rc file --- go.mod | 2 ++ go.sum | 2 ++ main.go | 30 +++++++++++++++++++++++++++++- 3 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 go.sum diff --git a/go.mod b/go.mod index bf8fb4c..d221980 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,5 @@ module github.com/chetan/elapsed go 1.17 + +require github.com/mitchellh/go-homedir v1.1.0 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..ae38d14 --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= +github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= diff --git a/main.go b/main.go index 7d7c040..730ac7e 100644 --- a/main.go +++ b/main.go @@ -5,7 +5,11 @@ import ( "flag" "fmt" "os" + "path/filepath" + "strings" "time" + + "github.com/mitchellh/go-homedir" ) var defaultDateTimeLayout = time.RFC3339 @@ -16,6 +20,30 @@ var showElapsed = true var showDelta = true var slow int64 = 0 +// getArgs from CLI or config file +func getArgs() []string { + args := os.Args[1:] + if len(args) != 0 { + return args + } + + // no cli args given, look for config file + dir, err := homedir.Dir() + if err != nil { + return args + } + rc := filepath.Join(dir, ".elapsedrc") + _, err = os.Stat(rc) + if err != nil { + return args + } + b, err := os.ReadFile(rc) + if err != nil { + return args + } + return strings.Split(strings.TrimSpace(string(b)), " ") +} + func parseFlags() { st := flag.Bool("datetime", false, "Show date/time stamp when message was received") stf := flag.String("format", "", "Date/time format (default: "+defaultDateTimeLayout+")") @@ -26,7 +54,7 @@ func parseFlags() { sl := flag.Bool("slow", false, "Show only slow deltas (over a certain threshold)") slm := flag.Int64("slow-ms", defaultSlowThreshold, "Slow delta threshold in ms") - flag.Parse() + flag.CommandLine.Parse(getArgs()) if se != nil && *se { showElapsed = false