all: Remove unused code

Using x/tools/cmd/deadcode
This commit is contained in:
Bjørn Erik Pedersen 2023-12-18 17:41:15 +01:00
parent 6f13430d4a
commit 8adba648cc
30 changed files with 32 additions and 405 deletions

View file

@ -30,7 +30,7 @@ jobs:
**/go.sum **/go.sum
**/go.mod **/go.mod
- name: Install Ruby - name: Install Ruby
uses: ruby/setup-ruby@ee2113536afb7f793eed4ce60e8d3b26db912da4 uses: ruby/setup-ruby@036ef458ddccddb148a2b9fb67e95a22fdbf728b
with: with:
ruby-version: '2.7' ruby-version: '2.7'
bundler-cache: true # bundler-cache: true #

View file

@ -32,7 +32,7 @@ jobs:
**/go.sum **/go.sum
**/go.mod **/go.mod
- name: Install Ruby - name: Install Ruby
uses: ruby/setup-ruby@ee2113536afb7f793eed4ce60e8d3b26db912da4 uses: ruby/setup-ruby@036ef458ddccddb148a2b9fb67e95a22fdbf728b
with: with:
ruby-version: '2.7' ruby-version: '2.7'
bundler-cache: true # bundler-cache: true #

View file

@ -15,14 +15,12 @@
package herrors package herrors
import ( import (
"bytes"
"errors" "errors"
"fmt" "fmt"
"io" "io"
"os" "os"
"runtime" "runtime"
"runtime/debug" "runtime/debug"
"strconv"
) )
// PrintStackTrace prints the current stacktrace to w. // PrintStackTrace prints the current stacktrace to w.
@ -49,16 +47,6 @@ func Recover(args ...any) {
} }
} }
// GetGID the current goroutine id. Used only for debugging.
func GetGID() uint64 {
b := make([]byte, 64)
b = b[:runtime.Stack(b, false)]
b = bytes.TrimPrefix(b, []byte("goroutine "))
b = b[:bytes.IndexByte(b, ' ')]
n, _ := strconv.ParseUint(string(b), 10, 64)
return n
}
// IsFeatureNotAvailableError returns true if the given error is or contains a FeatureNotAvailableError. // IsFeatureNotAvailableError returns true if the given error is or contains a FeatureNotAvailableError.
func IsFeatureNotAvailableError(err error) bool { func IsFeatureNotAvailableError(err error) bool {
return errors.Is(err, &FeatureNotAvailableError{}) return errors.Is(err, &FeatureNotAvailableError{})

View file

@ -95,9 +95,3 @@ func GetStringSlicePreserveString(cfg Provider, key string) []string {
sd := cfg.Get(key) sd := cfg.Get(key)
return types.ToStringSlicePreserveString(sd) return types.ToStringSlicePreserveString(sd)
} }
func setIfNotSet(cfg Provider, key string, value any) {
if !cfg.IsSet(key) {
cfg.Set(key, value)
}
}

View file

@ -266,24 +266,3 @@ func (c *ContentSpec) TrimShortHTML(input []byte) []byte {
func isEndOfSentence(r rune) bool { func isEndOfSentence(r rune) bool {
return r == '.' || r == '?' || r == '!' || r == '"' || r == '\n' return r == '.' || r == '?' || r == '!' || r == '"' || r == '\n'
} }
// Kept only for benchmark.
func (c *ContentSpec) truncateWordsToWholeSentenceOld(content string) (string, bool) {
words := strings.Fields(content)
if c.Cfg.SummaryLength() >= len(words) {
return strings.Join(words, " "), false
}
for counter, word := range words[c.Cfg.SummaryLength():] {
if strings.HasSuffix(word, ".") ||
strings.HasSuffix(word, "?") ||
strings.HasSuffix(word, ".\"") ||
strings.HasSuffix(word, "!") {
upper := c.Cfg.SummaryLength() + counter + 1
return strings.Join(words[:upper], " "), (upper < len(words))
}
}
return strings.Join(words[:c.Cfg.SummaryLength()], " "), true
}

View file

@ -30,12 +30,6 @@ var (
emojiMaxSize int emojiMaxSize int
) )
// Emoji returns the emoji given a key, e.g. ":smile:", nil if not found.
func Emoji(key string) []byte {
emojiInit.Do(initEmoji)
return emojis[key]
}
// Emojify "emojifies" the input source. // Emojify "emojifies" the input source.
// Note that the input byte slice will be modified if needed. // Note that the input byte slice will be modified if needed.
// See http://www.emoji-cheat-sheet.com/ // See http://www.emoji-cheat-sheet.com/

View file

@ -32,7 +32,6 @@ import (
"github.com/jdkato/prose/transform" "github.com/jdkato/prose/transform"
bp "github.com/gohugoio/hugo/bufferpool" bp "github.com/gohugoio/hugo/bufferpool"
"github.com/spf13/pflag"
) )
// FilePathSeparator as defined by os.Separator. // FilePathSeparator as defined by os.Separator.
@ -317,18 +316,6 @@ func IsWhitespace(r rune) bool {
return r == ' ' || r == '\t' || r == '\n' || r == '\r' return r == ' ' || r == '\t' || r == '\n' || r == '\r'
} }
// NormalizeHugoFlags facilitates transitions of Hugo command-line flags,
// e.g. --baseUrl to --baseURL, --uglyUrls to --uglyURLs
func NormalizeHugoFlags(f *pflag.FlagSet, name string) pflag.NormalizedName {
switch name {
case "baseUrl":
name = "baseURL"
case "uglyUrls":
name = "uglyURLs"
}
return pflag.NormalizedName(name)
}
// PrintFs prints the given filesystem to the given writer starting from the given path. // PrintFs prints the given filesystem to the given writer starting from the given path.
// This is useful for debugging. // This is useful for debugging.
func PrintFs(fs afero.Fs, path string, w io.Writer) { func PrintFs(fs afero.Fs, path string, w io.Writer) {

View file

@ -1,59 +0,0 @@
// Copyright 2018 The Hugo Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package htesting
import (
"path/filepath"
"testing"
"github.com/spf13/afero"
)
type testFile struct {
name string
content string
}
type testdataBuilder struct {
t testing.TB
fs afero.Fs
workingDir string
files []testFile
}
func NewTestdataBuilder(fs afero.Fs, workingDir string, t testing.TB) *testdataBuilder {
workingDir = filepath.Clean(workingDir)
return &testdataBuilder{fs: fs, workingDir: workingDir, t: t}
}
func (b *testdataBuilder) Add(filename, content string) *testdataBuilder {
b.files = append(b.files, testFile{name: filename, content: content})
return b
}
func (b *testdataBuilder) Build() *testdataBuilder {
for _, f := range b.files {
if err := afero.WriteFile(b.fs, filepath.Join(b.workingDir, f.name), []byte(f.content), 0666); err != nil {
b.t.Fatalf("failed to add %q: %s", f.name, err)
}
}
return b
}
func (b testdataBuilder) WithWorkingDir(dir string) *testdataBuilder {
b.workingDir = filepath.Clean(dir)
b.files = make([]testFile, 0)
return &b
}

View file

@ -15,6 +15,7 @@
package hugofs package hugofs
import ( import (
"errors"
"os" "os"
"path/filepath" "path/filepath"
"reflect" "reflect"
@ -28,8 +29,6 @@ import (
"github.com/gohugoio/hugo/hugofs/files" "github.com/gohugoio/hugo/hugofs/files"
"golang.org/x/text/unicode/norm" "golang.org/x/text/unicode/norm"
"errors"
"github.com/gohugoio/hugo/common/hreflect" "github.com/gohugoio/hugo/common/hreflect"
"github.com/gohugoio/hugo/common/htime" "github.com/gohugoio/hugo/common/htime"
@ -224,7 +223,8 @@ func newDirNameOnlyFileInfo(name string, meta *FileMeta, fileOpener func() (afer
func decorateFileInfo( func decorateFileInfo(
fi os.FileInfo, fi os.FileInfo,
fs afero.Fs, opener func() (afero.File, error), fs afero.Fs, opener func() (afero.File, error),
filename, filepath string, inMeta *FileMeta) FileMetaInfo { filename, filepath string, inMeta *FileMeta,
) FileMetaInfo {
var meta *FileMeta var meta *FileMeta
var fim FileMetaInfo var fim FileMetaInfo
@ -289,13 +289,6 @@ func fileInfosToNames(fis []os.FileInfo) []string {
return names return names
} }
func fromSlash(filenames []string) []string {
for i, name := range filenames {
filenames[i] = filepath.FromSlash(name)
}
return filenames
}
func sortFileInfos(fis []os.FileInfo) { func sortFileInfos(fis []os.FileInfo) {
sort.Slice(fis, func(i, j int) bool { sort.Slice(fis, func(i, j int) bool {
fimi, fimj := fis[i].(FileMetaInfo), fis[j].(FileMetaInfo) fimi, fimj := fis[i].(FileMetaInfo), fis[j].(FileMetaInfo)

View file

@ -23,9 +23,7 @@ import (
"github.com/spf13/afero" "github.com/spf13/afero"
) )
var ( var _ FilesystemUnwrapper = (*filenameFilterFs)(nil)
_ FilesystemUnwrapper = (*filenameFilterFs)(nil)
)
func newFilenameFilterFs(fs afero.Fs, base string, filter *glob.FilenameFilter) afero.Fs { func newFilenameFilterFs(fs afero.Fs, base string, filter *glob.FilenameFilter) afero.Fs {
return &filenameFilterFs{ return &filenameFilterFs{
@ -93,12 +91,6 @@ func (fs *filenameFilterFs) Stat(name string) (os.FileInfo, error) {
return fi, err return fi, err
} }
func (fs *filenameFilterFs) getOpener(name string) func() (afero.File, error) {
return func() (afero.File, error) {
return fs.Open(name)
}
}
type filenameFilterDir struct { type filenameFilterDir struct {
afero.File afero.File
base string base string
@ -162,9 +154,11 @@ func (fs *filenameFilterFs) RemoveAll(p string) error {
func (fs *filenameFilterFs) Rename(o, n string) error { func (fs *filenameFilterFs) Rename(o, n string) error {
return syscall.EPERM return syscall.EPERM
} }
func (fs *filenameFilterFs) Create(n string) (afero.File, error) { func (fs *filenameFilterFs) Create(n string) (afero.File, error) {
return nil, syscall.EPERM return nil, syscall.EPERM
} }
func (fs *filenameFilterFs) Name() string { func (fs *filenameFilterFs) Name() string {
return "FinameFilterFS" return "FinameFilterFS"
} }

View file

@ -60,14 +60,7 @@ type Fs struct {
WorkingDirWritable afero.Fs WorkingDirWritable afero.Fs
} }
// NewDefault creates a new Fs with the OS file system func NewDefault(cfg config.Provider) *Fs {
// as source and destination file systems.
func NewDefault(conf config.BaseConfig) *Fs {
fs := Os
return NewFrom(fs, conf)
}
func NewDefaultOld(cfg config.Provider) *Fs {
workingDir, publishDir := getWorkingPublishDir(cfg) workingDir, publishDir := getWorkingPublishDir(cfg)
fs := Os fs := Os
return newFs(fs, fs, workingDir, publishDir) return newFs(fs, fs, workingDir, publishDir)
@ -99,7 +92,6 @@ func getWorkingPublishDir(cfg config.Provider) (string, string) {
publishDir = cfg.GetString("publishDir") publishDir = cfg.GetString("publishDir")
} }
return workingDir, publishDir return workingDir, publishDir
} }
func newFs(source, destination afero.Fs, workingDir, publishDir string) *Fs { func newFs(source, destination afero.Fs, workingDir, publishDir string) *Fs {
@ -166,7 +158,7 @@ func MakeReadableAndRemoveAllModulePkgDir(fs afero.Fs, dir string) (int, error)
} }
if info.IsDir() { if info.IsDir() {
counter++ counter++
fs.Chmod(path, 0777) fs.Chmod(path, 0o777)
} }
return nil return nil
}) })
@ -217,7 +209,6 @@ func WalkFilesystems(fs afero.Fs, fn WalkFn) bool {
if WalkFilesystems(afs.UnwrapFilesystem(), fn) { if WalkFilesystems(afs.UnwrapFilesystem(), fn) {
return true return true
} }
} else if bfs, ok := fs.(FilesystemsUnwrapper); ok { } else if bfs, ok := fs.(FilesystemsUnwrapper); ok {
for _, sf := range bfs.UnwrapFilesystems() { for _, sf := range bfs.UnwrapFilesystems() {
if WalkFilesystems(sf, fn) { if WalkFilesystems(sf, fn) {

View file

@ -30,7 +30,6 @@ func TestIsOsFs(t *testing.T) {
c.Assert(IsOsFs(&afero.MemMapFs{}), qt.Equals, false) c.Assert(IsOsFs(&afero.MemMapFs{}), qt.Equals, false)
c.Assert(IsOsFs(afero.NewBasePathFs(&afero.MemMapFs{}, "/public")), qt.Equals, false) c.Assert(IsOsFs(afero.NewBasePathFs(&afero.MemMapFs{}, "/public")), qt.Equals, false)
c.Assert(IsOsFs(afero.NewBasePathFs(Os, t.TempDir())), qt.Equals, true) c.Assert(IsOsFs(afero.NewBasePathFs(Os, t.TempDir())), qt.Equals, true)
} }
func TestNewDefault(t *testing.T) { func TestNewDefault(t *testing.T) {
@ -38,7 +37,7 @@ func TestNewDefault(t *testing.T) {
v := config.New() v := config.New()
v.Set("workingDir", t.TempDir()) v.Set("workingDir", t.TempDir())
v.Set("publishDir", "public") v.Set("publishDir", "public")
f := NewDefaultOld(v) f := NewDefault(v)
c.Assert(f.Source, qt.IsNotNil) c.Assert(f.Source, qt.IsNotNil)
c.Assert(f.Source, hqt.IsSameType, new(afero.OsFs)) c.Assert(f.Source, hqt.IsSameType, new(afero.OsFs))

View file

@ -57,7 +57,6 @@ var filePathSeparator = string(filepath.Separator)
// to underline that even if they can be composites, they all have a base path set to a specific // to underline that even if they can be composites, they all have a base path set to a specific
// resource folder, e.g "/my-project/content". So, no absolute filenames needed. // resource folder, e.g "/my-project/content". So, no absolute filenames needed.
type BaseFs struct { type BaseFs struct {
// SourceFilesystems contains the different source file systems. // SourceFilesystems contains the different source file systems.
*SourceFilesystems *SourceFilesystems
@ -180,7 +179,6 @@ func (b *BaseFs) AbsProjectContentDir(filename string) (string, string, error) {
return filename, filepath.Join(meta.Filename, filename), nil return filename, filepath.Join(meta.Filename, filename), nil
} }
} }
} }
return "", "", fmt.Errorf("could not determine content directory for %q", filename) return "", "", fmt.Errorf("could not determine content directory for %q", filename)
@ -301,7 +299,6 @@ func (s SourceFilesystems) ContentStaticAssetFs(lang string) afero.Fs {
}, },
}, },
) )
} }
// StaticFs returns the static filesystem for the given language. // StaticFs returns the static filesystem for the given language.
@ -666,8 +663,8 @@ func (b *sourceFilesystemsBuilder) isStaticMount(mnt modules.Mount) bool {
func (b *sourceFilesystemsBuilder) createOverlayFs( func (b *sourceFilesystemsBuilder) createOverlayFs(
collector *filesystemsCollector, collector *filesystemsCollector,
mounts []mountsDescriptor) error { mounts []mountsDescriptor,
) error {
if len(mounts) == 0 { if len(mounts) == 0 {
appendNopIfEmpty := func(ofs *overlayfs.OverlayFs) *overlayfs.OverlayFs { appendNopIfEmpty := func(ofs *overlayfs.OverlayFs) *overlayfs.OverlayFs {
if ofs.NumFilesystems() > 0 { if ofs.NumFilesystems() > 0 {
@ -857,13 +854,6 @@ func (c *filesystemsCollector) addDir(rfs *hugofs.RootMappingFs, componentFolder
} }
} }
func (c *filesystemsCollector) reverseFis(fis []hugofs.FileMetaInfo) {
for i := len(fis)/2 - 1; i >= 0; i-- {
opp := len(fis) - 1 - i
fis[i], fis[opp] = fis[opp], fis[i]
}
}
type mountsDescriptor struct { type mountsDescriptor struct {
modules.Module modules.Module
dir string dir string

View file

@ -63,11 +63,11 @@ path="github.com/gohugoio/hugoTestModule2"
b := newTestSitesBuilder(t) b := newTestSitesBuilder(t)
tempDir := t.TempDir() tempDir := t.TempDir()
workingDir := filepath.Join(tempDir, "myhugosite") workingDir := filepath.Join(tempDir, "myhugosite")
b.Assert(os.MkdirAll(workingDir, 0777), qt.IsNil) b.Assert(os.MkdirAll(workingDir, 0o777), qt.IsNil)
cfg := config.New() cfg := config.New()
cfg.Set("workingDir", workingDir) cfg.Set("workingDir", workingDir)
cfg.Set("publishDir", "public") cfg.Set("publishDir", "public")
b.Fs = hugofs.NewDefaultOld(cfg) b.Fs = hugofs.NewDefault(cfg)
b.WithWorkingDir(workingDir).WithConfigFile("toml", createConfig(workingDir, moduleOpts)) b.WithWorkingDir(workingDir).WithConfigFile("toml", createConfig(workingDir, moduleOpts))
b.WithTemplates( b.WithTemplates(
"index.html", ` "index.html", `
@ -352,7 +352,7 @@ ignoreVendorPaths = %q
b := newTestSitesBuilder(t) b := newTestSitesBuilder(t)
// Need to use OS fs for this. // Need to use OS fs for this.
b.Fs = hugofs.NewDefaultOld(v) b.Fs = hugofs.NewDefault(v)
b.WithWorkingDir(workingDir).WithConfigFile("toml", config) b.WithWorkingDir(workingDir).WithConfigFile("toml", config)
b.WithContent("page.md", ` b.WithContent("page.md", `
@ -683,11 +683,11 @@ Data: {{ .Site.Data }}
createDirsAndFiles := func(baseDir string) { createDirsAndFiles := func(baseDir string) {
for _, dir := range files.ComponentFolders { for _, dir := range files.ComponentFolders {
realDir := filepath.Join(baseDir, dir, "real") realDir := filepath.Join(baseDir, dir, "real")
c.Assert(os.MkdirAll(realDir, 0777), qt.IsNil) c.Assert(os.MkdirAll(realDir, 0o777), qt.IsNil)
c.Assert(afero.WriteFile(fs.Source, filepath.Join(realDir, "data.toml"), []byte("[hello]\nother = \"hello\""), 0777), qt.IsNil) c.Assert(afero.WriteFile(fs.Source, filepath.Join(realDir, "data.toml"), []byte("[hello]\nother = \"hello\""), 0o777), qt.IsNil)
} }
c.Assert(afero.WriteFile(fs.Source, filepath.Join(baseDir, "layouts", "index.html"), []byte(homeTemplate), 0777), qt.IsNil) c.Assert(afero.WriteFile(fs.Source, filepath.Join(baseDir, "layouts", "index.html"), []byte(homeTemplate), 0o777), qt.IsNil)
} }
// Create project dirs and files. // Create project dirs and files.
@ -849,7 +849,7 @@ workingDir = %q
cfg.Set("workingDir", workingDir) cfg.Set("workingDir", workingDir)
cfg.Set("publishDir", "public") cfg.Set("publishDir", "public")
b.Fs = hugofs.NewDefaultOld(cfg) b.Fs = hugofs.NewDefault(cfg)
b.WithWorkingDir(workingDir).WithConfigFile("toml", tomlConfig) b.WithWorkingDir(workingDir).WithConfigFile("toml", tomlConfig)
b.WithTemplatesAdded("index.html", ` b.WithTemplatesAdded("index.html", `
@ -877,8 +877,8 @@ workingDir = %q
<a href="{{ $link | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}{{ if $isRemote }} target="_blank"{{ end }}>{{ .Text | safeHTML }}</a> <a href="{{ $link | safeURL }}"{{ with .Title}} title="{{ . }}"{{ end }}{{ if $isRemote }} target="_blank"{{ end }}>{{ .Text | safeHTML }}</a>
`) `)
os.Mkdir(filepath.Join(workingDir, "mycontent"), 0777) os.Mkdir(filepath.Join(workingDir, "mycontent"), 0o777)
os.Mkdir(filepath.Join(workingDir, "mycontent", "mybundle"), 0777) os.Mkdir(filepath.Join(workingDir, "mycontent", "mybundle"), 0o777)
b.WithSourceFile("README.md", `--- b.WithSourceFile("README.md", `---
title: "Readme Title" title: "Readme Title"
@ -974,9 +974,9 @@ workingDir = %q
cfg := config.New() cfg := config.New()
cfg.Set("workingDir", workingDir) cfg.Set("workingDir", workingDir)
cfg.Set("publishDir", "public") cfg.Set("publishDir", "public")
b.Fs = hugofs.NewDefaultOld(cfg) b.Fs = hugofs.NewDefault(cfg)
os.MkdirAll(filepath.Join(workingDir, "content", "blog"), 0777) os.MkdirAll(filepath.Join(workingDir, "content", "blog"), 0o777)
b.WithWorkingDir(workingDir).WithConfigFile("toml", tomlConfig) b.WithWorkingDir(workingDir).WithConfigFile("toml", tomlConfig)
@ -1034,12 +1034,12 @@ title: P1
defer test.clean() defer test.clean()
subContentDir := filepath.Join(test.workingDir, "mycontent", "sub") subContentDir := filepath.Join(test.workingDir, "mycontent", "sub")
os.MkdirAll(subContentDir, 0777) os.MkdirAll(subContentDir, 0o777)
myPartialsDir := filepath.Join(test.workingDir, "subdir", "mypartials") myPartialsDir := filepath.Join(test.workingDir, "subdir", "mypartials")
os.MkdirAll(myPartialsDir, 0777) os.MkdirAll(myPartialsDir, 0o777)
absShortcodesDir := filepath.Join(absDir, "abs", "myshortcodes") absShortcodesDir := filepath.Join(absDir, "abs", "myshortcodes")
os.MkdirAll(absShortcodesDir, 0777) os.MkdirAll(absShortcodesDir, 0o777)
b.WithSourceFile("README.md", "---\ntitle: Readme\n---") b.WithSourceFile("README.md", "---\ntitle: Readme\n---")
b.WithSourceFile("mycontent/sub/p1.md", "---\ntitle: P1\n---") b.WithSourceFile("mycontent/sub/p1.md", "---\ntitle: P1\n---")
@ -1128,7 +1128,7 @@ title: Abs
--- ---
Content. Content.
`), 0777) `), 0o777)
b.WithWorkingDir(workDir).WithConfigFile("toml", config) b.WithWorkingDir(workDir).WithConfigFile("toml", config)
b.WithContent("dummy.md", "") b.WithContent("dummy.md", "")

View file

@ -50,7 +50,6 @@ import (
"github.com/gohugoio/hugo/resources/kinds" "github.com/gohugoio/hugo/resources/kinds"
"github.com/gohugoio/hugo/resources/page" "github.com/gohugoio/hugo/resources/page"
"github.com/gohugoio/hugo/resources/page/pagemeta" "github.com/gohugoio/hugo/resources/page/pagemeta"
"github.com/gohugoio/hugo/tpl"
) )
// HugoSites represents the sites to build. Each site represents a language. // HugoSites represents the sites to build. Each site represents a language.
@ -319,21 +318,6 @@ func (h *HugoSites) loadGitInfo() error {
return nil return nil
} }
func (s *Site) withSiteTemplates(withTemplates ...func(templ tpl.TemplateManager) error) func(templ tpl.TemplateManager) error {
return func(templ tpl.TemplateManager) error {
for _, wt := range withTemplates {
if wt == nil {
continue
}
if err := wt(templ); err != nil {
return err
}
}
return nil
}
}
// Reset resets the sites and template caches etc., making it ready for a full rebuild. // Reset resets the sites and template caches etc., making it ready for a full rebuild.
func (h *HugoSites) reset(config *BuildCfg) { func (h *HugoSites) reset(config *BuildCfg) {
if config.ResetState { if config.ResetState {
@ -659,7 +643,6 @@ func (h *HugoSites) errWithFileContext(err error, f source.File) error {
realFilename := fim.Meta().Filename realFilename := fim.Meta().Filename
return herrors.NewFileErrorFromFile(err, realFilename, h.SourceSpec.Fs.Source, nil) return herrors.NewFileErrorFromFile(err, realFilename, h.SourceSpec.Fs.Source, nil)
} }
func (h *HugoSites) readData(f source.File) (any, error) { func (h *HugoSites) readData(f source.File) (any, error) {

View file

@ -851,10 +851,6 @@ func (p *pageState) pathOrTitle() string {
return p.Title() return p.Title()
} }
func (p *pageState) posFromPage(offset int) text.Position {
return p.posFromInput(p.source.parsed.Input(), offset)
}
func (p *pageState) posFromInput(input []byte, offset int) text.Position { func (p *pageState) posFromInput(input []byte, offset int) text.Position {
if offset < 0 { if offset < 0 {
return text.Position{ return text.Position{

View file

@ -484,10 +484,6 @@ func doRenderShortcode(
return prerenderedShortcode{s: result, hasVariants: hasVariants}, err return prerenderedShortcode{s: result, hasVariants: hasVariants}, err
} }
func (s *shortcodeHandler) hasShortcodes() bool {
return s != nil && len(s.shortcodes) > 0
}
func (s *shortcodeHandler) addName(name string) { func (s *shortcodeHandler) addName(name string) {
s.nameSetMu.Lock() s.nameSetMu.Lock()
defer s.nameSetMu.Unlock() defer s.nameSetMu.Unlock()
@ -529,13 +525,6 @@ func (s *shortcodeHandler) prepareShortcodesForPage(ctx context.Context, p *page
return rendered, nil return rendered, nil
} }
func (s *shortcodeHandler) parseError(err error, input []byte, pos int) error {
if s.p != nil {
return s.p.parseError(err, input, pos)
}
return err
}
// pageTokens state: // pageTokens state:
// - before: positioned just before the shortcode start // - before: positioned just before the shortcode start
// - after: shortcode(s) consumed (plural when they are nested) // - after: shortcode(s) consumed (plural when they are nested)

View file

@ -16,7 +16,6 @@ package hugolib
import ( import (
"fmt" "fmt"
"path/filepath" "path/filepath"
"strings"
"testing" "testing"
"github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config"
@ -636,10 +635,6 @@ func collectIdentities(set map[identity.Identity]bool, provider identity.Provide
} }
} }
func ident(level int) string {
return strings.Repeat(" ", level)
}
func TestPartialInline(t *testing.T) { func TestPartialInline(t *testing.T) {
b := newTestSitesBuilder(t) b := newTestSitesBuilder(t)

View file

@ -43,7 +43,6 @@ import (
"github.com/spf13/cast" "github.com/spf13/cast"
"github.com/gohugoio/hugo/helpers" "github.com/gohugoio/hugo/helpers"
"github.com/gohugoio/hugo/tpl"
"github.com/gohugoio/hugo/resources/resource" "github.com/gohugoio/hugo/resources/resource"
@ -522,7 +521,7 @@ func (s *sitesBuilder) CreateSitesE() error {
"data", "data",
"i18n", "i18n",
} { } {
if err := os.MkdirAll(filepath.Join(s.workingDir, dir), 0777); err != nil { if err := os.MkdirAll(filepath.Join(s.workingDir, dir), 0o777); err != nil {
return fmt.Errorf("failed to create %q: %w", dir, err) return fmt.Errorf("failed to create %q: %w", dir, err)
} }
} }
@ -555,7 +554,6 @@ func (s *sitesBuilder) CreateSitesE() error {
depsCfg.TestLogger = s.logger depsCfg.TestLogger = s.logger
sites, err := NewHugoSites(depsCfg) sites, err := NewHugoSites(depsCfg)
if err != nil { if err != nil {
return fmt.Errorf("failed to create sites: %w", err) return fmt.Errorf("failed to create sites: %w", err)
} }
@ -878,20 +876,6 @@ func (th testHelper) assertFileContent(filename string, matches ...string) {
} }
} }
func (th testHelper) assertFileContentRegexp(filename string, matches ...string) {
filename = th.replaceDefaultContentLanguageValue(filename)
content := readWorkingDir(th, th.Fs, filename)
for _, match := range matches {
match = th.replaceDefaultContentLanguageValue(match)
r := regexp.MustCompile(match)
matches := r.MatchString(content)
if !matches {
fmt.Println("Expected to match regexp:\n"+match+"\nGot:\n", content)
}
th.Assert(matches, qt.Equals, true)
}
}
func (th testHelper) assertFileNotExist(filename string) { func (th testHelper) assertFileNotExist(filename string) {
exists, err := helpers.Exists(filename, th.Fs.PublishDir) exists, err := helpers.Exists(filename, th.Fs.PublishDir)
th.Assert(err, qt.IsNil) th.Assert(err, qt.IsNil)
@ -908,16 +892,11 @@ func (th testHelper) replaceDefaultContentLanguageValue(value string) string {
return value return value
} }
func loadTestConfig(fs afero.Fs) (*allconfig.Configs, error) {
res, err := allconfig.LoadConfig(allconfig.ConfigSourceDescriptor{Fs: fs})
return res, err
}
func loadTestConfigFromProvider(cfg config.Provider) (*allconfig.Configs, error) { func loadTestConfigFromProvider(cfg config.Provider) (*allconfig.Configs, error) {
workingDir := cfg.GetString("workingDir") workingDir := cfg.GetString("workingDir")
fs := afero.NewMemMapFs() fs := afero.NewMemMapFs()
if workingDir != "" { if workingDir != "" {
fs.MkdirAll(workingDir, 0755) fs.MkdirAll(workingDir, 0o755)
} }
res, err := allconfig.LoadConfig(allconfig.ConfigSourceDescriptor{Flags: cfg, Fs: fs}) res, err := allconfig.LoadConfig(allconfig.ConfigSourceDescriptor{Flags: cfg, Fs: fs})
return res, err return res, err
@ -972,18 +951,6 @@ func newTestSitesFromConfig(t testing.TB, afs afero.Fs, tomlConfig string, layou
return th, h return th, h
} }
func createWithTemplateFromNameValues(additionalTemplates ...string) func(templ tpl.TemplateManager) error {
return func(templ tpl.TemplateManager) error {
for i := 0; i < len(additionalTemplates); i += 2 {
err := templ.AddTemplate(additionalTemplates[i], additionalTemplates[i+1])
if err != nil {
return err
}
}
return nil
}
}
// TODO(bep) replace these with the builder // TODO(bep) replace these with the builder
func buildSingleSite(t testing.TB, depsCfg deps.DepsCfg, buildCfg BuildCfg) *Site { func buildSingleSite(t testing.TB, depsCfg deps.DepsCfg, buildCfg BuildCfg) *Site {
t.Helper() t.Helper()

View file

@ -113,12 +113,6 @@ func ForceRefresh() {
RefreshPath("/x.js") RefreshPath("/x.js")
} }
// NavigateToPath tells livereload to navigate to the given path.
// This translates to `window.location.href = path` in the client.
func NavigateToPath(path string) {
RefreshPath(hugoNavigatePrefix + path)
}
// NavigateToPathForPort is similar to NavigateToPath but will also // NavigateToPathForPort is similar to NavigateToPath but will also
// set window.location.port to the given port value. // set window.location.port to the given port value.
func NavigateToPathForPort(path string, port int) { func NavigateToPathForPort(path string, port int) {

View file

@ -1,11 +1,9 @@
package images package images
import ( import (
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/ast" "github.com/yuin/goldmark/ast"
"github.com/yuin/goldmark/parser" "github.com/yuin/goldmark/parser"
"github.com/yuin/goldmark/text" "github.com/yuin/goldmark/text"
"github.com/yuin/goldmark/util"
) )
type ( type (
@ -20,18 +18,6 @@ const (
AttrIsBlock = "_h__isBlock" AttrIsBlock = "_h__isBlock"
) )
func New(wrapStandAloneImageWithinParagraph bool) goldmark.Extender {
return &linksExtension{wrapStandAloneImageWithinParagraph: wrapStandAloneImageWithinParagraph}
}
func (e *linksExtension) Extend(m goldmark.Markdown) {
m.Parser().AddOptions(
parser.WithASTTransformers(
util.Prioritized(&Transformer{wrapStandAloneImageWithinParagraph: e.wrapStandAloneImageWithinParagraph}, 300),
),
)
}
type Transformer struct { type Transformer struct {
wrapStandAloneImageWithinParagraph bool wrapStandAloneImageWithinParagraph bool
} }
@ -67,7 +53,5 @@ func (t *Transformer) Transform(doc *ast.Document, reader text.Reader, pctx pars
} }
return ast.WalkContinue, nil return ast.WalkContinue, nil
}) })
} }

View file

@ -232,7 +232,6 @@ func highlight(fw hugio.FlexiWriter, code, lang string, attributes []attributes.
return `` return ``
}, },
} }
} else { } else {
wrapper = getPreWrapper(lang, w) wrapper = getPreWrapper(lang, w)
} }
@ -314,10 +313,6 @@ func (s startEnd) End(code bool) string {
return s.end(code) return s.end(code)
} }
func WritePreEnd(w io.Writer) {
fmt.Fprint(w, preEnd)
}
func writeDivStart(w hugio.FlexiWriter, attrs []attributes.Attribute) { func writeDivStart(w hugio.FlexiWriter, attrs []attributes.Attribute) {
w.WriteString(`<div class="highlight`) w.WriteString(`<div class="highlight`)
if attrs != nil { if attrs != nil {

View file

@ -31,7 +31,6 @@ import (
var DefaultTypes Types var DefaultTypes Types
func init() { func init() {
ns, err := DecodeTypes(nil) ns, err := DecodeTypes(nil)
if err != nil { if err != nil {
panic(err) panic(err)
@ -61,7 +60,6 @@ type MediaTypeConfig struct {
// DecodeTypes decodes the given map of media types. // DecodeTypes decodes the given map of media types.
func DecodeTypes(in map[string]any) (*config.ConfigNamespace[map[string]MediaTypeConfig, Types], error) { func DecodeTypes(in map[string]any) (*config.ConfigNamespace[map[string]MediaTypeConfig, Types], error) {
buildConfig := func(v any) (Types, any, error) { buildConfig := func(v any) (Types, any, error) {
m, err := maps.ToStringMapE(v) m, err := maps.ToStringMapE(v)
if err != nil { if err != nil {
@ -106,34 +104,4 @@ func DecodeTypes(in map[string]any) (*config.ConfigNamespace[map[string]MediaTyp
return nil, fmt.Errorf("failed to decode media types: %w", err) return nil, fmt.Errorf("failed to decode media types: %w", err)
} }
return ns, nil return ns, nil
}
func suffixIsRemoved() error {
return errors.New(`MediaType.Suffix is removed. Before Hugo 0.44 this was used both to set a custom file suffix and as way
to augment the mediatype definition (what you see after the "+", e.g. "image/svg+xml").
This had its limitations. For one, it was only possible with one file extension per MIME type.
Now you can specify multiple file suffixes using "suffixes", but you need to specify the full MIME type
identifier:
[mediaTypes]
[mediaTypes."image/svg+xml"]
suffixes = ["svg", "abc" ]
In most cases, it will be enough to just change:
[mediaTypes]
[mediaTypes."my/custom-mediatype"]
suffix = "txt"
To:
[mediaTypes]
[mediaTypes."my/custom-mediatype"]
suffixes = ["txt"]
Note that you can still get the Media Type's suffix from a template: {{ $mediaType.Suffix }}. But this will now map to the MIME type filename.
`)
} }

View file

@ -15,6 +15,7 @@ package modules
import ( import (
"bufio" "bufio"
"errors"
"fmt" "fmt"
"os" "os"
"path/filepath" "path/filepath"
@ -37,8 +38,6 @@ import (
"github.com/rogpeppe/go-internal/module" "github.com/rogpeppe/go-internal/module"
"errors"
"github.com/gohugoio/hugo/config" "github.com/gohugoio/hugo/config"
"github.com/spf13/afero" "github.com/spf13/afero"
) )
@ -47,11 +46,6 @@ var ErrNotExist = errors.New("module does not exist")
const vendorModulesFilename = "modules.txt" const vendorModulesFilename = "modules.txt"
// IsNotExist returns whether an error means that a module could not be found.
func IsNotExist(err error) bool {
return errors.Is(err, os.ErrNotExist)
}
func (h *Client) Collect() (ModulesConfig, error) { func (h *Client) Collect() (ModulesConfig, error) {
mc, coll := h.collect(true) mc, coll := h.collect(true)
if coll.err != nil { if coll.err != nil {
@ -124,7 +118,6 @@ func (m ModulesConfig) HasConfigFile() bool {
if len(mod.ConfigFilenames()) > 0 { if len(mod.ConfigFilenames()) > 0 {
return true return true
} }
} }
return false return false
} }
@ -220,7 +213,6 @@ func (c *collector) getVendoredDir(path string) (vendoredModule, bool) {
} }
func (c *collector) add(owner *moduleAdapter, moduleImport Import) (*moduleAdapter, error) { func (c *collector) add(owner *moduleAdapter, moduleImport Import) (*moduleAdapter, error) {
var ( var (
mod *goModule mod *goModule
moduleDir string moduleDir string
@ -669,7 +661,6 @@ func (c *collector) normalizeMounts(owner *moduleAdapter, mounts []Mount) ([]Mou
} else { } else {
continue continue
} }
} }
// Verify that target points to one of the predefined component dirs // Verify that target points to one of the predefined component dirs

View file

@ -424,16 +424,6 @@ func (i *imageResource) doWithImageConfig(conf images.ImageConfig, f func(src im
return img, nil return img, nil
} }
func (i *imageResource) decodeImageConfig(action, spec string) (images.ImageConfig, error) {
options := strings.Fields(spec)
conf, err := images.DecodeImageConfig(action, options, i.Proc.Cfg, i.Format)
if err != nil {
return conf, err
}
return conf, nil
}
type giphy struct { type giphy struct {
image.Image image.Image
gif *gif.GIF gif *gif.GIF

View file

@ -66,7 +66,6 @@ type ResourceError interface {
// ErrProvider provides an Err. // ErrProvider provides an Err.
type ErrProvider interface { type ErrProvider interface {
// Err returns an error if this resource is in an error state. // Err returns an error if this resource is in an error state.
// This will currently only be set for resources obtained from resources.GetRemote. // This will currently only be set for resources obtained from resources.GetRemote.
Err() ResourceError Err() ResourceError
@ -215,15 +214,3 @@ func (r resourceTypesHolder) ResourceType() string {
func NewResourceTypesProvider(mediaType media.Type, resourceType string) ResourceTypesProvider { func NewResourceTypesProvider(mediaType media.Type, resourceType string) ResourceTypesProvider {
return resourceTypesHolder{mediaType: mediaType, resourceType: resourceType} return resourceTypesHolder{mediaType: mediaType, resourceType: resourceType}
} }
type languageHolder struct {
lang *langs.Language
}
func (l languageHolder) Language() *langs.Language {
return l.lang
}
func NewLanguageProvider(lang *langs.Language) LanguageProvider {
return languageHolder{lang: lang}
}

View file

@ -65,7 +65,6 @@ func responseToData(res *http.Response, readBody bool) map[string]any {
} }
return m return m
} }
func toHTTPError(err error, res *http.Response, readBody bool) *HTTPError { func toHTTPError(err error, res *http.Response, readBody bool) *HTTPError {
@ -141,7 +140,6 @@ func (c *Client) FromRemote(uri string, optionsm map[string]any) (resource.Resou
if res.StatusCode != http.StatusNotFound { if res.StatusCode != http.StatusNotFound {
if res.StatusCode < 200 || res.StatusCode > 299 { if res.StatusCode < 200 || res.StatusCode > 299 {
return nil, temporaryHTTPStatusCodes[res.StatusCode], toHTTPError(fmt.Errorf("failed to fetch remote resource: %s", http.StatusText(res.StatusCode)), res, !isHeadMethod) return nil, temporaryHTTPStatusCodes[res.StatusCode], toHTTPError(fmt.Errorf("failed to fetch remote resource: %s", http.StatusText(res.StatusCode)), res, !isHeadMethod)
} }
} }
@ -151,9 +149,7 @@ func (c *Client) FromRemote(uri string, optionsm map[string]any) (resource.Resou
} }
return b, false, nil return b, false, nil
}() }()
if err != nil { if err != nil {
if retry { if retry {
if start.IsZero() { if start.IsZero() {
@ -174,7 +170,6 @@ func (c *Client) FromRemote(uri string, optionsm map[string]any) (resource.Resou
return hugio.ToReadCloser(bytes.NewReader(b)), nil return hugio.ToReadCloser(bytes.NewReader(b)), nil
} }
}) })
if err != nil { if err != nil {
return nil, err return nil, err
@ -307,22 +302,6 @@ func addUserProvidedHeaders(headers map[string]any, req *http.Request) {
} }
} }
func hasHeaderValue(m http.Header, key, value string) bool {
var s []string
var ok bool
if s, ok = m[key]; !ok {
return false
}
for _, v := range s {
if v == value {
return true
}
}
return false
}
func hasHeaderKey(m http.Header, key string) bool { func hasHeaderKey(m http.Header, key string) bool {
_, ok := m[key] _, ok := m[key]
return ok return ok

View file

@ -129,21 +129,6 @@ type TemplatesProvider interface {
TextTmpl() TemplateParseFinder TextTmpl() TemplateParseFinder
} }
// WithInfo wraps the info in a template.
func WithInfo(templ Template, info Info) Template {
if manager, ok := info.(InfoManager); ok {
return &templateInfoManager{
Template: templ,
InfoManager: manager,
}
}
return &templateInfo{
Template: templ,
Info: info,
}
}
var baseOfRe = regexp.MustCompile("template: (.*?):") var baseOfRe = regexp.MustCompile("template: (.*?):")
func extractBaseOf(err string) string { func extractBaseOf(err string) string {
@ -173,17 +158,6 @@ type page interface {
IsNode() bool IsNode() bool
} }
func GetHasLockFromContext(ctx context.Context) bool {
if v := ctx.Value(texttemplate.HasLockContextKey); v != nil {
return v.(bool)
}
return false
}
func SetHasLockInContext(ctx context.Context, hasLock bool) context.Context {
return context.WithValue(ctx, texttemplate.HasLockContextKey, hasLock)
}
func GetCallbackFunctionFromContext(ctx context.Context) any { func GetCallbackFunctionFromContext(ctx context.Context) any {
return ctx.Value(texttemplate.CallbackContextKey) return ctx.Value(texttemplate.CallbackContextKey)
} }

View file

@ -39,22 +39,6 @@ type InfoManager interface {
identity.Manager identity.Manager
} }
type defaultInfo struct {
identity.Manager
parseInfo ParseInfo
}
func NewInfo(id identity.Manager, parseInfo ParseInfo) Info {
return &defaultInfo{
Manager: id,
parseInfo: parseInfo,
}
}
func (info *defaultInfo) ParseInfo() ParseInfo {
return info.parseInfo
}
type ParseInfo struct { type ParseInfo struct {
// Set for shortcode templates with any {{ .Inner }} // Set for shortcode templates with any {{ .Inner }}
IsInner bool IsInner bool

1
unused.sh Executable file
View file

@ -0,0 +1 @@
deadcode -test ./... | grep -v go_templ