summaryrefslogtreecommitdiffstats
path: root/cmd/root.go
blob: d09baf6bcd441f60f64d27846cbcdb0cf112ad23 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package cmd

import (
	"fmt"
	"os"

	"git.db.org.ai/dborg/internal/utils"
	"github.com/spf13/cobra"
)

var (
	jsonOutput  bool
	debugOutput bool
	outputFile  string
	appendFile  bool
	origStdout  *os.File
	outFile     *os.File
)

var rootCmd = &cobra.Command{
	Use:   "dborg",
	Short: "DB.org.ai CLI client",
	Long: `█▀▀▄ █▀▀▄   █▀▀█ █▀▀█ █▀▀▀   █▀▀█ ▀█▀
█░░█░█▀▀▄░░░█░░█░█▄▄▀░█░▀█░░░█▄▄█░░█
▀▀▀▀ ▀▀▀▀ ▀ ▀▀▀▀ ▀  ▀ ▀▀▀▀ ▀ ▀  ▀ ▀▀▀
DB.org.ai CLI client`,
	PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
		if err := setupOutputFile(); err != nil {
			return err
		}
		return utils.CheckForUpdates(cmd)
	},
	PersistentPostRunE: func(cmd *cobra.Command, args []string) error {
		return teardownOutputFile()
	},
	SilenceUsage:  true,
	SilenceErrors: true,
}

func Execute() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

func init() {
	rootCmd.PersistentFlags().BoolVarP(&jsonOutput, "json", "j", false, "Output raw JSON instead of formatted text")
	rootCmd.PersistentFlags().BoolVarP(&debugOutput, "debug", "d", false, "Enable debug output (shows raw API responses)")
	rootCmd.PersistentFlags().StringVarP(&outputFile, "output", "o", "", "Write output to file instead of stdout")
	rootCmd.PersistentFlags().BoolVar(&appendFile, "append", false, "Append to output file instead of overwriting (use with -o)")
}

func IsJSONOutput() bool {
	return jsonOutput
}

func IsDebugOutput() bool {
	return debugOutput
}

func setupOutputFile() error {
	if outputFile == "" {
		return nil
	}
	flags := os.O_CREATE | os.O_WRONLY
	if appendFile {
		flags |= os.O_APPEND
	} else {
		flags |= os.O_TRUNC
	}
	f, err := os.OpenFile(outputFile, flags, 0644)
	if err != nil {
		return fmt.Errorf("failed to open output file: %w", err)
	}
	origStdout = os.Stdout
	os.Stdout = f
	outFile = f
	return nil
}

func teardownOutputFile() error {
	if outFile == nil {
		return nil
	}
	err := outFile.Close()
	os.Stdout = origStdout
	if err != nil {
		return fmt.Errorf("failed to close output file: %w", err)
	}
	fmt.Fprintf(os.Stderr, "Output written to %s\n", outputFile)
	outFile = nil
	return nil
}