github.com/neohugo/neohugo@v0.123.8/resources/resource_transformers/tocss/dartsass/client.go (about)

     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 Dass Sass Embedded protocol to transpile
    15  // SCSS/SASS.
    16  package dartsass
    17  
    18  import (
    19  	"fmt"
    20  	"io"
    21  	"strings"
    22  
    23  	godartsassv1 "github.com/bep/godartsass"
    24  	"github.com/bep/godartsass/v2"
    25  	"github.com/bep/logg"
    26  	"github.com/neohugo/neohugo/common/herrors"
    27  	"github.com/neohugo/neohugo/common/neohugo"
    28  	"github.com/neohugo/neohugo/common/paths"
    29  	"github.com/neohugo/neohugo/helpers"
    30  	"github.com/neohugo/neohugo/hugofs"
    31  	"github.com/neohugo/neohugo/hugolib/filesystems"
    32  	"github.com/neohugo/neohugo/resources"
    33  	"github.com/neohugo/neohugo/resources/resource"
    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{dartSassNotAvailable: true}, nil
    49  	}
    50  
    51  	if neohugo.DartSassBinaryName == "" {
    52  		return nil, fmt.Errorf("no Dart Sass binary found in $PATH")
    53  	}
    54  
    55  	if err := rs.ExecHelper.Sec().CheckAllowedExec(neohugo.DartSassBinaryName); err != nil {
    56  		return nil, err
    57  	}
    58  
    59  	var (
    60  		transpiler   *godartsass.Transpiler
    61  		transpilerv1 *godartsassv1.Transpiler
    62  		err          error
    63  		infol        = rs.Logger.InfoCommand("Dart Sass")
    64  		warnl        = rs.Logger.WarnCommand("Dart Sass")
    65  	)
    66  
    67  	if neohugo.IsDartSassV2() {
    68  		transpiler, err = godartsass.Start(godartsass.Options{
    69  			DartSassEmbeddedFilename: neohugo.DartSassBinaryName,
    70  			LogEventHandler: func(event godartsass.LogEvent) {
    71  				message := strings.ReplaceAll(event.Message, dartSassStdinPrefix, "")
    72  				switch event.Type {
    73  				case godartsass.LogEventTypeDebug:
    74  					// Log as Info for now, we may adjust this if it gets too chatty.
    75  					infol.Log(logg.String(message))
    76  				default:
    77  					// The rest are either deprecations or @warn statements.
    78  					warnl.Log(logg.String(message))
    79  				}
    80  			},
    81  		})
    82  	} else {
    83  		transpilerv1, err = godartsassv1.Start(godartsassv1.Options{
    84  			DartSassEmbeddedFilename: neohugo.DartSassBinaryName,
    85  			LogEventHandler: func(event godartsassv1.LogEvent) {
    86  				message := strings.ReplaceAll(event.Message, dartSassStdinPrefix, "")
    87  				switch event.Type {
    88  				case godartsassv1.LogEventTypeDebug:
    89  					// Log as Info for now, we may adjust this if it gets too chatty.
    90  					infol.Log(logg.String(message))
    91  				default:
    92  					// The rest are either deprecations or @warn statements.
    93  					warnl.Log(logg.String(message))
    94  				}
    95  			},
    96  		})
    97  	}
    98  
    99  	if err != nil {
   100  		return nil, err
   101  	}
   102  	return &Client{sfs: fs, workFs: rs.BaseFs.Work, rs: rs, transpiler: transpiler, transpilerV1: transpilerv1}, nil
   103  }
   104  
   105  type Client struct {
   106  	dartSassNotAvailable bool
   107  	rs                   *resources.Spec
   108  	sfs                  *filesystems.SourceFilesystem
   109  	workFs               afero.Fs
   110  
   111  	// One of these are non-nil.
   112  	transpiler   *godartsass.Transpiler
   113  	transpilerV1 *godartsassv1.Transpiler
   114  }
   115  
   116  func (c *Client) ToCSS(res resources.ResourceTransformer, args map[string]any) (resource.Resource, error) {
   117  	if c.dartSassNotAvailable {
   118  		return res.Transform(resources.NewFeatureNotAvailableTransformer(transformationName, args))
   119  	}
   120  	return res.Transform(&transform{c: c, optsm: args})
   121  }
   122  
   123  func (c *Client) Close() error {
   124  	if c.transpilerV1 != nil {
   125  		return c.transpilerV1.Close()
   126  	}
   127  	if c.transpiler != nil {
   128  		return c.transpiler.Close()
   129  	}
   130  	return nil
   131  }
   132  
   133  func (c *Client) toCSS(args godartsass.Args, src io.Reader) (godartsass.Result, error) {
   134  	in := helpers.ReaderToString(src)
   135  
   136  	args.Source = in
   137  
   138  	var (
   139  		err error
   140  		res godartsass.Result
   141  	)
   142  
   143  	if c.transpilerV1 != nil {
   144  		var resv1 godartsassv1.Result
   145  		var argsv1 godartsassv1.Args
   146  		mapstructure.Decode(args, &argsv1) // nolint
   147  		if args.ImportResolver != nil {
   148  			argsv1.ImportResolver = importResolverV1{args.ImportResolver}
   149  		}
   150  		resv1, err = c.transpilerV1.Execute(argsv1)
   151  		if err == nil {
   152  			mapstructure.Decode(resv1, &res) // nolint
   153  		}
   154  	} else {
   155  		res, err = c.transpiler.Execute(args)
   156  	}
   157  
   158  	if err != nil {
   159  		if err.Error() == "unexpected EOF" {
   160  			//lint:ignore ST1005 end user message.
   161  			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.", neohugo.DartSassBinaryName)
   162  		}
   163  		return res, herrors.NewFileErrorFromFileInErr(err, hugofs.Os, herrors.OffsetMatcher)
   164  	}
   165  
   166  	return res, err
   167  }
   168  
   169  type Options struct {
   170  	// Hugo, will by default, just replace the extension of the source
   171  	// to .css, e.g. "scss/main.scss" becomes "scss/main.css". You can
   172  	// control this by setting this, e.g. "styles/main.css" will create
   173  	// a Resource with that as a base for RelPermalink etc.
   174  	TargetPath string
   175  
   176  	// Hugo automatically adds the entry directories (where the main.scss lives)
   177  	// for project and themes to the list of include paths sent to LibSASS.
   178  	// Any paths set in this setting will be appended. Note that these will be
   179  	// treated as relative to the working dir, i.e. no include paths outside the
   180  	// project/themes.
   181  	IncludePaths []string
   182  
   183  	// Default is nested.
   184  	// One of nested, expanded, compact, compressed.
   185  	OutputStyle string
   186  
   187  	// When enabled, Hugo will generate a source map.
   188  	EnableSourceMap bool
   189  
   190  	// If enabled, sources will be embedded in the generated source map.
   191  	SourceMapIncludeSources bool
   192  
   193  	// Vars will be available in 'hugo:vars', e.g:
   194  	//     @use "hugo:vars";
   195  	//     $color: vars.$color;
   196  	Vars map[string]any
   197  }
   198  
   199  func decodeOptions(m map[string]any) (opts Options, err error) {
   200  	if m == nil {
   201  		return
   202  	}
   203  	err = mapstructure.WeakDecode(m, &opts)
   204  
   205  	if opts.TargetPath != "" {
   206  		opts.TargetPath = paths.ToSlashTrimLeading(opts.TargetPath)
   207  	}
   208  
   209  	return
   210  }