summaryrefslogtreecommitdiffstats
path: root/scripts/fork_go_templates/main.go
blob: 38e81ac9ddd4d9720317dd5424bb61d73cc88201 (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
package main

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
	"regexp"
	"strings"

	"github.com/gohugoio/hugo/common/hexec"

	"github.com/gohugoio/hugo/common/hugio"

	"github.com/spf13/afero"
)

func main() {
	// The current is built with db6097f8cb [release-branch.go1.22] go1.22.1
	// TODO(bep) preserve the staticcheck.conf file.
	fmt.Println("Forking ...")
	defer fmt.Println("Done ...")

	cleanFork()

	htmlRoot := filepath.Join(forkRoot, "htmltemplate")

	for _, pkg := range goPackages {
		copyGoPackage(pkg.dstPkg, pkg.srcPkg)
	}

	for _, pkg := range goPackages {
		doWithGoFiles(pkg.dstPkg, pkg.rewriter, pkg.replacer)
	}

	goimports(htmlRoot)
	gofmt(forkRoot)
}

const (
	// TODO(bep)
	goSource = "/Users/bep/dev/go/misc/go/src"
	forkRoot = "../../tpl/internal/go_templates"
)

type goPackage struct {
	srcPkg   string
	dstPkg   string
	replacer func(name, content string) string
	rewriter func(name string)
}

var (
	textTemplateReplacers = strings.NewReplacer(
		`"text/template/`, `"github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/`,
		`"internal/fmtsort"`, `"github.com/gohugoio/hugo/tpl/internal/go_templates/fmtsort"`,
		`"internal/testenv"`, `"github.com/gohugoio/hugo/tpl/internal/go_templates/testenv"`,
		"TestLinkerGC", "_TestLinkerGC",
		// Rename types and function that we want to overload.
		"type state struct", "type stateOld struct",
		"func (s *state) evalFunction", "func (s *state) evalFunctionOld",
		"func (s *state) evalField(", "func (s *state) evalFieldOld(",
		"func (s *state) evalCall(", "func (s *state) evalCallOld(",
		"func isTrue(val reflect.Value) (truth, ok bool) {", "func isTrueOld(val reflect.Value) (truth, ok bool) {",
	)

	testEnvReplacers = strings.NewReplacer(
		`"internal/cfg"`, `"github.com/gohugoio/hugo/tpl/internal/go_templates/cfg"`,
	)

	htmlTemplateReplacers = strings.NewReplacer(
		`. "html/template"`, `. "github.com/gohugoio/hugo/tpl/internal/go_templates/htmltemplate"`,
		`"html/template"`, `template "github.com/gohugoio/hugo/tpl/internal/go_templates/htmltemplate"`,
		"\"text/template\"\n", "template \"github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate\"\n",
		`"html/template"`, `htmltemplate "html/template"`,
		`"fmt"`, `htmltemplate "html/template"`,
		`t.Skip("this test currently fails with -race; see issue #39807")`, `// t.Skip("this test currently fails with -race; see issue #39807")`,
	)
)

func commonReplace(name, content string) string {
	if strings.HasSuffix(name, "_test.go") {
		content = strings.Replace(content, "package template\n", `// +build go1.13,!windows

package template
`, 1)
		content = strings.Replace(content, "package template_test\n", `// +build go1.13

package template_test
`, 1)

		content = strings.Replace(content, "package parse\n", `// +build go1.13

package parse
`, 1)

	}

	return content
}

var goPackages = []goPackage{
	{
		srcPkg: "text/template", dstPkg: "texttemplate",
		replacer: func(name, content string) string { return textTemplateReplacers.Replace(commonReplace(name, content)) },
	},
	{
		srcPkg: "html/template", dstPkg: "htmltemplate", replacer: func(name, content string) string {
			if strings.HasSuffix(name, "content.go") {
				// Remove template.HTML types. We need to use the Go types.
				content = removeAll(`(?s)// Strings of content.*?\)\n`, content)
			}

			content = commonReplace(name, content)

			return htmlTemplateReplacers.Replace(content)
		},
		rewriter: func(name string) {
			for _, s := range []string{"CSS", "HTML", "HTMLAttr", "JS", "JSStr", "URL", "Srcset"} {
				rewrite(name, fmt.Sprintf("%s -> htmltemplate.%s", s, s))
			}
			rewrite(name, `"text/template/parse" -> "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse"`)
		},
	},
	{srcPkg: "internal/fmtsort", dstPkg: "fmtsort", rewriter: func(name string) {
		rewrite(name, `"internal/fmtsort" -> "github.com/gohugoio/hugo/tpl/internal/go_templates/fmtsort"`)
	}},
	{
		srcPkg: "internal/testenv", dstPkg: "testenv",
		replacer: func(name, content string) string { return testEnvReplacers.Replace(content) }, rewriter: func(name string) {
			rewrite(name, `"internal/testenv" -> "github.com/gohugoio/hugo/tpl/internal/go_templates/testenv"`)
		},
	},
	{srcPkg: "internal/cfg", dstPkg: "cfg", rewriter: func(name string) {
		rewrite(name, `"internal/cfg" -> "github.com/gohugoio/hugo/tpl/internal/go_templates/cfg"`)
	}},
}

var fs = afero.NewOsFs()

// Removes all non-Hugo files in the go_templates folder.
func cleanFork() {
	must(filepath.Walk(filepath.Join(forkRoot), func(path string, info os.FileInfo, err error) error {
		if !info.IsDir() && len(path) > 10 && !strings.Contains(path, "hugo") {
			must(fs.Remove(path))
		}
		return nil
	}))
}

func must(err error, what ...string) {
	if err != nil {
		log.Fatal(what, " ERROR: ", err)
	}
}

func copyGoPackage(dst, src string) {
	from := filepath.Join(goSource, src)
	to := filepath.Join(forkRoot, dst)
	fmt.Println("Copy", from, "to", to)
	must(hugio.CopyDir(fs, from, to, func(s string) bool { return true }))
}

func doWithGoFiles(dir string,
	rewrite func(name string),
	transform func(name, in string) string,
) {
	if rewrite == nil && transform == nil {
		return
	}
	must(filepath.Walk(filepath.Join(forkRoot, dir), func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if info.IsDir() {
			return nil
		}

		if !strings.HasSuffix(path, ".go") || strings.Contains(path, "hugo_") {
			return nil
		}

		fmt.Println("Handle", path)

		if rewrite != nil {
			rewrite(path)
		}

		if transform == nil {
			return nil
		}

		data, err := os.ReadFile(path)
		must(err)
		f, err := os.Create(path)
		must(err)
		defer f.Close()
		_, err = f.WriteString(transform(path, string(data)))
		must(err)

		return nil
	}))
}

func removeAll(expression, content string) string {
	re := regexp.MustCompile(expression)
	return re.ReplaceAllString(content, "")
}

func rewrite(filename, rule string) {
	cmf, _ := hexec.SafeCommand("gofmt", "-w", "-r", rule, filename)
	out, err := cmf.CombinedOutput()
	if err != nil {
		log.Fatal("gofmt failed:", string(out))
	}
}

func goimports(dir string) {
	cmf, _ :=