summaryrefslogtreecommitdiffstats
path: root/resources/resource_transformers/cssjs/tailwindcss.go
blob: a60a16222ac7918860c0010b22116bcb00e23edd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
// Copyright 2024 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cssjs

import (
	"bytes"
	"io"
	"regexp"
	"strings"

	"github.com/gohugoio/hugo/common/herrors"
	"github.com/gohugoio/hugo/common/hexec"
	"github.com/gohugoio/hugo/common/hugo"
	"github.com/gohugoio/hugo/common/loggers"
	"github.com/gohugoio/hugo/resources"
	"github.com/gohugoio/hugo/resources/internal"
	"github.com/gohugoio/hugo/resources/resource"
	"github.com/mitchellh/mapstructure"
)

var (
	tailwindcssImportRe   = regexp.MustCompile(`^tailwindcss/?`)
	tailwindImportExclude = func(s string) bool {
		return tailwindcssImportRe.MatchString(s) && !strings.Contains(s, ".")
	}
)

// NewTailwindCSSClient creates a new TailwindCSSClient with the given specification.
func NewTailwindCSSClient(rs *resources.Spec) *TailwindCSSClient {
	return &TailwindCSSClient{rs: rs}
}

// Client is the client used to do TailwindCSS transformations.
type TailwindCSSClient struct {
	rs *resources.Spec
}

// Process transforms the given Resource with the TailwindCSS processor.
func (c *TailwindCSSClient) Process(res resources.ResourceTransformer, options map[string]any) (resource.Resource, error) {
	return res.Transform(&tailwindcssTransformation{rs: c.rs, optionsm: options})
}

type tailwindcssTransformation struct {
	optionsm map[string]any
	rs       *resources.Spec
}

func (t *tailwindcssTransformation) Key() internal.ResourceTransformationKey {
	return internal.NewResourceTransformationKey("tailwindcss", t.optionsm)
}

type TailwindCSSOptions struct {
	Minify        bool // Optimize and minify the output
	Optimize      bool //  Optimize the output without minifying
	InlineImports `mapstructure:",squash"`
}

func (opts TailwindCSSOptions) toArgs() []any {
	var args []any
	if opts.Minify {
		args = append(args, "--minify")
	}
	if opts.Optimize {
		args = append(args, "--optimize")
	}
	return args
}

func (t *tailwindcssTransformation) Transform(ctx *resources.ResourceTransformationCtx) error {
	const binaryName = "tailwindcss"

	options, err := decodeTailwindCSSOptions(t.optionsm)
	if err != nil {
		return err
	}

	infol := t.rs.Logger.InfoCommand(binaryName)
	infow := loggers.LevelLoggerToWriter(infol)

	ex := t.rs.ExecHelper

	workingDir := t.rs.Cfg.BaseConfig().WorkingDir

	var cmdArgs []any = []any{
		"--input=-", // Read from stdin.
		"--cwd", workingDir,
	}

	cmdArgs = append(cmdArgs, options.toArgs()...)

	var errBuf bytes.Buffer

	stderr := io.MultiWriter(infow, &errBuf)
	cmdArgs = append(cmdArgs, hexec.WithStderr(stderr))
	cmdArgs = append(cmdArgs, hexec.WithStdout(ctx.To))
	cmdArgs = append(cmdArgs, hexec.WithEnviron(hugo.GetExecEnviron(workingDir, t.rs.Cfg, t.rs.BaseFs.Assets.Fs)))

	cmd, err := ex.Npx(binaryName, cmdArgs...)
	if err != nil {
		if hexec.IsNotFound(err) {
			// This may be on a CI server etc. Will fall back to pre-built assets.
			return &herrors.FeatureNotAvailableError{Cause: err}
		}
		return err
	}

	stdin, err := cmd.StdinPipe()
	if err != nil {
		return err
	}

	src := ctx.From

	imp := newImportResolver(
		ctx.From,
		ctx.InPath,
		options.InlineImports,
		t.rs.Assets.Fs, t.rs.Logger, ctx.DependencyManager,
	)

	if !options.InlineImports.DisableInlineImports {
		src, err = imp.resolve()
		if err != nil {
			return err
		}
	}

	go func() {
		defer stdin.Close()
		io.Copy(stdin, src)
	}()

	err = cmd.Run()
	if err != nil {
		if hexec.IsNotFound(err) {
			return &herrors.FeatureNotAvailableError{
				Cause: err,
			}
		}
		s := errBuf.String()
		if options.InlineImports.DisableInlineImports && strings.Contains(s, "Can't resolve") {
			s += "You may want to set the 'disableInlineImports' option to false to inline imports, see https://gohugo.io/functions/css/tailwindcss/#disableinlineimports"
		}
		return imp.toFileError(s)
	}

	return nil
}

func decodeTailwindCSSOptions(m map[string]any) (opts TailwindCSSOptions, err error) {
	if m == nil {
		return
	}
	err = mapstructure.WeakDecode(m, &opts)
	return
}