Documentation ¶
Overview ¶
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.
Index ¶
- Constants
- Variables
- func AddContextRoot(baseURL, relativePath string) string
- func BytesToHTML(b []byte) template.HTML
- func CompareVersion(version interface{}) int
- func Deprecated(object, item, alternative string, err bool)
- func DiffStringSlices(slice1 []string, slice2 []string) []string
- func DiffStrings(s1, s2 string) []string
- func DirExists(path string, fs afero.Fs) (bool, error)
- func Emojify(source []byte) []byte
- func Exists(path string, fs afero.Fs) (bool, error)
- func Ext(in string) string
- func ExtNoDelimiter(in string) string
- func ExtractRootPaths(paths []string) []string
- func ExtractTOC(content []byte) (newcontent []byte, toc []byte)
- func FileAndExt(in string) (string, string)
- func FileContains(filename string, subslice []byte, fs afero.Fs) (bool, error)
- func FileContainsAny(filename string, subslices [][]byte, fs afero.Fs) (bool, error)
- func Filename(in string) (name string)
- func FindAvailablePort() (*net.TCPAddr, error)
- func FindCWD() (string, error)
- func FirstUpper(s string) string
- func GetDottedRelativePath(inPath string) string
- func GetRealPath(fs afero.Fs, path string) (string, error)
- func GetRelativePath(path, base string) (final string, err error)
- func GetTempDir(subPath string, fs afero.Fs) string
- func GetTitleFunc(style string) func(s string) string
- func GuessType(in string) string
- func HasAsciidoc() bool
- func HasRst() bool
- func HasStringsPrefix(s, prefix []string) bool
- func HasStringsSuffix(s, suffix []string) bool
- func InStringArray(arr []string, el string) bool
- func InitLoggers()
- func IsAbsURL(path string) bool
- func IsDir(path string, fs afero.Fs) (bool, error)
- func IsEmpty(path string, fs afero.Fs) (bool, error)
- func IsWhitespace(r rune) bool
- func LstatIfPossible(fs afero.Fs, path string) (os.FileInfo, error)
- func MD5FromFile(f afero.File) (string, error)
- func MD5FromFileFast(r io.ReadSeeker) (string, error)
- func MD5String(f string) string
- func MakePermalink(host, plink string) *url.URL
- func MakeTitle(inpath string) string
- func NormalizeHugoFlags(f *pflag.FlagSet, name string) pflag.NormalizedName
- func OpenFileForWriting(fs afero.Fs, filename string) (afero.File, error)
- func OpenFilesForWriting(fs afero.Fs, filenames ...string) (io.WriteCloser, error)
- func PathAndExt(in string) (string, string)
- func PathPrep(ugly bool, in string) string
- func PrettifyPath(in string) string
- func PrettifyURL(in string) string
- func PrettifyURLPath(in string) string
- func PrintFs(fs afero.Fs, path string, w io.Writer)
- func ProcessingStatsTable(w io.Writer, stats ...*ProcessingStats)
- func ReaderContains(r io.Reader, subslice []byte) bool
- func ReaderToBytes(lines io.Reader) []byte
- func ReaderToString(lines io.Reader) string
- func ReplaceExtension(path string, newExt string) string
- func SafeWriteToDisk(inpath string, r io.Reader, fs afero.Fs) (err error)
- func SanitizeURL(in string) string
- func SanitizeURLKeepTrailingSlash(in string) string
- func SliceToLower(s []string) []string
- func StripHTML(s string) string
- func SymbolicWalk(fs afero.Fs, root string, walker filepath.WalkFunc) error
- func ToSlashTrimLeading(s string) string
- func TotalWords(s string) int
- func Uglify(in string) string
- func UniqueStrings(s []string) []string
- func WriteToDisk(inpath string, r io.Reader, fs afero.Fs) (err error)
- type BlackFriday
- type ContentSpec
- type DistinctLogger
- type HugoHTMLRenderer
- type HugoMmarkHTMLRenderer
- type HugoVersion
- type HugoVersionString
- type LogPrinter
- type PathSpec
- func (p *PathSpec) AbsURL(in string, addLanguage bool) string
- func (p *PathSpec) GetFirstThemeDir() string
- func (p *PathSpec) GetRelativeThemeDir() string
- func (p *PathSpec) GetThemesDir() string
- func (p *PathSpec) MakePath(s string) string
- func (p *PathSpec) MakePathSanitized(s string) string
- func (p *PathSpec) PermalinkForBaseURL(link, baseURL string) string
- func (p *PathSpec) PrependBasePath(rel string) string
- func (p *PathSpec) RelURL(in string, addLanguage bool) string
- func (p *PathSpec) URLEscape(uri string) string
- func (p *PathSpec) URLPrep(in string) string
- func (p *PathSpec) URLize(uri string) string
- func (p *PathSpec) URLizeAndPrep(in string) string
- func (p *PathSpec) URLizeFilename(filename string) string
- func (p *PathSpec) UnicodeSanitize(s string) string
- type ProcessingStats
- type RenderingContext
Constants ¶
const FilePathSeparator = string(filepath.Separator)
FilePathSeparator as defined by os.Separator.
Variables ¶
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() )
var CurrentHugoVersion = HugoVersion{
Number: 0.47,
PatchLevel: 1,
Suffix: "",
}
CurrentHugoVersion represents the current build version. This should be the only one.
var ( // ErrThemeUndefined is returned when a theme has not be defined by the user. ErrThemeUndefined = errors.New("no theme set") )
var SummaryDivider = []byte("<!--more-->")
SummaryDivider denotes where content summarization should end. The default is "<!--more-->".
Functions ¶
func AddContextRoot ¶
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.
func BytesToHTML ¶
BytesToHTML converts bytes to type template.HTML.
func CompareVersion ¶ added in v0.20.0
func CompareVersion(version interface{}) int
CompareVersion compares the given version string or number against the running Hugo version. It returns -1 if the given version is less than, 0 if equal and 1 if greater than the running version.
func Deprecated ¶
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.
func DiffStringSlices ¶ added in v0.17.0
DiffStringSlices returns the difference between two string slices. Useful in tests. See: http://stackoverflow.com/questions/19374219/how-to-find-the-difference-between-two-slices-of-strings-in-golang
func DiffStrings ¶ added in v0.37.0
DiffString splits the strings into fields and runs it into DiffStringSlices. Useful for tests.
func Emojify ¶ added in v0.16.0
Emojify "emojifies" the input source. Note that the input byte slice will be modified if needed. See http://www.emoji-cheat-sheet.com/
func Ext ¶ added in v0.24.0
Ext takes a path and returns the extension, including the delmiter, i.e. ".md".
func ExtNoDelimiter ¶ added in v0.43.0
ExtNoDelimiter takes a path and returns the extension, excluding the delmiter, i.e. "md".
func ExtractRootPaths ¶
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"
func ExtractTOC ¶
ExtractTOC extracts Table of Contents from content.
func FileAndExt ¶ added in v0.32.0
FileAndExt takes a path and returns the file and extension separated, the extension including the delmiter, i.e. ".md".
func FileContains ¶
FileContains checks if a file contains a specified string.
func FileContainsAny ¶ added in v0.16.0
FileContainsAny checks if a file contains any of the specified strings.
func FindAvailablePort ¶
FindAvailablePort returns an available and valid TCP port.
func FirstUpper ¶
FirstUpper returns a string with the first character as upper case.
func GetDottedRelativePath ¶
GetDottedRelativePath expects a relative path starting after the content directory. It returns a relative path with dots ("..") navigating up the path structure.
func GetRealPath ¶ added in v0.17.0
GetRealPath returns the real file path for the given path, whether it is a symlink or not.
func GetRelativePath ¶
GetRelativePath returns the relative path of a given path.
func GetTempDir ¶
GetTempDir returns a temporary directory with the given sub path.
func GetTitleFunc ¶ added in v0.26.0
GetTitleFunc returns a func that can be used to transform a string to title case.
The supported styles are ¶
- "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.
func HasAsciidoc ¶ added in v0.17.0
func HasAsciidoc() bool
HasAsciidoc returns whether Asciidoc or Asciidoctor is installed on this computer.
func HasRst ¶ added in v0.17.0
func HasRst() bool
HasRst returns whether rst2html is installed on this computer.
func HasStringsPrefix ¶ added in v0.25.0
HasStringsPrefix tests whether the string slice s begins with prefix slice s.
func HasStringsSuffix ¶ added in v0.25.0
HasStringsSuffix tests whether the string slice s ends with suffix slice s.
func InStringArray ¶
InStringArray checks if a string is an element of a slice of strings and returns a boolean value.
func InitLoggers ¶ added in v0.17.0
func InitLoggers()
InitLoggers sets up the global distinct loggers.
func IsAbsURL ¶ added in v0.17.0
IsAbsURL determines whether the given path points to an absolute URL.
func IsWhitespace ¶
IsWhitespace determines if the given rune is whitespace.
func LstatIfPossible ¶ added in v0.38.0
LstatIfPossible can be used to call Lstat if possible, else Stat.
func MD5FromFile ¶ added in v0.32.0
MD5FromFile creates a MD5 hash from the given file. It will not close the file.
func MD5FromFileFast ¶ added in v0.32.0
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.
func MakePermalink ¶
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
func MakeTitle ¶
MakeTitle converts the path given to a suitable title, trimming whitespace and replacing hyphens with whitespace.
func NormalizeHugoFlags ¶
func NormalizeHugoFlags(f *pflag.FlagSet, name string) pflag.NormalizedName
NormalizeHugoFlags facilitates transitions of Hugo command-line flags, e.g. --baseUrl to --baseURL, --uglyUrls to --uglyURLs
func OpenFileForWriting ¶ added in v0.47.0
OpenFileForWriting opens or creates the given file. If the target directory does not exist, it gets created.
func OpenFilesForWriting ¶ added in v0.47.0
OpenFileForWriting opens all the given filenames for writing.
func PathAndExt ¶ added in v0.43.0
PathAndExt is the same as FileAndExt, but it uses the path package.
func PathPrep ¶
PathPrep prepares the path using the uglify setting to create paths on either the form /section/name/index.html or /section/name.html.
func PrettifyPath ¶
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
func PrettifyURL ¶
PrettifyURL takes a URL string and returns a semantic, clean URL.
func PrettifyURLPath ¶
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
func PrintFs ¶ added in v0.42.0
PrintFs prints the given filesystem to the given writer starting from the given path. This is useful for debugging.
func ProcessingStatsTable ¶ added in v0.32.0
func ProcessingStatsTable(w io.Writer, stats ...*ProcessingStats)
func ReaderContains ¶
ReaderContains reports whether subslice is within r.
func ReaderToBytes ¶
ReaderToBytes takes an io.Reader argument, reads from it and returns bytes.
func ReaderToString ¶
ReaderToString is the same as ReaderToBytes, but returns a string.
func ReplaceExtension ¶
ReplaceExtension takes a path and an extension, strips the old extension and returns the path with the new extension.
func SafeWriteToDisk ¶
SafeWriteToDisk is the same as WriteToDisk but it also checks to see if file/directory already exists.
func SanitizeURLKeepTrailingSlash ¶
SanitizeURLKeepTrailingSlash is the same as SanitizeURL, but will keep any trailing slash.
func SliceToLower ¶
SliceToLower goes through the source slice and lowers all values.
func SymbolicWalk ¶ added in v0.16.0
SymbolicWalk is like filepath.Walk, but it supports the root being a symbolic link. It will still not follow symbolic links deeper down in the file structure.
func ToSlashTrimLeading ¶ added in v0.43.0
ToSlashTrimLeading is just a filepath.ToSlaas with an added / prefix trimmer.
func TotalWords ¶
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)).
func Uglify ¶
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
func UniqueStrings ¶
UniqueStrings returns a new slice with any duplicates removed.
Types ¶
type BlackFriday ¶ added in v0.32.0
type BlackFriday struct { Smartypants bool SmartypantsQuotesNBSP bool AngledQuotes bool Fractions bool HrefTargetBlank bool NofollowLinks bool NoreferrerLinks bool SmartDashes bool LatexDashes bool TaskLists bool PlainIDAnchors bool Extensions []string ExtensionsMask []string }
BlackFriday holds configuration values for BlackFriday rendering.
type ContentSpec ¶ added in v0.19.0
type ContentSpec struct { BlackFriday *BlackFriday BuildFuture bool BuildExpired bool BuildDrafts bool Highlight func(code, lang, optsStr string) (string, error) // contains filtered or unexported fields }
ContentSpec provides functionality to render markdown content.
func NewContentSpec ¶ added in v0.19.0
func NewContentSpec(cfg config.Provider) (*ContentSpec, error)
NewContentSpec returns a ContentSpec initialized with the appropriate fields from the given config.Provider.
func (ContentSpec) RenderBytes ¶ added in v0.19.0
func (c ContentSpec) RenderBytes(ctx *RenderingContext) []byte
RenderBytes renders a []byte.
func (*ContentSpec) TruncateWordsByRune ¶ added in v0.30.0
func (c *ContentSpec) TruncateWordsByRune(in []string) (string, bool)
TruncateWordsByRune truncates words by runes.
func (*ContentSpec) TruncateWordsToWholeSentence ¶ added in v0.30.0
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.
type DistinctLogger ¶ added in v0.16.0
DistinctLogger ignores duplicate log statements.
func NewDistinctErrorLogger ¶
func NewDistinctErrorLogger() *DistinctLogger
NewDistinctErrorLogger creates a new DistinctLogger that logs ERRORs
func NewDistinctFeedbackLogger ¶ added in v0.16.0
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 ¶ added in v0.41.0
func NewDistinctLogger(logger LogPrinter) *DistinctLogger
NewDistinctLogger creates a new DistinctLogger that logs to the provided logger.
func NewDistinctWarnLogger ¶ added in v0.20.0
func NewDistinctWarnLogger() *DistinctLogger
NewDistinctWarnLogger creates a new DistinctLogger that logs WARNs
func (*DistinctLogger) Printf ¶ added in v0.16.0
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 (*DistinctLogger) Println ¶ added in v0.16.0
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.
type HugoHTMLRenderer ¶ added in v0.16.0
type HugoHTMLRenderer struct { *RenderingContext blackfriday.Renderer // contains filtered or unexported fields }
HugoHTMLRenderer wraps a blackfriday.Renderer, typically a blackfriday.Html Enabling Hugo to customise the rendering experience
func (*HugoHTMLRenderer) BlockCode ¶ added in v0.16.0
func (r *HugoHTMLRenderer) BlockCode(out *bytes.Buffer, text []byte, lang string)
BlockCode renders a given text as a block of code. Pygments is used if it is setup to handle code fences.
type HugoMmarkHTMLRenderer ¶ added in v0.16.0
type HugoMmarkHTMLRenderer struct { mmark.Renderer Cfg config.Provider // contains filtered or unexported fields }
HugoMmarkHTMLRenderer wraps a mmark.Renderer, typically a mmark.html, enabling Hugo to customise the rendering experience.
type HugoVersion ¶
type HugoVersion struct { // Major and minor version. Number float32 // Increment this for bug releases PatchLevel int // HugoVersionSuffix is the suffix used in the Hugo version string. // It will be blank for release versions. Suffix string }
HugoVersion represents the Hugo build version.
func MustParseHugoVersion ¶ added in v0.25.0
func MustParseHugoVersion(s string) HugoVersion
MustParseHugoVersion parses a version string and panics if any error occurs.
func ParseHugoVersion ¶ added in v0.25.0
func ParseHugoVersion(s string) (HugoVersion, error)
ParseHugoVersion parses a version string.
func (HugoVersion) Next ¶ added in v0.20.3
func (v HugoVersion) Next() HugoVersion
Next returns the next Hugo release version.
func (HugoVersion) NextPatchLevel ¶ added in v0.20.3
func (v HugoVersion) NextPatchLevel(level int) HugoVersion
NextPatchLevel returns the next patch/bugfix Hugo version. This will be a patch increment on the previous Hugo version.
func (HugoVersion) Prev ¶ added in v0.20.3
func (v HugoVersion) Prev() HugoVersion
Prev returns the previous Hugo release version.
func (HugoVersion) ReleaseVersion ¶ added in v0.20.3
func (v HugoVersion) ReleaseVersion() HugoVersion
ReleaseVersion represents the release version.
func (HugoVersion) String ¶ added in v0.20.3
func (v HugoVersion) String() string
func (HugoVersion) Version ¶ added in v0.37.0
func (v HugoVersion) Version() HugoVersionString
type HugoVersionString ¶ added in v0.37.0
type HugoVersionString string
func (HugoVersionString) Compare ¶ added in v0.37.0
func (h HugoVersionString) Compare(other interface{}) int
Implements compare.Comparer
func (HugoVersionString) Eq ¶ added in v0.37.0
func (h HugoVersionString) Eq(other interface{}) bool
Implements compare.Eqer
func (HugoVersionString) String ¶ added in v0.37.0
func (h HugoVersionString) String() string
type LogPrinter ¶ added in v0.41.0
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.
type PathSpec ¶ added in v0.18.0
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.
func NewPathSpec ¶ added in v0.19.0
NewPathSpec creats a new PathSpec from the given filesystems and language.
func NewPathSpecWithBaseBaseFsProvided ¶ added in v0.42.0
func NewPathSpecWithBaseBaseFsProvided(fs *hugofs.Fs, cfg config.Provider, 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.
func (*PathSpec) AbsURL ¶ added in v0.18.0
AbsURL creates an absolute URL from the relative path given and the BaseURL set in config.
func (*PathSpec) GetFirstThemeDir ¶ added in v0.42.0
GetFirstThemeDir gets the root directory of the first theme, if there is one. If there is no theme, returns the empty string.
func (*PathSpec) GetRelativeThemeDir ¶ added in v0.19.0
GetRelativeThemeDir gets the relative root directory of the current theme, if there is one. If there is no theme, returns the empty string.
func (*PathSpec) GetThemesDir ¶ added in v0.42.0
GetThemesDir gets the absolute root theme dir path.
func (*PathSpec) MakePath ¶ added in v0.18.0
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
func (*PathSpec) MakePathSanitized ¶ added in v0.18.0
MakePathSanitized creates a Unicode-sanitized string, with the spaces replaced
func (*PathSpec) PermalinkForBaseURL ¶ added in v0.32.0
PermalinkForBaseURL creates a permalink from the given link and baseURL.
func (*PathSpec) PrependBasePath ¶ added in v0.20.0
PrependBasePath prepends any baseURL sub-folder to the given resource if canonifyURLs is disabled. If canonifyURLs is set, we will globally prepend the absURL with any sub-folder, so avoid doing anything here to avoid getting double paths.
func (*PathSpec) RelURL ¶ added in v0.18.0
RelURL creates a URL relative to the BaseURL root. Note: The result URL will not include the context root if canonifyURLs is enabled.
func (*PathSpec) URLize ¶ added in v0.18.0
URLize is similar to MakePath, but with Unicode handling Example:
uri: Vim (text editor) urlize: vim-text-editor
func (*PathSpec) URLizeAndPrep ¶ added in v0.18.0
URLizeAndPrep applies misc sanitation to the given URL to get it in line with the Hugo standard.
func (*PathSpec) URLizeFilename ¶ added in v0.20.0
URLizeFilename creates an URL from a filename by esacaping unicode letters and turn any filepath separator into forward slashes.
func (*PathSpec) UnicodeSanitize ¶ added in v0.18.0
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, Uniccode accents are also removed.
type ProcessingStats ¶ added in v0.32.0
type ProcessingStats struct { Name string Pages uint64 PaginatorPages uint64 Static uint64 ProcessedImages uint64 Files uint64 Aliases uint64 Sitemaps uint64 Cleaned uint64 }
func NewProcessingStats ¶ added in v0.32.0
func NewProcessingStats(name string) *ProcessingStats
func (*ProcessingStats) Add ¶ added in v0.32.0
func (s *ProcessingStats) Add(counter *uint64, amount int)
func (*ProcessingStats) Incr ¶ added in v0.32.0
func (s *ProcessingStats) Incr(counter *uint64)
func (*ProcessingStats) Table ¶ added in v0.32.0
func (s *ProcessingStats) Table(w io.Writer)
type RenderingContext ¶
type RenderingContext struct { Content []byte PageFmt string DocumentID string DocumentName string Config *BlackFriday RenderTOC bool Cfg config.Provider }
RenderingContext holds contextual information, like content and configuration, for a given content rendering. By creating you must set the Config, otherwise it will panic.