forked from processone/gogen-avro.v4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
100 lines (86 loc) · 2.47 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
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"gopkg.in/alanctgardner/gogen-avro.v4/generator"
"gopkg.in/alanctgardner/gogen-avro.v4/types"
)
func main() {
packageName := flag.String("package", "avro", "Name of generated package")
flag.Parse()
if flag.NArg() < 2 {
fmt.Fprintf(os.Stderr, "Usage: gogen-avro [--package=<package name>] <target directory> <schema files>\n")
os.Exit(1)
}
targetDir := flag.Arg(0)
files := flag.Args()[1:]
var err error
pkg := generator.NewPackage(*packageName)
namespace := types.NewNamespace()
for _, fileName := range files {
schema, err := ioutil.ReadFile(fileName)
if err != nil {
fmt.Fprintf(os.Stderr, "Error reading file %q - %v\n", fileName, err)
os.Exit(2)
}
_, err = namespace.FieldDefinitionForSchema(schema)
if err != nil {
fmt.Fprintf(os.Stderr, "Error decoding schema for file %q - %v\n", fileName, err)
os.Exit(3)
}
}
// Resolve dependencies and add the schemas to the package
err = addFieldsToPackage(namespace, pkg)
if err != nil {
fmt.Fprintf(os.Stderr, "Error generating code for schema - %v\n", err)
os.Exit(4)
}
// Add header comment to all generated files.
for _, f := range pkg.Files() {
pkg.AddHeader(f, codegenComment(files))
}
err = pkg.WriteFiles(targetDir)
if err != nil {
fmt.Fprintf(os.Stderr, "Error writing source files to directory %q - %v\n", targetDir, err)
os.Exit(4)
}
}
func addFieldsToPackage(namespace *types.Namespace, pkg *generator.Package) error {
for _, schema := range namespace.Schemas {
err := schema.Root.ResolveReferences(namespace)
if err != nil {
return err
}
schema.Root.AddStruct(pkg)
schema.Root.AddSerializer(pkg)
schema.Root.AddDeserializer(pkg)
}
return nil
}
// codegenComment generates a comment informing readers they are looking at
// generated code and lists the source avro files used to generate the code
//
// invariant: sources > 0
func codegenComment(sources []string) string {
const fileComment = `/*
* CODE GENERATED AUTOMATICALLY WITH gopkg.in/alanctgardner/gogen-avro.v4
* THIS FILE SHOULD NOT BE EDITED BY HAND
*
* %s
*/`
var sourceBlock []string
if len(sources) == 1 {
sourceBlock = append(sourceBlock, "SOURCE:")
} else {
sourceBlock = append(sourceBlock, "SOURCES:")
}
for _, source := range sources {
_, fName := filepath.Split(source)
sourceBlock = append(sourceBlock, fmt.Sprintf(" * %s", fName))
}
return fmt.Sprintf(fileComment, strings.Join(sourceBlock, "\n"))
}