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 (
82 prevDir string
83 inHugo = true
84 osDirs = options.to.IncludePaths
85 )
86
87 if prev == "stdin" {
88 prevDir = baseDir
89 } else {
90 prevDir, inHugo = t.c.sfs.MakePathRelative(filepath.Dir(prev), true)
91 osDirs = append([]string{filepath.Dir(prev)}, osDirs...)
92 }
93
94 urlDir := filepath.Dir(url)
95 name := filepath.Base(url)
96
97 // Libsass throws an error in cases where you have several possible candidates.
98 // We make this simpler and pick the first match.
99 var namePatterns []string
100 if strings.Contains(name, ".") {
101 namePatterns = []string{"_%s", "%s"}
102 } else if strings.HasPrefix(name, "_") {
103 namePatterns = []string{"_%s.scss", "_%s.sass"}
104 } else {
105 namePatterns = []string{
106 "_%s.scss", "%s.scss",
107 "_%s.sass", "%s.sass",
108 "%s/_index.scss", "%s/_index.sass",
109 "%s/index.scss", "%s/index.sass",
110 }
111 }
112
113 name = strings.TrimPrefix(name, "_")
114 names := make([]string, len(namePatterns))
115 for i, namePattern := range namePatterns {
116 names[i] = filepath.Join(urlDir, fmt.Sprintf(namePattern, name))
117 }
118
119 if inHugo {
120 for _, n := range names {
121 filenameToCheck := filepath.Join(prevDir, n)
122 fi, err := t.c.sfs.Fs.Stat(filenameToCheck)
123 if err == nil {
124 if fim, ok := fi.(hugofs.FileMetaInfo); ok {
125 ctx.DependencyManager.AddIdentity(identity.CleanStringIdentity(filenameToCheck))
126 return fim.Meta().Filename, "", true
127 }
128 }
129 }
130 }
131
132 // Not found in Hugo's file systems. LibSASS would now search relative to prev
133 // and the include paths on its own, so do that here where the result can be checked.
134 filename, err := sass.FindFile(t.c.rs.ExecHelper, osDirs, names)
135 if err != nil {
136 // The resolver cannot return an error, but @error fails the build.
137 return url, fmt.Sprintf("@error %q;", err.Error()), true
138 }
139 if filename != "" {
140 return filename, "", true
141 }
142
143 // Not found, let LibSASS report it.
144 return "", "", false
145 }
146
147 if ctx.InMediaType.SubType == media.Builtin.SASSType.SubType {
148 options.to.SassSyntax = true
149 }
150
151 if options.from.EnableSourceMap {
152
153 options.to.SourceMapOptions.Filename = outName + ".map"
154 options.to.SourceMapOptions.Root = t.c.rs.Cfg.BaseConfig().WorkingDir
155
156 // Setting this to the relative input filename will get the source map
157 // more correct for the main entry path (main.scss typically), but
158 // it will mess up the import mappings. As a workaround, we do a replacement
159 // in the source map itself (see below).
160 // options.InputPath = inputPath
161 options.to.SourceMapOptions.OutputPath = outName
162 options.to.SourceMapOptions.Contents = true
163 options.to.SourceMapOptions.OmitURL = false
164 options.to.SourceMapOptions.EnableEmbedded = false
165 }
166
167 res, err := t.c.toCSS(options.to, ctx.To, ctx.From)
168 if err != nil {
169 if sasserr, ok := err.(libsasserrors.Error); ok {
170 if sasserr.File == "stdin" && ctx.SourcePath != "" {
171 sasserr.File = t.c.sfs.RealFilename(ctx.SourcePath)
172 err = sasserr
173 }
174 }
175 return herrors.NewFileErrorFromFileInErr(err, hugofs.Os, nil)
176
177 }
178
179 if options.from.EnableSourceMap && res.SourceMapContent != "" {
180 sourcePath := t.c.sfs.RealFilename(ctx.SourcePath)
181
182 if strings.HasPrefix(sourcePath, t.c.rs.Cfg.BaseConfig().WorkingDir) {
183 sourcePath = strings.TrimPrefix(sourcePath, t.c.rs.Cfg.BaseConfig().WorkingDir+helpers.FilePathSeparator)
184 }
185
186 // This needs to be Unix-style slashes, even on Windows.
187 // See https://github.com/gohugoio/hugo/issues/4968
188 sourcePath = filepath.ToSlash(sourcePath)
189
190 // This is a workaround for what looks like a bug in Libsass. But
191 // getting this resolution correct in tools like Chrome Workspaces
192 // is important enough to go this extra mile.
193 mapContent := strings.Replace(res.SourceMapContent, `stdin"`, fmt.Sprintf("%s\"", sourcePath), 1)
194
195 return ctx.PublishSourceMap([]byte(mapContent))
196 }
197 return nil
198 }
199
200 func (c *Client) toCSS(options libsass.Options, dst io.Writer, src io.Reader) (libsass.Result, error) {
201 var res libsass.Result
202
203 transpiler, err := libsass.New(options)
204 if err != nil {
205 return res, err
206 }
207
208 in := helpers.ReaderToString(src)
209
210 // See https://github.com/gohugoio/hugo/issues/7059
211 // We need to preserve the regular CSS imports. This is by far
212 // a perfect solution, and only works for the main entry file, but
213 // that should cover many use cases, e.g. using SCSS as a preprocessor
214 // for Tailwind.
215 var importsReplaced bool
216 in, importsReplaced = replaceRegularImportsIn(in)
217
218 res, err = transpiler.Execute(in)
219 if err != nil {
220 return res, err
221 }
222
223 out := res.CSS
224 if importsReplaced {
225 out = replaceRegularImportsOut(out)
226 }
227
228 _, err = io.WriteString(dst, out)
229
230 return res, err
231 }