github.com/Capventis/moq@v0.2.6-0.20220316100624-05dd47497214/main.go (about) 1 package main 2 3 import ( 4 "bytes" 5 "errors" 6 "flag" 7 "fmt" 8 "io" 9 "io/ioutil" 10 "os" 11 "path/filepath" 12 13 "github.com/Capventis/moq/pkg/moq" 14 ) 15 16 // Version is the command version, injected at build time. 17 var Version string = "dev" 18 19 type userFlags struct { 20 outFile string 21 pkgName string 22 formatter string 23 stubImpl bool 24 skipEnsure bool 25 remove bool 26 args []string 27 } 28 29 func main() { 30 var flags userFlags 31 flag.StringVar(&flags.outFile, "out", "", "output file (default stdout)") 32 flag.StringVar(&flags.pkgName, "pkg", "", "package name (default will infer)") 33 flag.StringVar(&flags.formatter, "fmt", "", "go pretty-printer: gofmt, goimports or noop (default gofmt)") 34 flag.BoolVar(&flags.stubImpl, "stub", false, 35 "return zero values when no mock implementation is provided, do not panic") 36 printVersion := flag.Bool("version", false, "show the version for moq") 37 flag.BoolVar(&flags.skipEnsure, "skip-ensure", false, 38 "suppress mock implementation check, avoid import cycle if mocks generated outside of the tested package") 39 flag.BoolVar(&flags.remove, "rm", false, "first remove output file, if it exists") 40 41 flag.Usage = func() { 42 fmt.Println(`moq [flags] source-dir interface [interface2 [interface3 [...]]]`) 43 flag.PrintDefaults() 44 fmt.Println(`Specifying an alias for the mock is also supported with the format 'interface:alias'`) 45 fmt.Println(`Ex: moq -pkg different . MyInterface:MyMock`) 46 } 47 48 flag.Parse() 49 flags.args = flag.Args() 50 51 if *printVersion { 52 fmt.Printf("moq version %s\n", Version) 53 os.Exit(0) 54 } 55 56 if err := run(flags); err != nil { 57 fmt.Fprintln(os.Stderr, err) 58 flag.Usage() 59 os.Exit(1) 60 } 61 } 62 63 func run(flags userFlags) error { 64 if len(flags.args) < 2 { 65 return errors.New("not enough arguments") 66 } 67 68 if flags.remove && flags.outFile != "" { 69 if err := os.Remove(flags.outFile); err != nil { 70 if !errors.Is(err, os.ErrNotExist) { 71 return err 72 } 73 } 74 } 75 76 var buf bytes.Buffer 77 var out io.Writer = os.Stdout 78 if flags.outFile != "" { 79 out = &buf 80 } 81 82 srcDir, args := flags.args[0], flags.args[1:] 83 m, err := moq.New(moq.Config{ 84 SrcDir: srcDir, 85 PkgName: flags.pkgName, 86 Formatter: flags.formatter, 87 StubImpl: flags.stubImpl, 88 SkipEnsure: flags.skipEnsure, 89 }) 90 if err != nil { 91 return err 92 } 93 94 if err = m.Mock(out, args...); err != nil { 95 return err 96 } 97 98 if flags.outFile == "" { 99 return nil 100 } 101 102 // create the file 103 err = os.MkdirAll(filepath.Dir(flags.outFile), 0750) 104 if err != nil { 105 return err 106 } 107 108 return ioutil.WriteFile(flags.outFile, buf.Bytes(), 0600) 109 }