diff options
author | Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com> | 2022-05-02 16:07:52 +0200 |
---|---|---|
committer | Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com> | 2022-05-06 19:43:22 +0200 |
commit | f2946da9e806c2bafbdd26707fe339db79bd980b (patch) | |
tree | b5609317a861ea5f399e094e1b9287ca71dc22d1 /resources | |
parent | 6eea32bd6bc8e7a7dd07a8cb6a8343ae2c74aba0 (diff) |
Improve error messages, esp. when the server is running
* Add file context to minifier errors when publishing
* Misc fixes (see issues)
* Allow custom server error template in layouts/server/error.html
To get to this, this commit also cleans up and simplifies the code surrounding errors and files. This also removes the usage of `github.com/pkg/errors`, mostly because of https://github.com/pkg/errors/issues/223 -- but also because most of this is now built-in to Go.
Fixes #9852
Fixes #9857
Fixes #9863
Diffstat (limited to 'resources')
20 files changed, 61 insertions, 80 deletions
diff --git a/resources/image.go b/resources/image.go index 253caf735..f431784b4 100644 --- a/resources/image.go +++ b/resources/image.go @@ -38,9 +38,6 @@ import ( "github.com/gohugoio/hugo/resources/resource" - "github.com/pkg/errors" - _errors "github.com/pkg/errors" - "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources/images" @@ -325,7 +322,7 @@ func (i *imageResource) doWithImageConfig(conf images.ImageConfig, f func(src im }) if err != nil { if i.root != nil && i.root.getFileInfo() != nil { - return nil, errors.Wrapf(err, "image %q", i.root.getFileInfo().Meta().Filename) + return nil, fmt.Errorf("image %q: %w", i.root.getFileInfo().Meta().Filename, err) } } return img, nil @@ -345,7 +342,7 @@ func (i *imageResource) decodeImageConfig(action, spec string) (images.ImageConf func (i *imageResource) DecodeImage() (image.Image, error) { f, err := i.ReadSeekCloser() if err != nil { - return nil, _errors.Wrap(err, "failed to open image for decode") + return nil, fmt.Errorf("failed to open image for decode: %w", err) } defer f.Close() img, _, err := image.Decode(f) diff --git a/resources/images/color.go b/resources/images/color.go index 0a0db9fe0..057a9fb71 100644 --- a/resources/images/color.go +++ b/resources/images/color.go @@ -15,10 +15,9 @@ package images import ( "encoding/hex" + "fmt" "image/color" "strings" - - "github.com/pkg/errors" ) // AddColorToPalette adds c as the first color in p if not already there. @@ -50,7 +49,7 @@ func hexStringToColor(s string) (color.Color, error) { s = strings.TrimPrefix(s, "#") if len(s) != 3 && len(s) != 6 { - return nil, errors.Errorf("invalid color code: %q", s) + return nil, fmt.Errorf("invalid color code: %q", s) } s = strings.ToLower(s) diff --git a/resources/images/config.go b/resources/images/config.go index d553bda0f..62b5c72d8 100644 --- a/resources/images/config.go +++ b/resources/images/config.go @@ -22,7 +22,7 @@ import ( "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/media" - "github.com/pkg/errors" + "errors" "github.com/bep/gowebp/libwebp/webpoptions" @@ -158,7 +158,7 @@ func DecodeConfig(m map[string]any) (ImagingConfig, error) { if i.Cfg.Anchor != "" && i.Cfg.Anchor != smartCropIdentifier { anchor, found := anchorPositions[i.Cfg.Anchor] if !found { - return i, errors.Errorf("invalid anchor value %q in imaging config", i.Anchor) + return i, fmt.Errorf("invalid anchor value %q in imaging config", i.Anchor) } i.Anchor = anchor } else { @@ -263,7 +263,7 @@ func DecodeImageConfig(action, config string, defaults ImagingConfig, sourceForm return c, errors.New("must provide Width or Height") } default: - return c, errors.Errorf("BUG: unknown action %q encountered while decoding image configuration", c.Action) + return c, fmt.Errorf("BUG: unknown action %q encountered while decoding image configuration", c.Action) } if c.FilterStr == "" { diff --git a/resources/images/image.go b/resources/images/image.go index e8cca7769..b12f03b4e 100644 --- a/resources/images/image.go +++ b/resources/images/image.go @@ -34,8 +34,9 @@ import ( "golang.org/x/image/bmp" "golang.org/x/image/tiff" + "errors" + "github.com/gohugoio/hugo/common/hugio" - "github.com/pkg/errors" ) func NewImage(f Format, proc *ImageProcessor, img image.Image, s Spec) *Image { @@ -163,7 +164,7 @@ func (i *Image) initConfig() error { }) if err != nil { - return errors.Wrap(err, "failed to load image config") + return fmt.Errorf("failed to load image config: %w", err) } return nil @@ -239,7 +240,7 @@ func (p *ImageProcessor) ApplyFiltersFromConfig(src image.Image, conf ImageConfi case "fit": filters = append(filters, gift.ResizeToFit(conf.Width, conf.Height, conf.Filter)) default: - return nil, errors.Errorf("unsupported action: %q", conf.Action) + return nil, fmt.Errorf("unsupported action: %q", conf.Action) } img, err := p.Filter(src, filters...) diff --git a/resources/page/page_generate/generate_page_wrappers.go b/resources/page/page_generate/generate_page_wrappers.go index 9d790cc01..f4b40f717 100644 --- a/resources/page/page_generate/generate_page_wrappers.go +++ b/resources/page/page_generate/generate_page_wrappers.go @@ -20,7 +20,7 @@ import ( "path/filepath" "reflect" - "github.com/pkg/errors" + "errors" "github.com/gohugoio/hugo/common/maps" @@ -55,15 +55,15 @@ var ( func Generate(c *codegen.Inspector) error { if err := generateMarshalJSON(c); err != nil { - return errors.Wrap(err, "failed to generate JSON marshaler") + return fmt.Errorf("failed to generate JSON marshaler: %w", err) } if err := generateDeprecatedWrappers(c); err != nil { - return errors.Wrap(err, "failed to generate deprecate wrappers") + return fmt.Errorf("failed to generate deprecate wrappers: %w", err) } if err := generateFileIsZeroWrappers(c); err != nil { - return errors.Wrap(err, "failed to generate file wrappers") + return fmt.Errorf("failed to generate file wrappers: %w", err) } return nil diff --git a/resources/page/page_matcher.go b/resources/page/page_matcher.go index 4626186c5..c302ff21a 100644 --- a/resources/page/page_matcher.go +++ b/resources/page/page_matcher.go @@ -14,13 +14,13 @@ package page import ( + "fmt" "path/filepath" "strings" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/hugofs/glob" "github.com/mitchellh/mapstructure" - "github.com/pkg/errors" ) // A PageMatcher can be used to match a Page with Glob patterns. @@ -132,7 +132,7 @@ func DecodePageMatcher(m any, v *PageMatcher) error { } } if !found { - return errors.Errorf("%q did not match a valid Page Kind", v.Kind) + return fmt.Errorf("%q did not match a valid Page Kind", v.Kind) } } diff --git a/resources/page/pages_related.go b/resources/page/pages_related.go index 83910e0d4..35bb2965a 100644 --- a/resources/page/pages_related.go +++ b/resources/page/pages_related.go @@ -14,11 +14,11 @@ package page import ( + "fmt" "sync" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/related" - "github.com/pkg/errors" "github.com/spf13/cast" ) @@ -108,7 +108,7 @@ func (p Pages) withInvertedIndex(search func(idx *related.InvertedIndex) ([]rela d, ok := p[0].(InternalDependencies) if !ok { - return nil, errors.Errorf("invalid type %T in related search", p[0]) + return nil, fmt.Errorf("invalid type %T in related search", p[0]) } cache := d.GetRelatedDocsHandler() diff --git a/resources/page/permalinks.go b/resources/page/permalinks.go index aa20da4ed..cd9c1dc15 100644 --- a/resources/page/permalinks.go +++ b/resources/page/permalinks.go @@ -23,7 +23,7 @@ import ( "strings" "time" - "github.com/pkg/errors" + "errors" "github.com/gohugoio/hugo/helpers" ) diff --git a/resources/resource.go b/resources/resource.go index 01f20f09d..ead483d65 100644 --- a/resources/resource.go +++ b/resources/resource.go @@ -31,7 +31,7 @@ import ( "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/source" - "github.com/pkg/errors" + "errors" "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/common/maps" @@ -633,7 +633,7 @@ func (fi *resourceFileInfo) hash() (string, error) { var f hugio.ReadSeekCloser f, err = fi.ReadSeekCloser() if err != nil { - err = errors.Wrap(err, "failed to open source file") + err = fmt.Errorf("failed to open source file: %w", err) return } defer f.Close() diff --git a/resources/resource_factories/create/remote.go b/resources/resource_factories/create/remote.go index 32dfafe5c..51199dc93 100644 --- a/resources/resource_factories/create/remote.go +++ b/resources/resource_factories/create/remote.go @@ -16,6 +16,7 @@ package create import ( "bufio" "bytes" + "fmt" "io" "io/ioutil" "mime" @@ -34,7 +35,6 @@ import ( "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" "github.com/mitchellh/mapstructure" - "github.com/pkg/errors" ) type HTTPError struct { @@ -77,7 +77,7 @@ func toHTTPError(err error, res *http.Response) *HTTPError { func (c *Client) FromRemote(uri string, optionsm map[string]any) (resource.Resource, error) { rURL, err := url.Parse(uri) if err != nil { - return nil, errors.Wrapf(err, "failed to parse URL for resource %s", uri) + return nil, fmt.Errorf("failed to parse URL for resource %s: %w", uri, err) } resourceID := calculateResourceID(uri, optionsm) @@ -85,7 +85,7 @@ func (c *Client) FromRemote(uri string, optionsm map[string]any) (resource.Resou _, httpResponse, err := c.cacheGetResource.GetOrCreate(resourceID, func() (io.ReadCloser, error) { options, err := decodeRemoteOptions(optionsm) if err != nil { - return nil, errors.Wrapf(err, "failed to decode options for resource %s", uri) + return nil, fmt.Errorf("failed to decode options for resource %s: %w", uri, err) } if err := c.validateFromRemoteArgs(uri, options); err != nil { return nil, err @@ -93,7 +93,7 @@ func (c *Client) FromRemote(uri string, optionsm map[string]any) (resource.Resou req, err := http.NewRequest(options.Method, uri, options.BodyReader()) if err != nil { - return nil, errors.Wrapf(err, "failed to create request for resource %s", uri) + return nil, fmt.Errorf("failed to create request for resource %s: %w", uri, err) } addDefaultHeaders(req) @@ -113,7 +113,7 @@ func (c *Client) FromRemote(uri string, optionsm map[string]any) (resource.Resou if res.StatusCode != http.StatusNotFound { if res.StatusCode < 200 || res.StatusCode > 299 { - return nil, toHTTPError(errors.Errorf("failed to fetch remote resource: %s", http.StatusText(res.StatusCode)), res) + return nil, toHTTPError(fmt.Errorf("failed to fetch remote resource: %s", http.StatusText(res.StatusCode)), res) } } @@ -137,7 +137,7 @@ func (c *Client) FromRemote(uri string, optionsm map[string]any) (resource.Resou body, err := ioutil.ReadAll(res.Body) if err != nil { - return nil, errors.Wrapf(err, "failed to read remote resource %q", uri) + return nil, fmt.Errorf("failed to read remote resource %q: %w", uri, err) } filename := path.Base(rURL.Path) @@ -172,7 +172,7 @@ func (c *Client) FromRemote(uri string, optionsm map[string]any) (resource.Resou // Now resolve the media type primarily using the content. mediaType := media.FromContent(c.rs.MediaTypes, extensionHints, body) if mediaType.IsZero() { - return nil, errors.Errorf("failed to resolve media type for remote resource %q", uri) + return nil, fmt.Errorf("failed to resolve media type for remote resource %q", uri) } resourceID = filename[:len(filename)-len(path.Ext(filename))] + "_" + resourceID + mediaType.FirstSuffix.FullSuffix diff --git a/resources/resource_metadata.go b/resources/resource_metadata.go index 6c979b4bf..8954a5109 100644 --- a/resources/resource_metadata.go +++ b/resources/resource_metadata.go @@ -22,7 +22,6 @@ import ( "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/resources/resource" - "github.com/pkg/errors" "github.com/spf13/cast" "github.com/gohugoio/hugo/common/maps" @@ -85,7 +84,7 @@ func AssignMetadata(metadata []map[string]any, resources ...resource.Resource) e glob, err := glob.GetGlob(srcKey) if err != nil { - return errors.Wrap(err, "failed to match resource with metadata") + return fmt.Errorf("failed to match resource with metadata: %w", err) } match := glob.Match(resourceSrcKey) diff --git a/resources/resource_transformers/babel/babel.go b/resources/resource_transformers/babel/babel.go index a4744961e..9a9110f62 100644 --- a/resources/resource_transformers/babel/babel.go +++ b/resources/resource_transformers/babel/babel.go @@ -15,6 +15,7 @@ package babel import ( "bytes" + "fmt" "io" "io/ioutil" "os" @@ -34,7 +35,6 @@ import ( "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" - "github.com/pkg/errors" ) // Options from https://babeljs.io/docs/en/options @@ -141,7 +141,7 @@ func (t *babelTransformation) Transform(ctx *resources.ResourceTransformationCtx configFile = t.rs.BaseFs.ResolveJSConfigFile(configFile) if configFile == "" && t.options.Config != "" { // Only fail if the user specified config file is not found. - return errors.Errorf("babel config %q not found:", configFile) + return fmt.Errorf("babel config %q not found:", configFile) } } @@ -203,7 +203,7 @@ func (t *babelTransformation) Transform(ctx *resources.ResourceTransformationCtx if hexec.IsNotFound(err) { return herrors.ErrFeatureNotAvailable } - return errors.Wrap(err, errBuf.String()) + return fmt.Errorf(errBuf.String()+": %w", err) } content, err := ioutil.ReadAll(compileOutput) diff --git a/resources/resource_transformers/integrity/integrity.go b/resources/resource_transformers/integrity/integrity.go index bbd0b6675..e15754685 100644 --- a/resources/resource_transformers/integrity/integrity.go +++ b/resources/resource_transformers/integrity/integrity.go @@ -19,14 +19,13 @@ import ( "crypto/sha512" "encoding/base64" "encoding/hex" + "fmt" "hash" "html/template" "io" "github.com/gohugoio/hugo/resources/internal" - "github.com/pkg/errors" - "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/resource" ) @@ -92,7 +91,7 @@ func newHash(algo string) (hash.Hash, error) { case "sha512": return sha512.New(), nil default: - return nil, errors.Errorf("unsupported crypto algo: %q, use either md5, sha256, sha384 or sha512", algo) + return nil, fmt.Errorf("unsupported crypto algo: %q, use either md5, sha256, sha384 or sha512", algo) } } diff --git a/resources/resource_transformers/js/build.go b/resources/resource_transformers/js/build.go index 3c6f24fc0..d2fbf5065 100644 --- a/resources/resource_transformers/js/build.go +++ b/resources/resource_transformers/js/build.go @@ -22,13 +22,14 @@ import ( "regexp" "strings" - "github.com/pkg/errors" + "errors" "github.com/spf13/afero" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/common/herrors" + "github.com/gohugoio/hugo/common/text" "github.com/gohugoio/hugo/hugolib/filesystems" "github.com/gohugoio/hugo/media" @@ -109,13 +110,13 @@ func (t *buildTransformation) Transform(ctx *resources.ResourceTransformationCtx for i, ext := range opts.Inject { impPath := filepath.FromSlash(ext) if filepath.IsAbs(impPath) { - return errors.Errorf("inject: absolute paths not supported, must be relative to /assets") + return fmt.Errorf("inject: absolute paths not supported, must be relative to /assets") } m := resolveComponentInAssets(t.c.rs.Assets.Fs, impPath) if m == nil { - return errors.Errorf("inject: file %q not found", ext) + return fmt.Errorf("inject: file %q not found", ext) } opts.Inject[i] = m.Filename @@ -157,10 +158,12 @@ func (t *buildTransformation) Transform(ctx *resources.ResourceTransformationCtx } if err == nil { - fe := herrors.NewFileError("js", 0, loc.Line, loc.Column, errors.New(msg.Text)) - err, _ := herrors.WithFileContext(fe, path, f, herrors.SimpleLineMatcher) + fe := herrors.NewFileError(path, errors.New(msg.Text)). + UpdatePosition(text.Position{Offset: -1, LineNumber: loc.Line, ColumnNumber: loc.Column}). + UpdateContent(f, herrors.SimpleLineMatcher) + f.Close() - return err + return fe } return fmt.Errorf("%s", msg.Text) diff --git a/resources/resource_transformers/js/options.go b/resources/resource_transformers/js/options.go index 675e40d43..a0d1b506f 100644 --- a/resources/resource_transformers/js/options.go +++ b/resources/resource_transformers/js/options.go @@ -21,7 +21,6 @@ import ( "strings" "github.com/gohugoio/hugo/common/maps" - "github.com/pkg/errors" "github.com/spf13/afero" "github.com/evanw/esbuild/pkg/api" @@ -251,7 +250,7 @@ func createBuildPlugins(c *Client, opts Options) ([]api.Plugin, error) { func(args api.OnLoadArgs) (api.OnLoadResult, error) { b, err := ioutil.ReadFile(args.Path) if err != nil { - return api.OnLoadResult{}, errors.Wrapf(err, "failed to read %q", args.Path) + return api.OnLoadResult{}, fmt.Errorf("failed to read %q: %w", args.Path, err) } c := string(b) return api.OnLoadResult{ @@ -274,7 +273,7 @@ func createBuildPlugins(c *Client, opts Options) ([]api.Plugin, error) { b, err := json.Marshal(params) if err != nil { - return nil, errors.Wrap(err, "failed to marshal params") + return nil, fmt.Errorf("failed to marshal params: %w", err) } bs := string(b) paramsPlugin := api.Plugin{ diff --git a/resources/resource_transformers/postcss/postcss.go b/resources/resource_transformers/postcss/postcss.go index 61209fb23..733c958cf 100644 --- a/resources/resource_transformers/postcss/postcss.go +++ b/resources/resource_transformers/postcss/postcss.go @@ -17,6 +17,7 @@ import ( "bytes" "crypto/sha256" "encoding/hex" + "fmt" "io" "io/ioutil" "path" @@ -36,8 +37,9 @@ import ( "github.com/spf13/afero" "github.com/spf13/cast" + "errors" + "github.com/gohugoio/hugo/hugofs" - "github.com/pkg/errors" "github.com/mitchellh/mapstructure" @@ -161,7 +163,7 @@ func (t *postcssTransformation) Transform(ctx *resources.ResourceTransformationC configFile = t.rs.BaseFs.ResolveJSConfigFile(configFile) if configFile == "" && t.options.Config != "" { // Only fail if the user specified config file is not found. - return errors.Errorf("postcss config %q not found:", configFile) + return fmt.Errorf("postcss config %q not found:", configFile) } } @@ -388,15 +390,9 @@ func (imp *importResolver) toFileError(output string) error { if err != nil { return inErr } - realFilename := fi.(hugofs.FileMetaInfo).Meta().Filename - - ferr := herrors.NewFileError("css", -1, file.Offset+1, 1, inErr) - werr, ok := herrors.WithFileContextForFile(ferr, realFilename, file.Filename, imp.fs, herrors.SimpleLineMatcher) + realFilename := fi.(hugofs.FileMetaInfo).Meta().Filename - if !ok { - return ferr - } + return herrors.NewFileErrorFromFile(inErr, file.Filename, realFilename, hugofs.Os, herrors.SimpleLineMatcher) - return werr } diff --git a/resources/resource_transformers/templates/execute_as_template.go b/resources/resource_transformers/templates/execute_as_template.go index 5c2033ff9..5fe4230f1 100644 --- a/resources/resource_transformers/templates/execute_as_template.go +++ b/resources/resource_transformers/templates/execute_as_template.go @@ -15,12 +15,13 @@ package templates import ( + "fmt" + "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/resources" "github.com/gohugoio/hugo/resources/internal" "github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/tpl" - "github.com/pkg/errors" ) // Client contains methods to perform template processing of Resource objects. @@ -55,7 +56,7 @@ func (t *executeAsTemplateTransform) Transform(ctx *resources.ResourceTransforma tplStr := helpers.ReaderToString(ctx.From) templ, err := t.t.TextTmpl().Parse(ctx.InPath, tplStr) if err != nil { - return errors.Wrapf(err, "failed to parse Resource %q as Template:", ctx.InPath) + return fmt.Errorf("failed to parse Resource %q as Template:: %w", ctx.InPath, err) } ctx.OutPath = t.targetPath diff --git a/resources/resource_transformers/tocss/dartsass/transform.go b/resources/resource_transformers/tocss/dartsass/transform.go index 79c32fcfd..082e30710 100644 --- a/resources/resource_transformers/tocss/dartsass/transform.go +++ b/resources/resource_transformers/tocss/dartsass/transform.go @@ -120,18 +120,8 @@ func (t *transform) Transform(ctx *resources.ResourceTransformationCtx) error { return m.Offset+len(m.Line) >= start.Offset && strings.Contains(m.Line, context) } - ferr, ok := herrors.WithFileContextForFile( - herrors.NewFileError("scss", -1, -1, start.Column, sassErr), - filename, - filename, - hugofs.Os, - offsetMatcher) - - if !ok { - return sassErr - } + return herrors.NewFileErrorFromFile(sassErr, filename, filename, hugofs.Os, offsetMatcher) - return ferr } return err } diff --git a/resources/resource_transformers/tocss/scss/tocss.go b/resources/resource_transformers/tocss/scss/tocss.go index 802798e59..f9f4786f5 100644 --- a/resources/resource_transformers/tocss/scss/tocss.go +++ b/resources/resource_transformers/tocss/scss/tocss.go @@ -28,7 +28,6 @@ import ( "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/media" "github.com/gohugoio/hugo/resources" - "github.com/pkg/errors" ) // Used in tests. This feature requires Hugo to be built with the extended tag. @@ -172,7 +171,7 @@ func (c *Client) toCSS(options libsass.Options, dst io.Writer, src io.Reader) (l in := helpers.ReaderToString(src) // See https://github.com/gohugoio/hugo/issues/7059 - // We need to preserver the regular CSS imports. This is by far + // We need to preserve the regular CSS imports. This is by far // a perfect solution, and only works for the main entry file, but // that should cover many use cases, e.g. using SCSS as a preprocessor // for Tailwind. @@ -181,7 +180,7 @@ func (c *Client) toCSS(options libsass.Options, dst io.Writer, src io.Reader) (l res, err = transpiler.Execute(in) if err != nil { - return res, errors.Wrap(err, "SCSS processing failed") + return res, fmt.Errorf("SCSS processing failed: %w", err) } out := res.CSS diff --git a/resources/transform.go b/resources/transform.go index e269b7b10..a470c94da 100644 --- a/resources/transform.go +++ b/ |