github.com/daixiang0/gci@v0.13.0/cmd/gci/root.go (about) 1 package gci 2 3 import ( 4 "fmt" 5 "os" 6 7 "github.com/spf13/cobra" 8 9 "github.com/daixiang0/gci/pkg/config" 10 "github.com/daixiang0/gci/pkg/gci" 11 "github.com/daixiang0/gci/pkg/log" 12 "github.com/daixiang0/gci/pkg/section" 13 ) 14 15 type Executor struct { 16 rootCmd *cobra.Command 17 diffMode *bool 18 writeMode *bool 19 localFlags *[]string 20 } 21 22 func NewExecutor(version string) *Executor { 23 log.InitLogger() 24 defer log.L().Sync() 25 26 e := Executor{} 27 rootCmd := cobra.Command{ 28 Use: "gci [-diff | -write] [--local localPackageURLs] path...", 29 Short: "Gci controls golang package import order and makes it always deterministic", 30 Long: "Gci enables automatic formatting of imports in a deterministic manner" + 31 "\n" + 32 "If you want to integrate this as part of your CI take a look at golangci-lint.", 33 ValidArgsFunction: subCommandOrGoFileCompletion, 34 Args: cobra.MinimumNArgs(1), 35 Version: version, 36 RunE: e.runInCompatibilityMode, 37 } 38 e.rootCmd = &rootCmd 39 e.diffMode = rootCmd.Flags().BoolP("diff", "d", false, "display diffs instead of rewriting files") 40 e.writeMode = rootCmd.Flags().BoolP("write", "w", false, "write result to (source) file instead of stdout") 41 e.localFlags = rootCmd.Flags().StringSliceP("local", "l", []string{}, "put imports beginning with this string after 3rd-party packages, separate imports by comma") 42 e.initDiff() 43 e.initPrint() 44 e.initWrite() 45 e.initList() 46 return &e 47 } 48 49 // Execute adds all child commands to the root command and sets flags appropriately. 50 // This is called by main.main(). It only needs to happen once to the rootCmd. 51 func (e *Executor) Execute() error { 52 return e.rootCmd.Execute() 53 } 54 55 func (e *Executor) runInCompatibilityMode(cmd *cobra.Command, args []string) error { 56 // Workaround since the Deprecation message in Cobra can not be printed to STDERR 57 _, _ = fmt.Fprintln(os.Stderr, "Using the old parameters is deprecated, please use the named subcommands!") 58 59 if *e.writeMode && *e.diffMode { 60 return fmt.Errorf("diff and write must not be specified at the same time") 61 } 62 // generate section specification from old localFlags format 63 sections := gci.LocalFlagsToSections(*e.localFlags) 64 sectionSeparators := section.DefaultSectionSeparators() 65 cfg := config.Config{ 66 BoolConfig: config.BoolConfig{ 67 NoInlineComments: false, 68 NoPrefixComments: false, 69 Debug: false, 70 SkipGenerated: false, 71 SkipVendor: false, 72 }, 73 Sections: sections, 74 SectionSeparators: sectionSeparators, 75 } 76 if *e.writeMode { 77 return gci.WriteFormattedFiles(args, cfg) 78 } 79 if *e.diffMode { 80 return gci.DiffFormattedFiles(args, cfg) 81 } 82 return gci.PrintFormattedFiles(args, cfg) 83 }