summaryrefslogtreecommitdiff
path: root/vendor/golang.org/x/text/cmd/gotext/generate.go
blob: 2d3446502d76d6f4fad06fec066a5a2d3545b91a (plain)
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
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"regexp"
	"strings"

	"golang.org/x/text/message/pipeline"
	"golang.org/x/tools/go/loader"
)

func init() {
	out = cmdGenerate.Flag.String("out", "", "output file to write to")
}

var (
	out *string
)

var cmdGenerate = &Command{
	Run:       runGenerate,
	UsageLine: "generate <package>",
	Short:     "generates code to insert translated messages",
}

var transRe = regexp.MustCompile(`messages\.(.*)\.json`)

func runGenerate(cmd *Command, args []string) error {

	prog, err := loadPackages(&loader.Config{}, args)
	if err != nil {
		return wrap(err, "could not load package")
	}

	pkgs := prog.InitialPackages()
	if len(pkgs) != 1 {
		return fmt.Errorf("more than one package selected: %v", pkgs)
	}
	pkg := pkgs[0].Pkg.Name()

	// TODO: add in external input. Right now we assume that all files are
	// manually created and stored in the textdata directory.

	// Build up index of translations and original messages.
	extracted := pipeline.Locale{}
	translations := []*pipeline.Locale{}

	err = filepath.Walk(*dir, func(path string, f os.FileInfo, err error) error {
		if err != nil {
			return wrap(err, "loading data")
		}
		if f.IsDir() {
			return nil
		}
		if f.Name() == extractFile {
			b, err := ioutil.ReadFile(path)
			if err != nil {
				return wrap(err, "read file failed")
			}
			if err := json.Unmarshal(b, &extracted); err != nil {
				return wrap(err, "unmarshal source failed")
			}
			return nil
		}
		if f.Name() == outFile {
			return nil
		}
		if !strings.HasSuffix(path, gotextSuffix) {
			return nil
		}
		b, err := ioutil.ReadFile(path)
		if err != nil {
			return wrap(err, "read file failed")
		}
		var locale pipeline.Locale
		if err := json.Unmarshal(b, &locale); err != nil {
			return wrap(err, "parsing translation file failed")
		}
		translations = append(translations, &locale)
		return nil
	})
	if err != nil {
		return err
	}

	w := os.Stdout
	if *out != "" {
		w, err = os.Create(*out)
		if err != nil {
			return wrap(err, "create file failed")
		}
	}

	_, err = pipeline.Generate(w, pkg, &extracted, translations...)
	return err
}