Debian Codegraph @

resources/resource_transformers/cssjs/inline_imports.go

raw
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
15
16 import (
17 "context"
18 "crypto/sha256"
19 "encoding/hex"
20 "errors"
21 "fmt"
22 "io"
23 "path"
24 "path/filepath"
25 "regexp"
26 "strconv"
27 "strings"
28
29 "github.com/gohugoio/hugo/common/herrors"
30 "github.com/gohugoio/hugo/common/loggers"
31 "github.com/gohugoio/hugo/common/text"
32 "github.com/gohugoio/hugo/hugofs"
33 "github.com/gohugoio/hugo/identity"
34 "github.com/gohugoio/hugo/resources"
35 "github.com/gohugoio/hugo/resources/resource"
36 "github.com/spf13/afero"
37 )
38
39 const importIdentifier = "@import"
40
41 var (
42 cssSyntaxErrorRe = regexp.MustCompile(`> (\d+) \|`)
43 shouldImportRe = regexp.MustCompile(`^@import ["'](.*?)["'];?\s*(/\*.*\*/)?$`)
44 )
45
46 type fileOffset struct {
47 Filename string
48 Offset int
49 }
50
51 type importResolver struct {
52 ctx context.Context
53 r io.Reader
54 inPath string
55 opts InlineImports
56
57 importContext resource.ResourceGetter
58 contentSeen map[string]bool
59 dependencyManager identity.Manager
60 linemap map[int]fileOffset
61 fs afero.Fs
62 logger loggers.Logger
63 }
64
65 func newImportResolver(ctx context.Context, r io.Reader, inPath string, opts InlineImports, fs afero.Fs, logger loggers.Logger, dependencyManager identity.Manager) *importResolver {
66 imp := &importResolver{
67 ctx: ctx,
68 r: r,
69 dependencyManager: dependencyManager,
70 inPath: inPath,
71 fs: fs, logger: logger,
72 linemap: make(map[int]fileOffset), contentSeen: make(map[string]bool),
73 opts: opts,
74 }
75 if opts.ImportContext != nil {
76 imp.importContext = resource.NewCachedResourceGetter(opts.ImportContext)
77 }
78 return imp
79 }
80
81 func (imp *importResolver) contentHash(filename string) ([]byte, string) {
82 b, err := afero.ReadFile(imp.fs, filename)
83 if err != nil {
84 return nil, ""
85 }
86 return b, hashBytes(b)
87 }
88
89 func hashBytes(b []byte) string {
90 h := sha256.New()
91 h.Write(b)
92 return hex.EncodeToString(h.Sum(nil))
93 }
94
95 func (imp *importResolver) importRecursive(
96 lineNum int,
97 content string,
98 inPath string,
99 ) (int, string, error) {
100 basePath := path.Dir(inPath)
101
102 var replacements []string
103 lines := strings.Split(content, "\n")
104
105 trackLine := func(i, offset int, line string) {
106 // TODO(bep) this is not very efficient.
107 imp.linemap[i+lineNum] = fileOffset{Filename: inPath, Offset: offset}
108 }
109
110 i := 0
111 for offset, line := range lines {
112 i++
113 lineTrimmed := strings.TrimSpace(line)
114 column := strings.Index(line, lineTrimmed)
115 line = lineTrimmed
116
117 if !imp.shouldImport(line) {
118 trackLine(i, offset, line)
119 } else {
120 path := strings.Trim(strings.TrimPrefix(line, importIdentifier), " \"';")
121 filename := filepath.Join(basePath, path)
122 var (
123 importContent []byte
124 hash string
125 nestedInPath string
126 )
127 if imp.importContext != nil {
128 // Try first the path as written in the import statement,
129 // then resolved relative to the importing file.
130 for _, name := range []string{path, filepath.ToSlash(filename)} {
131 r := imp.importContext.Get(name)
132 if r == nil {
133 continue
134 }
135 imp.dependencyManager.AddIdentity(identity.FirstIdentity(r))
136 s, err := resources.InternalResourceSourceContent(imp.ctx, r)
137 if err != nil {
138 return 0, "", err
139 }
140 importContent, hash = []byte(s), hashBytes([]byte(s))
141 nestedInPath = name
142 break
143 }
144 }
145
146 if importContent == nil {
147 imp.dependencyManager.AddIdentity(identity.CleanStringIdentity(filename))
148 importContent, hash = imp.contentHash(filename)
149 nestedInPath = filepath.ToSlash(filename)
150 }
151
152 if importContent == nil {
153 if imp.opts.SkipInlineImportsNotFound {
154 trackLine(i, offset, line)
155 continue
156 }
157 pos := text.Position{
158 Filename: inPath,
159 LineNumber: offset + 1,
160 ColumnNumber: column + 1,
161 }
162 msgDetail := "if this import's source lives in node_modules, enable the skipInlineImportsNotFound option, see https://gohugo.io/functions/css/postcss/#skipinlineimportsnotfound"
163 return 0, "", herrors.NewFileErrorFromFileInPos(fmt.Errorf("failed to resolve CSS @import \"%s\"; %s", filename, msgDetail), pos, imp.fs, nil)
164 }
165
166 i--
167
168 if imp.contentSeen[hash] {
169 i++
170 // Just replace the line with an empty string.
171 replacements = append(replacements, []string{line, ""}...)
172 trackLine(i, offset, "IMPORT")
173 continue
174 }
175
176 imp.contentSeen[hash] = true
177
178 // Handle recursive imports.
179 l, nested, err := imp.importRecursive(i+lineNum, string(importContent), nestedInPath)
180 if err != nil {
181 return 0, "", err
182 }
183
184 trackLine(i, offset, line)
185
186 i += l
187
188 importContent = []byte(nested)
189
190 replacements = append(replacements, []string{line, string(importContent)}...)
191 }
192 }
193
194 if len(replacements) > 0 {
195 repl := strings.NewReplacer(replacements...)
196 content = repl.Replace(content)
197 }
198
199 return i, content, nil
200 }
201
202 func (imp *importResolver) resolve() (io.Reader, error) {
203 content, err := io.ReadAll(imp.r)
204 if err != nil {
205 return nil, err
206 }
207
208 contents := string(content)
209
210 _, newContent, err := imp.importRecursive(0, contents, imp.inPath)
211 if err != nil {
212 return nil, err
213 }
214
215 return strings.NewReader(newContent), nil
216 }
217
218 // See https://www.w3schools.com/cssref/pr_import_rule.asp
219 // We currently only support simple file imports, no urls, no media queries.
220 // So this is OK:
221 //
222 // @import "navigation.css";
223 //
224 // This is not:
225 //
226 // @import url("navigation.css");
227 // @import "mobstyle.css" screen and (max-width: 768px);
228 func (imp *importResolver) shouldImport(s string) bool {
229 if !strings.HasPrefix(s, importIdentifier) {
230 return false
231 }
232 if strings.Contains(s, "url(") {
233 return false
234 }
235
236 m := shouldImportRe.FindStringSubmatch(s)
237 if m == nil {
238 return false
239 }
240
241 if len(m) != 3 {
242 return false
243 }
244
245 if tailwindImportExclude(m[1]) {
246 return false
247 }
248
249 return true
250 }
251
252 func (imp *importResolver) toFileError(output string) error {
253 inErr := errors.New(output)
254
255 match := cssSyntaxErrorRe.FindStringSubmatch(output)
256 if match == nil {
257 return inErr
258 }
259
260 lineNum, err := strconv.Atoi(match[1])
261 if err != nil {
262 return inErr
263 }
264
265 file, ok := imp.linemap[lineNum]
266 if !ok {
267 return inErr
268 }
269
270 fi, err := imp.fs.Stat(file.Filename)
271 if err != nil {
272 return inErr
273 }
274
275 meta := fi.(hugofs.FileMetaInfo).Meta()
276 realFilename := meta.Filename
277 f, err := meta.Open()
278 if err != nil {
279 return inErr
280 }
281 defer f.Close()
282
283 ferr := herrors.NewFileErrorFromName(inErr, realFilename)
284 pos := ferr.Position()
285 pos.LineNumber = file.Offset + 1
286 return ferr.UpdatePosition(pos).UpdateContent(f, nil)
287
288 // return herrors.NewFileErrorFromFile(inErr, file.Filename, realFilename, hugofs.Os, herrors.SimpleLineMatcher)
289 }