OSDN Git Service

new repo
[bytom/vapor.git] / vendor / golang.org / x / text / cmd / gotext / main.go
1 // Copyright 2016 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 //go:generate go build -o gotext.latest
6 //go:generate ./gotext.latest help gendocumentation
7 //go:generate rm gotext.latest
8
9 package main
10
11 import (
12         "bufio"
13         "bytes"
14         "flag"
15         "fmt"
16         "go/build"
17         "go/format"
18         "io"
19         "io/ioutil"
20         "log"
21         "os"
22         "strings"
23         "sync"
24         "text/template"
25         "unicode"
26         "unicode/utf8"
27
28         "golang.org/x/text/language"
29         "golang.org/x/tools/go/buildutil"
30 )
31
32 func init() {
33         flag.Var((*buildutil.TagsFlag)(&build.Default.BuildTags), "tags", buildutil.TagsFlagDoc)
34 }
35
36 var (
37         dir   = flag.String("dir", "textdata", "default subdirectory to store translation files")
38         langs = flag.String("lang", "en", "comma-separated list of languages to process")
39 )
40
41 // NOTE: the Command struct is copied from the go tool in core.
42
43 // A Command is an implementation of a go command
44 // like go build or go fix.
45 type Command struct {
46         // Run runs the command.
47         // The args are the arguments after the command name.
48         Run func(cmd *Command, args []string) error
49
50         // UsageLine is the one-line usage message.
51         // The first word in the line is taken to be the command name.
52         UsageLine string
53
54         // Short is the short description shown in the 'go help' output.
55         Short string
56
57         // Long is the long message shown in the 'go help <this-command>' output.
58         Long string
59
60         // Flag is a set of flags specific to this command.
61         Flag flag.FlagSet
62 }
63
64 // Name returns the command's name: the first word in the usage line.
65 func (c *Command) Name() string {
66         name := c.UsageLine
67         i := strings.Index(name, " ")
68         if i >= 0 {
69                 name = name[:i]
70         }
71         return name
72 }
73
74 func (c *Command) Usage() {
75         fmt.Fprintf(os.Stderr, "usage: %s\n\n", c.UsageLine)
76         fmt.Fprintf(os.Stderr, "%s\n", strings.TrimSpace(c.Long))
77         os.Exit(2)
78 }
79
80 // Runnable reports whether the command can be run; otherwise
81 // it is a documentation pseudo-command such as importpath.
82 func (c *Command) Runnable() bool {
83         return c.Run != nil
84 }
85
86 // Commands lists the available commands and help topics.
87 // The order here is the order in which they are printed by 'go help'.
88 var commands = []*Command{
89         cmdExtract,
90         // TODO:
91         // - generate code from translations.
92         // - update: full-cycle update of extraction, sending, and integration
93         // - report: report of freshness of translations
94 }
95
96 var exitStatus = 0
97 var exitMu sync.Mutex
98
99 func setExitStatus(n int) {
100         exitMu.Lock()
101         if exitStatus < n {
102                 exitStatus = n
103         }
104         exitMu.Unlock()
105 }
106
107 var origEnv []string
108
109 func main() {
110         flag.Usage = usage
111         flag.Parse()
112         log.SetFlags(0)
113
114         args := flag.Args()
115         if len(args) < 1 {
116                 usage()
117         }
118
119         if args[0] == "help" {
120                 help(args[1:])
121                 return
122         }
123
124         for _, cmd := range commands {
125                 if cmd.Name() == args[0] && cmd.Runnable() {
126                         cmd.Flag.Usage = func() { cmd.Usage() }
127                         cmd.Flag.Parse(args[1:])
128                         args = cmd.Flag.Args()
129                         if err := cmd.Run(cmd, args); err != nil {
130                                 fatalf("gotext: %v", err)
131                         }
132                         exit()
133                         return
134                 }
135         }
136
137         fmt.Fprintf(os.Stderr, "gotext: unknown subcommand %q\nRun 'go help' for usage.\n", args[0])
138         setExitStatus(2)
139         exit()
140 }
141
142 var usageTemplate = `gotext is a tool for managing text in Go source code.
143
144 Usage:
145
146         gotext command [arguments]
147
148 The commands are:
149 {{range .}}{{if .Runnable}}
150         {{.Name | printf "%-11s"}} {{.Short}}{{end}}{{end}}
151
152 Use "go help [command]" for more information about a command.
153
154 Additional help topics:
155 {{range .}}{{if not .Runnable}}
156         {{.Name | printf "%-11s"}} {{.Short}}{{end}}{{end}}
157
158 Use "gotext help [topic]" for more information about that topic.
159
160 `
161
162 var helpTemplate = `{{if .Runnable}}usage: go {{.UsageLine}}
163
164 {{end}}{{.Long | trim}}
165 `
166
167 var documentationTemplate = `{{range .}}{{if .Short}}{{.Short | capitalize}}
168
169 {{end}}{{if .Runnable}}Usage:
170
171         go {{.UsageLine}}
172
173 {{end}}{{.Long | trim}}
174
175
176 {{end}}`
177
178 // commentWriter writes a Go comment to the underlying io.Writer,
179 // using line comment form (//).
180 type commentWriter struct {
181         W            io.Writer
182         wroteSlashes bool // Wrote "//" at the beginning of the current line.
183 }
184
185 func (c *commentWriter) Write(p []byte) (int, error) {
186         var n int
187         for i, b := range p {
188                 if !c.wroteSlashes {
189                         s := "//"
190                         if b != '\n' {
191                                 s = "// "
192                         }
193                         if _, err := io.WriteString(c.W, s); err != nil {
194                                 return n, err
195                         }
196                         c.wroteSlashes = true
197                 }
198                 n0, err := c.W.Write(p[i : i+1])
199                 n += n0
200                 if err != nil {
201                         return n, err
202                 }
203                 if b == '\n' {
204                         c.wroteSlashes = false
205                 }
206         }
207         return len(p), nil
208 }
209
210 // An errWriter wraps a writer, recording whether a write error occurred.
211 type errWriter struct {
212         w   io.Writer
213         err error
214 }
215
216 func (w *errWriter) Write(b []byte) (int, error) {
217         n, err := w.w.Write(b)
218         if err != nil {
219                 w.err = err
220         }
221         return n, err
222 }
223
224 // tmpl executes the given template text on data, writing the result to w.
225 func tmpl(w io.Writer, text string, data interface{}) {
226         t := template.New("top")
227         t.Funcs(template.FuncMap{"trim": strings.TrimSpace, "capitalize": capitalize})
228         template.Must(t.Parse(text))
229         ew := &errWriter{w: w}
230         err := t.Execute(ew, data)
231         if ew.err != nil {
232                 // I/O error writing. Ignore write on closed pipe.
233                 if strings.Contains(ew.err.Error(), "pipe") {
234                         os.Exit(1)
235                 }
236                 fatalf("writing output: %v", ew.err)
237         }
238         if err != nil {
239                 panic(err)
240         }
241 }
242
243 func capitalize(s string) string {
244         if s == "" {
245                 return s
246         }
247         r, n := utf8.DecodeRuneInString(s)
248         return string(unicode.ToTitle(r)) + s[n:]
249 }
250
251 func printUsage(w io.Writer) {
252         bw := bufio.NewWriter(w)
253         tmpl(bw, usageTemplate, commands)
254         bw.Flush()
255 }
256
257 func usage() {
258         printUsage(os.Stderr)
259         os.Exit(2)
260 }
261
262 // help implements the 'help' command.
263 func help(args []string) {
264         if len(args) == 0 {
265                 printUsage(os.Stdout)
266                 // not exit 2: succeeded at 'go help'.
267                 return
268         }
269         if len(args) != 1 {
270                 fmt.Fprintf(os.Stderr, "usage: go help command\n\nToo many arguments given.\n")
271                 os.Exit(2) // failed at 'go help'
272         }
273
274         arg := args[0]
275
276         // 'go help documentation' generates doc.go.
277         if strings.HasSuffix(arg, "documentation") {
278                 w := &bytes.Buffer{}
279
280                 fmt.Fprintln(w, "// Copyright 2016 The Go Authors. All rights reserved.")
281                 fmt.Fprintln(w, "// Use of this source code is governed by a BSD-style")
282                 fmt.Fprintln(w, "// license that can be found in the LICENSE file.")
283                 fmt.Fprintln(w)
284                 fmt.Fprintln(w, "// DO NOT EDIT THIS FILE. GENERATED BY go generate.")
285                 fmt.Fprintln(w, "// Edit the documentation in other files and rerun go generate to generate this one.")
286                 fmt.Fprintln(w)
287                 buf := new(bytes.Buffer)
288                 printUsage(buf)
289                 usage := &Command{Long: buf.String()}
290                 tmpl(&commentWriter{W: w}, documentationTemplate, append([]*Command{usage}, commands...))
291                 fmt.Fprintln(w, "package main")
292                 if arg == "gendocumentation" {
293                         b, err := format.Source(w.Bytes())
294                         if err != nil {
295                                 errorf("Could not format generated docs: %v\n", err)
296                         }
297                         if err := ioutil.WriteFile("doc.go", b, 0666); err != nil {
298                                 errorf("Could not create file alldocs.go: %v\n", err)
299                         }
300                 } else {
301                         fmt.Println(w.String())
302                 }
303                 return
304         }
305
306         for _, cmd := range commands {
307                 if cmd.Name() == arg {
308                         tmpl(os.Stdout, helpTemplate, cmd)
309                         // not exit 2: succeeded at 'go help cmd'.
310                         return
311                 }
312         }
313
314         fmt.Fprintf(os.Stderr, "Unknown help topic %#q.  Run 'go help'.\n", arg)
315         os.Exit(2) // failed at 'go help cmd'
316 }
317
318 func getLangs() (tags []language.Tag) {
319         for _, t := range strings.Split(*langs, ",") {
320                 tag, err := language.Parse(t)
321                 if err != nil {
322                         fatalf("gotext: could not parse language %q: %v", t, err)
323                 }
324                 tags = append(tags, tag)
325         }
326         return tags
327 }
328
329 var atexitFuncs []func()
330
331 func atexit(f func()) {
332         atexitFuncs = append(atexitFuncs, f)
333 }
334
335 func exit() {
336         for _, f := range atexitFuncs {
337                 f()
338         }
339         os.Exit(exitStatus)
340 }
341
342 func fatalf(format string, args ...interface{}) {
343         errorf(format, args...)
344         exit()
345 }
346
347 func errorf(format string, args ...interface{}) {
348         log.Printf(format, args...)
349         setExitStatus(1)
350 }
351
352 func exitIfErrors() {
353         if exitStatus != 0 {
354                 exit()
355         }
356 }