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.
5 //go:generate go build -o gotext.latest
6 //go:generate ./gotext.latest help gendocumentation
7 //go:generate rm gotext.latest
28 "golang.org/x/text/language"
29 "golang.org/x/tools/go/buildutil"
33 flag.Var((*buildutil.TagsFlag)(&build.Default.BuildTags), "tags", buildutil.TagsFlagDoc)
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")
41 // NOTE: the Command struct is copied from the go tool in core.
43 // A Command is an implementation of a go command
44 // like go build or go fix.
46 // Run runs the command.
47 // The args are the arguments after the command name.
48 Run func(cmd *Command, args []string) error
50 // UsageLine is the one-line usage message.
51 // The first word in the line is taken to be the command name.
54 // Short is the short description shown in the 'go help' output.
57 // Long is the long message shown in the 'go help <this-command>' output.
60 // Flag is a set of flags specific to this command.
64 // Name returns the command's name: the first word in the usage line.
65 func (c *Command) Name() string {
67 i := strings.Index(name, " ")
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))
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 {
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{
91 // - generate code from translations.
92 // - update: full-cycle update of extraction, sending, and integration
93 // - report: report of freshness of translations
99 func setExitStatus(n int) {
119 if args[0] == "help" {
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)
137 fmt.Fprintf(os.Stderr, "gotext: unknown subcommand %q\nRun 'go help' for usage.\n", args[0])
142 var usageTemplate = `gotext is a tool for managing text in Go source code.
146 gotext command [arguments]
149 {{range .}}{{if .Runnable}}
150 {{.Name | printf "%-11s"}} {{.Short}}{{end}}{{end}}
152 Use "go help [command]" for more information about a command.
154 Additional help topics:
155 {{range .}}{{if not .Runnable}}
156 {{.Name | printf "%-11s"}} {{.Short}}{{end}}{{end}}
158 Use "gotext help [topic]" for more information about that topic.
162 var helpTemplate = `{{if .Runnable}}usage: go {{.UsageLine}}
164 {{end}}{{.Long | trim}}
167 var documentationTemplate = `{{range .}}{{if .Short}}{{.Short | capitalize}}
169 {{end}}{{if .Runnable}}Usage:
173 {{end}}{{.Long | trim}}
178 // commentWriter writes a Go comment to the underlying io.Writer,
179 // using line comment form (//).
180 type commentWriter struct {
182 wroteSlashes bool // Wrote "//" at the beginning of the current line.
185 func (c *commentWriter) Write(p []byte) (int, error) {
187 for i, b := range p {
193 if _, err := io.WriteString(c.W, s); err != nil {
196 c.wroteSlashes = true
198 n0, err := c.W.Write(p[i : i+1])
204 c.wroteSlashes = false
210 // An errWriter wraps a writer, recording whether a write error occurred.
211 type errWriter struct {
216 func (w *errWriter) Write(b []byte) (int, error) {
217 n, err := w.w.Write(b)
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)
232 // I/O error writing. Ignore write on closed pipe.
233 if strings.Contains(ew.err.Error(), "pipe") {
236 fatalf("writing output: %v", ew.err)
243 func capitalize(s string) string {
247 r, n := utf8.DecodeRuneInString(s)
248 return string(unicode.ToTitle(r)) + s[n:]
251 func printUsage(w io.Writer) {
252 bw := bufio.NewWriter(w)
253 tmpl(bw, usageTemplate, commands)
258 printUsage(os.Stderr)
262 // help implements the 'help' command.
263 func help(args []string) {
265 printUsage(os.Stdout)
266 // not exit 2: succeeded at 'go help'.
270 fmt.Fprintf(os.Stderr, "usage: go help command\n\nToo many arguments given.\n")
271 os.Exit(2) // failed at 'go help'
276 // 'go help documentation' generates doc.go.
277 if strings.HasSuffix(arg, "documentation") {
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.")
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.")
287 buf := new(bytes.Buffer)
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())
295 errorf("Could not format generated docs: %v\n", err)
297 if err := ioutil.WriteFile("doc.go", b, 0666); err != nil {
298 errorf("Could not create file alldocs.go: %v\n", err)
301 fmt.Println(w.String())
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'.
314 fmt.Fprintf(os.Stderr, "Unknown help topic %#q. Run 'go help'.\n", arg)
315 os.Exit(2) // failed at 'go help cmd'
318 func getLangs() (tags []language.Tag) {
319 for _, t := range strings.Split(*langs, ",") {
320 tag, err := language.Parse(t)
322 fatalf("gotext: could not parse language %q: %v", t, err)
324 tags = append(tags, tag)
329 var atexitFuncs []func()
331 func atexit(f func()) {
332 atexitFuncs = append(atexitFuncs, f)
336 for _, f := range atexitFuncs {
342 func fatalf(format string, args ...interface{}) {
343 errorf(format, args...)
347 func errorf(format string, args ...interface{}) {
348 log.Printf(format, args...)
352 func exitIfErrors() {