package config import ( "context" "fmt" "os" "os/exec" "time" "git.dotya.ml/mirre-mt/pcmt/slogging" "github.com/philandstuff/dhall-golang/v6" ) type session struct { CookieName string CookieSecret string } type Config struct { Host string Port int AppName string LiveMode bool DevelMode bool Session session Registration struct{ Allowed bool } Logger struct { Json bool //nolint:revive Fmt string } } func LoadConfig(conf string, isPath bool) (*Config, error) { var config Config var err error if isPath { slogging.GetLogger().Debug("config from file") err = dhall.UnmarshalFile(conf, &config) } else { slogging.GetLogger().Debug("config raw from cmdline") err = dhall.Unmarshal([]byte(conf), &config) } if err != nil { return nil, err } if config.DevelMode { _ = slogging.SetLevel(slogging.LevelDebug) slogging.GetLogger().Debugf("parsed config: %+v", config) if dhallCmdExists() { _ = prettyPrintConfig(conf, isPath) } } return &config, nil } func prettyPrintConfig(conf string, isPath bool) error { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() var cmd *exec.Cmd if isPath { cmd = exec.CommandContext(ctx, "/bin/sh", "-c", "dhall --file "+conf) //nolint:gosec } else { cmd = exec.CommandContext(ctx, "/bin/sh", "-c", "dhall <<< \""+conf+"\"") //nolint:gosec } output, err := cmd.CombinedOutput() if err != nil { slogging.GetLogger().Debug("could not pretty-print config", "error", err) return err } if isPath { fmt.Fprintln(os.Stderr, "\n"+conf+":\n"+string(output)) } else { fmt.Fprintln(os.Stderr, "\nconfig:\n"+string(output)) } return nil } func dhallCmdExists() bool { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() if err := exec.CommandContext(ctx, "/bin/sh", "-c", "command -v dhall").Run(); err != nil { slogging.GetLogger().Debug("no command dhall") return false } return true }