diff options
| author | Paul Buetow <paul@buetow.org> | 2026-03-03 22:39:16 +0200 |
|---|---|---|
| committer | Paul Buetow <paul@buetow.org> | 2026-03-03 22:39:16 +0200 |
| commit | ac0a71de2a4a8894de849d10bbc4de962a5c0c2b (patch) | |
| tree | c0ddc25df27c7518ed8df08f8e9e16b4ccfdb6c8 /internal/cli/root.go | |
| parent | c3c347d6faed97d9cc02bf326e2a74786b0bde99 (diff) | |
Task 355: add cobra root command with config preload
Diffstat (limited to 'internal/cli/root.go')
| -rw-r--r-- | internal/cli/root.go | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/internal/cli/root.go b/internal/cli/root.go new file mode 100644 index 0000000..6029e81 --- /dev/null +++ b/internal/cli/root.go @@ -0,0 +1,59 @@ +package cli + +import ( + "fmt" + + timr "codeberg.org/snonux/timr/internal" + "codeberg.org/snonux/timr/internal/config" + "github.com/spf13/cobra" +) + +var loadedConfig = config.Default() + +// Execute runs the root command. +func Execute() error { + return NewRootCmd().Execute() +} + +// NewRootCmd creates the Cobra root command. +func NewRootCmd() *cobra.Command { + var configPath string + var showVersion bool + + cmd := &cobra.Command{ + Use: "timr", + Short: "Track time from your terminal", + SilenceUsage: true, + PersistentPreRunE: func(cmd *cobra.Command, args []string) error { + if showVersion { + return nil + } + + cfg, err := config.Load(configPath) + if err != nil { + return fmt.Errorf("load config: %w", err) + } + + loadedConfig = cfg + return nil + }, + RunE: func(cmd *cobra.Command, args []string) error { + if showVersion { + _, err := fmt.Fprintln(cmd.OutOrStdout(), timr.Version) + return err + } + + return cmd.Help() + }, + } + + cmd.Flags().BoolVar(&showVersion, "version", false, "Print version and exit") + cmd.PersistentFlags().StringVar(&configPath, "config", "", "Path to config file") + + return cmd +} + +// CurrentConfig returns the config loaded in PersistentPreRunE. +func CurrentConfig() config.Config { + return loadedConfig +} |
