{{ .Version }}
- Reload Page -diff --git a/cache/filecache/filecache_config.go b/cache/filecache/filecache_config.go index 816c6b8a6..a82133ab7 100644 --- a/cache/filecache/filecache_config.go +++ b/cache/filecache/filecache_config.go @@ -14,6 +14,7 @@ package filecache import ( + "fmt" "path" "path/filepath" "strings" @@ -25,8 +26,9 @@ import ( "github.com/gohugoio/hugo/helpers" + "errors" + "github.com/mitchellh/mapstructure" - "github.com/pkg/errors" "github.com/spf13/afero" ) @@ -153,7 +155,7 @@ func DecodeConfig(fs afero.Fs, cfg config.Provider) (Configs, error) { } if err := decoder.Decode(v); err != nil { - return nil, errors.Wrap(err, "failed to decode filecache config") + return nil, fmt.Errorf("failed to decode filecache config: %w", err) } if cc.Dir == "" { @@ -162,7 +164,7 @@ func DecodeConfig(fs afero.Fs, cfg config.Provider) (Configs, error) { name := strings.ToLower(k) if !valid[name] { - return nil, errors.Errorf("%q is not a valid cache name", name) + return nil, fmt.Errorf("%q is not a valid cache name", name) } c[name] = cc @@ -197,12 +199,12 @@ func DecodeConfig(fs afero.Fs, cfg config.Provider) (Configs, error) { if !v.isResourceDir { if isOsFs && !filepath.IsAbs(v.Dir) { - return c, errors.Errorf("%q must resolve to an absolute directory", v.Dir) + return c, fmt.Errorf("%q must resolve to an absolute directory", v.Dir) } // Avoid cache in root, e.g. / (Unix) or c:\ (Windows) if len(strings.TrimPrefix(v.Dir, filepath.VolumeName(v.Dir))) == 1 { - return c, errors.Errorf("%q is a root folder and not allowed as cache dir", v.Dir) + return c, fmt.Errorf("%q is a root folder and not allowed as cache dir", v.Dir) } } @@ -242,5 +244,5 @@ func resolveDirPlaceholder(fs afero.Fs, cfg config.Provider, placeholder string) return filepath.Base(workingDir), false, nil } - return "", false, errors.Errorf("%q is not a valid placeholder (valid values are :cacheDir or :resourceDir)", placeholder) + return "", false, fmt.Errorf("%q is not a valid placeholder (valid values are :cacheDir or :resourceDir)", placeholder) } diff --git a/cache/filecache/filecache_pruner.go b/cache/filecache/filecache_pruner.go index db1875701..e5e571972 100644 --- a/cache/filecache/filecache_pruner.go +++ b/cache/filecache/filecache_pruner.go @@ -14,12 +14,12 @@ package filecache import ( + "fmt" "io" "os" "github.com/gohugoio/hugo/hugofs" - "github.com/pkg/errors" "github.com/spf13/afero" ) @@ -39,7 +39,7 @@ func (c Caches) Prune() (int, error) { if os.IsNotExist(err) { continue } - return counter, errors.Wrapf(err, "failed to prune cache %q", k) + return counter, fmt.Errorf("failed to prune cache %q: %w", k, err) } } diff --git a/commands/commandeer.go b/commands/commandeer.go index c42de5d11..5b192c172 100644 --- a/commands/commandeer.go +++ b/commands/commandeer.go @@ -14,7 +14,6 @@ package commands import ( - "bytes" "errors" "io/ioutil" "net" @@ -141,19 +140,11 @@ func (c *commandeer) getErrorWithContext() any { m := make(map[string]any) - m["Error"] = errors.New(removeErrorPrefixFromLog(c.logger.Errors())) + //xwm["Error"] = errors.New(cleanErrorLog(removeErrorPrefixFromLog(c.logger.Errors()))) + m["Error"] = errors.New(cleanErrorLog(removeErrorPrefixFromLog(c.logger.Errors()))) m["Version"] = hugo.BuildVersionString() - - fe := herrors.UnwrapErrorWithFileContext(c.buildErr) - if fe != nil { - m["File"] = fe - } - - if c.h.verbose { - var b bytes.Buffer - herrors.FprintStackTraceFromErr(&b, c.buildErr) - m["StackTrace"] = b.String() - } + ferrors := herrors.UnwrapFileErrorsWithErrorContext(c.buildErr) + m["Files"] = ferrors return m } diff --git a/commands/convert.go b/commands/convert.go index d3cad2bd6..1ec965a0b 100644 --- a/commands/convert.go +++ b/commands/convert.go @@ -31,8 +31,6 @@ import ( "github.com/gohugoio/hugo/parser" "github.com/gohugoio/hugo/parser/metadecoders" - "github.com/pkg/errors" - "github.com/gohugoio/hugo/hugolib" "github.com/spf13/cobra" @@ -193,7 +191,7 @@ func (cc *convertCmd) convertAndSavePage(p page.Page, site *hugolib.Site, target fs := hugofs.Os if err := helpers.WriteToDisk(newFilename, &newContent, fs); err != nil { - return errors.Wrapf(err, "Failed to save file %q:", newFilename) + return fmt.Errorf("Failed to save file %q:: %w", newFilename, err) } return nil diff --git a/commands/hugo.go b/commands/hugo.go index 9033fac90..6bd0605db 100644 --- a/commands/hugo.go +++ b/commands/hugo.go @@ -39,9 +39,6 @@ import ( "github.com/gohugoio/hugo/resources/page" - "github.com/pkg/errors" - - "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/common/loggers" "github.com/gohugoio/hugo/common/terminal" @@ -300,14 +297,14 @@ func (c *commandeer) fullBuild(noBuildLock bool) error { copyStaticFunc := func() error { cnt, err := c.copyStatic() if err != nil { - return errors.Wrap(err, "Error copying static files") + return fmt.Errorf("Error copying static files: %w", err) } langCount = cnt return nil } buildSitesFunc := func() error { if err := c.buildSites(noBuildLock); err != nil { - return errors.Wrap(err, "Error building site") + return fmt.Errorf("Error building site: %w", err) } return nil } @@ -354,10 +351,10 @@ func (c *commandeer) initCPUProfile() (func(), error) { f, err := os.Create(c.h.cpuprofile) if err != nil { - return nil, errors.Wrap(err, "failed to create CPU profile") + return nil, fmt.Errorf("failed to create CPU profile: %w", err) } if err := pprof.StartCPUProfile(f); err != nil { - return nil, errors.Wrap(err, "failed to start CPU profile") + return nil, fmt.Errorf("failed to start CPU profile: %w", err) } return func() { pprof.StopCPUProfile() @@ -388,11 +385,11 @@ func (c *commandeer) initTraceProfile() (func(), error) { f, err := os.Create(c.h.traceprofile) if err != nil { - return nil, errors.Wrap(err, "failed to create trace file") + return nil, fmt.Errorf("failed to create trace file: %w", err) } if err := trace.Start(f); err != nil { - return nil, errors.Wrap(err, "failed to start trace") + return nil, fmt.Errorf("failed to start trace: %w", err) } return func() { @@ -735,9 +732,7 @@ func (c *commandeer) handleBuildErr(err error, msg string) { c.logger.Errorln(msg + ":\n") c.logger.Errorln(helpers.FirstUpper(err.Error())) - if !c.h.quiet && c.h.verbose { - herrors.PrintStackTraceFromErr(err) - } + } func (c *commandeer) rebuildSites(events []fsnotify.Event) error { diff --git a/commands/new_site.go b/commands/new_site.go index e49a60202..384c6365b 100644 --- a/commands/new_site.go +++ b/commands/new_site.go @@ -16,14 +16,13 @@ package commands import ( "bytes" "errors" + "fmt" "path/filepath" "strings" "github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/parser/metadecoders" - _errors "github.com/pkg/errors" - "github.com/gohugoio/hugo/create" "github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/hugofs" @@ -94,7 +93,7 @@ func (n *newSiteCmd) doNewSite(fs *hugofs.Fs, basepath string, force bool) error for _, dir := range dirs { if err := fs.Source.MkdirAll(dir, 0777); err != nil { - return _errors.Wrap(err, "Failed to create dir") + return fmt.Errorf("Failed to create dir: %w", err) } } diff --git a/commands/server.go b/commands/server.go index 145a889bb..985775336 100644 --- a/commands/server.go +++ b/commands/server.go @@ -36,8 +36,6 @@ import ( "github.com/gohugoio/hugo/common/paths" "golang.org/x/sync/errgroup" - "github.com/pkg/errors" - "github.com/gohugoio/hugo/livereload" "github.com/gohugoio/hugo/config" @@ -366,7 +364,7 @@ func (f *fileServer) createEndpoint(i int) (*http.ServeMux, net.Listener, string // We're only interested in the path u, err := url.Parse(baseURL) if err != nil { - return nil, nil, "", "", errors.Wrap(err, "Invalid baseURL") + return nil, nil, "", "", fmt.Errorf("Invalid baseURL: %w", err) } decorate := func(h http.Handler) http.Handler { @@ -480,6 +478,21 @@ var logErrorRe = regexp.MustCompile(`(?s)ERROR \d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{ func removeErrorPrefixFromLog(content string) string { return logErrorRe.ReplaceAllLiteralString(content, "") } +func cleanErrorLog(content string) string { + content = strings.ReplaceAll(content, "Rebuild failed:\n", "") + content = strings.ReplaceAll(content, "\n", "") + seen := make(map[string]bool) + parts := strings.Split(content, ": ") + keep := make([]string, 0, len(parts)) + for _, part := range parts { + if seen[part] { + continue + } + seen[part] = true + keep = append(keep, part) + } + return strings.Join(keep, ": ") +} func (c *commandeer) serve(s *serverCmd) error { isMultiHost := c.hugo().IsMultihost() @@ -500,17 +513,16 @@ func (c *commandeer) serve(s *serverCmd) error { roots = []string{""} } - templ, err := c.hugo().TextTmpl().Parse("__default_server_error", buildErrorTemplate) - if err != nil { - return err - } - srv := &fileServer{ baseURLs: baseURLs, roots: roots, c: c, s: s, errorTemplate: func(ctx any) (io.Reader, error) { + templ, found := c.hugo().Tmpl().Lookup("server/error.html") + if !found { + panic("template server/error.html not found") + } b := &bytes.Buffer{} err := c.hugo().Tmpl().Execute(templ, b, ctx) return b, err @@ -627,7 +639,7 @@ func (sc *serverCmd) fixURL(cfg config.Provider, s string, port int) (string, er if strings.Contains(u.Host, ":") { u.Host, _, err = net.SplitHostPort(u.Host) if err != nil { - return "", errors.Wrap(err, "Failed to split baseURL hostpost") + return "", fmt.Errorf("Failed to split baseURL hostpost: %w", err) } } u.Host += fmt.Sprintf(":%d", port) diff --git a/commands/server_errors.go b/commands/server_errors.go index 0e3bc50de..edf658156 100644 --- a/commands/server_errors.go +++ b/commands/server_errors.go @@ -22,67 +22,6 @@ import ( "github.com/gohugoio/hugo/transform/livereloadinject" ) -var buildErrorTemplate = ` - -
- -{{ .Version }}
- Reload Page -(.*)
\n\z` innerCleanupExpand = "$1" + pageFileErrorName = "page.md" ) func renderShortcode( @@ -297,9 +299,10 @@ func renderShortcode( var err error tmpl, err = s.TextTmpl().Parse(templName, templStr) if err != nil { - fe := herrors.ToFileError("html", err) - l1, l2 := p.posOffset(sc.pos).LineNumber, fe.Position().LineNumber - fe = herrors.ToFileErrorWithLineNumber(fe, l1+l2-1) + fe := herrors.NewFileError(pageFileErrorName, err) + pos := fe.Position() + pos.LineNumber += p.posOffset(sc.pos).LineNumber + fe = fe.UpdatePosition(pos) return "", false, p.wrapError(fe) } @@ -308,7 +311,7 @@ func renderShortcode( var found bool tmpl, found = s.TextTmpl().Lookup(templName) if !found { - return "", false, errors.Errorf("no earlier definition of shortcode %q found", sc.name) + return "", false, fmt.Errorf("no earlier definition of shortcode %q found", sc.name) } } } else { @@ -389,9 +392,10 @@ func renderShortcode( result, err := renderShortcodeWithPage(s.Tmpl(), tmpl, data) if err != nil && sc.isInline { - fe := herrors.ToFileError("html", err) - l1, l2 := p.posFromPage(sc.pos).LineNumber, fe.Position().LineNumber - fe = herrors.ToFileErrorWithLineNumber(fe, l1+l2-1) + fe := herrors.NewFileError("shortcode.md", err) + pos := fe.Position() + pos.LineNumber += p.posOffset(sc.pos).LineNumber + fe = fe.UpdatePosition(pos) return "", false, fe } @@ -415,7 +419,7 @@ func (s *shortcodeHandler) renderShortcodesForPage(p *pageState, f output.Format for _, v := range s.shortcodes { s, more, err := renderShortcode(0, s.s, tplVariants, v, nil, p) if err != nil { - err = p.parseError(errors.Wrapf(err, "failed to render shortcode %q", v.name), p.source.parsed.Input(), v.pos) + err = p.parseError(fmt.Errorf("failed to render shortcode %q: %w", v.name, err), p.source.parsed.Input(), v.pos) return nil, false, err } hasVariants = hasVariants || more @@ -447,9 +451,10 @@ func (s *shortcodeHandler) extractShortcode(ordinal, level int, pt *pageparser.I cnt := 0 nestedOrdinal := 0 nextLevel := level + 1 + const errorPrefix = "failed to extract shortcode" fail := func(err error, i pageparser.Item) error { - return s.parseError(err, pt.Input(), i.Pos) + return s.parseError(fmt.Errorf("%s: %w", errorPrefix, err), pt.Input(), i.Pos) } Loop: @@ -508,7 +513,7 @@ Loop: // return that error, more specific continue } - return sc, fail(errors.Errorf("shortcode %q has no .Inner, yet a closing tag was provided", next.Val), next) + return sc, fail(fmt.Errorf("shortcode %q has no .Inner, yet a closing tag was provided", next.Val), next) } } if next.IsRightShortcodeDelim() { @@ -538,7 +543,7 @@ Loop: // Used to check if the template expects inner content. templs := s.s.Tmpl().LookupVariants(sc.name) if templs == nil { - return nil, errors.Errorf("template for shortcode %q not found", sc.name) + return nil, fmt.Errorf("%s: template for shortcode %q not found", errorPrefix, sc.name) } sc.info = templs[0].(tpl.Info) @@ -639,7 +644,7 @@ func renderShortcodeWithPage(h tpl.TemplateHandler, tmpl tpl.Template, data *Sho err := h.Execute(tmpl, buffer, data) if err != nil { - return "", errors.Wrap(err, "failed to process shortcode") + return "", fmt.Errorf("failed to process shortcode: %w", err) } return buffer.String(), nil } diff --git a/hugolib/shortcode_test.go b/hugolib/shortcode_test.go index c2c5abe87..d1a844423 100644 --- a/hugolib/shortcode_test.go +++ b/hugolib/shortcode_test.go @@ -1340,7 +1340,7 @@ func TestShortcodeNoInner(t *testing.T) { b := newTestSitesBuilder(t) - b.WithContent("page.md", `--- + b.WithContent("mypage.md", `--- title: "No Inner!" --- {{< noinner >}}{{< /noinner >}} @@ -1350,7 +1350,7 @@ title: "No Inner!" "layouts/shortcodes/noinner.html", `No inner here.`) err := b.BuildE(BuildCfg{}) - b.Assert(err.Error(), qt.Contains, `failed to extract shortcode: shortcode "noinner" has no .Inner, yet a closing tag was provided`) + b.Assert(err.Error(), qt.Contains, filepath.FromSlash(`"content/mypage.md:4:21": failed to extract shortcode: shortcode "noinner" has no .Inner, yet a closing tag was provided`)) } func TestShortcodeStableOutputFormatTemplates(t *testing.T) { diff --git a/hugolib/site.go b/hugolib/site.go index bbabf91a3..cf7f0ff82 100644 --- a/hugolib/site.go +++ b/hugolib/site.go @@ -59,8 +59,6 @@ import ( "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/publisher" - "github.com/pkg/errors" - _errors "github.com/pkg/errors" "github.com/gohugoio/hugo/langs" @@ -508,7 +506,7 @@ But this also means that your site configuration may not do what you expect. If if cfg.Language.IsSet("related") { relatedContentConfig, err = related.DecodeConfig(cfg.Language.GetParams("related")) if err != nil { - return nil, errors.Wrap(err, "failed to decode related config") + return nil, fmt.Errorf("failed to decode related config: %w", err) } } else { relatedContentConfig = related.DefaultConfig @@ -546,7 +544,7 @@ But this also means that your site configuration may not do what you expect. If var err error cascade, err := page.DecodeCascade(cfg.Language.Get("cascade")) if err != nil { - return nil, errors.Errorf("failed to decode cascade config: %s", err) + return nil, fmt.Errorf("failed to decode cascade config: %s", err) } siteBucket = &pagesMapBucket{ @@ -1211,11 +1209,11 @@ func (s *Site) processPartial(config *BuildCfg, init func(config *BuildCfg) erro func (s *Site) process(config BuildCfg) (err error) { if err = s.initialize(); err != nil { - err = errors.Wrap(err, "initialize") + err = fmt.Errorf("initialize: %w", err) return } if err = s.readAndProcessContent(config); err != nil { - err = errors.Wrap(err, "readAndProcessContent") + err = fmt.Errorf("readAndProcessContent: %w", err) return } return err @@ -1534,7 +1532,7 @@ func (s *Site) assembleMenus() { for name, me := range p.pageMenus.menus() { if _, ok := flat[twoD{name, me.KeyName()}]; ok { - err := p.wrapError(errors.Errorf("duplicate menu entry with identifier %q in menu %q", me.KeyName(), name)) + err := p.wrapError(fmt.Errorf("duplicate menu entry with identifier %q in menu %q", me.KeyName(), name)) s.Log.Warnln(err) continue } @@ -1819,7 +1817,7 @@ func (s *Site) renderForTemplate(name, outputFormat string, d any, w io.Writer, } if err = s.Tmpl().Execute(templ, w, d); err != nil { - return _errors.Wrapf(err, "render of %q failed", name) + return fmt.Errorf("render of %q failed: %w", name, err) } return } diff --git a/hugolib/site_render.go b/hugolib/site_render.go index c09e5cc99..b572c443e 100644 --- a/hugolib/site_render.go +++ b/hugolib/site_render.go @@ -23,8 +23,9 @@ import ( "github.com/gohugoio/hugo/config" + "errors" + "github.com/gohugoio/hugo/output" - "github.com/pkg/errors" "github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/page/pagemeta" @@ -95,7 +96,7 @@ func (s *Site) renderPages(ctx *siteRenderContext) error { err := <-errs if err != nil { - return errors.Wrap(err, "failed to render pages") + return fmt.Errorf("failed to render pages: %w", err) } return nil } diff --git a/hugolib/testhelpers_test.go b/hugolib/testhelpers_test.go index 6c1aa6fd0..4a72836af 100644 --- a/hugolib/testhelpers_test.go +++ b/hugolib/testhelpers_test.go @@ -28,10 +28,8 @@ import ( "github.com/google/go-cmp/cmp" "github.com/gohugoio/hugo/parser" - "github.com/pkg/errors" "github.com/fsnotify/fsnotify" - "github.com/gohugoio/hugo/common/herrors" "github.com/gohugoio/hugo/common/hexec" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/config" @@ -471,7 +469,6 @@ func (s *sitesBuilder) writeFilePairs(folder string, files []filenameContent) *s func (s *sitesBuilder) CreateSites() *sitesBuilder { if err := s.CreateSitesE(); err != nil { - herrors.PrintStackTraceFromErr(err) s.Fatalf("Failed to create sites: %s", err) } @@ -517,7 +514,7 @@ func (s *sitesBuilder) CreateSitesE() error { "i18n", } { if err := os.MkdirAll(filepath.Join(s.workingDir, dir), 0777); err != nil { - return errors.Wrapf(err, "failed to create %q", dir) + return fmt.Errorf("failed to create %q: %w", dir, err) } } } @@ -536,7 +533,7 @@ func (s *sitesBuilder) CreateSitesE() error { } if err := s.LoadConfig(); err != nil { - return errors.Wrap(err, "failed to load config") + return fmt.Errorf("failed to load config: %w", err) } s.Fs.PublishDir = hugofs.NewCreateCountingFs(s.Fs.PublishDir) @@ -549,7 +546,7 @@ func (s *sitesBuilder) CreateSitesE() error { sites, err := NewHugoSites(depsCfg) if err != nil { - return errors.Wrap(err, "failed to create sites") + return fmt.Errorf("failed to create sites: %w", err) } s.H = sites @@ -612,7 +609,6 @@ func (s *sitesBuilder) build(cfg BuildCfg, shouldFail bool) *sitesBuilder { } } if err != nil && !shouldFail { - herrors.PrintStackTraceFromErr(err) s.Fatalf("Build failed: %s", err) } else if err == nil && shouldFail { s.Fatalf("Expected error") diff --git a/langs/config.go b/langs/config.go index ef63e700e..81e6fc2ab 100644 --- a/langs/config.go +++ b/langs/config.go @@ -23,7 +23,7 @@ import ( "github.com/spf13/cast" - "github.com/pkg/errors" + "errors" "github.com/gohugoio/hugo/config" ) @@ -72,7 +72,7 @@ func LoadLanguageSettings(cfg config.Provider, oldLangs Languages) (c LanguagesC } else { languages2, err = toSortedLanguages(cfg, languages) if err != nil { - return c, errors.Wrap(err, "Failed to parse multilingual config") + return c, fmt.Errorf("Failed to parse multilingual config: %w", err) } } diff --git a/langs/i18n/translationProvider.go b/langs/i18n/translationProvider.go index 44bd52f0c..52f9349c2 100644 --- a/langs/i18n/translationProvider.go +++ b/langs/i18n/translationProvider.go @@ -15,6 +15,7 @@ package i18n import ( "encoding/json" + "fmt" "strings" "github.com/gohugoio/hugo/common/paths" @@ -30,7 +31,6 @@ import ( "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/hugofs" "github.com/gohugoio/hugo/source" - _errors "github.com/pkg/errors" ) // TranslationProvider provides translation handling, i.e. loading @@ -83,7 +83,7 @@ const artificialLangTagPrefix = "art-x-" func addTranslationFile(bundle *i18n.Bundle, r source.File) error { f, err := r.FileInfo().Meta().Open() if err != nil { - return _errors.Wrapf(err, "failed to open translations file %q:", r.LogicalName()) + return fmt.Errorf("failed to open translations file %q:: %w", r.LogicalName(), err) } b := helpers.ReaderToBytes(f) @@ -96,7 +96,7 @@ func addTranslationFile(bundle *i18n.Bundle, r source.File) error { try := artificialLangTagPrefix + lang _, err = language.Parse(try) if err != nil { - return _errors.Errorf("%q %s.", try, err) + return fmt.Errorf("%q: %s", try, err) } name = artificialLangTagPrefix + name } @@ -111,7 +111,7 @@ func addTranslationFile(bundle *i18n.Bundle, r source.File) error { return nil } } - return errWithFileContext(_errors.Wrapf(err, "failed to load translations"), r) + return errWithFileContext(fmt.Errorf("failed to load translations: %w", err), r) } return nil @@ -138,11 +138,6 @@ func errWithFileContext(inerr error, r source.File) error { } defer f.Close() - err, _ = herrors.WithFileContext( - inerr, - realFilename, - f, - herrors.SimpleLineMatcher) + return herrors.NewFileError(realFilename, inerr).UpdateContent(f, herrors.SimpleLineMatcher) - return err } diff --git a/langs/language.go b/langs/language.go index a0294a103..d6b30ec10 100644 --- a/langs/language.go +++ b/langs/language.go @@ -14,6 +14,7 @@ package langs import ( + "fmt" "sort" "strings" "sync" @@ -22,8 +23,6 @@ import ( "golang.org/x/text/collate" "golang.org/x/text/language" - "github.com/pkg/errors" - "github.com/gohugoio/hugo/common/htime" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/config" @@ -311,7 +310,7 @@ func GetCollator(l *Language) *Collator { func (l *Language) loadLocation(tzStr string) error { location, err := time.LoadLocation(tzStr) if err != nil { - return errors.Wrapf(err, "invalid timeZone for language %q", l.Lang) + return fmt.Errorf("invalid timeZone for language %q: %w", l.Lang, err) } l.location = location diff --git a/lazy/init.go b/lazy/init.go index 48e9e2489..b998d0305 100644 --- a/lazy/init.go +++ b/lazy/init.go @@ -19,7 +19,7 @@ import ( "sync/atomic" "time" - "github.com/pkg/errors" + "errors" ) // New creates a new empty Init. diff --git a/markup/blackfriday/blackfriday_config/config.go b/markup/blackfriday/blackfriday_config/config.go index 668478ece..8c276c9f6 100644 --- a/markup/blackfriday/blackfriday_config/config.go +++ b/markup/blackfriday/blackfriday_config/config.go @@ -19,8 +19,9 @@ package blackfriday_config import ( + "fmt" + "github.com/mitchellh/mapstructure" - "github.com/pkg/errors" ) // Default holds the default BlackFriday config. @@ -64,7 +65,7 @@ type Config struct { func UpdateConfig(b Config, m map[string]any) (Config, error) { if err := mapstructure.Decode(m, &b); err != nil { - return b, errors.WithMessage(err, "failed to decode rendering config") + return b, fmt.Errorf("failed to decode rendering config: %w", err) } return b, nil } diff --git a/modules/client.go b/modules/client.go index 6e1cfe881..78ba9f5ae 100644 --- a/modules/client.go +++ b/modules/client.go @@ -47,7 +47,8 @@ import ( "github.com/gohugoio/hugo/common/hugio" - "github.com/pkg/errors" + "errors" + "github.com/spf13/afero" ) @@ -241,7 +242,7 @@ func (c *Client) Vendor() error { // See https://github.com/gohugoio/hugo/issues/8239 // This is an error situation. We need something to vendor. if t.Mounts() == nil { - return errors.Errorf("cannot vendor module %q, need at least one mount", t.Path()) + return fmt.Errorf("cannot vendor module %q, need at least one mount", t.Path()) } fmt.Fprintln(&modulesContent, "# "+t.Path()+" "+t.Version()) @@ -253,22 +254,22 @@ func (c *Client) Vendor() error { targetFilename := filepath.Join(vendorDir, t.Path(), mount.Source) fi, err := c.fs.Stat(sourceFilename) if err != nil { - return errors.Wrap(err, "failed to vendor module") + return fmt.Errorf("failed to vendor module: %w", err) } if fi.IsDir() { if err := hugio.CopyDir(c.fs, sourceFilename, targetFilename, nil); err != nil { - return errors.Wrap(err, "failed to copy module to vendor dir") + return fmt.Errorf("failed to copy module to vendor dir: %w", err) } } else { targetDir := filepath.Dir(targetFilename) if err := c.fs.MkdirAll(targetDir, 0755); err != nil { - return errors.Wrap(err, "failed to make target dir") + return fmt.Errorf("failed to make target dir: %w", err) } if err := hugio.CopyFile(c.fs, sourceFilename, targetFilename); err != nil { - return errors.Wrap(err, "failed to copy module file to vendor") + return fmt.Errorf("failed to copy module file to vendor: %w", err) } } } @@ -278,7 +279,7 @@ func (c *Client) Vendor() error { _, err := c.fs.Stat(resourcesDir) if err == nil { if err := hugio.CopyDir(c.fs, resourcesDir, filepath.Join(vendorDir, t.Path(), files.FolderResources), nil); err != nil { - return errors.Wrap(err, "failed to copy resources to vendor dir") + return fmt.Errorf("failed to copy resources to vendor dir: %w", err) } } @@ -287,7 +288,7 @@ func (c *Client) Vendor() error { _, err = c.fs.Stat(configDir) if err == nil { if err := hugio.CopyDir(c.fs, configDir, filepath.Join(vendorDir, t.Path(), "config"), nil); err != nil { - return errors.Wrap(err, "failed to copy config dir to vendor dir") + return fmt.Errorf("failed to copy config dir to vendor dir: %w", err) } } @@ -361,7 +362,7 @@ func (c *Client) get(args ...string) error { args = append([]string{"-d"}, args...) } if err := c.runGo(context.Background(), c.logger.Out(), append([]string{"get"}, args...)...); err != nil { - errors.Wrapf(err, "failed to get %q", args) + return fmt.Errorf("failed to get %q: %w", args, err) } return nil } @@ -372,7 +373,7 @@ func (c *Client) get(args ...string) error { func (c *Client) Init(path string) error { err := c.runGo(context.Background(), c.logger.Out(), "mod", "init", path) if err != nil { - return errors.Wrap(err, "failed to init modules") + return fmt.Errorf("failed to init modules: %w", err) } c.GoModulesFilename = filepath.Join(c.ccfg.WorkingDir, goModFilename) @@ -458,7 +459,7 @@ func (c *Client) listGoMods() (goModules, error) { out := ioutil.Discard err := c.runGo(context.Background(), out, args...) if err != nil { - return errors.Wrap(err, "failed to download modules") + return fmt.Errorf("failed to download modules: %w", err) } return nil } @@ -477,7 +478,7 @@ func (c *Client) listGoMods() (goModules, error) { } err := c.runGo(context.Background(), b, args...) if err != nil { - return errors.Wrap(err, "failed to list modules") + return fmt.Errorf("failed to list modules: %w", err) } dec := json.NewDecoder(b) @@ -487,7 +488,7 @@ func (c *Client) listGoMods() (goModules, error) { if err == io.EOF { break } - return errors.Wrap(err, "failed to decode modules list") + return fmt.Errorf("failed to decode modules list: %w", err) } if err := handle(m); err != nil { @@ -657,7 +658,7 @@ If you then run 'hugo mod graph' it should resolve itself to the most recent ver _, ok := err.(*exec.ExitError) if !ok { - return errors.Errorf("failed to execute 'go %v': %s %T", args, err, err) + return fmt.Errorf("failed to execute 'go %v': %s %T", args, err, err) } // Too old Go version @@ -666,7 +667,7 @@ If you then run 'hugo mod graph' it should resolve itself to the most recent ver return nil } - return errors.Errorf("go command failed: %s", stderr) + return fmt.Errorf("go command failed: %s", stderr) } @@ -706,7 +707,7 @@ func (c *Client) shouldVendor(path string) bool { } func (c *Client) createThemeDirname(modulePath string, isProjectMod bool) (string, error) { - invalid := errors.Errorf("invalid module path %q; must be relative to themesDir when defined outside of the project", modulePath) + invalid := fmt.Errorf("invalid module path %q; must be relative to themesDir when defined outside of the project", modulePath) modulePath = filepath.Clean(modulePath) if filepath.IsAbs(modulePath) { diff --git a/modules/collect.go b/modules/collect.go index e012d4696..ff83f9ecc 100644 --- a/modules/collect.go +++ b/modules/collect.go @@ -36,7 +36,7 @@ import ( "github.com/rogpeppe/go-internal/module" - "github.com/pkg/errors" + "errors" "github.com/gohugoio/hugo/config" "github.com/spf13/afero" @@ -48,7 +48,7 @@ const vendorModulesFilename = "modules.txt" // IsNotExist returns whether an error means that a module could not be found. func IsNotExist(err error) bool { - return errors.Cause(err) == ErrNotExist + return errors.Is(err, os.ErrNotExist) } // CreateProjectModule creates modules from the given config. @@ -289,7 +289,7 @@ func (c *collector) add(owner *moduleAdapter, moduleImport Import, disabled bool return nil, nil } if found, _ := afero.Exists(c.fs, moduleDir); !found { - c.err = c.wrapModuleNotFound(errors.Errorf(`module %q not found; either add it as a Hugo Module or store it in %q.`, modulePath, c.ccfg.ThemesDir)) + c.err = c.wrapModuleNotFound(fmt.Errorf(`module %q not found; either add it as a Hugo Module or store it in %q.`, modulePath, c.ccfg.ThemesDir)) return nil, nil } } @@ -297,7 +297,7 @@ func (c *collector) add(owner *moduleAdapter, moduleImport Import, disabled bool } if found, _ := afero.Exists(c.fs, moduleDir); !found { - c.err = c.wrapModuleNotFound(errors.Errorf("%q not found", moduleDir)) + c.err = c.wrapModuleNotFound(fmt.Errorf("%q not found", moduleDir)) return nil, nil } @@ -557,7 +557,7 @@ func (c *collector) collectModulesTXT(owner Module) error { line = strings.TrimSpace(line) parts := strings.Fields(line) if len(parts) != 2 { - return errors.Errorf("invalid modules list: %q", filename) + return fmt.Errorf("invalid modules list: %q", filename) } path := parts[0] @@ -662,7 +662,7 @@ func (c *collector) normalizeMounts(owner *moduleAdapter, mounts []Mount) ([]Mou targetBase = mnt.Target[0:idxPathSep] } if !files.IsComponentFolder(targetBase) { - return nil, errors.Errorf("%s: mount target must be one of: %v", errMsg, files.ComponentFolders) + return nil, fmt.Errorf("%s: mount target must be one of: %v", errMsg, files.ComponentFolders) } out = append(out, mnt) @@ -672,7 +672,7 @@ func (c *collector) normalizeMounts(owner *moduleAdapter, mounts []Mount) ([]Mou } func (c *collector) wrapModuleNotFound(err error) error { - err = errors.Wrap(ErrNotExist, err.Error()) + err = fmt.Errorf(err.Error()+": %w", ErrNotExist) if c.GoModulesFilename == "" { return err } @@ -681,9 +681,9 @@ func (c *collector) wrapModuleNotFound(err error) error { switch c.goBinaryStatus { case goBinaryStatusNotFound: - return errors.Wrap(err, baseMsg+" you need to install Go to use it. See https://golang.org/dl/.") + return fmt.Errorf(baseMsg+" you need to install Go to use it. See https://golang.org/dl/ : %q", err) case goBinaryStatusTooOld: - return errors.Wrap(err, baseMsg+" you need to a newer version of Go to use it. See https://golang.org/dl/.") + return fmt.Errorf(baseMsg+" you need to a newer version of Go to use it. See https://golang.org/dl/ : %w", err) } return err diff --git a/modules/config.go b/modules/config.go index 04bf1b422..08154bc11 100644 --- a/modules/config.go +++ b/modules/config.go @@ -18,8 +18,6 @@ import ( "path/filepath" "strings" - "github.com/pkg/errors" - "github.com/gohugoio/hugo/common/hugo" "github.com/gohugoio/hugo/config" @@ -226,7 +224,7 @@ func decodeConfig(cfg config.Provider, pathReplacements map[string]string) (Conf for _, repl := range c.Replacements { parts := strings.Split(repl, "->") if len(parts) != 2 { - return c, errors.Errorf(`invalid module.replacements: %q; configure replacement pairs on the form "oldpath->newpath" `, repl) + return c, fmt.Errorf(`invalid module.replacements: %q; configure replacement pairs on the form "oldpath->newpath" `, repl) } c.replacementsMap[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1]) diff --git a/modules/npm/package_builder.go b/modules/npm/package_builder.go index 911241813..9bdc7eb78 100644 --- a/modules/npm/package_builder.go +++ b/modules/npm/package_builder.go @@ -24,8 +24,6 @@ import ( "github.com/gohugoio/hugo/hugofs/files" - "github.com/pkg/errors" - "github.com/gohugoio/hugo/hugofs" "github.com/spf13/afero" @@ -57,7 +55,7 @@ func Pack(fs afero.Fs, fis []hugofs.FileMetaInfo) error { if err == nil { // Preserve the original in package.hugo.json. if err = hugio.CopyFile(fs, packageJSONName, files.FilenamePackageHugoJSON); err != nil { - return errors.Wrap(err, "npm pack: failed to copy package file") + return fmt.Errorf("npm pack: failed to copy package file: %w", err) } } else { // Create one. @@ -83,7 +81,7 @@ func Pack(fs afero.Fs, fis []hugofs.FileMetaInfo) error { masterFilename := meta.Filename f, err := meta.Open() if err != nil { - return errors.Wrap(err, "npm pack: failed to open package file") + return fmt.Errorf("npm pack: failed to open package file: %w", err) } b = newPackageBuilder(meta.Module, f) f.Close() @@ -106,14 +104,14 @@ func Pack(fs afero.Fs, fis []hugofs.FileMetaInfo) error { f, err := meta.Open() if err != nil { - return errors.Wrap(err, "npm pack: failed to open package file") + return fmt.Errorf("npm pack: failed to open package file: %w", err) } b.Add(meta.Module, f) f.Close() } if b.Err() != nil { - return errors.Wrap(b.Err(), "npm pack: failed to build") + return fmt.Errorf("npm pack: failed to build: %w", b.Err()) } // Replace the dependencies in the original template with the merged set. @@ -136,11 +134,11 @@ func Pack(fs afero.Fs, fis []hugofs.FileMetaInfo) error { encoder.SetEscapeHTML(false) encoder.SetIndent("", strings.Repeat(" ", 2)) if err := encoder.Encode(b.originalPackageJSON); err != nil { - return errors.Wrap(err, "npm pack: failed to marshal JSON") + return fmt.Errorf("npm pack: failed to marshal JSON: %w", err) } if err := afero.WriteFile(fs, packageJSONName, packageJSONData.Bytes(), 0666); err != nil { - return errors.Wrap(err, "npm pack: failed to write package.json") + return fmt.Errorf("npm pack: failed to write package.json: %w", err) } return nil diff --git a/navigation/menu.go b/navigation/menu.go index 02e1f8fec..5e4996f39 100644 --- a/navigation/menu.go +++ b/navigation/menu.go @@ -19,8 +19,6 @@ import ( "sort" "strings" - "github.com/pkg/errors" - "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/compare" @@ -190,7 +188,7 @@ func (m *MenuEntry) MarshallMap(ime map[string]any) error { } if err != nil { - return errors.Wrapf(err, "failed to marshal menu entry %q", m.KeyName()) + return fmt.Errorf("failed to marshal menu entry %q: %w", m.KeyName(), err) } return nil diff --git a/navigation/pagemenus.go b/navigation/pagemenus.go index 46ed5221e..7b4f6f648 100644 --- a/navigation/pagemenus.go +++ b/navigation/pagemenus.go @@ -14,10 +14,11 @@ package navigation import ( + "fmt" + "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" - "github.com/pkg/errors" "github.com/spf13/cast" ) @@ -76,7 +77,7 @@ func PageMenusFromPage(p Page) (PageMenus, error) { } var wrapErr = func(err error) error { - return errors.Wrapf(err, "unable to process menus for page %q", p.Path()) + return fmt.Errorf("unable to process menus for page %q: %w", p.Path(), err) } // Could be a structured menu entry diff --git a/output/outputFormat.go b/output/outputFormat.go index 34bec9911..1f1556eaf 100644 --- a/output/outputFormat.go +++ b/output/outputFormat.go @@ -20,8 +20,6 @@ import ( "sort" "strings" - "github.com/pkg/errors" - "github.com/mitchellh/mapstructure" "github.com/gohugoio/hugo/media" @@ -364,7 +362,7 @@ func decode(mediaTypes media.Types, input any, output *Format) error { } dataVal.SetMapIndex(key, reflect.ValueOf(mediaType)) default: - return nil, errors.Errorf("invalid output format configuration; wrong type for media type, expected string (e.g. text/html), got %T", vvi) + return nil, fmt.Errorf("invalid output format configuration; wrong type for media type, expected string (e.g. text/html), got %T", vvi) } } } @@ -379,7 +377,7 @@ func decode(mediaTypes media.Types, input any, output *Format) error { } if err = decoder.Decode(input); err != nil { - return errors.Wrap(err, "failed to decode output format configuration") + return fmt.Errorf("failed to decode output format configuration: %w", err) } return nil diff --git a/parser/metadecoders/decoder.go b/parser/metadecoders/decoder.go index 5bf96b2d8..fe0581734 100644 --- a/parser/metadecoders/decoder.go +++ b/parser/metadecoders/decoder.go @@ -26,7 +26,6 @@ import ( xml "github.com/clbanning/mxj/v2" toml "github.com/pelletier/go-toml/v2" - "github.com/pkg/errors" "github.com/spf13/afero" "github.com/spf13/cast" jww "github.com/spf13/jwalterweatherman" @@ -74,7 +73,7 @@ func (d Decoder) UnmarshalToMap(data []byte, f Format) (map[string]any, error) { func (d Decoder) UnmarshalFileToMap(fs afero.Fs, filename string) (map[string]any, error) { format := FormatFromString(filename) if format == "" { - return nil, errors.Errorf("%q is not a valid configuration format", filename) + return nil, fmt.Errorf("%q is not a valid configuration format", filename) } data, err := afero.ReadFile(fs, filename) @@ -106,7 +105,7 @@ func (d Decoder) UnmarshalStringTo(data string, typ any) (any, error) { case float64: return cast.ToFloat64E(data) default: - return nil, errors.Errorf("unmarshal: %T not supported", typ) + return nil, fmt.Errorf("unmarshal: %T not supported", typ) } } @@ -144,7 +143,7 @@ func (d Decoder) UnmarshalTo(data []byte, f Format, v any) error { if err == nil { xmlRootName, err := xmlRoot.Root() if err != nil { - return toFileError(f, errors.Wrap(err, "failed to unmarshal XML")) + return toFileError(f, data, fmt.Errorf("failed to unmarshal XML: %w", err)) } xmlValue = xmlRoot[xmlRootName].(map[string]any) } @@ -160,7 +159,7 @@ func (d Decoder) UnmarshalTo(data []byte, f Format, v any) error { case YAML: err = yaml.Unmarshal(data, v) if err != nil { - return toFileError(f, errors.Wrap(err, "failed to unmarshal YAML")) + return toFileError(f, data, fmt.Errorf("failed to unmarshal YAML: %w", err)) } // To support boolean keys, the YAML package unmarshals maps to @@ -191,14 +190,14 @@ func (d Decoder) UnmarshalTo(data []byte, f Format, v any) error { return d.unmarshalCSV(data, v) default: - return errors.Errorf("unmarshal of format %q is not supported", f) + return fmt.Errorf("unmarshal of format %q is not supported", f) } if err == nil { return nil } - return toFileError(f, errors.Wrap(err, "unmarshal failed")) + return toFileError(f, data, fmt.Errorf("unmarshal failed: %w", err)) } func (d Decoder) unmarshalCSV(data []byte, v any) error { @@ -215,7 +214,7 @@ func (d Decoder) unmarshalCSV(data []byte, v any) error { case *any: *v.(*any) = records default: - return errors.Errorf("CSV cannot be unmarshaled into %T", v) + return fmt.Errorf("CSV cannot be unmarshaled into %T", v) } @@ -260,8 +259,8 @@ func (d Decoder) unmarshalORG(data []byte, v any) error { return nil } -func toFileError(f Format, err error) error { - return herrors.ToFileError(string(f), err) +func toFileError(f Format, data []byte, err error) error { + return herrors.NewFileError(fmt.Sprintf("_stream.%s", f), err).UpdateContent(bytes.NewReader(data), nil) } // stringifyMapKeys recurses into in and changes all instances of diff --git a/parser/pageparser/pageparser.go b/parser/pageparser/pageparser.go index 3338e063e..bfbedcf26 100644 --- a/parser/pageparser/pageparser.go +++ b/parser/pageparser/pageparser.go @@ -15,11 +15,11 @@ package pageparser import ( "bytes" + "fmt" "io" "io/ioutil" "github.com/gohugoio/hugo/parser/metadecoders" - "github.com/pkg/errors" ) // Result holds the parse result. @@ -102,7 +102,7 @@ func ParseMain(r io.Reader, cfg Config) (Result, error) { func parseSection(r io.Reader, cfg Config, start stateFunc) (Result, error) { b, err := ioutil.ReadAll(r) if err != nil { - return nil, errors.Wrap(err, "failed to read page content") + return nil, fmt.Errorf("failed to read page content: %w", err) } return parseBytes(b, cfg, start) } diff --git a/publisher/publisher.go b/publisher/publisher.go index fc1fc0799..63eb1011f 100644 --- a/publisher/publisher.go +++ b/publisher/publisher.go @@ -15,6 +15,7 @@ package publisher import ( "errors" + "fmt" "io" "net/url" "sync/atomic" @@ -104,7 +105,7 @@ func (p DestinationPublisher) Publish(d Descriptor) error { defer bp.PutBuffer(b) if err := transformers.Apply(b, d.Src); err != nil { - return err + return fmt.Errorf("failed to process %q: %w", d.TargetPath, err) } // This is now what we write to disk. diff --git a/releaser/releaser.go b/releaser/releaser.go index cdfba3c7a..6bcfe3c80 100644 --- a/releaser/releaser.go +++ b/releaser/releaser.go @@ -26,8 +26,9 @@ import ( "github.com/gohugoio/hugo/common/hexec" + "errors" + "github.com/gohugoio/hugo/common/hugo" - "github.com/pkg/errors" ) const commitPrefix = "releaser:" @@ -217,7 +218,7 @@ func (r *ReleaseHandler) release(releaseNotesFile string) error { cmd.Stderr = os.Stderr err := cmd.Run() if err != nil { - return errors.Wrap(err, "goreleaser failed") + return fmt.Errorf("goreleaser failed: %w", err) } return nil } 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) + return herrors.NewFileErrorFromFile(inErr, file.Filename, realFilename, hugofs.Os, herrors.SimpleLineMatcher) - werr, ok := herrors.WithFileContextForFile(ferr, realFilename, file.Filename, imp.fs, herrors.SimpleLineMatcher) - - if !ok { - return ferr - } - - 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) + return herrors.NewFileErrorFromFile(sassErr, filename, filename, hugofs.Os, offsetMatcher) - if !ok { - return sassErr - } - - 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/resources/transform.go @@ -24,8 +24,6 @@ import ( "github.com/gohugoio/hugo/common/paths" - "github.com/pkg/errors" - "github.com/gohugoio/hugo/resources/images" "github.com/gohugoio/hugo/resources/images/exif" "github.com/spf13/afero" @@ -431,10 +429,10 @@ func (r *resourceAdapter) transform(publish, setContent bool) error { errMsg = ". You need to install Babel, see https://gohugo.io/hugo-pipes/babel/" } - return errors.Wrap(err, msg+errMsg) + return fmt.Errorf(msg+errMsg+": %w", err) } - return errors.Wrap(err, msg) + return fmt.Errorf(msg+": %w", err) } var tryFileCache bool @@ -461,7 +459,7 @@ func (r *resourceAdapter) transform(publish, setContent bool) error { if err != nil { return newErr(err) } - return newErr(errors.Errorf("resource %q not found in file cache", key)) + return newErr(fmt.Errorf("resource %q not found in file cache", key)) } transformedContentr = f updates.sourceFs = cache.fileCache.Fs diff --git a/source/fileInfo.go b/source/fileInfo.go index 13c4495bf..f882eb898 100644 --- a/source/fileInfo.go +++ b/source/fileInfo.go @@ -14,6 +14,7 @@ package source import ( + "fmt" "path/filepath" "strings" "sync" @@ -22,8 +23,6 @@ import ( "github.com/gohugoio/hugo/hugofs/files" - "github.com/pkg/errors" - "github.com/gohugoio/hugo/common/hugio" "github.com/gohugoio/hugo/hugofs" @@ -244,11 +243,11 @@ func (sp *SourceSpec) NewFileInfo(fi hugofs.FileMetaInfo) (*FileInfo, error) { relPath := m.Path if relPath == "" { - return nil, errors.Errorf("no Path provided by %v (%T)", m, m.Fs) + return nil, fmt.Errorf("no Path provided by %v (%T)", m, m.Fs) } if filename == "" { - return nil, errors.Errorf("no Filename provided by %v (%T)", m, m.Fs) + return nil, fmt.Errorf("no Filename provided by %v (%T)", m, m.Fs) } relDir := filepath.Dir(relPath) diff --git a/source/filesystem.go b/source/filesystem.go index 4d509c566..79d027c5c 100644 --- a/source/filesystem.go +++ b/source/filesystem.go @@ -14,11 +14,10 @@ package source import ( + "fmt" "path/filepath" "sync" - "github.com/pkg/errors" - "github.com/gohugoio/hugo/hugofs" ) @@ -49,7 +48,7 @@ func (f *Filesystem) Files() ([]File, error) { f.filesInit.Do(func() { err := f.captureFiles() if err != nil { - f.filesInitErr = errors.Wrap(err, "capture files") + f.filesInitErr = fmt.Errorf("capture files: %w", err) } }) return f.files, f.filesInitErr diff --git a/tpl/collections/collections.go b/tpl/collections/collections.go index 24f43e62c..516e2c272 100644 --- a/tpl/collections/collections.go +++ b/tpl/collections/collections.go @@ -24,12 +24,13 @@ import ( "strings" "time" + "errors" + "github.com/gohugoio/hugo/common/collections" "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/common/types" "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/helpers" - "github.com/pkg/errors" "github.com/spf13/cast" ) @@ -736,7 +737,7 @@ func (ns *Namespace) Uniq(seq any) (any, error) { case reflect.Array: slice = reflect.MakeSlice(reflect.SliceOf(v.Type().Elem()), 0, 0) default: - return nil, errors.Errorf("type %T not supported", seq) + return nil, fmt.Errorf("type %T not supported", seq) } seen := make(map[any]bool) diff --git a/tpl/collections/merge.go b/tpl/collections/merge.go index abfc2da9c..4d408302b 100644 --- a/tpl/collections/merge.go +++ b/tpl/collections/merge.go @@ -14,13 +14,14 @@ package collections import ( + "fmt" "reflect" "strings" "github.com/gohugoio/hugo/common/hreflect" "github.com/gohugoio/hugo/common/maps" - "github.com/pkg/errors" + "errors" ) // Merge creates a copy of the final parameter and merges the preceding @@ -49,7 +50,7 @@ func (ns *Namespace) merge(src, dst any) (any, error) { vdst, vsrc := reflect.ValueOf(dst), reflect.ValueOf(src) if vdst.Kind() != reflect.Map { - return nil, errors.Errorf("destination must be a map, got %T", dst) + return nil, fmt.Errorf("destination must be a map, got %T", dst) } if !hreflect.IsTruthfulValue(vsrc) { @@ -57,11 +58,11 @@ func (ns *Namespace) merge(src, dst any) (any, error) { } if vsrc.Kind() != reflect.Map { - return nil, errors.Errorf("source must be a map, got %T", src) + return nil, fmt.Errorf("source must be a map, got %T", src) } if vsrc.Type().Key() != vdst.Type().Key() { - return nil, errors.Errorf("incompatible map types, got %T to %T", src, dst) + return nil, fmt.Errorf("incompatible map types, got %T to %T", src, dst) } return mergeMap(vdst, vsrc).Interface(), nil diff --git a/tpl/collections/reflect_helpers.go b/tpl/collections/reflect_helpers.go index 4aa137e88..4178850aa 100644 --- a/tpl/collections/reflect_helpers.go +++ b/tpl/collections/reflect_helpers.go @@ -18,8 +18,9 @@ import ( "reflect" "time" + "errors" + "github.com/mitchellh/hashstructure" - "github.com/pkg/errors" ) var ( @@ -103,7 +104,7 @@ func convertValue(v reflect.Value, to reflect.Type) (reflect.Value, error) { case isNumber(kind): return convertNumber(v, kind) default: - return reflect.Value{}, errors.Errorf("%s is not assignable to %s", v.Type(), to) + return reflect.Value{}, fmt.Errorf("%s is not assignable to %s", v.Type(), to) } } diff --git a/tpl/collections/symdiff.go b/tpl/collections/symdiff.go index 1c411bc35..8ecee3c4a 100644 --- a/tpl/collections/symdiff.go +++ b/tpl/collections/symdiff.go @@ -16,8 +16,6 @@ package collections import ( "fmt" "reflect" - - "github.com/pkg/errors" ) // SymDiff returns the symmetric difference of s1 and s2. @@ -54,7 +52,7 @@ func (ns *Namespace) SymDiff(s2, s1 any) (any, error) { if ids1[key] != ids2[key] { v, err := convertValue(ev, sliceElemType) if err != nil { - return nil, errors.WithMessage(err, "symdiff: failed to convert value") + return nil, fmt.Errorf("symdiff: failed to convert value: %w", err) } slice = reflect.Append(slice, v) } diff --git a/tpl/data/data.go b/tpl/data/data.go index 5e03d52c3..926f6773d 100644 --- a/tpl/data/data.go +++ b/tpl/data/data.go @@ -20,6 +20,7 @@ import ( "encoding/csv" "encoding/json" "errors" + "fmt" "net/http" "strings" @@ -35,7 +36,6 @@ import ( "github.com/gohugoio/hugo/cache/filecache" "github.com/gohugoio/hugo/deps" - _errors "github.com/pkg/errors" ) // New returns a new instance of the data-namespaced template functions. @@ -69,7 +69,7 @@ func (ns *Namespace) GetCSV(sep string, args ...any) (d [][]string, err error) { unmarshal := func(b []byte) (bool, error) { if d, err = parseCSV(b, sep); err != nil { - err = _errors.Wrapf(err, "failed to parse CSV file %s", url) + err = fmt.Errorf("failed to parse CSV file %s: %w", url, err) return true, err } @@ -80,7 +80,7 @@ func (ns *Namespace) GetCSV(sep string, args ...any) (d [][]string, err error) { var req *http.Request req, err = http.NewRequest("GET", url, nil) if err != nil { - return nil, _errors.Wrapf(err, "failed to create request for getCSV for resource %s", url) + return nil, fmt.Errorf("failed to create request for getCSV for resource %s: %w", url, err) } // Add custom user headers. @@ -109,7 +109,7 @@ func (ns *Namespace) GetJSON(args ...any) (any, error) { req, err := http.NewRequest("GET", url, nil) if err != nil { - return nil, _errors.Wrapf(err, "Failed to create request for getJSON resource %s", url) + return nil, fmt.Errorf("Failed to create request for getJSON resource %s: %w", url, err) } unmarshal := func(b []byte) (bool, error) { diff --git a/tpl/data/resources.go b/tpl/data/resources.go index dca25efb2..0470faf51 100644 --- a/tpl/data/resources.go +++ b/tpl/data/resources.go @@ -15,14 +15,13 @@ package data import ( "bytes" + "fmt" "io/ioutil" "net/http" "net/url" "path/filepath" "time" - "github.com/pkg/errors" - "github.com/gohugoio/hugo/cache/filecache" "github.com/gohugoio/hugo/config" @@ -70,7 +69,7 @@ func (ns *Namespace) getRemote(cache *filecache.Cache, unmarshal func([]byte) (b res.Body.Close() if isHTTPError(res) { - return nil, errors.Errorf("Failed to retrieve remote file: %s, body: %q", http.StatusText(res.StatusCode), b) + return nil, fmt.Errorf("Failed to retrieve remote file: %s, body: %q", http.StatusText(res.StatusCode), b) } retry, err = unmarshal(b) diff --git a/tpl/images/images.go b/tpl/images/images.go index 20af019cf..1abee1b0c 100644 --- a/tpl/images/images.go +++ b/tpl/images/images.go @@ -18,7 +18,7 @@ import ( "image" "sync" - "github.com/pkg/errors" + "errors" "github.com/gohugoio/hugo/resources/images" diff --git a/tpl/internal/resourcehelpers/helpers.go b/tpl/internal/resourcehelpers/helpers.go index d1c9bbb75..2d50c59a4 100644 --- a/tpl/internal/resourcehelpers/helpers.go +++ b/tpl/internal/resourcehelpers/helpers.go @@ -19,8 +19,6 @@ import ( "errors" "fmt" - _errors "github.com/pkg/errors" - "github.com/gohugoio/hugo/common/maps" "github.com/gohugoio/hugo/resources" ) @@ -64,7 +62,7 @@ func ResolveArgs(args []any) (resources.ResourceTransformer, map[string]any, err m, err := maps.ToStringMapE(args[0]) if err != nil { - return nil, nil, _errors.Wrap(err, "invalid options type") + return nil, nil, fmt.Errorf("invalid options type: %w", err) } return r, m, nil diff --git a/tpl/lang/lang.go b/tpl/lang/lang.go index ee349bd1d..17d37faa4 100644 --- a/tpl/lang/lang.go +++ b/tpl/lang/lang.go @@ -20,9 +20,10 @@ import ( "strconv" "strings" + "errors" + "github.com/gohugoio/locales" translators "github.com/gohugoio/localescompressed" - "github.com/pkg/errors" "github.com/gohugoio/hugo/common/hreflect" "github.com/gohugoio/hugo/deps" @@ -49,7 +50,7 @@ func (ns *Namespace) Translate(id any, args ...any) (string, error) { if len(args) > 0 { if len(args) > 1 { - return "", errors.Errorf("wrong number of arguments, expecting at most 2, got %d", len(args)+1) + return "", fmt.Errorf("wrong number of arguments, expecting at most 2, got %d", len(args)+1) } templateData = args[0] } diff --git a/tpl/openapi/openapi3/openapi3.go b/tpl/openapi/openapi3/openapi3.go index 276673889..1eea04b25 100644 --- a/tpl/openapi/openapi3/openapi3.go +++ b/tpl/openapi/openapi3/openapi3.go @@ -14,11 +14,12 @@ package openapi3 import ( + "fmt" "io/ioutil" gyaml "github.com/ghodss/yaml" - "github.com/pkg/errors" + "errors" kopenapi3 "github.com/getkin/kin-openapi/openapi3" "github.com/gohugoio/hugo/cache/namedmemcache" @@ -57,7 +58,7 @@ func (ns *Namespace) Unmarshal(r resource.UnmarshableResource) (*kopenapi3.T, er v, err := ns.cache.GetOrCreate(key, func() (any, error) { f := metadecoders.FormatFromMediaType(r.MediaType()) if f == "" { - return nil, errors.Errorf("MIME %q not supported", r.MediaType()) + return nil, fmt.Errorf("MIME %q not supported", r.MediaType()) } reader, err := r.ReadSeekCloser() diff --git a/tpl/resources/resources.go b/tpl/resources/resources.go index d3a98002f..2adec358c 100644 --- a/tpl/resources/resources.go +++ b/tpl/resources/resources.go @@ -20,8 +20,9 @@ import ( "github.com/gohugoio/hugo/common/herrors" + "errors" + "github.com/gohugoio/hugo/common/maps" - "github.com/pkg/errors" "github.com/gohugoio/hugo/tpl/internal/resourcehelpers" @@ -162,7 +163,7 @@ func (ns *Namespace) GetRemote(args ...any) resource.Resource { case *create.HTTPError: return resources.NewErrorResource(resource.NewResourceError(v, v.Data)) default: - return resources.NewErrorResource(resource.NewResourceError(errors.Wrap(err, "error calling resources.GetRemote"), make(map[string]any))) + return resources.NewErrorResource(resource.NewResourceError(fmt.Errorf("error calling resources.GetRemote: %w", err), make(map[string]any))) } } @@ -354,7 +355,7 @@ func (ns *Namespace) ToCSS(args ...any) (resource.Resource, error) { case transpilerDart, transpilerLibSass: transpiler = cast.ToString(t) default: - return nil, errors.Errorf("unsupported transpiler %q; valid values are %q or %q", t, transpilerLibSass, transpilerDart) + return nil, fmt.Errorf("unsupported transpiler %q; valid values are %q or %q", t, transpilerLibSass, transpilerDart) } } } diff --git a/tpl/strings/strings.go b/tpl/strings/strings.go index 000490f85..482a8a837 100644 --- a/tpl/strings/strings.go +++ b/tpl/strings/strings.go @@ -16,6 +16,7 @@ package strings import ( "errors" + "fmt" "html/template" "regexp" "strings" @@ -25,7 +26,6 @@ import ( "github.com/gohugoio/hugo/deps" "github.com/gohugoio/hugo/helpers" - _errors "github.com/pkg/errors" "github.com/spf13/cast" ) @@ -48,7 +48,7 @@ type Namespace struct { func (ns *Namespace) CountRunes(s any) (int, error) { ss, err := cast.ToStringE(s) if err != nil { - return 0, _errors.Wrap(err, "Failed to convert content to string") + return 0, fmt.Errorf("Failed to convert content to string: %w", err) } counter := 0 @@ -65,7 +65,7 @@ func (ns *Namespace) CountRunes(s any) (int, error) { func (ns *Namespace) RuneCount(s any) (int, error) { ss, err := cast.ToStringE(s) if err != nil { - return 0, _errors.Wrap(err, "Failed to convert content to string") + return 0, fmt.Errorf("Failed to convert content to string: %w", err) } return utf8.RuneCountInString(ss), nil } @@ -74,12 +74,12 @@ func (ns *Namespace) RuneCount(s any) (int, error) { func (ns *Namespace) CountWords(s any) (int, error) { ss, err := cast.ToStringE(s) if err != nil { - return 0, _errors.Wrap(err, "Failed to convert content to string") + return 0, fmt.Errorf("Failed to convert content to string: %w", err) } isCJKLanguage, err := regexp.MatchString(`\p{Han}|\p{Hangul}|\p{Hiragana}|\p{Katakana}`, ss) if err != nil { - return 0, _errors.Wrap(err, "Failed to match regex pattern against string") + return 0, fmt.Errorf("Failed to match regex pattern against string: %w", err) } if !isCJKLanguage { @@ -104,11 +104,11 @@ func (ns *Namespace) CountWords(s any) (int, error) { func (ns *Namespace) Count(substr, s any) (int, error) { substrs, err := cast.ToStringE(substr) if err != nil { - return 0, _errors.Wrap(err, "Failed to convert substr to string") + return 0, fmt.Errorf("Failed to convert substr to string: %w", err) } ss, err := cast.ToStringE(s) if err != nil { - return 0, _errors.Wrap(err, "Failed to convert s to string") + return 0, fmt.Errorf("Failed to convert s to string: %w", err) } return strings.Count(ss, substrs), nil } diff --git a/tpl/tplimpl/embedded/templates/server/error.html b/tpl/tplimpl/embedded/templates/server/error.html new file mode 100644 index 000000000..e5c6d0cbf --- /dev/null +++ b/tpl/tplimpl/embedded/templates/server/error.html @@ -0,0 +1,63 @@ + + + + +{{ path.Base .Position.Filename }}:
{{ .Version }}
+ Reload Page +