Welcome to mirror list, hosted at ThFree Co, Russian Federation.

main.go « gen - github.com/gohugoio/localescompressed.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 3b96828bb01e60e8b6a4d3b4c3dab1a221fe3259 (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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package main

import (
	"bytes"
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"go/ast"
	"go/token"
	"io"
	"io/fs"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"sort"
	"strings"

	"golang.org/x/tools/go/packages"
)

const header = `
// This file is autogenerated.
package localescompressed
`

func main() {
	createTranslatorsMap()
	createCurrenciesMap()
}

func createTranslatorsMap() {
	const localeMod = "github.com/gohugoio/locales"
	b := &bytes.Buffer{}
	cmd := exec.Command("go", "list", "-m", "-json", localeMod)
	cmd.Stdout = b

	if err := cmd.Run(); err != nil {
		log.Fatal(err)
	}

	m := make(map[string]interface{})
	if err := json.Unmarshal(b.Bytes(), &m); err != nil {
		log.Fatal(err)
	}

	dir := m["Dir"].(string)

	var packageNames []string

	filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
		if !d.IsDir() || d.Name() == "currency" {
			return nil
		}

		name := filepath.Base(path)

		if _, err := os.Stat(filepath.Join(path, fmt.Sprintf("%s.go", name))); err == nil {
			packageNames = append(packageNames, name)
		}

		return nil
	})

	sort.Strings(packageNames)

	cfg := &packages.Config{Mode: packages.NeedSyntax | packages.NeedFiles}
	f, err := os.Create(filepath.Join("..", "locales.autogen.go"))
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	fmt.Fprint(f, header)
	fmt.Fprintf(f, "import(\n\"math\"\n\"time\"\n\"strconv\"\n\"github.com/gohugoio/locales\"\n\"github.com/gohugoio/locales/currency\"\n)\n\n")

	var (
		allFields []string
		methodSet = make(map[string]bool)
		initW     = &bytes.Buffer{}
		counter   = 0
	)

	for _, k := range packageNames {
		counter++

		if counter%50 == 0 {
			fmt.Printf("[%d] Handling locale %s ...\n", counter, k)
		}

		pkgs, err := packages.Load(cfg, fmt.Sprintf("github.com/gohugoio/locales/%s", k))
		if err != nil {
			log.Fatal(err)
		}

		pkg := pkgs[0]
		gf := pkg.GoFiles[0]

		src, err := ioutil.ReadFile(gf)
		if err != nil {
			log.Fatal(err)
		}

		collector := &coll{src: src, locale: k, w: f, initW: initW, methodSet: methodSet}

		for _, f := range pkg.Syntax {
			for _, node := range f.Decls {
				ast.Inspect(node, collector.collectFields)
			}
		}

		collector.fields = uniqueStringsSorted(collector.fields)
		collector.methods = uniqueStringsSorted(collector.methods)
		allFields = append(allFields, collector.fields...)
		allFields = uniqueStringsSorted(allFields)

		for _, f := range pkg.Syntax {
			for _, node := range f.Decls {
				ast.Inspect(node, collector.collectNew)
			}
		}

	}

	fmt.Fprint(f, "\ntype localen struct {\n")
	for _, field := range allFields {
		fmt.Fprintf(f, "\t%s\n", field)
	}

	fmt.Fprint(f, "\n}\n")

	fmt.Fprint(f, "func init() {\n")
	fmt.Fprint(f, initW.String())
	fmt.Fprint(f, "\n}")
}

type coll struct {
	// Global
	w         io.Writer
	initW     io.Writer
	methodSet map[string]bool

	// Local
	locale  string
	fields  []string
	methods []string
	src     []byte
}

func (c *coll) collectFields(node ast.Node) bool {
	switch vv := node.(type) {

	case *ast.FuncDecl:
		if vv.Recv != nil {
			recName := vv.Recv.List[0].Names[0].Name
			name := vv.Name.Name

			start := vv.Pos() - 1
			end := vv.End()

			body := string(c.src[start : end-1])
			re := regexp.MustCompile(`\b` + recName + `\.`)
			body = re.ReplaceAllString(body, " ln.")
			body = body[strings.Index(body, name):]
			hash := toMd5(body)
			body = body[len(name)+1:]
			fullName := name + "_" + hash

			sig := body[:strings.Index(body, "{")]
			funcSig := "func(ln *localen"
			if !strings.HasPrefix(sig, ")") {
				funcSig += ", "
			}
			field := fmt.Sprintf("fn%s %s%s", name, funcSig, sig)
			method := fmt.Sprintf("fn%s fn%s", name, fullName)

			c.methods = append(c.methods, method)
			c.fields = append(c.fields, field)

			body = "var fn" + fullName + " = " + funcSig + body + "\n"

			if !c.methodSet[hash] {
				fmt.Fprint(c.w, body)
			}
			c.methodSet[hash] = true
		}
	case *ast.GenDecl:
		for _, spec := range vv.Specs {
			switch spec.(type) {
			case *ast.TypeSpec:
				typeSpec := spec.(*ast.TypeSpec)
				switch typeSpec.Type.(type) {
				case *ast.StructType:
					structType := typeSpec.Type.(*ast.StructType)
					for _, field := range structType.Fields.List {
						typeExpr := field.Type

						start := typeExpr.Pos() - 1
						end := typeExpr.End() - 1

						typeInSource := c.src[start:end]

						c.fields = append(c.fields, fmt.Sprintf("%s %s", field.Names[0].Name, string(typeInSource)))
					}
				}
			}
		}

	}

	return false
}

var returnStructRe = regexp.MustCompile(`return &.*{`)

func (c *coll) collectNew(node ast.Node) bool {
	switch vv := node.(type) {
	case *ast.FuncDecl:
		if vv.Name.Name == "New" {
			start := vv.Body.Pos() - 1
			end := vv.Body.End() - 1

			body := string(c.src[start : end-1])

			body = strings.Replace(body, "{\n\t", "", 1)
			body = strings.Replace(body, "\t}", "", 1)

			body = returnStructRe.ReplaceAllString(body, "")

			for _, method := range c.methods {
				if strings.HasPrefix(method, "fn") {
					parts := strings.Fields(method)
					body += fmt.Sprintf("\n%s: %s,", parts[0], parts[1])
				}
			}
			fmt.Fprintf(c.initW, "\ttranslatorFuncs[%q] = %s\n", strings.ToLower(c.locale), fmt.Sprintf("func() locales.Translator {\nreturn &localen{\n%s\n}\n}", body))
		}
	}
	return false
}

func uniqueStringsSorted(s []string) []string {
	if len(s) == 0 {
		return nil
	}
	ss := sort.StringSlice(s)
	ss.Sort()
	i := 0
	for j := 1; j < len(s); j++ {
		if !ss.Less(i, j) {
			continue
		}
		i++
		s[i] = s[j]
	}

	return s[:i+1]
}

func toMd5(f string) string {
	h := md5.New()
	h.Write([]byte(f))
	return hex.EncodeToString(h.Sum([]byte{}))
}

func createCurrenciesMap() {
	cfg := &packages.Config{
		Mode:  packages.LoadSyntax,
		Tests: false,
	}

	pkgs, err := packages.Load(cfg, "github.com/gohugoio/locales/currency")
	if err != nil {
		log.Fatal(err)
	}

	pkg := pkgs[0]

	collector := &currencyCollector{}

	for _, f := range pkg.Syntax {
		ast.Inspect(f, collector.handleNode)
	}

	sort.Strings(collector.constants)

	f, err := os.Create(filepath.Join("../currencies.autogen.go"))
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	fmt.Fprintf(f, "%s\nimport \"github.com/gohugoio/locales/currency\"\n", header)

	fmt.Fprintf(f, "var currencies = map[string]currency.Type {")
	for _, currency := range collector.constants {
		fmt.Fprintf(f, "\n%q: currency.%s,", currency, currency)
	}
	fmt.Fprintln(f, "}")
}

type currencyCollector struct {
	constants []string
}

func (c *currencyCollector) handleNode(node ast.Node) bool {
	decl, ok := node.(*ast.GenDecl)
	if !ok || decl.Tok != token.CONST {
		return true
	}
	typ := ""
	for _, spec := range decl.Specs {
		vspec := spec.(*ast.ValueSpec)
		if vspec.Type == nil && len(vspec.Values) > 0 {
			typ = ""

			ce, ok := vspec.Values[0].(*ast.CallExpr)
			if !ok {
				continue
			}
			id, ok := ce.Fun.(*ast.Ident)
			if !ok {
				continue
			}
			typ = id.Name
		}
		if vspec.Type != nil {
			ident, ok := vspec.Type.(*ast.Ident)
			if !ok {
				continue
			}
			typ = ident.Name
		}
		if typ != "Type" {
			// This is not the type we're looking for.
			continue
		}
		// We now have a list of names (from one line of source code) all being
		// declared with the desired type.
		// Grab their names and actual values and store them in f.values.
		for _, name := range vspec.Names {
			c.constants = append(c.constants, name.String())
		}
	}
	return false
}