forked from semrush/zenrpc
/
main.go
111 lines (89 loc) · 2.11 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package main
import (
"bytes"
"fmt"
"go/format"
"os"
"path/filepath"
"time"
"github.com/IlyushaZ/zenrpc/v3/parser"
)
const (
version = "3.0.0"
openIssueURL = "https://github.com/semrush/zenrpc/issues/new"
githubURL = "https://github.com/semrush/zenrpc"
)
func main() {
start := time.Now()
fmt.Printf("Generator version: %s\n", version)
var filename string
if len(os.Args) > 1 {
filename = os.Args[len(os.Args)-1]
} else {
filename = os.Getenv("GOFILE")
}
if filename == "" {
_, _ = fmt.Fprintln(os.Stderr, "File path is empty")
os.Exit(1)
}
fmt.Printf("Entrypoint: %s\n", filename)
// create package info
pi, err := parser.NewPackageInfo(filename)
if err != nil {
printError(err)
os.Exit(1)
}
outputFileName := filepath.Join(pi.Dir, "zenrpc.go")
// remove output file if it already exists
if _, err := os.Stat(outputFileName); err == nil {
if err := os.Remove(outputFileName); err != nil {
printError(err)
os.Exit(1)
}
}
if err := pi.Parse(filename); err != nil {
printError(err)
os.Exit(1)
}
if len(pi.Services) == 0 {
fmt.Fprintln(os.Stderr, "Services not found")
os.Exit(1)
}
if err := generateFile(outputFileName, pi); err != nil {
printError(err)
os.Exit(1)
}
fmt.Printf("Generated: %s\n", outputFileName)
fmt.Printf("Duration: %dms\n", int64(time.Since(start)/time.Millisecond))
fmt.Println()
fmt.Print(pi)
fmt.Println()
}
func printError(err error) {
// print error to stderr
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
// print contact information to stdout
fmt.Println("\nYou may help us and create issue:")
fmt.Printf("\t%s\n", openIssueURL)
fmt.Println("For more information, see:")
fmt.Printf("\t%s\n\n", githubURL)
}
func generateFile(outputFileName string, pi *parser.PackageInfo) error {
file, err := os.Create(outputFileName)
if err != nil {
return err
}
defer file.Close()
output := new(bytes.Buffer)
if err := serviceTemplate.Execute(output, pi); err != nil {
return err
}
source, err := format.Source(output.Bytes())
if err != nil {
return err
}
if _, err = file.Write(source); err != nil {
return err
}
return nil
}