-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
110 lines (102 loc) · 2.19 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
package main
import (
"bytes"
"fmt"
"io"
"log"
"os"
flag "github.com/spf13/pflag"
)
const currentVersion = "v0.1.0"
var (
input string
output string
pkgname string
varname string
version bool
)
func init() {
flag.StringVarP(&input, "input", "i", "", "Input file name, default is stdin.")
flag.StringVarP(&output, "output", "o", "", "Output file name, default is stdout.")
flag.StringVarP(&pkgname, "pkgname", "p", "", "package name, if not empty, output is in go's format.")
flag.StringVarP(&varname, "varname", "v", "varname", "var name")
flag.BoolVarP(&version, "version", "", false, "print version.")
flag.Usage = func() {
fmt.Println(`Wrap string in go style with backtick(` + "`)")
fmt.Printf("Usage of %s\n", os.Args[0])
flag.PrintDefaults()
}
}
func main() {
flag.Parse()
if version {
fmt.Println(currentVersion)
return
}
var ifs io.Reader
var ofs io.Writer
var err error
if input == "" {
ifs = os.Stdin
} else {
if ifs, err = os.Open(input); err != nil {
log.Println(err)
}
}
if output == "" {
ofs = os.Stdout
} else {
// Must Trunc when the origin file is longer than the new one.
if ofs, err = os.OpenFile(output, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666); err != nil {
log.Println(err)
}
}
var buf bytes.Buffer
if _, err := io.Copy(&buf, ifs); err != nil {
log.Println(err)
}
bt := backtick(buf.String())
if pkgname != "" {
fmt.Fprintf(ofs, "package %s\n\nvar %s = ", pkgname, varname)
}
fmt.Fprint(ofs, bt)
}
// func openOrDefault(f string, )
func backtick(s string) string {
buf := bytes.NewBufferString("")
// var inbacktick = false
var backticks = ""
bs := []byte(s)
n := len(bs)
first := true
inbacktick := false
for i := 0; i < n; i++ {
b := bs[i]
if b == '`' {
inbacktick = false
backticks += "`"
if i == n-1 || bs[i+1] != '`' {
if !first {
buf.WriteString("+\n")
}
buf.WriteString(`"` + backticks + `"`)
backticks = ""
first = false
}
} else {
if !inbacktick {
if !first {
buf.WriteString("+\n")
}
buf.WriteByte('`')
inbacktick = true
}
buf.WriteByte(b)
if i == n-1 || bs[i+1] == '`' {
buf.WriteByte('`')
}
first = false
}
}
return buf.String()
}