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 "func safeCall(", "func safeCallOld(",
77 )
78
79 testEnvReplacers = strings.NewReplacer(
80 `"internal/cfg"`, `"github.com/gohugoio/hugo/tpl/internal/go_templates/cfg"`,
81 )
82
83 htmlTemplateReplacers = strings.NewReplacer(
84 `. "html/template"`, `. "github.com/gohugoio/hugo/tpl/internal/go_templates/htmltemplate"`,
85 `"html/template"`, `template "github.com/gohugoio/hugo/tpl/internal/go_templates/htmltemplate"`,
86 "\"text/template\"\n", "template \"github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate\"\n",
87 `"html/template"`, `htmltemplate "html/template"`,
88 `"fmt"`, `htmltemplate "html/template"`,
89 `"internal/testenv"`, `"github.com/gohugoio/hugo/tpl/internal/go_templates/testenv"`,
90 // Renamed so hugo_template.go can wrap it.
91 "func indirect(", "func doIndirect(",
92 `t.Skip("this test currently fails with -race; see issue #39807")`, `// t.Skip("this test currently fails with -race; see issue #39807")`,
93 )
94
95 // We don't want the internal/godebug dependency; meta content URL escaping is always on.
96 escapeGodebugReplacers = strings.NewReplacer(
97 `var debugAllowActionJSTmpl = godebug.New("jstmpllitinterp")`, ``,
98 `var htmlmetacontenturlescape = godebug.New("htmlmetacontenturlescape")`, `var htmlmetacontenturlescape = true`,
99 `if htmlmetacontenturlescape.Value() != "0" {`, `if htmlmetacontenturlescape {`,
100 )
101 )
102
103 func commonReplace(name, content string) string {
104 if strings.HasSuffix(name, "_test.go") {
105 content = strings.Replace(content, "package template\n", `//go:build !windows
106
107 package template
108 `, 1)
109 }
110
111 return content
112 }
113
114 var goPackages = []goPackage{
115 {
116 srcPkg: "text/template", dstPkg: "texttemplate",
117 replacer: func(name, content string) string { return textTemplateReplacers.Replace(commonReplace(name, content)) },
118 },
119 {
120 srcPkg: "html/template", dstPkg: "htmltemplate", replacer: func(name, content string) string {
121 if strings.HasSuffix(name, "content.go") {
122 // Remove template.HTML types. We need to use the Go types.
123 content = removeAll(`(?s)// Strings of content.*?\)\n`, content)
124 }
125
126 if strings.HasSuffix(name, "escape.go") {
127 content = escapeGodebugReplacers.Replace(content)
128 // Drop the else branch calling IncNonDefault; goimports removes the then-unused godebug import.
129 content = removeAll(` else \{\n(?:\t*//.*\n)*\t*htmlmetacontenturlescape\.IncNonDefault\(\)\n\t*\}`, content)
130 }
131
132 if strings.HasSuffix(name, "escape_test.go") {
133 // Tests the GODEBUG=htmlmetacontenturlescape=0 path, which we hard code to on.
134 content = removeAll(`(?s)func TestMetaContentEscapeGODEBUG.*?\n\}\n`, content)
135 }
136
137 content = commonReplace(name, content)
138
139 return htmlTemplateReplacers.Replace(content)
140 },
141 rewriter: func(name string) {
142 for _, s := range []string{"CSS", "HTML", "HTMLAttr", "JS", "JSStr", "URL", "Srcset"} {
143 rewrite(name, fmt.Sprintf("%s -> htmltemplate.%s", s, s))
144 }
145 rewrite(name, `"text/template/parse" -> "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse"`)
146 },
147 },
148 {srcPkg: "internal/fmtsort", dstPkg: "fmtsort", rewriter: func(name string) {
149 rewrite(name, `"internal/fmtsort" -> "github.com/gohugoio/hugo/tpl/internal/go_templates/fmtsort"`)
150 }},
151 {
152 srcPkg: "internal/testenv", dstPkg: "testenv",
153 replacer: func(name, content string) string { return testEnvReplacers.Replace(content) }, rewriter: func(name string) {
154 rewrite(name, `"internal/testenv" -> "github.com/gohugoio/hugo/tpl/internal/go_templates/testenv"`)
155 },
156 // testenv.go is a heavily stubbed Hugo version; keep it. The tests test the stubbed away parts.
157 skip: func(name string) bool {
158 base := filepath.Base(name)
159 return base == "testenv.go" || base == "testenv_test.go"
160 },
161 },
162 {srcPkg: "internal/cfg", dstPkg: "cfg", rewriter: func(name string) {
163 rewrite(name, `"internal/cfg" -> "github.com/gohugoio/hugo/tpl/internal/go_templates/cfg"`)
164 }},
165 }
166
167 var fs = afero.NewOsFs()
168
169 // Removes all non-Hugo files in the go_templates folder.
170 func cleanFork() {
171 keepRe := regexp.MustCompile(`(?i)hugo|staticcheck\.conf|^testenv\.go$`)
172 must(filepath.Walk(filepath.Join(forkRoot), func(path string, info os.FileInfo, err error) error {
173 if info.IsDir() || len(path) <= 10 {
174 return nil
175 }
176
177 if keepRe.MatchString(info.Name()) {
178 return nil
179 }
180
181 must(fs.Remove(path))
182
183 return nil
184 }))
185 }
186
187 func must(err error, what ...string) {
188 if err != nil {
189 log.Fatal(what, " ERROR: ", err)
190 }
191 }
192
193 func copyGoPackage(dst, src string, skip func(name string) bool) {
194 from := filepath.Join(goSource, src)
195 to := filepath.Join(forkRoot, dst)
196 fmt.Println("Copy", from, "to", to)
197 must(hugio.CopyDir(fs, from, to, func(s string) bool { return skip == nil || !skip(s) }))
198 }
199
200 func doWithGoFiles(dir string,
201 rewrite func(name string),
202 transform func(name, in string) string,
203 ) {
204 if rewrite == nil && transform == nil {
205 return
206 }
207 must(filepath.Walk(filepath.Join(forkRoot, dir), func(path string, info os.FileInfo, err error) error {
208 if err != nil {
209 return err
210 }
211 if info.IsDir() {
212 return nil
213 }
214
215 if !strings.HasSuffix(path, ".go") || strings.Contains(path, "hugo_") {
216 return nil
217 }
218
219 fmt.Println("Handle", path)
220
221 if rewrite != nil {
222 rewrite(path)
223 }
224
225 if transform == nil {
226 return nil
227 }
228
229 data, err := os.ReadFile(path)
230 must(err)
231 f, err := os.Create(path)
232 must(err)
233 defer f.Close()
234 _, err = f.WriteString(transform(path, string(data)))
235 must(err)
236
237 return nil
238 }))
239 }
240
241 func removeAll(expression, content string) string {
242 re := regexp.MustCompile(expression)
243 return re.ReplaceAllString(content, "")
244 }
245
246 func rewrite(filename, rule string) {
247 cmf := exec.Command("gofmt", "-w", "-r", rule, filename)
248 out, err := cmf.CombinedOutput()
249 if err != nil {
250 log.Fatal("gofmt failed:", string(out))
251 }
252 }
253
254 func goimports(dir string) {
255 // Needs go install golang.org/x/tools/cmd/goimports@latest
256 cmf := exec.Command("goimports", "-w", dir)
257 out, err := cmf.CombinedOutput()
258 if err != nil {
259 log.Fatal("goimports failed:", string(out))
260 }
261 }
262
263 func gofmt(dir string) {
264 cmf := exec.Command("gofmt", "-w", dir)
265 out, err := cmf.CombinedOutput()
266 if err != nil {
267 log.Fatal("gofmt failed:", string(out))
268 }
269 }