Debian Codegraph @

resources/resource_transformers/tocss/dartsass/client.go

raw
1 // Copyright 2020 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 integrates with the Dart Sass Embedded protocol to transpile
15 // SCSS/SASS.
16 package dartsass
17
18 import (
19 "fmt"
20 "io"
21 "strings"
22
23 "github.com/bep/godartsass/v2"
24 "github.com/bep/logg"
25 "github.com/gohugoio/hugo/common/herrors"
26 "github.com/gohugoio/hugo/common/hugo"
27 "github.com/gohugoio/hugo/common/paths"
28 "github.com/gohugoio/hugo/helpers"
29 "github.com/gohugoio/hugo/hugofs"
30 "github.com/gohugoio/hugo/hugolib/filesystems"
31 "github.com/gohugoio/hugo/resources"
32 "github.com/gohugoio/hugo/resources/resource"
33 "github.com/gohugoio/hugo/resources/resource_transformers/tocss/sass"
34 "github.com/spf13/afero"
35
36 "github.com/mitchellh/mapstructure"
37 )
38
39 // used as part of the cache key.
40 const transformationName = "tocss-dart"
41
42 // See https://github.com/sass/dart-sass-embedded/issues/24
43 // Note: This prefix must be all lower case.
44 const dartSassStdinPrefix = "hugostdin:"
45
46 func New(fs *filesystems.SourceFilesystem, rs *resources.Spec) (*Client, error) {
47 if !Supports() {
48 return &Client{}, nil
49 }
50
51 if hugo.DartSassBinaryName == "" {
52 return nil, fmt.Errorf("no Dart Sass binary found in $PATH")
53 }
54
55 if !hugo.IsDartSassGeV2() {
56 return nil, fmt.Errorf("unsupported Dart Sass version detected, please upgrade to Dart Sass 1.63.0 or later, see https://gohugo.io/functions/css/sass/#dart-sass")
57 }
58
59 if err := rs.ExecHelper.Sec().CheckAllowedExec(hugo.DartSassBinaryName); err != nil {
60 return nil, err
61 }
62
63 var (
64 transpiler *godartsass.Transpiler
65 err error
66 infol = rs.Logger.InfoCommand("Dart Sass")
67 warnl = rs.Logger.WarnCommand("Dart Sass")
68 )
69
70 transpiler, err = godartsass.Start(godartsass.Options{
71 DartSassEmbeddedFilename: hugo.DartSassBinaryName,
72 LogEventHandler: func(event godartsass.LogEvent) {
73 message := strings.ReplaceAll(event.Message, dartSassStdinPrefix, "")
74 switch event.Type {
75 case godartsass.LogEventTypeDebug:
76 // Log as Info for now, we may adjust this if it gets too chatty.
77 infol.Log(logg.String(message))
78 case godartsass.LogEventTypeDeprecated:
79 warnl.Logf("DEPRECATED [%s]: %s", event.DeprecationType, message)
80 default:
81 // The rest are @warn statements.
82 warnl.Log(logg.String(message))
83 }
84 },
85 })
86 if err != nil {
87 return nil, err
88 }
89 return &Client{sfs: fs, workFs: rs.BaseFs.Work, rs: rs, transpiler: transpiler}, nil
90 }
91
92 type Client struct {
93 rs *resources.Spec
94 sfs *filesystems.SourceFilesystem
95 workFs afero.Fs
96
97 // This may be nil if Dart Sass is not available.
98 transpiler *godartsass.Transpiler
99 }
100
101 func (c *Client) ToCSS(res resources.ResourceTransformer, args map[string]any) (resource.Resource, error) {
102 if c.transpiler == nil {
103 return res.Transform(resources.NewFeatureNotAvailableTransformer(transformationName, args))
104 }
105 return res.Transform(&transform{c: c, optsm: args})
106 }
107
108 func (c *Client) Close() error {
109 if c.transpiler == nil {
110 return nil
111 }
112 return c.transpiler.Close()
113 }
114
115 func (c *Client) toCSS(args godartsass.Args, src io.Reader) (godartsass.Result, error) {
116 in := helpers.ReaderToString(src)
117
118 args.Source = in
119
120 res, err := c.transpiler.Execute(args)
121 if err != nil {
122 if err.Error() == "unexpected EOF" {
123 //lint:ignore ST1005 end user message.
124 return res, fmt.Errorf("got unexpected EOF when executing %q. The user running hugo must have read and execute permissions on this program. With execute permissions only, this error is thrown.", hugo.DartSassBinaryName)
125 }
126 return res, herrors.NewFileErrorFromFileInErr(err, hugofs.Os, herrors.OffsetMatcher)
127 }
128
129 return res, err
130 }
131
132 type Options struct {
133 // Hugo, will by default, just replace the extension of the source
134 // to .css, e.g. "scss/main.scss" becomes "scss/main.css". You can
135 // control this by setting this, e.g. "styles/main.css" will create
136 // a Resource with that as a base for RelPermalink etc.
137 TargetPath string
138
139 // Hugo automatically adds the entry directories (where the main.scss lives)
140 // for project and themes to the list of include paths sent to LibSASS.
141 // Any paths set in this setting will be appended. Note that these will be
142 // treated as relative to the working dir, i.e. no include paths outside the
143 // project/themes.
144 IncludePaths []string
145
146 // Default is nested.
147 // One of nested, expanded, compact, compressed.
148 OutputStyle string
149
150 // When enabled, Hugo will generate a source map.
151 EnableSourceMap bool
152
153 // If enabled, sources will be embedded in the generated source map.
154 SourceMapIncludeSources bool
155
156 // Vars will be available in 'hugo:vars', e.g:
157 // @use "hugo:vars";
158 // $color: vars.$color;
159 Vars map[string]any
160
161 // User provided import context. If set, imports are looked up here first,
162 // then in the assets filesystem.
163 ImportContext any
164
165 // Deprecations IDs in this slice will be silenced.
166 // The IDs can be found in the Dart Sass log output, e.g. "import" in
167 // WARN Dart Sass: DEPRECATED [import].
168 SilenceDeprecations []string
169
170 // Whether to silence deprecation warnings from dependencies, where a
171 // dependency is considered any file transitively imported through a load
172 // path. This does not apply to @warn or @debug rules.
173 SilenceDependencyDeprecations bool
174 }
175
176 func decodeOptions(m map[string]any) (opts Options, err error) {
177 if m == nil {
178 return
179 }
180 err = mapstructure.WeakDecode(m, &opts)
181
182 if opts.TargetPath != "" {
183 opts.TargetPath = paths.ToSlashTrimLeading(opts.TargetPath)
184 }
185
186 opts.Vars = sass.PrepareVars(opts.Vars)
187
188 return
189 }