Debian Codegraph @

scripts/fork_go_templates/main.go

raw
1 package main
2
3 import (
4 "fmt"
5 "log"
6 "os"
7 "os/exec"
8 "path/filepath"
9 "regexp"
10 "strings"
11
12 "github.com/gohugoio/hugo/common/hugio"
13
14 "github.com/spf13/afero"
15 )
16
17 func main() {
18 /*
19 Previously: with 2dc996f71b0ebafb77e64433e58333e049488a3c go1.26.3
20 Current: 8af21751f0 [release-branch.go1.27] go1.27.0
21
22 Note that the upgrade here is mostly automatic, but:
23
24 * testenv.go is a stubbed Hugo version and is never overwritten; if the template tests start using new helpers from it, stub them in by hand.
25 * Some of the replacements below match exact upstream source; if upstream drifts, the build breaks and they need updating.
26 * Some test code depends on Go internals we don't fork; remove or stub these out to make it build.
27 * We're only patching the execution part of the template packages, so it's also good to check the execution package's Git history to check for valuable changes in our patched files.
28 */
29 fmt.Println("Forking ...")
30 defer fmt.Println("Done ...")
31
32 cleanFork()
33
34 htmlRoot := filepath.Join(forkRoot, "htmltemplate")
35
36 for _, pkg := range goPackages {
37 copyGoPackage(pkg.dstPkg, pkg.srcPkg, pkg.skip)
38 }
39
40 for _, pkg := range goPackages {
41 doWithGoFiles(pkg.dstPkg, pkg.rewriter, pkg.replacer)
42 }
43
44 goimports(htmlRoot)
45 gofmt(forkRoot)
46 }
47
48 const (
49 goSource = "/Users/bep/dev/go/misc/go/src"
50 forkRoot = "../../tpl/internal/go_templates"
51 )
52
53 type goPackage struct {
54 srcPkg string
55 dstPkg string
56 replacer func(name, content string) string
57 rewriter func(name string)
58 skip func(name string) bool
59 }
60
61 var (
62 textTemplateReplacers = strings.NewReplacer(
63 `"text/template/`, `"github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/`,
64 `"internal/fmtsort"`, `"github.com/gohugoio/hugo/tpl/internal/go_templates/fmtsort"`,
65 `"internal/testenv"`, `"github.com/gohugoio/hugo/tpl/internal/go_templates/testenv"`,
66 "TestLinkerGC", "_TestLinkerGC",
67 "{new(int), true},", "//{new(int), true}, // Commented out for Hugo. We have a slightly different view on ... the truth.",
68 // Rename types and function that we want to overload.
69 "type state struct", "type stateOld struct",
70 "func (s *state) evalFunction", "func (s *state) evalFunctionOld",
71 "func (s *state) evalField(", "func (s *state) evalFieldOld(",
72 "func (s *state) evalCall(", "func (s *state) evalCallOld(",
73 "func (s *state) walkTemplate(", "func (s *state) walkTemplateOld(",
74 "func (s *state) validateType(", "func (s *state) _validateType(",
75 "func isTrue(val reflect.Value) (truth, ok bool) {", "func isTrueOld(val reflect.Value) (truth, ok bool) {",
76 )
77
78 testEnvReplacers = strings.NewReplacer(
79 `"internal/cfg"`, `"github.com/gohugoio/hugo/tpl/internal/go_templates/cfg"`,
80 )
81
82 htmlTemplateReplacers = strings.NewReplacer(
83 `. "html/template"`, `. "github.com/gohugoio/hugo/tpl/internal/go_templates/htmltemplate"`,
84 `"html/template"`, `template "github.com/gohugoio/hugo/tpl/internal/go_templates/htmltemplate"`,
85 "\"text/template\"\n", "template \"github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate\"\n",
86 `"html/template"`, `htmltemplate "html/template"`,
87 `"fmt"`, `htmltemplate "html/template"`,
88 `"internal/testenv"`, `"github.com/gohugoio/hugo/tpl/internal/go_templates/testenv"`,
89 // Renamed so hugo_template.go can wrap it.
90 "func indirect(", "func doIndirect(",
91 `t.Skip("this test currently fails with -race; see issue #39807")`, `// t.Skip("this test currently fails with -race; see issue #39807")`,
92 )
93
94 // We don't want the internal/godebug dependency; meta content URL escaping is always on.
95 escapeGodebugReplacers = strings.NewReplacer(
96 `var debugAllowActionJSTmpl = godebug.New("jstmpllitinterp")`, ``,
97 `var htmlmetacontenturlescape = godebug.New("htmlmetacontenturlescape")`, `var htmlmetacontenturlescape = true`,
98 `if htmlmetacontenturlescape.Value() != "0" {`, `if htmlmetacontenturlescape {`,
99 )
100 )
101
102 func commonReplace(name, content string) string {
103 if strings.HasSuffix(name, "_test.go") {
104 content = strings.Replace(content, "package template\n", `//go:build !windows
105
106 package template
107 `, 1)
108 }
109
110 return content
111 }
112
113 var goPackages = []goPackage{
114 {
115 srcPkg: "text/template", dstPkg: "texttemplate",
116 replacer: func(name, content string) string { return textTemplateReplacers.Replace(commonReplace(name, content)) },
117 },
118 {
119 srcPkg: "html/template", dstPkg: "htmltemplate", replacer: func(name, content string) string {
120 if strings.HasSuffix(name, "content.go") {
121 // Remove template.HTML types. We need to use the Go types.
122 content = removeAll(`(?s)// Strings of content.*?\)\n`, content)
123 }
124
125 if strings.HasSuffix(name, "escape.go") {
126 content = escapeGodebugReplacers.Replace(content)
127 // Drop the else branch calling IncNonDefault; goimports removes the then-unused godebug import.
128 content = removeAll(` else \{\n(?:\t*//.*\n)*\t*htmlmetacontenturlescape\.IncNonDefault\(\)\n\t*\}`, content)
129 }
130
131 if strings.HasSuffix(name, "escape_test.go") {
132 // Tests the GODEBUG=htmlmetacontenturlescape=0 path, which we hard code to on.
133 content = removeAll(`(?s)func TestMetaContentEscapeGODEBUG.*?\n\}\n`, content)
134 }
135
136 content = commonReplace(name, content)
137
138 return htmlTemplateReplacers.Replace(content)
139 },
140 rewriter: func(name string) {
141 for _, s := range []string{"CSS", "HTML", "HTMLAttr", "JS", "JSStr", "URL", "Srcset"} {
142 rewrite(name, fmt.Sprintf("%s -> htmltemplate.%s", s, s))
143 }
144 rewrite(name, `"text/template/parse" -> "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse"`)
145 },
146 },
147 {srcPkg: "internal/fmtsort", dstPkg: "fmtsort", rewriter: func(name string) {
148 rewrite(name, `"internal/fmtsort" -> "github.com/gohugoio/hugo/tpl/internal/go_templates/fmtsort"`)
149 }},
150 {
151 srcPkg: "internal/testenv", dstPkg: "testenv",
152 replacer: func(name, content string) string { return testEnvReplacers.Replace(content) }, rewriter: func(name string) {
153 rewrite(name, `"internal/testenv" -> "github.com/gohugoio/hugo/tpl/internal/go_templates/testenv"`)
154 },
155 // testenv.go is a heavily stubbed Hugo version; keep it. The tests test the stubbed away parts.
156 skip: func(name string) bool {
157 base := filepath.Base(name)
158 return base == "testenv.go" || base == "testenv_test.go"
159 },
160 },
161 {srcPkg: "internal/cfg", dstPkg: "cfg", rewriter: func(name string) {
162 rewrite(name, `"internal/cfg" -> "github.com/gohugoio/hugo/tpl/internal/go_templates/cfg"`)
163 }},
164 }
165
166 var fs = afero.NewOsFs()
167
168 // Removes all non-Hugo files in the go_templates folder.
169 func cleanFork() {
170 keepRe := regexp.MustCompile(`(?i)hugo|staticcheck\.conf|^testenv\.go$`)
171 must(filepath.Walk(filepath.Join(forkRoot), func(path string, info os.FileInfo, err error) error {
172 if info.IsDir() || len(path) <= 10 {
173 return nil
174 }
175
176 if keepRe.MatchString(info.Name()) {
177 return nil
178 }
179
180 must(fs.Remove(path))
181
182 return nil
183 }))
184 }
185
186 func must(err error, what ...string) {
187 if err != nil {
188 log.Fatal(what, " ERROR: ", err)
189 }
190 }
191
192 func copyGoPackage(dst, src string, skip func(name string) bool) {
193 from := filepath.Join(goSource, src)
194 to := filepath.Join(forkRoot, dst)
195 fmt.Println("Copy", from, "to", to)
196 must(hugio.CopyDir(fs, from, to, func(s string) bool { return skip == nil || !skip(s) }))
197 }
198
199 func doWithGoFiles(dir string,
200 rewrite func(name string),
201 transform func(name, in string) string,
202 ) {
203 if rewrite == nil && transform == nil {
204 return
205 }
206 must(filepath.Walk(filepath.Join(forkRoot, dir), func(path string, info os.FileInfo, err error) error {
207 if err != nil {
208 return err
209 }
210 if info.IsDir() {
211 return nil
212 }
213
214 if !strings.HasSuffix(path, ".go") || strings.Contains(path, "hugo_") {
215 return nil
216 }
217
218 fmt.Println("Handle", path)
219
220 if rewrite != nil {
221 rewrite(path)
222 }
223
224 if transform == nil {
225 return nil
226 }
227
228 data, err := os.ReadFile(path)
229 must(err)
230 f, err := os.Create(path)
231 must(err)
232 defer f.Close()
233 _, err = f.WriteString(transform(path, string(data)))
234 must(err)
235
236 return nil
237 }))
238 }
239
240 func removeAll(expression, content string) string {
241 re := regexp.MustCompile(expression)
242 return re.ReplaceAllString(content, "")
243 }
244
245 func rewrite(filename, rule string) {
246 cmf := exec.Command("gofmt", "-w", "-r", rule, filename)
247 out, err := cmf.CombinedOutput()
248 if err != nil {
249 log.Fatal("gofmt failed:", string(out))
250 }
251 }
252
253 func goimports(dir string) {
254 // Needs go install golang.org/x/tools/cmd/goimports@latest
255 cmf := exec.Command("goimports", "-w", dir)
256 out, err := cmf.CombinedOutput()
257 if err != nil {
258 log.Fatal("goimports failed:", string(out))
259 }
260 }
261
262 func gofmt(dir string) {
263 cmf := exec.Command("gofmt", "-w", dir)
264 out, err := cmf.CombinedOutput()
265 if err != nil {
266 log.Fatal("gofmt failed:", string(out))
267 }
268 }