import "github.com/gohugoio/hugo/helpers"
Package helpers implements general utility functions that work with and on content. The helper functions defined here lay down the foundation of how Hugo works with files and filepaths, and perform string operations on content.
content.go docshelper.go emoji.go general.go path.go pathspec.go processing_stats.go url.go
FilePathSeparator as defined by os.Separator.
var ( // DistinctErrorLog can be used to avoid spamming the logs with errors. DistinctErrorLog = NewDistinctErrorLogger() // DistinctWarnLog can be used to avoid spamming the logs with warnings. DistinctWarnLog = NewDistinctWarnLogger() // DistinctFeedbackLog can be used to avoid spamming the logs with info messages. DistinctFeedbackLog = NewDistinctFeedbackLogger() )
ErrThemeUndefined is returned when a theme has not be defined by the user.
SummaryDivider denotes where content summarization should end. The default is "<!--more-->".
AddContextRoot adds the context root to an URL if it's not already set. For relative URL entries on sites with a base url with a context root set (i.e. http://example.com/mysite), relative URLs must not include the context root if canonifyURLs is enabled. But if it's disabled, it must be set.
AddTrailingSlash adds a trailing Unix styled slash (/) if not already there.
BytesToHTML converts bytes to type template.HTML.
Deprecated informs about a deprecation, but only once for a given set of arguments' values. If the err flag is enabled, it logs as an ERROR (will exit with -1) and the text will point at the next Hugo release. The idea is two remove an item in two Hugo releases to give users and theme authors plenty of time to fix their templates.
DirExists checks if a path exists and is a directory.
Emoji returns the emojy given a key, e.g. ":smile:", nil if not found.
Emojify "emojifies" the input source. Note that the input byte slice will be modified if needed. See http://www.emoji-cheat-sheet.com/
Exists checks if a file or directory exists.
Ext takes a path and returns the extension, including the delimiter, i.e. ".md".
ExtNoDelimiter takes a path and returns the extension, excluding the delimiter, i.e. "md".
ExtractRootPaths extracts the root paths from the supplied list of paths. The resulting root path will not contain any file separators, but there may be duplicates. So "/content/section/" becomes "content"
ExtractTOC extracts Table of Contents from content.
FileAndExt takes a path and returns the file and extension separated, the extension including the delimiter, i.e. ".md".
FileAndExtNoDelimiter takes a path and returns the file and extension separated, the extension excluding the delimiter, e.g "md".
FileContains checks if a file contains a specified string.
FileContainsAny checks if a file contains any of the specified strings.
Filename takes a file path, strips out the extension, and returns the name of the file.
FindAvailablePort returns an available and valid TCP port.
FindCWD returns the current working directory from where the Hugo executable is run.
FirstUpper returns a string with the first character as upper case.
GetCacheDir returns a cache dir from the given filesystem and config. The dir will be created if it does not exist.
GetDottedRelativePath expects a relative path starting after the content directory. It returns a relative path with dots ("..") navigating up the path structure.
GetRelativePath returns the relative path of a given path.
GetTempDir returns a temporary directory with the given sub path.
GetTitleFunc returns a func that can be used to transform a string to title case.
- "Go" (strings.Title) - "AP" (see https://www.apstylebook.com/) - "Chicago" (see http://www.chicagomanualofstyle.org/home.html)
If an unknown or empty style is provided, AP style is what you get.
HasStringsPrefix tests whether the string slice s begins with prefix slice s.
HasStringsSuffix tests whether the string slice s ends with suffix slice s.
HashString returns a hash from the given elements. It will panic if the hash cannot be calculated.
InStringArray checks if a string is an element of a slice of strings and returns a boolean value.
func InitLoggers()
InitLoggers resets the global distinct loggers.
IsAbsURL determines whether the given path points to an absolute URL.
IsDir checks if a given path is a directory.
IsEmpty checks if a given path is empty.
IsWhitespace determines if the given rune is whitespace.
LstatIfPossible can be used to call Lstat if possible, else Stat.
func MD5FromFileFast(r io.ReadSeeker) (string, error)
MD5FromFileFast creates a MD5 hash from the given file. It only reads parts of the file for speed, so don't use it if the files are very subtly different. It will not close the file.
MD5FromReader creates a MD5 hash from the given reader.
MD5String takes a string and returns its MD5 hash.
MakePermalink combines base URL with content path to create full URL paths. Example
base: http://spf13.com/ path: post/how-i-blog result: http://spf13.com/post/how-i-blog
MakeTitle converts the path given to a suitable title, trimming whitespace and replacing hyphens with whitespace.
NormalizeHugoFlags facilitates transitions of Hugo command-line flags, e.g. --baseUrl to --baseURL, --uglyUrls to --uglyURLs
OpenFileForWriting opens or creates the given file. If the target directory does not exist, it gets created.
OpenFilesForWriting opens all the given filenames for writing.
PathAndExt is the same as FileAndExt, but it uses the path package.
PathNoExt takes a path, strips out the extension, and returns the name of the file.
PathPrep prepares the path using the uglify setting to create paths on either the form /section/name/index.html or /section/name.html.
PrettifyPath is the same as PrettifyURLPath but for file paths.
/section/name.html becomes /section/name/index.html /section/name/ becomes /section/name/index.html /section/name/index.html becomes /section/name/index.html
PrettifyURL takes a URL string and returns a semantic, clean URL.
PrettifyURLPath takes a URL path to a content and converts it to enable pretty URLs.
/section/name.html becomes /section/name/index.html /section/name/ becomes /section/name/index.html /section/name/index.html becomes /section/name/index.html
PrintFs prints the given filesystem to the given writer starting from the given path. This is useful for debugging.
func ProcessingStatsTable(w io.Writer, stats ...*ProcessingStats)
ProcessingStatsTable writes a table-formatted representation of stats to w.
ReaderContains reports whether subslice is within r.
ReaderToBytes takes an io.Reader argument, reads from it and returns bytes.
ReaderToString is the same as ReaderToBytes, but returns a string.
ReplaceExtension takes a path and an extension, strips the old extension and returns the path with the new extension.
SafeWriteToDisk is the same as WriteToDisk but it also checks to see if file/directory already exists.
SanitizeURL sanitizes the input URL string.
SanitizeURLKeepTrailingSlash is the same as SanitizeURL, but will keep any trailing slash.
SliceToLower goes through the source slice and lowers all values.
StripHTML accepts a string, strips out all HTML tags and returns it.
SymbolicWalk is like filepath.Walk, but it follows symbolic links.
ToSlashTrimLeading is just a filepath.ToSlaas with an added / prefix trimmer.
TotalWords counts instance of one or more consecutive white space characters, as defined by unicode.IsSpace, in s. This is a cheaper way of word counting than the obvious len(strings.Fields(s)).
Uglify does the opposite of PrettifyURLPath().
/section/name/index.html becomes /section/name.html /section/name/ becomes /section/name.html /section/name.html becomes /section/name.html
UniqueStrings returns a new slice with any duplicates removed.
UniqueStringsReuse returns a slice with any duplicates removed. It will modify the input slice.
UniqueStringsReuse returns a sorted slice with any duplicates removed. It will modify the input slice.
WriteToDisk writes content to disk.
type ContentSpec struct { Converters markup.ConverterProvider MardownConverter converter.Converter // Markdown converter with no document context BuildFuture bool BuildExpired bool BuildDrafts bool Cfg config.Provider // contains filtered or unexported fields }
ContentSpec provides functionality to render markdown content.
func NewContentSpec(cfg config.Provider, logger loggers.Logger, contentFs afero.Fs) (*ContentSpec, error)
NewContentSpec returns a ContentSpec initialized with the appropriate fields from the given config.Provider.
func (c *ContentSpec) RenderMarkdown(src []byte) ([]byte, error)
func (c *ContentSpec) ResolveMarkup(in string) string
func (c *ContentSpec) SanitizeAnchorName(s string) string
func (c *ContentSpec) TrimShortHTML(input []byte) []byte
TrimShortHTML removes the <p>/</p> tags from HTML input in the situation where said tags are the only <p> tags in the input and enclose the content of the input (whitespace excluded).
func (c *ContentSpec) TruncateWordsByRune(in []string) (string, bool)
TruncateWordsByRune truncates words by runes.
func (c *ContentSpec) TruncateWordsToWholeSentence(s string) (string, bool)
TruncateWordsToWholeSentence takes content and truncates to whole sentence limited by max number of words. It also returns whether it is truncated.
DistinctLogger ignores duplicate log statements.
func NewDistinctErrorLogger() *DistinctLogger
NewDistinctErrorLogger creates a new DistinctLogger that logs ERRORs
func NewDistinctFeedbackLogger() *DistinctLogger
NewDistinctFeedbackLogger creates a new DistinctLogger that can be used to give feedback to the user while not spamming with duplicates.
func NewDistinctLogger(logger LogPrinter) *DistinctLogger
NewDistinctLogger creates a new DistinctLogger that logs to the provided logger.
func NewDistinctWarnLogger() *DistinctLogger
NewDistinctWarnLogger creates a new DistinctLogger that logs WARNs
func (l *DistinctLogger) Printf(format string, v ...interface{})
Printf will log the string returned from fmt.Sprintf given the arguments, but not if it has been logged before. Note: A newline is appended.
func (l *DistinctLogger) Println(v ...interface{})
Println will log the string returned from fmt.Sprintln given the arguments, but not if it has been logged before.
func (l *DistinctLogger) Reset()
type LogPrinter interface { // Println is the only common method that works in all of JWWs loggers. Println(a ...interface{}) }
LogPrinter is the common interface of the JWWs loggers.
func ExtractAndGroupRootPaths(paths []string) []NamedSlice
func (n NamedSlice) String() string
type PathSpec struct { *paths.Paths *filesystems.BaseFs ProcessingStats *ProcessingStats // The file systems to use Fs *hugofs.Fs // The config provider to use Cfg config.Provider }
PathSpec holds methods that decides how paths in URLs and files in Hugo should look like.
NewPathSpec creates a new PathSpec from the given filesystems and language.
func NewPathSpecWithBaseBaseFsProvided(fs *hugofs.Fs, cfg config.Provider, logger loggers.Logger, baseBaseFs *filesystems.BaseFs) (*PathSpec, error)
NewPathSpecWithBaseBaseFsProvided creats a new PathSpec from the given filesystems and language. If an existing BaseFs is provided, parts of that is reused.
AbsURL creates an absolute URL from the relative path given and the BaseURL set in config.
MakePath takes a string with any characters and replace it so the string could be used in a path. It does so by creating a Unicode-sanitized string, with the spaces replaced, whilst preserving the original casing of the string. E.g. Social Media -> Social-Media
MakePathSanitized creates a Unicode-sanitized string, with the spaces replaced
MakePathsSanitized applies MakePathSanitized on every item in the slice
PermalinkForBaseURL creates a permalink from the given link and baseURL.
PrependBasePath prepends any baseURL sub-folder to the given resource
RelURL creates a URL relative to the BaseURL root. Note: The result URL will not include the context root if canonifyURLs is enabled.
URLEscape escapes unicode letters.
URLPrep applies misc sanitation to the given URL.
URLize is similar to MakePath, but with Unicode handling Example:
uri: Vim (text editor) urlize: vim-text-editor
URLizeAndPrep applies misc sanitation to the given URL to get it in line with the Hugo standard.
URLizeFilename creates an URL from a filename by escaping unicode letters and turn any filepath separator into forward slashes.
UnicodeSanitize sanitizes string to be used in Hugo URL's, allowing only a predefined set of special Unicode characters. If RemovePathAccents configuration flag is enabled, Unicode accents are also removed. Spaces will be replaced with a single hyphen, and sequential hyphens will be reduced to one.
type ProcessingStats struct { Name string Pages uint64 PaginatorPages uint64 Static uint64 ProcessedImages uint64 Files uint64 Aliases uint64 Sitemaps uint64 Cleaned uint64 }
ProcessingStats represents statistics about a site build.
func NewProcessingStats(name string) *ProcessingStats
NewProcessingStats returns a new ProcessingStats instance.
func (s *ProcessingStats) Add(counter *uint64, amount int)
Add adds an amount to a given counter.
func (s *ProcessingStats) Incr(counter *uint64)
Incr increments a given counter.
func (s *ProcessingStats) Table(w io.Writer)
Table writes a table-formatted representation of the stats in a ProcessingStats instance to w.
Package helpers imports 42 packages (graph) and is imported by 846 packages. Updated 2020-12-30. Refresh now. Tools for package owners.