Debian Codegraph @

resources/resource_transformers/tocss/scss/tocss.go

raw
1 // Copyright 2018 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 //go:build extended
15
16 package scss
17
18 import (
19 "fmt"
20 "io"
21 "path"
22 "path/filepath"
23 "strings"
24
25 "github.com/bep/golibsass/libsass"
26 "github.com/bep/golibsass/libsass/libsasserrors"
27 "github.com/gohugoio/hugo/common/herrors"
28 "github.com/gohugoio/hugo/helpers"
29 "github.com/gohugoio/hugo/hugofs"
30 "github.com/gohugoio/hugo/identity"
31 "github.com/gohugoio/hugo/media"
32 "github.com/gohugoio/hugo/resources"
33 "github.com/gohugoio/hugo/resources/resource_transformers/tocss/sass"
34 )
35
36 // Used in tests. This feature requires Hugo to be built with the extended tag.
37 func Supports() bool {
38 return true
39 }
40
41 func (t *toCSSTransformation) Transform(ctx *resources.ResourceTransformationCtx) error {
42 ctx.OutMediaType = media.Builtin.CSSType
43
44 var outName string
45 if t.options.from.TargetPath != "" {
46 ctx.OutPath = t.options.from.TargetPath
47 } else {
48 ctx.ReplaceOutPathExtension(".css")
49 }
50
51 outName = path.Base(ctx.OutPath)
52
53 options := t.options
54 baseDir := path.Dir(ctx.SourcePath)
55 options.to.IncludePaths = t.c.sfs.RealDirs(baseDir)
56
57 // Append any workDir relative include paths
58 for _, ip := range options.from.IncludePaths {
59 info, err := t.c.workFs.Stat(filepath.Clean(ip))
60 if err == nil {
61 filename := info.(hugofs.FileMetaInfo).Meta().Filename
62 options.to.IncludePaths = append(options.to.IncludePaths, filename)
63 }
64 }
65
66 varsStylesheet := sass.CreateVarsStyleSheet(sass.TranspilerLibSass, options.from.Vars)
67
68 // To allow for overrides of SCSS files anywhere in the project/theme hierarchy, we need
69 // to help libsass revolve the filename by looking in the composite filesystem first.
70 // We add the entry directories for both project and themes to the include paths list, but
71 // that only work for overrides on the top level.
72 options.to.ImportResolver = func(url string, prev string) (newUrl string, body string, resolved bool) {
73 if url == sass.HugoVarsNamespace {
74 return url, varsStylesheet, true
75 }
76
77 // We get URL paths from LibSASS, but we need file paths.
78 url = filepath.FromSlash(url)
79 prev = filepath.FromSlash(prev)
80
81 var basePath string
82 urlDir := filepath.Dir(url)
83 var prevDir string
84
85 if prev == "stdin" {
86 prevDir = baseDir
87 } else {
88 prevDir, _ = t.c.sfs.MakePathRelative(filepath.Dir(prev), true)
89
90 if prevDir == "" {
91 // Not a member of this filesystem. Let LibSASS handle it.
92 return "", "", false
93 }
94 }
95
96 basePath = filepath.Join(prevDir, urlDir)
97 name := filepath.Base(url)
98
99 // Libsass throws an error in cases where you have several possible candidates.
100 // We make this simpler and pick the first match.
101 var namePatterns []string
102 if strings.Contains(name, ".") {
103 namePatterns = []string{"_%s", "%s"}
104 } else if strings.HasPrefix(name, "_") {
105 namePatterns = []string{"_%s.scss", "_%s.sass"}
106 } else {
107 namePatterns = []string{
108 "_%s.scss", "%s.scss",
109 "_%s.sass", "%s.sass",
110 "%s/_index.scss", "%s/_index.sass",
111 "%s/index.scss", "%s/index.sass",
112 }
113 }
114
115 name = strings.TrimPrefix(name, "_")
116
117 for _, namePattern := range namePatterns {
118 filenameToCheck := filepath.Join(basePath, fmt.Sprintf(namePattern, name))
119 fi, err := t.c.sfs.Fs.Stat(filenameToCheck)
120 if err == nil {
121 if fim, ok := fi.(hugofs.FileMetaInfo); ok {
122 ctx.DependencyManager.AddIdentity(identity.CleanStringIdentity(filenameToCheck))
123 return fim.Meta().Filename, "", true
124 }
125 }
126 }
127
128 // Not found, let LibSASS handle it
129 return "", "", false
130 }
131
132 if ctx.InMediaType.SubType == media.Builtin.SASSType.SubType {
133 options.to.SassSyntax = true
134 }
135
136 if options.from.EnableSourceMap {
137
138 options.to.SourceMapOptions.Filename = outName + ".map"
139 options.to.SourceMapOptions.Root = t.c.rs.Cfg.BaseConfig().WorkingDir
140
141 // Setting this to the relative input filename will get the source map
142 // more correct for the main entry path (main.scss typically), but
143 // it will mess up the import mappings. As a workaround, we do a replacement
144 // in the source map itself (see below).
145 // options.InputPath = inputPath
146 options.to.SourceMapOptions.OutputPath = outName
147 options.to.SourceMapOptions.Contents = true
148 options.to.SourceMapOptions.OmitURL = false
149 options.to.SourceMapOptions.EnableEmbedded = false
150 }
151
152 res, err := t.c.toCSS(options.to, ctx.To, ctx.From)
153 if err != nil {
154 if sasserr, ok := err.(libsasserrors.Error); ok {
155 if sasserr.File == "stdin" && ctx.SourcePath != "" {
156 sasserr.File = t.c.sfs.RealFilename(ctx.SourcePath)
157 err = sasserr
158 }
159 }
160 return herrors.NewFileErrorFromFileInErr(err, hugofs.Os, nil)
161
162 }
163
164 if options.from.EnableSourceMap && res.SourceMapContent != "" {
165 sourcePath := t.c.sfs.RealFilename(ctx.SourcePath)
166
167 if strings.HasPrefix(sourcePath, t.c.rs.Cfg.BaseConfig().WorkingDir) {
168 sourcePath = strings.TrimPrefix(sourcePath, t.c.rs.Cfg.BaseConfig().WorkingDir+helpers.FilePathSeparator)
169 }
170
171 // This needs to be Unix-style slashes, even on Windows.
172 // See https://github.com/gohugoio/hugo/issues/4968
173 sourcePath = filepath.ToSlash(sourcePath)
174
175 // This is a workaround for what looks like a bug in Libsass. But
176 // getting this resolution correct in tools like Chrome Workspaces
177 // is important enough to go this extra mile.
178 mapContent := strings.Replace(res.SourceMapContent, `stdin"`, fmt.Sprintf("%s\"", sourcePath), 1)
179
180 return ctx.PublishSourceMap([]byte(mapContent))
181 }
182 return nil
183 }
184
185 func (c *Client) toCSS(options libsass.Options, dst io.Writer, src io.Reader) (libsass.Result, error) {
186 var res libsass.Result
187
188 transpiler, err := libsass.New(options)
189 if err != nil {
190 return res, err
191 }
192
193 in := helpers.ReaderToString(src)
194
195 // See https://github.com/gohugoio/hugo/issues/7059
196 // We need to preserve the regular CSS imports. This is by far
197 // a perfect solution, and only works for the main entry file, but
198 // that should cover many use cases, e.g. using SCSS as a preprocessor
199 // for Tailwind.
200 var importsReplaced bool
201 in, importsReplaced = replaceRegularImportsIn(in)
202
203 res, err = transpiler.Execute(in)
204 if err != nil {
205 return res, err
206 }
207
208 out := res.CSS
209 if importsReplaced {
210 out = replaceRegularImportsOut(out)
211 }
212
213 _, err = io.WriteString(dst, out)
214
215 return res, err
216 }