Debian Codegraph @

resources/resource_transformers/cssjs/postcss.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 cssjs provides resource transformations backed by some popular JS based frameworks.
15 package cssjs
16
17 import (
18 "bytes"
19 "fmt"
20 "io"
21 "path/filepath"
22 "strings"
23
24 "github.com/gohugoio/hugo/common/collections"
25 "github.com/gohugoio/hugo/common/hexec"
26 "github.com/gohugoio/hugo/common/loggers"
27
28 "github.com/gohugoio/hugo/common/hugo"
29
30 "github.com/gohugoio/hugo/resources/internal"
31 "github.com/spf13/cast"
32
33 "github.com/mitchellh/mapstructure"
34
35 "github.com/gohugoio/hugo/common/herrors"
36 "github.com/gohugoio/hugo/resources"
37 "github.com/gohugoio/hugo/resources/resource"
38 )
39
40 // NewPostCSSClient creates a new PostCSSClient with the given specification.
41 func NewPostCSSClient(rs *resources.Spec) *PostCSSClient {
42 return &PostCSSClient{rs: rs}
43 }
44
45 func decodePostCSSOptions(m map[string]any) (opts PostCSSOptions, err error) {
46 if m == nil {
47 return
48 }
49 err = mapstructure.WeakDecode(m, &opts)
50
51 if !opts.NoMap {
52 // There was for a long time a discrepancy between documentation and
53 // implementation for the noMap property, so we need to support both
54 // camel and snake case.
55 opts.NoMap = cast.ToBool(m["no-map"])
56 }
57
58 return
59 }
60
61 // PostCSSClient is the client used to do PostCSS transformations.
62 type PostCSSClient struct {
63 rs *resources.Spec
64 }
65
66 // Process transforms the given Resource with the PostCSS processor.
67 func (c *PostCSSClient) Process(res resources.ResourceTransformer, options map[string]any) (resource.Resource, error) {
68 return res.Transform(&postcssTransformation{rs: c.rs, optionsm: options})
69 }
70
71 type InlineImports struct {
72 // Enable inlining of @import statements.
73 // Does so recursively, but currently once only per file;
74 // that is, it's not possible to import the same file in
75 // different scopes (root, media query...)
76 // Note that this import routine does not care about the CSS spec,
77 // so you can have @import anywhere in the file.
78 InlineImports bool
79
80 // See issue https://github.com/gohugoio/hugo/issues/13719
81 // Disable inlining of @import statements
82 // This is currenty only used for css.TailwindCSS.
83 DisableInlineImports bool
84
85 // When InlineImports is enabled, we fail the build if an import cannot be resolved.
86 // You can enable this to allow the build to continue and leave the import statement in place.
87 // Note that the inline importer does not process url location or imports with media queries,
88 // so those will be left as-is even without enabling this option.
89 SkipInlineImportsNotFound bool
90
91 // User provided import context. If set, imports are looked up here first,
92 // by the path as written in the @import statement, then in the assets filesystem.
93 ImportContext any
94 }
95
96 // Some of the options from https://github.com/postcss/postcss-cli
97 type PostCSSOptions struct {
98 // Set a custom path to look for a config file.
99 Config string
100
101 NoMap bool // Disable the default inline sourcemaps
102
103 InlineImports `mapstructure:",squash"`
104
105 // Options for when not using a config file
106 Use string // List of postcss plugins to use
107 Parser string // Custom postcss parser
108 Stringifier string // Custom postcss stringifier
109 Syntax string // Custom postcss syntax
110 }
111
112 func (opts PostCSSOptions) toArgs() []string {
113 var args []string
114 if opts.NoMap {
115 args = append(args, "--no-map")
116 }
117 if opts.Use != "" {
118 args = append(args, "--use")
119 args = append(args, strings.Fields(opts.Use)...)
120 }
121 if opts.Parser != "" {
122 args = append(args, "--parser", opts.Parser)
123 }
124 if opts.Stringifier != "" {
125 args = append(args, "--stringifier", opts.Stringifier)
126 }
127 if opts.Syntax != "" {
128 args = append(args, "--syntax", opts.Syntax)
129 }
130 return args
131 }
132
133 type postcssTransformation struct {
134 optionsm map[string]any
135 rs *resources.Spec
136 }
137
138 func (t *postcssTransformation) Key() internal.ResourceTransformationKey {
139 return internal.NewResourceTransformationKey("postcss", t.optionsm)
140 }
141
142 // Transform shells out to postcss-cli to do the heavy lifting.
143 // For this to work, you need some additional tools. To install them globally:
144 // npm install -g postcss-cli
145 // npm install -g autoprefixer
146 func (t *postcssTransformation) Transform(ctx *resources.ResourceTransformationCtx) error {
147 const binaryName = "postcss"
148
149 infol := t.rs.Logger.InfoCommand(binaryName)
150 infow := loggers.LevelLoggerToWriter(infol)
151
152 ex := t.rs.ExecHelper
153
154 var configFile string
155
156 options, err := decodePostCSSOptions(t.optionsm)
157 if err != nil {
158 return err
159 }
160
161 if options.Config != "" {
162 configFile = options.Config
163 } else {
164 for _, name := range []string{"postcss.config.js", "postcss.config.mjs", "postcss.config.cjs"} {
165 configFile = t.rs.BaseFs.ResolveJSConfigFile(name)
166 if configFile != "" {
167 break
168 }
169 }
170 }
171
172 if configFile != "" {
173 configFile = filepath.Clean(configFile)
174 // We need an absolute filename to the config file.
175 if !filepath.IsAbs(configFile) {
176 configFile = t.rs.BaseFs.ResolveJSConfigFile(configFile)
177 if configFile == "" && options.Config != "" {
178 // Only fail if the user specified config file is not found.
179 return fmt.Errorf("postcss config %q not found", options.Config)
180 }
181 }
182 }
183
184 var cmdArgs []any
185
186 if configFile != "" {
187 infol.Logf("use config file %q", configFile)
188 cmdArgs = []any{"--config", configFile}
189 }
190
191 if optArgs := options.toArgs(); len(optArgs) > 0 {
192 cmdArgs = append(cmdArgs, collections.StringSliceToInterfaceSlice(optArgs)...)
193 }
194
195 var errBuf bytes.Buffer
196
197 stderr := io.MultiWriter(infow, &errBuf)
198 cmdArgs = append(cmdArgs, hexec.WithStderr(stderr))
199 cmdArgs = append(cmdArgs, hexec.WithStdout(ctx.To))
200 cmdArgs = append(cmdArgs, hexec.WithDir(t.rs.Cfg.BaseConfig().WorkingDir))
201 cmdArgs = append(cmdArgs, hexec.WithEnviron(hugo.GetExecEnviron(t.rs.Cfg.BaseConfig().WorkingDir, t.rs.Cfg, t.rs.BaseFs.Assets.Fs)))
202
203 cmd, err := ex.Npx(binaryName, cmdArgs...)
204 if err != nil {
205 if hexec.IsNotFound(err) {
206 // This may be on a CI server etc. Will fall back to pre-built assets.
207 return &herrors.FeatureNotAvailableError{Cause: err}
208 }
209 return err
210 }
211
212 stdin, err := cmd.StdinPipe()
213 if err != nil {
214 return err
215 }
216
217 src := ctx.From
218
219 imp := newImportResolver(
220 ctx.Ctx,
221 ctx.From,
222 ctx.InPath,
223 options.InlineImports,
224 t.rs.Assets.Fs, t.rs.Logger, ctx.DependencyManager,
225 )
226
227 if options.InlineImports.InlineImports {
228 var err error
229 src, err = imp.resolve()
230 if err != nil {
231 return err
232 }
233 }
234
235 go func() {
236 defer stdin.Close()
237 io.Copy(stdin, src)
238 }()
239
240 err = cmd.Run()
241 if err != nil {
242 if hexec.IsNotFound(err) {
243 return &herrors.FeatureNotAvailableError{
244 Cause: err,
245 }
246 }
247 return imp.toFileError(errBuf.String())
248 }
249
250 return nil
251 }