-
-
Notifications
You must be signed in to change notification settings - Fork 132
/
main.go
108 lines (96 loc) · 2.17 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
// Binary gotdgen generates go source code from TL schema.
package main
import (
"flag"
"fmt"
"go/format"
"os"
"path/filepath"
"strings"
"time"
"github.com/gotd/tl"
"github.com/gotd/td/internal/gen"
)
type formattedSource struct {
Format bool
Root string
}
func (t formattedSource) WriteFile(name string, content []byte) error {
out := content
if t.Format {
buf, err := format.Source(content)
if err != nil {
return err
}
out = buf
}
return os.WriteFile(filepath.Join(t.Root, name), out, 0600)
}
func main() {
schemaPath := flag.String("schema", "", "Path to .tl file")
targetDir := flag.String("target", "td", "Path to target dir")
packageName := flag.String("package", "td", "Target package name")
performFormat := flag.Bool("format", true, "Perform code formatting")
clean := flag.Bool("clean", false, "Clean generated files before generation")
genOpts := gen.GeneratorOptions{}
genOpts.RegisterFlags(flag.CommandLine)
flag.Parse()
if *schemaPath == "" {
panic("no schema provided")
}
f, err := os.Open(*schemaPath)
if err != nil {
panic(err)
}
defer func() { _ = f.Close() }()
schema, err := tl.Parse(f)
if err != nil {
panic(err)
}
files, err := os.ReadDir(*targetDir)
if err != nil && !os.IsNotExist(err) {
panic(err)
}
if os.IsNotExist(err) {
if err := os.Mkdir(*targetDir, 0750); err != nil {
panic(err)
}
}
if *clean {
for _, f := range files {
if f.IsDir() {
continue
}
name := f.Name()
if !strings.HasSuffix(name, "_gen.go") {
continue
}
if !strings.HasPrefix(name, "tl_") {
continue
}
if err := os.Remove(filepath.Join(*targetDir, name)); err != nil {
panic(err)
}
}
}
start := time.Now()
fs := formattedSource{
Root: *targetDir,
Format: *performFormat,
}
g, err := gen.NewGenerator(schema, genOpts)
if err != nil {
panic(fmt.Sprintf("%+v", err))
}
collectInfoTime := time.Since(start)
start = time.Now()
if err := g.WriteSource(fs, *packageName, gen.Template()); err != nil {
panic(fmt.Sprintf("%+v", err))
}
writeTime := time.Since(start)
fmt.Printf("Generation %s complete, collect time: %s, write time: %s\n",
*packageName,
collectInfoTime,
writeTime,
)
}