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