This repository has been archived by the owner on Feb 27, 2021. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
107 lines (95 loc) · 2.05 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
package main
import (
"bufio"
"flag"
"fmt"
"go/build"
"io"
"log"
"os"
"path"
"strings"
)
func main() {
var (
inFile = flag.String("in", "", "input file (required)")
outFile = flag.String("out", "", "output file")
pkgName = flag.String("pkg", "", "package name")
)
flag.Parse()
if *inFile == "" {
flag.Usage()
return
}
if *outFile == "" {
*outFile = fileName(*inFile)
}
if *pkgName == "" {
pkg, err := packageName(*outFile)
if err != nil {
log.Fatal(err)
}
*pkgName = pkg
}
r, err := os.Open(*inFile)
if err != nil {
log.Fatal(err)
}
defer r.Close()
w, err := os.Create(*outFile)
if err != nil {
log.Fatal(err)
}
defer w.Close()
banner := strings.Join(os.Args, " ")
if err := generate(w, r, *inFile, *pkgName, banner); err != nil {
log.Fatal(err)
}
}
func generate(w io.Writer, r io.Reader, fname, pkg, banner string) error {
vname := varName(fname)
fmt.Fprintf(w, "// Code generated by %q; DO NOT EDIT.\n\n", banner)
fmt.Fprintf(w, "package %s\n\n", pkg)
fmt.Fprintf(w, "// %s holds content of %s\n", vname, fname)
fmt.Fprintf(w, "var %s = []byte{", vname)
scanner := bufio.NewScanner(r)
scanner.Split(scanBytes)
for scanner.Scan() {
fmt.Fprint(w, "\n\t")
b := scanner.Bytes()
for i, v := range b {
fmt.Fprintf(w, "%#02x,", v)
if i != len(b)-1 {
fmt.Fprint(w, " ")
}
}
}
fmt.Fprint(w, "\n}\n")
return scanner.Err()
}
func scanBytes(data []byte, atEOF bool) (advance int, token []byte, err error) {
const n = 12
switch {
case atEOF && len(data) == 0:
return 0, nil, nil
case !atEOF && len(data) < n:
return 0, nil, nil
case atEOF:
return len(data), data, nil
default:
return n, data[:n], nil
}
}
func varName(file string) string {
return strings.Replace(strings.Title(path.Base(file)), ".", "", -1)
}
func fileName(file string) string {
return strings.Replace(strings.ToLower(path.Base(file)), ".", "_", -1) + ".go"
}
func packageName(dir string) (string, error) {
pkg, err := build.Default.ImportDir(path.Dir(dir), 0)
if err != nil {
return "", err
}
return pkg.Name, nil
}