helpers

package
v0.18.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 29, 2016 License: Apache-2.0 Imports: 37 Imported by: 0

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.

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

View Source
const (
	// Major and minor version.
	HugoVersionNumber = 0.18

	// Increment this for bug releases
	HugoPatchVersion = 1
)

HugoVersionNumber represents the current build version. This should be the only one

View Source
const FilePathSeparator = string(filepath.Separator)

FilePathSeparator as defined by os.Separator.

View Source
const HugoVersionSuffix = "" // use this line when doing a release

HugoVersionSuffix is the suffix used in the Hugo version string. It will be blank for release versions. const HugoVersionSuffix = "-DEV" // use this when not doing a release

Variables

View Source
var (
	// DistinctErrorLog can be used to avoid spamming the logs with errors.
	DistinctErrorLog = NewDistinctErrorLogger()

	// DistinctFeedbackLog can be used to avoid spamming the logs with info messages.
	DistinctFeedbackLog = NewDistinctFeedbackLogger()
)
View Source
var ErrWalkRootTooShort = errors.New("Path too short. Stop walking.")
View Source
var SummaryDivider = []byte("<!--more-->")

SummaryDivider denotes where content summarization should end. The default is "<!--more-->".

View Source
var SummaryLength = 70

SummaryLength is the length of the summary that Hugo extracts from a content.

Functions

func AbsPathify

func AbsPathify(inPath string) string

AbsPathify creates an absolute path if given a relative path. If already absolute, the path is just cleaned.

func AddContextRoot

func AddContextRoot(baseURL, relativePath string) string

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

func BytesToHTML(b []byte) template.HTML

BytesToHTML converts bytes to type template.HTML.

func Deprecated

func Deprecated(object, item, alternative string, err bool)

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

func DiffStringSlices(slice1 []string, slice2 []string) []string

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 DirExists

func DirExists(path string, fs afero.Fs) (bool, error)

DirExists checks if a path exists and is a directory.

func DoArithmetic

func DoArithmetic(a, b interface{}, op rune) (interface{}, error)

DoArithmetic performs arithmetic operations (+,-,*,/) using reflection to determine the type of the two terms.

func Emojify

func Emojify(source []byte) []byte

Emojify "emojifies" the input source. Note that the input byte slice will be modified if needed. See http://www.emoji-cheat-sheet.com/

func Exists

func Exists(path string, fs afero.Fs) (bool, error)

Exists checks if a file or directory exists.

func ExtractRootPaths

func ExtractRootPaths(paths []string) []string

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

func ExtractTOC(content []byte) (newcontent []byte, toc []byte)

ExtractTOC extracts Table of Contents from content.

func FileContains

func FileContains(filename string, subslice []byte, fs afero.Fs) (bool, error)

FileContains checks if a file contains a specified string.

func FileContainsAny

func FileContainsAny(filename string, subslices [][]byte, fs afero.Fs) (bool, error)

FileContainsAny checks if a file contains any of the specified strings.

func Filename

func Filename(in string) (name string)

Filename takes a path, strips out the extension, and returns the name of the file.

func FindAvailablePort

func FindAvailablePort() (*net.TCPAddr, error)

FindAvailablePort returns an available and valid TCP port.

func FindCWD

func FindCWD() (string, error)

FindCWD returns the current working directory from where the Hugo executable is run.

func FirstUpper

func FirstUpper(s string) string

FirstUpper returns a string with the first character as upper case.

func GetDottedRelativePath

func GetDottedRelativePath(inPath string) string

GetDottedRelativePath expects a relative path starting after the content directory. It returns a relative path with dots ("..") navigating up the path structure.

func GetLayoutDirPath

func GetLayoutDirPath() string

GetLayoutDirPath returns the absolute path to the layout file dir for the current Hugo project.

func GetRealPath

func GetRealPath(fs afero.Fs, path string) (string, error)

GetRealPath returns the real file path for the given path, whether it is a symlink or not.

func GetRelativePath

func GetRelativePath(path, base string) (final string, err error)

GetRelativePath returns the relative path of a given path.

func GetRelativeThemeDir

func GetRelativeThemeDir() string

GetRelativeThemeDir gets the relative root directory of the current theme, if there is one. If there is no theme, returns the empty string.

func GetStaticDirPath

func GetStaticDirPath() string

GetStaticDirPath returns the absolute path to the static file dir for the current Hugo project.

func GetTempDir

func GetTempDir(subPath string, fs afero.Fs) string

GetTempDir returns a temporary directory with the given sub path.

func GetThemeDataDirPath

func GetThemeDataDirPath() (string, error)

GetThemeDataDirPath returns the theme's data dir path if theme is set. If theme is set and the data dir doesn't exist, an error is returned.

func GetThemeDir

func GetThemeDir() string

GetThemeDir gets the root directory of the current theme, if there is one. If there is no theme, returns the empty string.

func GetThemeI18nDirPath

func GetThemeI18nDirPath() (string, error)

GetThemeI18nDirPath returns the theme's i18n dir path if theme is set. If theme is set and the i18n dir doesn't exist, an error is returned.

func GetThemeStaticDirPath

func GetThemeStaticDirPath() (string, error)

GetThemeStaticDirPath returns the theme's static dir path if theme is set. If theme is set and the static dir doesn't exist, an error is returned.

func GetThemesDirPath

func GetThemesDirPath() string

GetThemesDirPath gets the static files directory of the current theme, if there is one. Ignores underlying errors. TODO(bep) Candidate for deprecation?

func GuessSection

func GuessSection(in string) string

GuessSection returns the section given a source path. A section is the part between the root slash and the second slash or before the first slash.

func GuessType

func GuessType(in string) string

GuessType attempts to guess the type of file from a given string.

func HasAsciidoc

func HasAsciidoc() bool

HasAsciidoc returns whether Asciidoctor or Asciidoc is installed on this computer.

func HasPygments

func HasPygments() bool

HasPygments checks to see if Pygments is installed and available on the system.

func HasRst

func HasRst() bool

HasRst returns whether rst2html is installed on this computer.

func Highlight

func Highlight(code, lang, optsStr string) string

Highlight takes some code and returns highlighted code.

func HugoReleaseVersion

func HugoReleaseVersion() string

HugoReleaseVersion is same as HugoVersion, but no suffix.

func HugoVersion

func HugoVersion() string

HugoVersion returns the current Hugo version. It will include a suffix, typically '-DEV', if it's development version.

func InStringArray

func InStringArray(arr []string, el string) bool

InStringArray checks if a string is an element of a slice of strings and returns a boolean value.

func InitConfigProviderForCurrentContentLanguage

func InitConfigProviderForCurrentContentLanguage()

InitConfigProviderForCurrentContentLanguage does what it says.

func InitLoggers

func InitLoggers()

InitLoggers sets up the global distinct loggers.

func IsAbsURL

func IsAbsURL(path string) bool

IsAbsURL determines whether the given path points to an absolute URL.

func IsDir

func IsDir(path string, fs afero.Fs) (bool, error)

IsDir checks if a given path is a directory.

func IsEmpty

func IsEmpty(path string, fs afero.Fs) (bool, error)

IsEmpty checks if a given path is empty.

func IsWhitespace

func IsWhitespace(r rune) bool

IsWhitespace determines if the given rune is whitespace.

func MakePermalink(host, plink string) *url.URL

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 MakeStaticPathRelative

func MakeStaticPathRelative(inPath string) (string, error)

MakeStaticPathRelative makes a relative path to the static files directory. It does so by taking either the project's static path or the theme's static path into consideration.

func MakeTitle

func MakeTitle(inpath string) string

MakeTitle converts the path given to a suitable title, trimming whitespace and replacing hyphens with whitespace.

func Md5String

func Md5String(f string) string

Md5String takes a string and returns its MD5 hash.

func NextHugoReleaseVersion

func NextHugoReleaseVersion() string

NextHugoReleaseVersion returns the next Hugo release version.

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 PaginateAliasPath

func PaginateAliasPath(base string, page int) string

PaginateAliasPath creates a path used to access the aliases in the paginator.

func PathPrep

func PathPrep(ugly bool, in string) string

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

func PrettifyPath(in string) string

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

func PrettifyURL(in string) string

PrettifyURL takes a URL string and returns a semantic, clean URL.

func PrettifyURLPath

func PrettifyURLPath(in string) string

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 ReaderContains

func ReaderContains(r io.Reader, subslice []byte) bool

ReaderContains reports whether subslice is within r.

func ReaderToBytes

func ReaderToBytes(lines io.Reader) []byte

ReaderToBytes takes an io.Reader argument, reads from it and returns bytes.

func ReaderToString

func ReaderToString(lines io.Reader) string

ReaderToString is the same as ReaderToBytes, but returns a string.

func RenderBytes

func RenderBytes(ctx *RenderingContext) []byte

RenderBytes renders a []byte.

func ReplaceExtension

func ReplaceExtension(path string, newExt string) string

ReplaceExtension takes a path and an extension, strips the old extension and returns the path with the new extension.

func ResetConfigProvider

func ResetConfigProvider()

ResetConfigProvider is used in tests.

func SafeWriteToDisk

func SafeWriteToDisk(inpath string, r io.Reader, fs afero.Fs) (err error)

SafeWriteToDisk is the same as WriteToDisk but it also checks to see if file/directory already exists.

func SanitizeURL

func SanitizeURL(in string) string

SanitizeURL sanitizes the input URL string.

func SanitizeURLKeepTrailingSlash

func SanitizeURLKeepTrailingSlash(in string) string

SanitizeURLKeepTrailingSlash is the same as SanitizeURL, but will keep any trailing slash.

func Seq

func Seq(args ...interface{}) ([]int, error)

Seq creates a sequence of integers. It's named and used as GNU's seq. Examples: 3 => 1, 2, 3 1 2 4 => 1, 3 -3 => -1, -2, -3 1 4 => 1, 2, 3, 4 1 -2 => 1, 0, -1, -2

func SliceToLower

func SliceToLower(s []string) []string

SliceToLower goes through the source slice and lowers all values.

func StripHTML

func StripHTML(s string) string

StripHTML accepts a string, strips out all HTML tags and returns it.

func SymbolicWalk

func SymbolicWalk(fs afero.Fs, root string, walker filepath.WalkFunc) error

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 ThemeSet

func ThemeSet() bool

ThemeSet checks whether a theme is in use or not.

func ToLowerMap

func ToLowerMap(m map[string]interface{})

ToLowerMap makes all the keys in the given map lower cased and will do so recursively. Notes: * This will modify the map given. * Any nested map[interface{}]interface{} will be converted to map[string]interface{}.

func TotalWords

func TotalWords(s string) int

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 TruncateWordsByRune

func TruncateWordsByRune(words []string, max int) (string, bool)

TruncateWordsByRune truncates words by runes.

func TruncateWordsToWholeSentence

func TruncateWordsToWholeSentence(s string, max int) (string, bool)

TruncateWordsToWholeSentence takes content and truncates to whole sentence limited by max number of words. It also returns whether it is truncated.

func Uglify

func Uglify(in string) string

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

func UniqueStrings(s []string) []string

UniqueStrings returns a new slice with any duplicates removed.

func WordCount

func WordCount(s string) map[string]int

WordCount takes content and returns a map of words and count of each word.

func WriteToDisk

func WriteToDisk(inpath string, r io.Reader, fs afero.Fs) (err error)

WriteToDisk writes content to disk.

Types

type Blackfriday

type Blackfriday struct {
	Smartypants                      bool
	AngledQuotes                     bool
	Fractions                        bool
	HrefTargetBlank                  bool
	SmartDashes                      bool
	LatexDashes                      bool
	TaskLists                        bool
	PlainIDAnchors                   bool
	SourceRelativeLinksEval          bool
	SourceRelativeLinksProjectFolder string
	Extensions                       []string
	ExtensionsMask                   []string
}

Blackfriday holds configuration values for Blackfriday rendering.

func NewBlackfriday

func NewBlackfriday(c ConfigProvider) *Blackfriday

NewBlackfriday creates a new Blackfriday filled with site config or some sane defaults.

type ConfigProvider

type ConfigProvider interface {
	GetString(key string) string
	GetInt(key string) int
	GetBool(key string) bool
	GetStringMap(key string) map[string]interface{}
	GetStringMapString(key string) map[string]string
	Get(key string) interface{}
}

ConfigProvider provides the configuration settings for Hugo.

func Config

func Config() ConfigProvider

Config returns the currently active Hugo config. This will be set per site (language) rendered.

type DistinctLogger

type DistinctLogger struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

DistinctLogger ignores duplicate log statements.

func NewDistinctErrorLogger

func NewDistinctErrorLogger() *DistinctLogger

NewDistinctErrorLogger creates a new DistinctLogger that logs ERRORs

func NewDistinctFeedbackLogger

func NewDistinctFeedbackLogger() *DistinctLogger

NewDistinctFeedbackLogger creates a new DistinctLogger that can be used to give feedback to the user while not spamming with duplicates.

func (*DistinctLogger) Printf

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

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 FileResolverFunc

type FileResolverFunc func(ref string) (string, error)

type HugoHTMLRenderer

type HugoHTMLRenderer struct {
	*RenderingContext
	blackfriday.Renderer
}

HugoHTMLRenderer wraps a blackfriday.Renderer, typically a blackfriday.Html Enabling Hugo to customise the rendering experience

func (*HugoHTMLRenderer) BlockCode

func (renderer *HugoHTMLRenderer) BlockCode(out *bytes.Buffer, text []byte, lang string)

func (*HugoHTMLRenderer) Image

func (renderer *HugoHTMLRenderer) Image(out *bytes.Buffer, link []byte, title []byte, alt []byte)
func (renderer *HugoHTMLRenderer) Link(out *bytes.Buffer, link []byte, title []byte, content []byte)

func (*HugoHTMLRenderer) List

func (renderer *HugoHTMLRenderer) List(out *bytes.Buffer, text func() bool, flags int)

List adds task list support to the Blackfriday renderer.

func (*HugoHTMLRenderer) ListItem

func (renderer *HugoHTMLRenderer) ListItem(out *bytes.Buffer, text []byte, flags int)

ListItem adds task list support to the Blackfriday renderer.

type HugoMmarkHTMLRenderer

type HugoMmarkHTMLRenderer struct {
	mmark.Renderer
}

HugoMmarkHTMLRenderer wraps a mmark.Renderer, typically a mmark.html Enabling Hugo to customise the rendering experience

func (*HugoMmarkHTMLRenderer) BlockCode

func (renderer *HugoMmarkHTMLRenderer) BlockCode(out *bytes.Buffer, text []byte, lang string, caption []byte, subfigure bool, callouts bool)

type Language

type Language struct {
	Lang         string
	LanguageName string
	Title        string
	Weight       int
	// contains filtered or unexported fields
}

func NewDefaultLanguage

func NewDefaultLanguage() *Language

func NewLanguage

func NewLanguage(lang string) *Language

func (*Language) Get

func (l *Language) Get(key string) interface{}

Get returns a value associated with the key relying on specified language. Get is case-insensitive for a key.

Get returns an interface. For a specific value use one of the Get____ methods.

func (*Language) GetBool

func (l *Language) GetBool(key string) bool

GetBool returns the value associated with the key as a boolean.

func (*Language) GetInt

func (l *Language) GetInt(key string) int

GetInt returns the value associated with the key as an int.

func (*Language) GetString

func (l *Language) GetString(key string) string

GetString returns the value associated with the key as a string.

func (*Language) GetStringMap

func (l *Language) GetStringMap(key string) map[string]interface{}

GetStringMap returns the value associated with the key as a map of interfaces.

func (*Language) GetStringMapString

func (l *Language) GetStringMapString(key string) map[string]string

GetStringMapString returns the value associated with the key as a map of strings.

func (*Language) Params

func (l *Language) Params() map[string]interface{}

func (*Language) SetParam

func (l *Language) SetParam(k string, v interface{})

func (*Language) String

func (l *Language) String() string

type Languages

type Languages []*Language

func NewLanguages

func NewLanguages(l ...*Language) Languages

func (Languages) Len

func (l Languages) Len() int

func (Languages) Less

func (l Languages) Less(i, j int) bool

func (Languages) Swap

func (l Languages) Swap(i, j int)

type LinkResolverFunc

type LinkResolverFunc func(ref string) (string, error)

type PathSpec

type PathSpec struct {
	// contains filtered or unexported fields
}

PathSpec holds methods that decides how paths in URLs and files in Hugo should look like.

func CurrentPathSpec

func CurrentPathSpec() *PathSpec

CurrentPathSpec returns the current PathSpec. If it is not set, a new will be created based in the currently active Hugo config.

func NewPathSpecFromConfig

func NewPathSpecFromConfig(config ConfigProvider) *PathSpec

NewPathSpecFromConfig creats a new PathSpec from the given ConfigProvider.

func (*PathSpec) AbsURL

func (p *PathSpec) AbsURL(in string, addLanguage bool) string

AbsURL creates a absolute URL from the relative path given and the BaseURL set in config.

func (*PathSpec) MakePath

func (p *PathSpec) MakePath(s string) string

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

func (p *PathSpec) MakePathSanitized(s string) string

MakePathSanitized creates a Unicode-sanitized string, with the spaces replaced

func (*PathSpec) PaginatePath

func (p *PathSpec) PaginatePath() string

PaginatePath returns the configured root path used for paginator pages.

func (*PathSpec) RelURL

func (p *PathSpec) RelURL(in string, addLanguage bool) string

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) URLPrep

func (p *PathSpec) URLPrep(in string) string

URLPrep applies misc sanitation to the given URL.

func (*PathSpec) URLize

func (p *PathSpec) URLize(uri string) string

URLize is similar to MakePath, but with Unicode handling Example:

uri: Vim (text editor)
urlize: vim-text-editor

func (*PathSpec) URLizeAndPrep

func (p *PathSpec) URLizeAndPrep(in string) string

URLizeAndPrep applies misc sanitation to the given URL to get it in line with the Hugo standard.

func (*PathSpec) UnicodeSanitize

func (p *PathSpec) UnicodeSanitize(s string) string

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 RenderingContext

type RenderingContext struct {
	Content        []byte
	PageFmt        string
	DocumentID     string
	DocumentName   string
	Config         *Blackfriday
	RenderTOC      bool
	FileResolver   FileResolverFunc
	LinkResolver   LinkResolverFunc
	ConfigProvider ConfigProvider
	// contains filtered or unexported fields
}

RenderingContext holds contextual information, like content and configuration, for a given content rendering.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL