summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/paulrosania/go-charset/data/generate.go
blob: a790e6bdf2918a5b9c8bc3011a44056bcddb8c8a (plain) (blame)
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
// +build ignore

// go run generate.go && go fmt

// The generate-charset-data command generates the Go source code
// for github.com/paulrosania/go-charset/data from the data files
// found in github.com/paulrosania/go-charset/datafiles.
// It should be run in the go-charset root directory.
// The resulting Go files will need gofmt'ing.
package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"text/template"
)

type info struct {
	Path string
}

var tfuncs = template.FuncMap{
	"basename": func(s string) string {
		return filepath.Base(s)
	},
	"read": func(path string) ([]byte, error) {
		return ioutil.ReadFile(path)
	},
}

var tmpl = template.Must(template.New("").Funcs(tfuncs).Parse(`
	// This file is automatically generated by generate-charset-data.
	// Do not hand-edit.

	package data
	import (
		"github.com/paulrosania/go-charset/charset"
		"io"
		"io/ioutil"
		"strings"
	)

	func init() {
		charset.RegisterDataFile({{basename .Path | printf "%q"}}, func() (io.ReadCloser, error) {
			r := strings.NewReader({{read .Path | printf "%q"}})
			return ioutil.NopCloser(r), nil
		})
	}
`))

var docTmpl = template.Must(template.New("").Funcs(tfuncs).Parse(`
	// This file is automatically generated by generate-charset-data.
	// Do not hand-edit.

	// The {{basename .Package}} package embeds all the charset
	// data files as Go data. It registers the data with the charset
	// package as a side effect of its import. To use:
	//
	//	import _ "github.com/paulrosania/go-charset"
	package {{basename .Package}}
`))

func main() {
	dataDir := filepath.Join("..", "datafiles")
	d, err := os.Open(dataDir)
	if err != nil {
		fatalf("%v", err)
	}
	names, err := d.Readdirnames(0)
	if err != nil {
		fatalf("cannot read datafiles dir: %v", err)
	}
	for _, name := range names {
		writeFile("data_"+name+".go", tmpl, info{
			Path: filepath.Join(dataDir, name),
		})
	}
}

func writeFile(name string, t *template.Template, data interface{}) {
	w, err := os.Create(name)
	if err != nil {
		fatalf("cannot create output file: %v", err)
	}
	defer w.Close()
	err = t.Execute(w, data)
	if err != nil {
		fatalf("template execute %q: %v", name, err)
	}
}

func fatalf(f string, a ...interface{}) {
	fmt.Fprintf(os.Stderr, "%s\n", fmt.Sprintf(f, a...))
	os.Exit(2)
}