Debian Codegraph @

resources/resource_transformers/cssjs/postcss_integration_test.go

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // Copyright 2024 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package cssjs_test
15
16 import (
17 "fmt"
18 "os"
19 "path/filepath"
20 "runtime"
21 "strings"
22 "testing"
23
24 qt "github.com/frankban/quicktest"
25 "github.com/gohugoio/hugo/common/herrors"
26 "github.com/gohugoio/hugo/htesting"
27 "github.com/gohugoio/hugo/hugofs"
28 "github.com/gohugoio/hugo/hugolib"
29 )
30
31 const postCSSIntegrationTestFiles = `
32 -- assets/css/components/a.css --
33 /* A comment. */
34 /* Another comment. */
35 class-in-a {
36 color: blue;
37 }
38
39 -- assets/css/components/all.css --
40 @import "a.css";
41 @import "b.css";
42 -- assets/css/components/b.css --
43 @import "a.css";
44
45 class-in-b {
46 color: blue;
47 }
48
49 -- assets/css/styles.css --
50 @tailwind base;
51 @tailwind components;
52 @tailwind utilities;
53 @import "components/all.css";
54 h1 {
55 @apply text-2xl font-bold;
56 }
57
58 -- hugo.toml --
59 disablekinds = ['taxonomy', 'term', 'page']
60 baseURL = "https://example.com"
61 [build]
62 useResourceCacheWhen = 'never'
63 -- content/p1.md --
64 -- data/hugo.toml --
65 slogan = "Hugo Rocks!"
66 -- i18n/en.yaml --
67 hello:
68 other: "Hello"
69 -- i18n/fr.yaml --
70 hello:
71 other: "Bonjour"
72 -- layouts/home.html --
73 {{ $options := dict "inlineImports" true }}
74 {{ $styles := resources.Get "css/styles.css" | css.PostCSS $options }}
75 Styles RelPermalink: {{ $styles.RelPermalink }}
76 {{ $cssContent := $styles.Content }}
77 Styles Content: Len: {{ len $styles.Content }}|
78 -- package.json --
79 {
80 "scripts": {},
81
82 "devDependencies": {
83 "postcss-cli": "7.1.0",
84 "tailwindcss": "1.2.0"
85 }
86 }
87 -- postcss.config.js --
88 console.error("Hugo Environment:", process.env.HUGO_ENVIRONMENT );
89 console.error("Hugo PublishDir:", process.env.HUGO_PUBLISHDIR );
90 // https://github.com/gohugoio/hugo/issues/7656
91 console.error("package.json:", process.env.HUGO_FILE_PACKAGE_JSON );
92 console.error("PostCSS Config File:", process.env.HUGO_FILE_POSTCSS_CONFIG_JS );
93
94 module.exports = {
95 plugins: [
96 require('tailwindcss')
97 ]
98 }
99
100 `
101
102 func TestTransformPostCSS(t *testing.T) {
103 if !htesting.IsCI() {
104 t.Skip("Skip long running test when running locally")
105 }
106
107 c := qt.New(t)
108 tempDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-integration-test")
109 c.Assert(err, qt.IsNil)
110 c.Cleanup(clean)
111
112 for _, s := range []string{"never", "always"} {
113
114 repl := strings.NewReplacer(
115 "https://example.com",
116 "https://example.com/foo",
117 "useResourceCacheWhen = 'never'",
118 fmt.Sprintf("useResourceCacheWhen = '%s'", s),
119 )
120
121 files := repl.Replace(postCSSIntegrationTestFiles)
122
123 b := hugolib.Test(c, files, hugolib.TestOptOsFs(), hugolib.TestOptWithNpmInstall(), hugolib.TestOptInfo(), hugolib.TestOptWithConfig(func(cfg *hugolib.IntegrationTestConfig) {
124 cfg.WorkingDir = tempDir
125 }))
126
127 b.AssertFileContent("public/index.html", `
128 Styles RelPermalink: /foo/css/styles.css
129 Styles Content: Len: 770917|
130 `)
131
132 if s == "never" {
133 b.AssertLogContains("Hugo Environment: production")
134 b.AssertLogContains("Hugo PublishDir: " + filepath.Join(tempDir, "public"))
135 }
136 }
137 }
138
139 // 9880
140 func TestTransformPostCSSError(t *testing.T) {
141 if !htesting.IsCI() {
142 t.Skip("Skip long running test when running locally")
143 }
144
145 if runtime.GOOS == "windows" {
146 // TODO(bep) This has started to fail on Windows with Go 1.19 on GitHub Actions for some mysterious reason.
147 t.Skip("Skip on Windows")
148 }
149
150 c := qt.New(t)
151
152 b, err := hugolib.TestE(c, strings.ReplaceAll(postCSSIntegrationTestFiles, "color: blue;", "@apply foo;"), hugolib.TestOptOsFs(), hugolib.TestOptWithNpmInstall())
153
154 ferrs := herrors.UnwrapFileErrors(err)
155 b.Assert(len(ferrs), qt.Equals, 2)
156 b.Assert(err.Error(), qt.Contains, "a.css:4:2")
157 }
158
159 // #9895
160 func TestTransformPostCSSImportError(t *testing.T) {
161 if !htesting.IsCI() {
162 t.Skip("Skip long running test when running locally")
163 }
164
165 c := qt.New(t)
166
167 _, err := hugolib.TestE(c, strings.ReplaceAll(postCSSIntegrationTestFiles, `@import "components/all.css";`, `@import "components/doesnotexist.css";`), hugolib.TestOptOsFs(), hugolib.TestOptWithNpmInstall(), hugolib.TestOptInfo())
168 ferrs := herrors.UnwrapFileErrors(err)
169 c.Assert(len(ferrs), qt.Equals, 2)
170 c.Assert(err.Error(), qt.Contains, "styles.css:4:3")
171 c.Assert(err.Error(), qt.Contains, filepath.FromSlash(`failed to resolve CSS @import "/css/components/doesnotexist.css"`))
172 }
173
174 func TestTransformPostCSSImporSkipInlineImportsNotFound(t *testing.T) {
175 if !htesting.IsCI() {
176 t.Skip("Skip long running test when running locally")
177 }
178
179 c := qt.New(t)
180
181 files := strings.ReplaceAll(postCSSIntegrationTestFiles, `@import "components/all.css";`, `@import "components/doesnotexist.css";`)
182 files = strings.ReplaceAll(files, `{{ $options := dict "inlineImports" true }}`, `{{ $options := dict "inlineImports" true "skipInlineImportsNotFound" true }}`)
183
184 s := hugolib.Test(c, files, hugolib.TestOptOsFs(), hugolib.TestOptWithNpmInstall(), hugolib.TestOptInfo())
185
186 s.AssertFileContent("public/css/styles.css", `@import "components/doesnotexist.css";`)
187 }
188
189 // Issue 9787
190 func TestTransformPostCSSResourceCacheWithPathInBaseURL(t *testing.T) {
191 if !htesting.IsCI() {
192 t.Skip("Skip long running test when running locally")
193 }
194
195 c := qt.New(t)
196 tempDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-integration-test")
197 c.Assert(err, qt.IsNil)
198 c.Cleanup(clean)
199
200 for i := range 2 {
201 files := postCSSIntegrationTestFiles
202
203 if i == 1 {
204 files = strings.ReplaceAll(files, "https://example.com", "https://example.com/foo")
205 files = strings.ReplaceAll(files, "useResourceCacheWhen = 'never'", " useResourceCacheWhen = 'always'")
206 }
207
208 b := hugolib.Test(c, files, hugolib.TestOptOsFs(), hugolib.TestOptWithNpmInstall(), hugolib.TestOptInfo(), hugolib.TestOptWithConfig(func(cfg *hugolib.IntegrationTestConfig) {
209 cfg.WorkingDir = tempDir
210 }))
211
212 b.AssertFileContent("public/index.html", `
213 Styles Content: Len: 770917
214 `)
215
216 }
217 }
218
219 // See Issue 15039.
220 // See Issue 15040.
221 func TestTransformPostCSSConfigResolution(t *testing.T) {
222 if !htesting.IsCI() {
223 t.Skip("Skip long running test when running locally")
224 }
225
226 files := `
227 -- hugo.toml --
228 disableKinds = ['page','rss','section','sitemap','taxonomy','term']
229 [[module.imports]]
230 path = "github.com/bep/hugo-mod-nop"
231 -- assets/css/styles.css --
232 body { color: red }
233 -- layouts/home.html --
234 {{ $styles := resources.Get "css/styles.css" | css.PostCSS }}
235 RelPermalink: {{ $styles.RelPermalink }}|HasBody: {{ in $styles.Content "color:" }}|
236 -- package.json --
237 {
238 "devDependencies": {
239 "postcss-cli": "11.0.0"
240 }
241 }
242 -- go.mod --
243 module github.com/example/project
244
245 go 1.26
246
247 replace github.com/bep/hugo-mod-nop => ../external-module
248 -- ../external-module/go.mod --
249 module github.com/bep/hugo-mod-nop
250
251 go 1.26
252 -- ../external-module/CONFIG_FILE_NAME --
253 CONFIG_FILE_CONTENT
254 `
255
256 tests := []struct {
257 name string
258 configFileName string
259 configFileContent string
260 }{
261 {
262 name: "mjs in module",
263 configFileName: "postcss.config.mjs",
264 configFileContent: "export default {};\n",
265 },
266 {
267 name: "cjs in module",
268 configFileName: "postcss.config.cjs",
269 configFileContent: "module.exports = {};\n",
270 },
271 {
272 name: "js in module",
273 configFileName: "postcss.config.js",
274 configFileContent: "module.exports = {};\n",
275 },
276 }
277
278 for _, tt := range tests {
279 t.Run(tt.name, func(t *testing.T) {
280 c := qt.New(t)
281 rootDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-integration-test")
282 c.Assert(err, qt.IsNil)
283 c.Cleanup(clean)
284
285 projectDir := filepath.Join(rootDir, "project")
286 moduleDir := filepath.Join(rootDir, "external-module")
287 c.Assert(os.MkdirAll(projectDir, 0o755), qt.IsNil)
288 c.Assert(os.MkdirAll(moduleDir, 0o755), qt.IsNil)
289
290 f := strings.ReplaceAll(files, "CONFIG_FILE_NAME", tt.configFileName)
291 f = strings.ReplaceAll(f, "CONFIG_FILE_CONTENT", tt.configFileContent)
292
293 b := hugolib.Test(c, f,
294 hugolib.TestOptWithConfig(func(cfg *hugolib.IntegrationTestConfig) {
295 cfg.WorkingDir = projectDir
296 cfg.NeedsOsFS = true
297 cfg.NeedsNpmInstall = true
298 }),
299 hugolib.TestOptInfo(),
300 )
301
302 b.AssertFileContent("public/index.html",
303 "RelPermalink: /css/styles.css|HasBody: true|",
304 )
305 b.AssertLogContains(tt.configFileName)
306 })
307 }
308 }
309
310 // See Issue 13987.
311 func TestTransformPostCSSESMConfigInModule(t *testing.T) {
312 if !htesting.IsCI() {
313 t.Skip("Skip long running test when running locally")
314 }
315
316 c := qt.New(t)
317 // Use htesting.CreateTempDir to get canonical paths on macOS
318 // (/private/var/...); Node's --permission model rejects the symlinked
319 // /var/folders/... form when crossing the project boundary.
320 rootDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-integration-test")
321 c.Assert(err, qt.IsNil)
322 c.Cleanup(clean)
323
324 projectDir := filepath.Join(rootDir, "project")
325 moduleDir := filepath.Join(rootDir, "external-module")
326 c.Assert(os.MkdirAll(projectDir, 0o755), qt.IsNil)
327 c.Assert(os.MkdirAll(moduleDir, 0o755), qt.IsNil)
328
329 files := `
330 -- hugo.toml --
331 disableKinds = ['taxonomy', 'term', 'page']
332 baseURL = "https://example.com"
333 [[module.imports]]
334 path = "github.com/bep/hugo-mod-nop"
335 -- assets/css/styles.css --
336 body { color: red }
337 -- layouts/home.html --
338 {{ $styles := resources.Get "css/styles.css" | css.PostCSS }}
339 RelPermalink: {{ $styles.RelPermalink }}|HasBody: {{ in $styles.Content "color:" }}|
340 -- content/_index.md --
341 ---
342 title: home
343 ---
344 -- package.json --
345 {
346 "devDependencies": {
347 "postcss-cli": "11.0.0",
348 "postcss-import": "16.0.0"
349 }
350 }
351 -- go.mod --
352 module github.com/example/project
353
354 go 1.20
355
356 replace github.com/bep/hugo-mod-nop => ../external-module
357 -- ../external-module/go.mod --
358 module github.com/bep/hugo-mod-nop
359
360 go 1.20
361 -- ../external-module/postcss.config.js --
362 import postcssImport from "postcss-import";
363 export default { plugins: [postcssImport()] };
364
365 `
366
367 b := hugolib.Test(c, files,
368 hugolib.TestOptWithConfig(func(cfg *hugolib.IntegrationTestConfig) {
369 cfg.WorkingDir = projectDir
370 cfg.NeedsOsFS = true
371 cfg.NeedsNpmInstall = true
372 }),
373 )
374
375 b.AssertFileContent("public/index.html",
376 "RelPermalink: /css/styles.css|HasBody: true|",
377 )
378 }
379
380 // Netlify stores its node_modules cache in the same tree as the Hugo file
381 // cache, so Node's resolver can walk up from a module's postcss.config.js and
382 // hit a node_modules outside the permission allow-list, aborting with
383 // ERR_ACCESS_DENIED instead of falling through to NODE_PATH. The restricted
384 // postcss-import below (an ancestor of the external module, never installed by
385 // us) forces that walk to fail; the build must still succeed by resolving the
386 // real postcss-import via NODE_PATH.
387 //
388 // See issue 15041.
389 func TestTransformPostCSSESMConfigAccessDenied(t *testing.T) {
390 if !htesting.IsCI() {
391 t.Skip("Skip long running test when running locally")
392 }
393
394 c := qt.New(t)
395 // Use htesting.CreateTempDir to get canonical paths on macOS
396 // (/private/var/...); Node's --permission model rejects the symlinked
397 // /var/folders/... form when crossing the project boundary.
398 rootDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-integration-test")
399 c.Assert(err, qt.IsNil)
400 c.Cleanup(clean)
401
402 projectDir := filepath.Join(rootDir, "project")
403 moduleDir := filepath.Join(rootDir, "external-module")
404 c.Assert(os.MkdirAll(projectDir, 0o755), qt.IsNil)
405 c.Assert(os.MkdirAll(moduleDir, 0o755), qt.IsNil)
406
407 files := `
408 -- hugo.toml --
409 disableKinds = ['taxonomy', 'term', 'page']
410 baseURL = "https://example.com"
411 [[module.imports]]
412 path = "github.com/bep/hugo-mod-nop"
413 -- assets/css/styles.css --
414 body { color: red }
415 -- layouts/home.html --
416 {{ $styles := resources.Get "css/styles.css" | css.PostCSS }}
417 RelPermalink: {{ $styles.RelPermalink }}|HasBody: {{ in $styles.Content "color:" }}|
418 -- content/_index.md --
419 ---
420 title: home
421 ---
422 -- package.json --
423 {
424 "devDependencies": {
425 "postcss-cli": "11.0.0",
426 "postcss-import": "16.0.0"
427 }
428 }
429 -- go.mod --
430 module github.com/example/project
431
432 go 1.20
433
434 replace github.com/bep/hugo-mod-nop => ../external-module
435 -- ../node_modules/postcss-import/package.json --
436 { "name": "postcss-import", "version": "0.0.0-RESTRICTED", "main": "index.js" }
437 -- ../external-module/go.mod --
438 module github.com/bep/hugo-mod-nop
439
440 go 1.20
441 -- ../external-module/postcss.config.js --
442 import postcssImport from "postcss-import";
443 export default { plugins: [postcssImport()] };
444
445 `
446
447 b := hugolib.Test(c, files,
448 hugolib.TestOptWithConfig(func(cfg *hugolib.IntegrationTestConfig) {
449 cfg.WorkingDir = projectDir
450 cfg.NeedsOsFS = true
451 cfg.NeedsNpmInstall = true
452 }),
453 )
454
455 b.AssertFileContent("public/index.html",
456 "RelPermalink: /css/styles.css|HasBody: true|",
457 )
458 }
459
460 // Node's permission model follows symlinks outside the allowed paths, so Hugo
461 // rejects them before invoking Node.
462 func TestTransformPostCSSSymlinkOutsideAllowRead(t *testing.T) {
463 if !htesting.IsCI() {
464 t.Skip("Skip long running test when running locally")
465 }
466 if runtime.GOOS == "windows" {
467 t.Skip("symlinks")
468 }
469
470 c := qt.New(t)
471 tempDir, clean, err := htesting.CreateTempDir(hugofs.Os, "hugo-integration-test")
472 c.Assert(err, qt.IsNil)
473 c.Cleanup(clean)
474
475 site := filepath.Join(tempDir, "site")
476 outside := filepath.Join(tempDir, "outside")
477 c.Assert(os.MkdirAll(filepath.Join(site, "assets", "css"), 0o755), qt.IsNil)
478 c.Assert(os.MkdirAll(outside, 0o755), qt.IsNil)
479 c.Assert(os.WriteFile(filepath.Join(outside, "secret.txt"), []byte("secret"), 0o644), qt.IsNil)
480 c.Assert(os.Symlink(filepath.Join(outside, "secret.txt"), filepath.Join(site, "assets", "css", "slink.css")), qt.IsNil)
481
482 files := `
483 -- hugo.toml --
484 disableKinds = ['taxonomy', 'term', 'page', 'section', 'rss', 'sitemap']
485 [security.node.permissions]
486 allowRead = ['.']
487 -- assets/css/styles.css --
488 body { color: red; }
489 -- layouts/home.html --
490 {{ $styles := resources.Get "css/styles.css" | css.PostCSS }}
491 Styles: {{ $styles.Content | safeCSS }}|
492 -- package.json --
493 {
494 "devDependencies": {
495 "postcss": "8.5.6",
496 "postcss-cli": "11.0.0"
497 }
498 }
499 -- postcss.config.js --
500 module.exports = { plugins: [] }
501 `
502
503 withWorkingDir := hugolib.TestOptWithConfig(func(cfg *hugolib.IntegrationTestConfig) {
504 cfg.WorkingDir = site
505 })
506
507 b, err := hugolib.TestE(c, files, hugolib.TestOptOsFs(), hugolib.TestOptWithNpmInstall(), withWorkingDir)
508 b.Assert(err, qt.ErrorMatches, `.*symlink ".*slink.css" resolves to ".*secret.txt" outside .*allowRead.*`)
509
510 files = strings.ReplaceAll(files, "allowRead = ['.']", fmt.Sprintf("allowRead = ['.', %q]", outside))
511 b = hugolib.Test(c, files, hugolib.TestOptOsFs(), hugolib.TestOptWithNpmInstall(), withWorkingDir)
512 b.AssertFileContent("public/index.html", "Styles: body { color: red; }|")
513 }