@@ -22,13 +22,18 @@ THE SOFTWARE.
2222package cmd
2323
2424import (
25- "github.com/foolin/sumdiff/internal/plog"
2625 "os"
26+ "path/filepath"
2727
28+ "github.com/foolin/sumdiff/internal/util"
29+ "github.com/foolin/sumdiff/internal/vlog"
30+ "github.com/foolin/sumdiff/internal/write"
2831 "github.com/spf13/cobra"
2932)
3033
31- var verbose bool
34+ var config * Config
35+ var writer * write.Writer
36+ var file * os.File
3237
3338// rootCmd represents the base command when called without any subcommands
3439var rootCmd = & cobra.Command {
@@ -39,8 +44,43 @@ var rootCmd = &cobra.Command{
3944 // has an action associated with it:
4045 // Run: func(cmd *cobra.Command, args []string) { },
4146 PersistentPreRun : func (cmd * cobra.Command , args []string ) {
42- //fmt.Println("verbose:", verbose)
43- plog .SetVerbose (verbose )
47+ //Verbose
48+ vlog .SetVerbose (config .Verbose )
49+
50+ //Write
51+ format := write .Table
52+ if config .Format != "" {
53+ var ok bool
54+ format , ok = write .FormatOfName (config .Format )
55+ if ! ok {
56+ vlog .Exit (1 , "Format invalid: %v\n " , config .Format )
57+ return
58+ }
59+ }
60+
61+ w := os .Stdout
62+ if config .Output != "" {
63+ path := util .FormatPath (config .Output )
64+ _ = os .MkdirAll (filepath .Dir (path ), 0755 )
65+ var err error
66+ file , err = os .OpenFile (path , os .O_CREATE | os .O_TRUNC | os .O_RDWR , 0666 )
67+ if err != nil {
68+ vlog .Exit (1 , "Open file %v error: %\n " , path , err )
69+ return
70+ }
71+ w = file
72+ }
73+
74+ //Create writer
75+ writer = write .New (w , format )
76+ },
77+ PersistentPostRun : func (cmd * cobra.Command , args []string ) {
78+ if file != nil {
79+ err := file .Close ()
80+ if err != nil {
81+ vlog .Printf ("Close file error: %v\n " , err )
82+ }
83+ }
4484 },
4585}
4686
@@ -59,8 +99,15 @@ func init() {
5999 // Cobra supports persistent flags, which, if defined here,
60100 // will be global for your application.
61101
102+ config = & Config {
103+ Verbose : false ,
104+ Format : "table" ,
105+ Output : "" ,
106+ }
62107 // rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.sumdiff.yaml)")
63- rootCmd .PersistentFlags ().BoolVarP (& verbose , "verbose" , "v" , false , "Verbose output info" )
108+ rootCmd .PersistentFlags ().BoolVarP (& config .Verbose , "verbose" , "v" , false , "Verbose output info" )
109+ rootCmd .PersistentFlags ().StringVarP (& config .Format , "format" , "f" , "table" , "Format: table|json|csv|yaml" )
110+ rootCmd .PersistentFlags ().StringVarP (& config .Output , "output" , "o" , "" , "Output filename" )
64111
65112 // Cobra also supports local flags, which will only run
66113 // when this action is called directly.
0 commit comments