Bluemage/go/cmd/bluemage/main.go

79 lines
1.7 KiB
Go

package main
import (
"context"
"fmt"
"log/slog"
"os"
"os/signal"
"github.com/adrg/xdg"
"github.com/joho/godotenv"
"github.com/spf13/cobra"
"github.com/tigorlazuardi/bluemage/go/cmd/bluemage/serve"
"github.com/tigorlazuardi/bluemage/go/config"
)
var Cmd = &cobra.Command{
Use: "bluemage",
Short: "Bluemage is a reddit image downloader",
}
func init() {
Cmd.AddCommand(serve.Cmd)
flags := Cmd.PersistentFlags()
for _, entry := range config.DefaultConfig {
key, value, desc, hidden := entry.Key, entry.Value, entry.Desc, entry.Hidden
switch v := value.(type) {
case bool:
flags.Bool(key, v, desc)
case string:
flags.String(key, v, desc)
case int:
flags.Int(key, v, desc)
case float32:
flags.Float32(key, v, desc)
case float64:
flags.Float64(key, v, desc)
case []string:
flags.StringSlice(key, v, desc)
default:
flags.String(key, fmt.Sprintf("%v", v), desc)
}
if hidden {
flags.MarkHidden(key)
}
}
}
func main() {
_ = godotenv.Load()
xdgJson, _ := xdg.ConfigFile("bluemage/config.json")
xdgYaml, _ := xdg.ConfigFile("bluemage/config.yaml")
cfg, err := config.NewConfigBuilder().
LoadDefault().
LoadJSONFile("/etc/bluemage/config.json").
LoadYamlFile("/etc/bluemage/config.yaml").
LoadJSONFile(xdgJson).
LoadYamlFile(xdgYaml).
LoadJSONFile("config.json").
LoadYamlFile("config.yaml").
LoadEnv().
LoadFlags(Cmd.PersistentFlags()).
BuildHandle()
if err != nil {
slog.Error("BLUEMAGE: failed to load config", "error", err)
os.Exit(1)
}
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()
ctx = config.WithContext(ctx, cfg)
if err := Cmd.ExecuteContext(ctx); err != nil {
slog.ErrorContext(ctx, err.Error(), "error", err)
os.Exit(1)
}
}