-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
86 lines (76 loc) · 2.22 KB
/
main.go
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
package main
import (
"bytes"
"flag"
"fmt"
"github.com/go-leo/gors/cmd/internal"
"github.com/go-leo/gors/internal/pkg/parser"
"go/format"
"log"
"os"
"path/filepath"
"strings"
)
var (
serviceName = flag.String("service", "", "service interface Name; must be set")
pathToLower = flag.Bool("path_to_lower", false, "make path to lower case")
)
// Usage is a replacement usage function for the flags package.
func Usage() {
fmt.Fprintf(os.Stderr, "Usage of gors:\n")
fmt.Fprintf(os.Stderr, "\tgors -service S\n")
fmt.Fprintf(os.Stderr, "Flags:\n")
flag.PrintDefaults()
}
func init() {
log.SetFlags(0)
log.SetPrefix("gors: ")
}
func main() {
showVersion := flag.Bool("version", false, "print the version and exit")
flag.Usage = Usage
flag.Parse()
if *showVersion {
fmt.Printf("gors %v\n", internal.Version)
return
}
// must set service names
if len(*serviceName) == 0 {
flag.Usage()
os.Exit(2)
}
// We accept either one directory or a list of files. Which do we have?
args := flag.Args()
if len(args) == 0 {
// Default: process whole package in current directory.
args = []string{"."}
}
serviceInfo, err := parser.ParseService(args, *serviceName, *pathToLower)
if err != nil {
log.Fatal(err)
}
g := &generate{
buf: &bytes.Buffer{},
headerBuf: &bytes.Buffer{},
importsBuf: &bytes.Buffer{},
functionBuf: &bytes.Buffer{},
header: fmt.Sprintf(`// Code generated by "gors %s"; DO NOT EDIT.`, strings.Join(os.Args[1:], " ")),
usedPackageNames: make(map[string]bool),
serviceInfo: serviceInfo,
}
content := g.content()
// Format the output.
src, err := format.Source(content)
if err != nil {
// Should never happen, but can arise when developing this code.
// The user can compile the output to see the error.
log.Printf("warning: internal error: invalid Go generated: %s", err)
log.Printf("warning: compile the package to analyze the error")
src = content
}
outputPath := filepath.Join(serviceInfo.OutDir, fmt.Sprintf("%s_gors.go", strings.ToLower(*serviceName)))
if err := os.WriteFile(outputPath, src, 0644); err != nil {
log.Fatalf("writing output: %s", err)
}
log.Printf("%s.%s wrote %s", serviceInfo.PkgPath, *serviceName, outputPath)
}