Debian Codegraph @

resources/resource_transformers/tocss/dartsass/transform.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 dartsass
15
16 import (
17 "context"
18 "fmt"
19 "io"
20 "path"
21 "path/filepath"
22 "strings"
23
24 "github.com/gohugoio/hugo/common/hugo"
25 "github.com/gohugoio/hugo/common/paths"
26 "github.com/gohugoio/hugo/htesting"
27 "github.com/gohugoio/hugo/identity"
28 "github.com/gohugoio/hugo/media"
29
30 "github.com/gohugoio/hugo/resources"
31 "github.com/gohugoio/hugo/resources/resource"
32
33 "github.com/gohugoio/hugo/resources/internal"
34 "github.com/gohugoio/hugo/resources/resource_transformers/tocss/sass"
35
36 "github.com/spf13/afero"
37
38 "github.com/gohugoio/hugo/hugofs"
39
40 "github.com/bep/godartsass/v2"
41 )
42
43 // Prefix for canonical URLs of stylesheets resolved in the user provided import context.
44 // Note: This prefix must be all lower case.
45 const dartSassImportContextPrefix = "hugoimportcontext:"
46
47 // Supports returns whether sass, dart-sass, or dart-sass-embedded is found in $PATH.
48 func Supports() bool {
49 if htesting.SupportsAll() {
50 return true
51 }
52 return hugo.DartSassBinaryName != ""
53 }
54
55 type transform struct {
56 optsm map[string]any
57 c *Client
58 }
59
60 func (t *transform) Key() internal.ResourceTransformationKey {
61 return internal.NewResourceTransformationKey(transformationName, t.optsm)
62 }
63
64 func (t *transform) Transform(ctx *resources.ResourceTransformationCtx) error {
65 ctx.OutMediaType = media.Builtin.CSSType
66
67 opts, err := decodeOptions(t.optsm)
68 if err != nil {
69 return err
70 }
71
72 if opts.TargetPath != "" {
73 ctx.OutPath = opts.TargetPath
74 } else {
75 ctx.ReplaceOutPathExtension(".css")
76 }
77
78 baseDir := path.Dir(ctx.SourcePath)
79 filename := dartSassStdinPrefix
80
81 if ctx.SourcePath != "" {
82 filename += t.c.sfs.RealFilename(ctx.SourcePath)
83 }
84
85 var ic resource.ResourceGetter
86 if opts.ImportContext != nil {
87 ic = resource.NewCachedResourceGetter(opts.ImportContext)
88 }
89
90 // Dart Sass gets no load paths; the import resolver handles these so
91 // all file reads go through Hugo.
92 osDirs := t.c.sfs.RealDirs(baseDir)
93 for _, ip := range opts.IncludePaths {
94 info, err := t.c.workFs.Stat(filepath.Clean(ip))
95 if err == nil {
96 osDirs = append(osDirs, info.(hugofs.FileMetaInfo).Meta().Filename)
97 }
98 }
99
100 args := godartsass.Args{
101 URL: filename,
102 ImportResolver: importResolver{
103 baseDir: baseDir,
104 osDirs: osDirs,
105 c: t.c,
106 dependencyManager: ctx.DependencyManager,
107 importContext: ic,
108 ctx: ctx.Ctx,
109
110 vars: opts.Vars,
111 },
112 OutputStyle: godartsass.ParseOutputStyle(opts.OutputStyle),
113 EnableSourceMap: opts.EnableSourceMap,
114 SourceMapIncludeSources: opts.SourceMapIncludeSources,
115 SilenceDeprecations: opts.SilenceDeprecations,
116 SilenceDependencyDeprecations: opts.SilenceDependencyDeprecations,
117 }
118
119 if ctx.InMediaType.SubType == media.Builtin.SASSType.SubType {
120 args.SourceSyntax = godartsass.SourceSyntaxSASS
121 }
122
123 res, err := t.c.toCSS(args, ctx.From)
124 if err != nil {
125 return err
126 }
127
128 out := res.CSS
129
130 _, err = io.WriteString(ctx.To, out)
131 if err != nil {
132 return err
133 }
134
135 if opts.EnableSourceMap && res.SourceMap != "" {
136 if err := ctx.PublishSourceMap([]byte(res.SourceMap)); err != nil {
137 return err
138 }
139 _, err = fmt.Fprintf(ctx.To, "\n\n/*# sourceMappingURL=%s */", path.Base(ctx.OutPath)+".map")
140 }
141
142 return err
143 }
144
145 type importResolver struct {
146 baseDir string
147 // Real dirs of baseDir and the include paths.
148 osDirs []string
149 c *Client
150 dependencyManager identity.Manager
151 importContext resource.ResourceGetter
152 ctx context.Context
153 vars map[string]any
154 }
155
156 func (t importResolver) CanonicalizeURL(url string) (string, error) {
157 if _, ok := sass.HugoVarsSubPath(url); ok {
158 return strings.ToLower(url), nil
159 }
160
161 if r := t.resolveInImportContext(url); r != nil {
162 t.dependencyManager.AddIdentity(identity.FirstIdentity(r))
163 return dartSassImportContextPrefix + paths.ToSlashTrimLeading(resources.InternalResourceTargetPath(r)), nil
164 }
165
166 filePath, isURL := paths.UrlStringToFilename(url)
167 var (
168 prevDir string
169 pathDir string
170 inHugo = true
171 osDirs []string
172 )
173 if isURL {
174 // Relative to the importing file.
175 prevDir, inHugo = t.c.sfs.MakePathRelative(filepath.Dir(filePath), true)
176 osDirs = []string{filepath.Dir(filePath)}
177 } else {
178 // Relative to the entry file or the include paths.
179 prevDir = t.baseDir
180 pathDir = path.Dir(url)
181 osDirs = t.osDirs
182 }
183
184 name := filepath.Base(filePath)
185 namePatterns := sassNamePatterns(name)
186 name = strings.TrimPrefix(name, "_")
187 names := make([]string, len(namePatterns))
188 for i, namePattern := range namePatterns {
189 names[i] = filepath.Join(pathDir, fmt.Sprintf(namePattern, name))
190 }
191
192 if inHugo {
193 // Pick the first match.
194 for _, n := range names {
195 filenameToCheck := filepath.Join(prevDir, n)
196 fi, err := t.c.sfs.Fs.Stat(filenameToCheck)
197 if err == nil {
198 if fim, ok := fi.(hugofs.FileMetaInfo); ok {
199 t.dependencyManager.AddIdentity(identity.CleanStringIdentity(filenameToCheck))
200 return "file://" + filepath.ToSlash(fim.Meta().Filename), nil
201 }
202 }
203 }
204 }
205
206 // Not found in Hugo's file systems. Dart Sass gets no load paths of its own, so
207 // this is the only way to reach the include paths and files hidden from Hugo's file
208 // systems (e.g. symlinks); FindFile keeps it inside the allowed paths.
209 filename, err := sass.FindFile(t.c.rs.ExecHelper, osDirs, names)
210 if err != nil || filename == "" {
211 return "", err
212 }
213 return "file://" + filepath.ToSlash(filename), nil
214 }
215
216 func sassNamePatterns(name string) []string {
217 if strings.Contains(name, ".") {
218 return []string{"_%s", "%s"}
219 }
220 if strings.HasPrefix(name, "_") {
221 return []string{"_%s.scss", "_%s.sass", "_%s.css"}
222 }
223 return []string{
224 "_%s.scss", "%s.scss",
225 "_%s.sass", "%s.sass",
226 "_%s.css", "%s.css",
227 "%s/_index.scss", "%s/_index.sass",
228 "%s/index.scss", "%s/index.sass",
229 }
230 }
231
232 // resolveInImportContext resolves url in the user provided import context, if any,
233 // using the same name patterns as for the file system.
234 func (t importResolver) resolveInImportContext(url string) resource.Resource {
235 if t.importContext == nil {
236 return nil
237 }
238 url = strings.TrimPrefix(url, dartSassImportContextPrefix)
239 if r := t.importContext.Get(url); r != nil {
240 return r
241 }
242 dir, name := path.Split(url)
243 namePatterns := sassNamePatterns(name)
244 name = strings.TrimPrefix(name, "_")
245 for _, namePattern := range namePatterns {
246 if r := t.importContext.Get(path.Join(dir, fmt.Sprintf(namePattern, name))); r != nil {
247 return r
248 }
249 }
250 return nil
251 }
252
253 func (t importResolver) Load(url string) (godartsass.Import, error) {
254 if subPath, ok := sass.HugoVarsSubPath(url); ok {
255 return godartsass.Import{
256 Content: sass.CreateVarsStyleSheet(sass.TranspilerDart, sass.ResolveVars(t.vars, subPath)),
257 }, nil
258 }
259
260 if strings.HasPrefix(url, dartSassImportContextPrefix) {
261 r := t.resolveInImportContext(url)
262 if r == nil {
263 return godartsass.Import{}, fmt.Errorf("could not find %q in the import context", url)
264 }
265 content, err := resources.InternalResourceSourceContent(t.ctx, r)
266 return godartsass.Import{Content: content, SourceSyntax: sassSourceSyntax(url)}, err
267 }
268
269 filename, _ := paths.UrlStringToFilename(url)
270 b, err := afero.ReadFile(hugofs.Os, filename)
271
272 return godartsass.Import{Content: string(b), SourceSyntax: sassSourceSyntax(filename)}, err
273 }
274
275 func sassSourceSyntax(name string) godartsass.SourceSyntax {
276 switch {
277 case strings.HasSuffix(name, ".sass"):
278 return godartsass.SourceSyntaxSASS
279 case strings.HasSuffix(name, ".css"):
280 return godartsass.SourceSyntaxCSS
281 default:
282 return godartsass.SourceSyntaxSCSS
283 }
284 }