Debian Codegraph @

resources/resource_transformers/cssjs/tailwindcss.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
15
16 import (
17 "bytes"
18 "errors"
19 "io"
20 "regexp"
21 "strings"
22
23 "github.com/gohugoio/hugo/common/herrors"
24 "github.com/gohugoio/hugo/common/hexec"
25 "github.com/gohugoio/hugo/common/hugo"
26 "github.com/gohugoio/hugo/common/loggers"
27 "github.com/gohugoio/hugo/config/security"
28 "github.com/gohugoio/hugo/resources"
29 "github.com/gohugoio/hugo/resources/internal"
30 "github.com/gohugoio/hugo/resources/resource"
31 "github.com/mitchellh/mapstructure"
32 )
33
34 var (
35 tailwindcssImportRe = regexp.MustCompile(`^tailwindcss/?`)
36 tailwindImportExclude = func(s string) bool {
37 return tailwindcssImportRe.MatchString(s) && !strings.Contains(s, ".")
38 }
39 )
40
41 // NewTailwindCSSClient creates a new TailwindCSSClient with the given specification.
42 func NewTailwindCSSClient(rs *resources.Spec) *TailwindCSSClient {
43 return &TailwindCSSClient{rs: rs}
44 }
45
46 // Client is the client used to do TailwindCSS transformations.
47 type TailwindCSSClient struct {
48 rs *resources.Spec
49 }
50
51 // Process transforms the given Resource with the TailwindCSS processor.
52 func (c *TailwindCSSClient) Process(res resources.ResourceTransformer, options map[string]any) (resource.Resource, error) {
53 return res.Transform(&tailwindcssTransformation{rs: c.rs, optionsm: options})
54 }
55
56 type tailwindcssTransformation struct {
57 optionsm map[string]any
58 rs *resources.Spec
59 }
60
61 func (t *tailwindcssTransformation) Key() internal.ResourceTransformationKey {
62 return internal.NewResourceTransformationKey("tailwindcss", t.optionsm)
63 }
64
65 type TailwindCSSOptions struct {
66 Minify bool // Optimize and minify the output
67 Optimize bool // Optimize the output without minifying
68 InlineImports `mapstructure:",squash"`
69 }
70
71 func (opts TailwindCSSOptions) toArgs() []any {
72 var args []any
73 if opts.Minify {
74 args = append(args, "--minify")
75 }
76 if opts.Optimize {
77 args = append(args, "--optimize")
78 }
79 return args
80 }
81
82 func (t *tailwindcssTransformation) Transform(ctx *resources.ResourceTransformationCtx) error {
83 const binaryName = "tailwindcss"
84
85 options, err := decodeTailwindCSSOptions(t.optionsm)
86 if err != nil {
87 return err
88 }
89
90 infol := t.rs.Logger.InfoCommand(binaryName)
91 infow := loggers.LevelLoggerToWriter(infol)
92
93 ex := t.rs.ExecHelper
94
95 workingDir := t.rs.Cfg.BaseConfig().WorkingDir
96
97 var cmdArgs []any = []any{
98 "--input=-", // Read from stdin.
99 "--cwd", workingDir,
100 }
101
102 cmdArgs = append(cmdArgs, options.toArgs()...)
103
104 var errBuf bytes.Buffer
105
106 stderr := io.MultiWriter(infow, &errBuf)
107 cmdArgs = append(cmdArgs, hexec.WithStderr(stderr))
108 cmdArgs = append(cmdArgs, hexec.WithStdout(ctx.To))
109 cmdArgs = append(cmdArgs, hexec.WithDir(workingDir))
110 cmdArgs = append(cmdArgs, hexec.WithEnviron(hugo.GetExecEnviron(workingDir, t.rs.Cfg, t.rs.BaseFs.Assets.Fs)))
111
112 cmd, err := ex.Npx(binaryName, cmdArgs...)
113 if err != nil {
114 if hexec.IsNotFound(err) {
115 // This may be on a CI server etc. Will fall back to pre-built assets.
116 return &herrors.FeatureNotAvailableError{Cause: err}
117 }
118
119 var accessDeniedErr *security.AccessDeniedError
120 if errors.As(err, &accessDeniedErr) {
121 if t.rs.Cfg.IgnoreTailwindCSSSecurityError() {
122 // This construct is here so the Hugo theme checker can build TailwindCSS sites with default security config without errors.
123 // Add some dummy CSS to the output so we can continue the build.
124 ctx.To.Write([]byte(".tailwindcss-security-error-ignored { display: none; }"))
125 return nil
126 }
127 }
128
129 return err
130 }
131
132 stdin, err := cmd.StdinPipe()
133 if err != nil {
134 return err
135 }
136
137 src := ctx.From
138
139 imp := newImportResolver(
140 ctx.Ctx,
141 ctx.From,
142 ctx.InPath,
143 options.InlineImports,
144 t.rs.Assets.Fs, t.rs.Logger, ctx.DependencyManager,
145 )
146
147 if !options.InlineImports.DisableInlineImports {
148 src, err = imp.resolve()
149 if err != nil {
150 return err
151 }
152 }
153
154 go func() {
155 defer stdin.Close()
156 io.Copy(stdin, src)
157 }()
158
159 err = cmd.Run()
160 if err != nil {
161 if hexec.IsNotFound(err) {
162 return &herrors.FeatureNotAvailableError{
163 Cause: err,
164 }
165 }
166 s := errBuf.String()
167 if options.InlineImports.DisableInlineImports && strings.Contains(s, "Can't resolve") {
168 s += "You may want to set the 'disableInlineImports' option to false to inline imports, see https://gohugo.io/functions/css/tailwindcss/#disableinlineimports"
169 }
170 return imp.toFileError(s)
171 }
172
173 return nil
174 }
175
176 func decodeTailwindCSSOptions(m map[string]any) (opts TailwindCSSOptions, err error) {
177 if m == nil {
178 return
179 }
180 err = mapstructure.WeakDecode(m, &opts)
181 return
182 }