Skip to content

Commit

Permalink
Fix: cli arg, config, and logger fixes
Browse files Browse the repository at this point in the history
additionally:
  - fix `-c` flag
  - make main package test better
  • Loading branch information
yunginnanet committed Jun 26, 2024
1 parent 303aa0b commit 362c1d3
Show file tree
Hide file tree
Showing 6 changed files with 98 additions and 22 deletions.
27 changes: 26 additions & 1 deletion cmd/HellPot/HellPot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,16 @@ package main

import (
"os"
"path/filepath"
"testing"
"time"

"github.com/yunginnanet/HellPot/internal/http"
)

func testMain(t interface{ Error(...any) }) (string, string, chan os.Signal, error) {
func testMain(t *testing.T) (string, string, chan os.Signal, error) {
stopChan := make(chan os.Signal, 1)

log, logFile, resolvedConf, err := setup(stopChan)
if err == nil {
log.Info().Msg("🔥 Starting HellPot 🔥")
Expand All @@ -26,13 +28,36 @@ func testMain(t interface{ Error(...any) }) (string, string, chan os.Signal, err
}

func TestHellPot(t *testing.T) {
logDir := filepath.Join(t.TempDir(), "logs")
if err := os.MkdirAll(logDir, 0755); err != nil {
t.Fatal(err)
}
confFile := filepath.Join(t.TempDir(), "HellPot_test.toml")
t.Setenv("HELLPOT_LOGGER_DIRECTORY", logDir)
t.Setenv("HELLPOT_CONFIG", confFile)

resolvedConf, logFile, stopChan, err := testMain(t)
if err != nil {
t.Fatal(err)
}
if stopChan == nil {
t.Fatal("stopChan is nil")
}
if resolvedConf == "" {
t.Fatal("resolvedConf is empty")
}
if logFile == "" {
t.Fatal("logFile is empty")
}
if _, err = os.Stat(logFile); err != nil {
t.Fatal(err)
}
if resolvedConf != confFile {
t.Errorf("expected %s, got %s", confFile, resolvedConf)
}
if logFile != filepath.Join(logDir, "HellPot.log") {
t.Errorf("expected %s, got %s", filepath.Join(logDir, "HellPot.log"), logFile)
}
t.Log("resolvedConf: ", resolvedConf)
t.Log("logFile: ", logFile)
time.Sleep(100 * time.Millisecond)
Expand Down
49 changes: 40 additions & 9 deletions cmd/HellPot/boot.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"errors"
"flag"
"fmt"
"io"
"os"
Expand All @@ -18,23 +19,32 @@ import (
"github.com/yunginnanet/HellPot/internal/logger"
)

func writeConfig(target string) bool {
func writeConfig(target string) (*config.Parameters, bool) {
var f *os.File
var err error
f, err = os.Create(target) // #nosec G304 -- go home gosec, you're drunk
if err != nil {
println("failed to create config file: " + err.Error())
return false
return nil, false
}
if _, err = io.Copy(f, config.Defaults.IO); err != nil {
println("failed to write default config to file: " + err.Error())
_ = f.Close()
return false
return nil, false
}
if err = f.Sync(); err != nil {
panic(err)
}
println("wrote default config to " + target)
runningConfig, _ = config.Setup(f)
var newConf *config.Parameters
newConf, err = config.Setup(f)
if err != nil {
println("failed to setup config with newly written file: " + err.Error())
_ = f.Close()
return nil, false
}
_ = f.Close()
return true
return newConf, true
}

func searchConfig() string {
Expand Down Expand Up @@ -74,13 +84,15 @@ func readConfig(resolvedConf string) error {
switch {
case setupErr != nil:
println("failed to setup config: " + setupErr.Error())
_ = f.Close()
err = setupErr
case err != nil:
println("failed to open config file for reading: " + err.Error())
println("trying to create it....")
wroteOK := writeConfig(resolvedConf)
newRunningConfig, wroteOK := writeConfig(resolvedConf)
if wroteOK {
break
runningConfig = newRunningConfig
return nil
}
println("failed to create config file, cannot continue")
return fmt.Errorf("failed to create config file: %w", err)
Expand All @@ -92,10 +104,18 @@ func readConfig(resolvedConf string) error {
}

func resolveConfig() (usingDefaults bool, resolvedConf string, err error) {
if config.CLIFlags != nil {
confRoot := config.CLIFlags.Lookup("config")
setIfPresent := func(confRoot *flag.Flag) (ok bool) {
if confRoot != nil && confRoot.Value.String() != "" {
resolvedConf = confRoot.Value.String()
return true
}
return false
}
if config.CLIFlags != nil {
confRoot := config.CLIFlags.Lookup("config")
if !setIfPresent(confRoot) {
confRoot = config.CLIFlags.Lookup("c")
setIfPresent(confRoot)
}
}

Expand Down Expand Up @@ -125,12 +145,18 @@ func resolveConfig() (usingDefaults bool, resolvedConf string, err error) {
}

func setup(stopChan chan os.Signal) (log zerolog.Logger, logFile string, resolvedConf string, err error) {
config.InitCLI()
var usingDefaults bool

if usingDefaults, resolvedConf, err = resolveConfig(); err != nil {
return
}

if runningConfig == nil {
err = errors.New("running configuration is nil, cannot continue")
return
}

//goland:noinspection GoNilness // we check for nil above
if log, err = logger.New(runningConfig.Logger); err != nil {
return
Expand All @@ -156,5 +182,10 @@ func setup(stopChan chan os.Signal) (log zerolog.Logger, logFile string, resolve
}

signal.Notify(stopChan, syscall.SIGINT, syscall.SIGTERM)

if absResolvedConf, err := filepath.Abs(resolvedConf); err == nil {
resolvedConf = absResolvedConf
}

return
}
23 changes: 14 additions & 9 deletions internal/config/command_line.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,14 @@ import (
"github.com/yunginnanet/HellPot/internal/version"
)

var CLIFlags = flag.NewFlagSet("cli", flag.ExitOnError)
var CLIFlags = flag.NewFlagSet("config", flag.ExitOnError)

func init() {
func InitCLI() {
newArgs := make([]string, 0)
for _, arg := range os.Args {
// check for unit test flags
if strings.Contains(arg, "test.testlogfile") {
// we're in a unit test, bail
return
}
if strings.Contains(arg, "test.v") {
return
if !strings.HasPrefix(arg, "-test.") {
newArgs = append(newArgs, arg)
}
}

Expand All @@ -36,10 +33,18 @@ func init() {
CLIFlags.String("config", "", "specify config file")
CLIFlags.String("version", "", "show version and exit")
CLIFlags.String("v", "", "show version and exit")
if err := CLIFlags.Parse(os.Args[1:]); err != nil {
if err := CLIFlags.Parse(newArgs[1:]); err != nil {
println(err.Error())
// flag.ExitOnError will call os.Exit(2)
}
if os.Getenv("HELLPOT_CONFIG") != "" {
if err := CLIFlags.Set("config", os.Getenv("HELLPOT_CONFIG")); err != nil {
panic(err)
}
if err := CLIFlags.Set("c", os.Getenv("HELLPOT_CONFIG")); err != nil {
panic(err)
}
}
if CLIFlags.Lookup("h").Value.String() == "true" || CLIFlags.Lookup("help").Value.String() == "true" {
CLIFlags.Usage()
os.Exit(0)
Expand Down
1 change: 1 addition & 0 deletions internal/config/defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ var defOpts = map[string]interface{}{
"debug": true,
"trace": false,
"nocolor": runtime.GOOS == "windows",
"noconsole": false,
"use_date_filename": false,
"docker_logging": false,
"console_time_format": time.Kitchen,
Expand Down
2 changes: 1 addition & 1 deletion internal/config/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ type readerProvider struct {
}

func (r *readerProvider) ReadBytes() ([]byte, error) {
return io.ReadAll(r.source)
return io.ReadAll(r.source) //nolint:wrapcheck
}

func (r *readerProvider) Read() (map[string]interface{}, error) {
Expand Down
18 changes: 16 additions & 2 deletions internal/logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ type Configuration struct {
Debug bool `koanf:"debug"`
Trace bool `koanf:"trace"`
NoColor bool `koanf:"nocolor"`
NoConsole bool `koanf:"noconsole"`
DockerLogging bool `koanf:"docker_logging"`
// ConsoleTimeFormat sets the time format for the console.
// The string is passed to time.Format() down the line.
Expand Down Expand Up @@ -92,7 +93,6 @@ func (c *Configuration) Validate() error {
func (c *Configuration) setupDirAndFile() error {
switch {
case c.Directory != "":
println(c.Directory)
stat, err := os.Stat(c.Directory)
if err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("failed to access specified log directory: %w", err)
Expand All @@ -109,7 +109,6 @@ func (c *Configuration) setupDirAndFile() error {
c.File = "HellPot.log"
}
case c.Directory == "" && c.File != "":
println(c.File)
stat, err := os.Stat(filepath.Dir(c.File))
if err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("failed to access specified log directory: %w", err)
Expand Down Expand Up @@ -183,6 +182,21 @@ func (c *Configuration) SetupOutputs() error {
}
}

consoleSeen := false

for _, out := range c.Outputs {
if out == nil {
return fmt.Errorf("nil output provided")
}
if out == os.Stdout || out == os.Stderr {
consoleSeen = true
}
}

if !consoleSeen && !c.NoConsole {
c.Outputs = append(c.Outputs, os.Stdout)
}

return nil
}

Expand Down

0 comments on commit 362c1d3

Please sign in to comment.