| 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 |
args := godartsass.Args{ |
| 91 |
URL: filename, |
| 92 |
IncludePaths: t.c.sfs.RealDirs(baseDir), |
| 93 |
ImportResolver: importResolver{ |
| 94 |
baseDir: baseDir, |
| 95 |
c: t.c, |
| 96 |
dependencyManager: ctx.DependencyManager, |
| 97 |
importContext: ic, |
| 98 |
ctx: ctx.Ctx, |
| 99 |
|
| 100 |
vars: opts.Vars, |
| 101 |
}, |
| 102 |
OutputStyle: godartsass.ParseOutputStyle(opts.OutputStyle), |
| 103 |
EnableSourceMap: opts.EnableSourceMap, |
| 104 |
SourceMapIncludeSources: opts.SourceMapIncludeSources, |
| 105 |
SilenceDeprecations: opts.SilenceDeprecations, |
| 106 |
SilenceDependencyDeprecations: opts.SilenceDependencyDeprecations, |
| 107 |
} |
| 108 |
|
| 109 |
// Append any workDir relative include paths |
| 110 |
for _, ip := range opts.IncludePaths { |
| 111 |
info, err := t.c.workFs.Stat(filepath.Clean(ip)) |
| 112 |
if err == nil { |
| 113 |
filename := info.(hugofs.FileMetaInfo).Meta().Filename |
| 114 |
args.IncludePaths = append(args.IncludePaths, filename) |
| 115 |
} |
| 116 |
} |
| 117 |
|
| 118 |
if ctx.InMediaType.SubType == media.Builtin.SASSType.SubType { |
| 119 |
args.SourceSyntax = godartsass.SourceSyntaxSASS |
| 120 |
} |
| 121 |
|
| 122 |
res, err := t.c.toCSS(args, ctx.From) |
| 123 |
if err != nil { |
| 124 |
return err |
| 125 |
} |
| 126 |
|
| 127 |
out := res.CSS |
| 128 |
|
| 129 |
_, err = io.WriteString(ctx.To, out) |
| 130 |
if err != nil { |
| 131 |
return err |
| 132 |
} |
| 133 |
|
| 134 |
if opts.EnableSourceMap && res.SourceMap != "" { |
| 135 |
if err := ctx.PublishSourceMap([]byte(res.SourceMap)); err != nil { |
| 136 |
return err |
| 137 |
} |
| 138 |
_, err = fmt.Fprintf(ctx.To, "\n\n/*# sourceMappingURL=%s */", path.Base(ctx.OutPath)+".map") |
| 139 |
} |
| 140 |
|
| 141 |
return err |
| 142 |
} |
| 143 |
|
| 144 |
type importResolver struct { |
| 145 |
baseDir string |
| 146 |
c *Client |
| 147 |
dependencyManager identity.Manager |
| 148 |
importContext resource.ResourceGetter |
| 149 |
ctx context.Context |
| 150 |
vars map[string]any |
| 151 |
} |
| 152 |
|
| 153 |
func (t importResolver) CanonicalizeURL(url string) (string, error) { |
| 154 |
if _, ok := sass.HugoVarsSubPath(url); ok { |
| 155 |
return strings.ToLower(url), nil |
| 156 |
} |
| 157 |
|
| 158 |
if r := t.resolveInImportContext(url); r != nil { |
| 159 |
t.dependencyManager.AddIdentity(identity.FirstIdentity(r)) |
| 160 |
return dartSassImportContextPrefix + paths.ToSlashTrimLeading(resources.InternalResourceTargetPath(r)), nil |
| 161 |
} |
| 162 |
|
| 163 |
filePath, isURL := paths.UrlStringToFilename(url) |
| 164 |
var prevDir string |
| 165 |
var pathDir string |
| 166 |
if isURL { |
| 167 |
var found bool |
| 168 |
prevDir, found = t.c.sfs.MakePathRelative(filepath.Dir(filePath), true) |
| 169 |
|
| 170 |
if !found { |
| 171 |
// Not a member of this filesystem, let Dart Sass handle it. |
| 172 |
return "", nil |
| 173 |
} |
| 174 |
} else { |
| 175 |
prevDir = t.baseDir |
| 176 |
pathDir = path.Dir(url) |
| 177 |
} |
| 178 |
|
| 179 |
basePath := filepath.Join(prevDir, pathDir) |
| 180 |
name := filepath.Base(filePath) |
| 181 |
|
| 182 |
// Pick the first match. |
| 183 |
namePatterns := sassNamePatterns(name) |
| 184 |
name = strings.TrimPrefix(name, "_") |
| 185 |
|
| 186 |
for _, namePattern := range namePatterns { |
| 187 |
filenameToCheck := filepath.Join(basePath, fmt.Sprintf(namePattern, name)) |
| 188 |
fi, err := t.c.sfs.Fs.Stat(filenameToCheck) |
| 189 |
if err == nil { |
| 190 |
if fim, ok := fi.(hugofs.FileMetaInfo); ok { |
| 191 |
t.dependencyManager.AddIdentity(identity.CleanStringIdentity(filenameToCheck)) |
| 192 |
return "file://" + filepath.ToSlash(fim.Meta().Filename), nil |
| 193 |
} |
| 194 |
} |
| 195 |
} |
| 196 |
|
| 197 |
// Not found, let Dart Sass handle it |
| 198 |
return "", nil |
| 199 |
} |
| 200 |
|
| 201 |
func sassNamePatterns(name string) []string { |
| 202 |
if strings.Contains(name, ".") { |
| 203 |
return []string{"_%s", "%s"} |
| 204 |
} |
| 205 |
if strings.HasPrefix(name, "_") { |
| 206 |
return []string{"_%s.scss", "_%s.sass", "_%s.css"} |
| 207 |
} |
| 208 |
return []string{ |
| 209 |
"_%s.scss", "%s.scss", |
| 210 |
"_%s.sass", "%s.sass", |
| 211 |
"_%s.css", "%s.css", |
| 212 |
"%s/_index.scss", "%s/_index.sass", |
| 213 |
"%s/index.scss", "%s/index.sass", |
| 214 |
} |
| 215 |
} |
| 216 |
|
| 217 |
// resolveInImportContext resolves url in the user provided import context, if any, |
| 218 |
// using the same name patterns as for the file system. |
| 219 |
func (t importResolver) resolveInImportContext(url string) resource.Resource { |
| 220 |
if t.importContext == nil { |
| 221 |
return nil |
| 222 |
} |
| 223 |
url = strings.TrimPrefix(url, dartSassImportContextPrefix) |
| 224 |
if r := t.importContext.Get(url); r != nil { |
| 225 |
return r |
| 226 |
} |
| 227 |
dir, name := path.Split(url) |
| 228 |
namePatterns := sassNamePatterns(name) |
| 229 |
name = strings.TrimPrefix(name, "_") |
| 230 |
for _, namePattern := range namePatterns { |
| 231 |
if r := t.importContext.Get(path.Join(dir, fmt.Sprintf(namePattern, name))); r != nil { |
| 232 |
return r |
| 233 |
} |
| 234 |
} |
| 235 |
return nil |
| 236 |
} |
| 237 |
|
| 238 |
func (t importResolver) Load(url string) (godartsass.Import, error) { |
| 239 |
if subPath, ok := sass.HugoVarsSubPath(url); ok { |
| 240 |
return godartsass.Import{ |
| 241 |
Content: sass.CreateVarsStyleSheet(sass.TranspilerDart, sass.ResolveVars(t.vars, subPath)), |
| 242 |
}, nil |
| 243 |
} |
| 244 |
|
| 245 |
if strings.HasPrefix(url, dartSassImportContextPrefix) { |
| 246 |
r := t.resolveInImportContext(url) |
| 247 |
if r == nil { |
| 248 |
return godartsass.Import{}, fmt.Errorf("could not find %q in the import context", url) |
| 249 |
} |
| 250 |
content, err := resources.InternalResourceSourceContent(t.ctx, r) |
| 251 |
return godartsass.Import{Content: content, SourceSyntax: sassSourceSyntax(url)}, err |
| 252 |
} |
| 253 |
|
| 254 |
filename, _ := paths.UrlStringToFilename(url) |
| 255 |
b, err := afero.ReadFile(hugofs.Os, filename) |
| 256 |
|
| 257 |
return godartsass.Import{Content: string(b), SourceSyntax: sassSourceSyntax(filename)}, err |
| 258 |
} |
| 259 |
|
| 260 |
func sassSourceSyntax(name string) godartsass.SourceSyntax { |
| 261 |
switch { |
| 262 |
case strings.HasSuffix(name, ".sass"): |
| 263 |
return godartsass.SourceSyntaxSASS |
| 264 |
case strings.HasSuffix(name, ".css"): |
| 265 |
return godartsass.SourceSyntaxCSS |
| 266 |
default: |
| 267 |
return godartsass.SourceSyntaxSCSS |
| 268 |
} |
| 269 |
} |