summaryrefslogtreecommitdiffstats
path: root/cmd
diff options
context:
space:
mode:
Diffstat (limited to 'cmd')
-rw-r--r--cmd/root.go46
1 files changed, 46 insertions, 0 deletions
diff --git a/cmd/root.go b/cmd/root.go
index a5d407f..d09baf6 100644
--- a/cmd/root.go
+++ b/cmd/root.go
@@ -11,6 +11,10 @@ import (
var (
jsonOutput bool
debugOutput bool
+ outputFile string
+ appendFile bool
+ origStdout *os.File
+ outFile *os.File
)
var rootCmd = &cobra.Command{
@@ -21,8 +25,14 @@ var rootCmd = &cobra.Command{
▀▀▀▀ ▀▀▀▀ ▀ ▀▀▀▀ ▀ ▀ ▀▀▀▀ ▀ ▀ ▀ ▀▀▀
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,
}
@@ -37,6 +47,8 @@ func Execute() {
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 {
@@ -46,3 +58,37 @@ func IsJSONOutput() bool {
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
+}